001/*
002 * Licensed to the Apache Software Foundation (ASF) under one or more
003 * contributor license agreements.  See the NOTICE file distributed with
004 * this work for additional information regarding copyright ownership.
005 * The ASF licenses this file to You under the Apache License, Version 2.0
006 * (the "License"); you may not use this file except in compliance with
007 * the License.  You may obtain a copy of the License at
008 *
009 *      http://www.apache.org/licenses/LICENSE-2.0
010 *
011 * Unless required by applicable law or agreed to in writing, software
012 * distributed under the License is distributed on an "AS IS" BASIS,
013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
014 * See the License for the specific language governing permissions and
015 * limitations under the License.
016 */
017package org.apache.juneau.microservice.examples;
018
019import static org.apache.juneau.commons.utils.Shorts.*;
020
021import java.util.*;
022import java.util.regex.*;
023
024import org.apache.juneau.microservice.*;
025import org.apache.juneau.rest.server.filter.*;
026
027import jakarta.servlet.*;
028
029/**
030 * The CSRF boundary for the admin resources {@link ConfigResource}, {@link LogsResource} and {@link ShutdownResource}.
031 *
032 * <p>
033 * This boundary is not authentication.  It checks the {@code Host} and {@code Origin} headers a browser sends; it does
034 * not identify the caller, and any client that is not a browser passes it.  The admin resources have no authentication
035 * of their own, so an application that mounts them must add its own, and must not expose them on an untrusted network.
036 *
037 * <p>
038 * {@link #registration(String, String...)} returns a {@link ServletFilterRegistration} that puts the three resources
039 * behind their own {@link CsrfBoundary}.  A write from another site's page is refused with {@code 403} and an
040 * {@value RequestBoundaryFilter#REJECTION_HEADER} header naming the reason.  So is a write that a browser could
041 * have sent cross-site without a CORS preflight and that carries no {@code Origin}: a urlencoded, multipart or
042 * {@code text/plain} {@code POST}, or a {@code GET} claiming another method through {@code ?method=} or an override
043 * header.  Reads are allowed.
044 *
045 * <p>
046 * The admin resources have no HTML forms or write links, so no page ever carries a token, and a browser write to them
047 * always fails.  Writes come from REST clients and the command line as requests a browser could not send cross-site
048 * without a preflight, and the boundary admits those with no token:
049 * <p class='bcode'>
050 *    curl -X PUT -H 'Content-Type: text/plain' -d 'newValue' http://localhost:10000/config/MySection/myKey
051 *    curl -X DELETE http://localhost:10000/logs/old.log
052 *    curl -X POST -H 'Content-Type: application/json' http://localhost:10000/shutdown
053 * </p>
054 *
055 * <p>
056 * Every request, reads included, must name one of the allowed hosts in its {@code Host} header, or it is refused with
057 * {@code 421}.  Unless other host names are given, only the loopback names {@link #LOOPBACK_HOSTS} are answered, so a
058 * page on a rebound DNS name cannot read the configuration or the logs.  A server reached under any other name must
059 * list that name.
060 *
061 * <p>
062 * The boundary answers only CSRF and DNS rebinding.  It does not authenticate anyone, and a direct network caller
063 * passes it.  The admin resources have no authentication of their own, so do not expose them on an untrusted network.
064 *
065 * <p>
066 * The filter is mapped on the request path as the servlet container normalizes it, while Juneau routes on the path
067 * segments it receives.  The two agree under the container's default URI handling (for Jetty 12,
068 * {@code UriCompliance.DEFAULT}, which rejects ambiguous paths such as encoded separators and dot segments).  A
069 * container configured to accept ambiguous paths could route a request to an admin resource without the filter seeing
070 * it, so keep the default, and verify any other container the same way.
071 *
072 * <h2 class='section'>Example:</h2>
073 * <p>
074 * In a Juneau microservice whose root resource mounts the three resources as children, contribute the registration
075 * as a <c>@Bean</c>:
076 * <p class='bjava'>
077 *    <ja>@Bean</ja>(name=<js>"adminBoundary"</js>)
078 *    <jk>public</jk> ServletFilterRegistration adminBoundary() {
079 *       <jk>return</jk> AdminBoundary.<jsm>registration</jsm>(<js>""</js>, <js>"app.example.com"</js>);
080 *    }
081 * </p>
082 *
083 * <h2 class='section'>See Also:</h2><ul>
084 *    <li class='jc'>{@link CsrfBoundary}
085 *    <li class='jc'>{@link ServletFilterRegistration}
086 * </ul>
087 *
088 * @since 10.0.0
089 */
090public final class AdminBoundary {
091
092   /** The host names answered when none are given: {@code localhost}, {@code 127.0.0.1} and {@code [::1]}, on any port. */
093   public static final List<String> LOOPBACK_HOSTS = List.of("localhost", "127.0.0.1", "[::1]");
094
095   /** The order the registration runs at: ahead of authentication, behind anything registered at the very front. */
096   public static final int ORDER = ServletFilterRegistration.HIGHEST_PRECEDENCE + 20;
097
098   private static final String[] PATHS = { "/config", "/logs", "/shutdown" };
099
100   // One or more "/segment" parts of unreserved characters, so every pattern built on it is one the container matches.
101   private static final Pattern PREFIX = Pattern.compile("(?:/[A-Za-z0-9_~-][A-Za-z0-9._~-]*+)*+");
102
103   private AdminBoundary() {}
104
105   /**
106    * A registration of a new CSRF boundary over the three admin resources.
107    *
108    * <p>
109    * The registration maps each resource's path both exactly and as a prefix ({@code /config} and
110    * {@code /config/*}, and so on: six patterns), for {@code REQUEST} dispatches only, at {@link #ORDER}.  Each call
111    * builds its own filter, so the registration never shares an instance with another boundary.  The boundary's token
112    * is per process; no admin page carries one.
113    *
114    * @param prefix The path the three resources are mounted under: <js>""</js> when they are children of the root
115    *    resource, otherwise a path such as <js>"/admin"</js>: one or more {@code /}-separated segments of letters,
116    *    digits, {@code .}, {@code _}, {@code ~} or {@code -}, none starting with {@code .}, and no trailing {@code /}.
117    *    A prefix the container would not match as written is refused, so the resources are never left uncovered.
118    *    Must not be <jk>null</jk>.
119    * @param allowedHosts The host names this server is reached under, without ports.  A request to the admin
120    *    resources under any other {@code Host} is refused with {@code 421}, reads included: this is the DNS-rebinding
121    *    defence a server on plain HTTP needs.  With none, {@link #LOOPBACK_HOSTS} applies.  The list replaces the
122    *    loopback names rather than adding to them.  Must not be <jk>null</jk>, and no entry may be <jk>null</jk> or
123    *    blank.
124    * @return A new registration.
125    * @throws IllegalArgumentException If {@code prefix} is malformed, or {@code allowedHosts} or an entry is
126    *    <jk>null</jk>, blank or not a bare host name.
127    */
128   public static ServletFilterRegistration registration(String prefix, String...allowedHosts) {
129      if (prefix == null || ! PREFIX.matcher(prefix).matches())
130         throw iaex("Argument 'prefix' must be empty or a path such as '/admin': '/'-separated segments of letters, "
131            + "digits, '.', '_', '~' or '-', none starting with '.'.");
132      if (allowedHosts == null)
133         throw iaex("Argument 'allowedHosts' must not be null.");
134      var boundary = CsrfBoundary.create()
135         .tokens(CsrfTokens.perProcess())
136         .allowedHosts(allowedHosts.length == 0 ? LOOPBACK_HOSTS.toArray(String[]::new) : allowedHosts)
137         .build();
138      var patterns = new ArrayList<String>();
139      for (var p : PATHS) {
140         patterns.add(prefix + p);
141         patterns.add(prefix + p + "/*");
142      }
143      return ServletFilterRegistration.create(new RequestBoundaryFilter(boundary))
144         .urlPatterns(patterns.toArray(String[]::new))
145         .dispatcherTypes(DispatcherType.REQUEST)
146         .order(ORDER)
147         .build();
148   }
149}