public class AuthenticationFilter implements Filter {

    private static final transient Logger LOG = LoggerFactory.getLogger(AuthenticationFilter.class);

    private int timeout;
    private AuthenticationConfiguration authConfiguration;

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        authConfiguration = AuthenticationConfiguration.getConfiguration(filterConfig.getServletContext());
        timeout = AuthSessionHelpers.getSessionTimeout(filterConfig.getServletContext());
    }

    @Override
    public void doFilter(final ServletRequest request, final ServletResponse response, final FilterChain chain) throws IOException, ServletException {
        LOG.trace("Applying {}", getClass().getSimpleName());

        HttpServletRequest httpRequest = (HttpServletRequest) request;
        String path = httpRequest.getServletPath();

        LOG.debug("Handling request for path {}", path);

        if (authConfiguration.getRealm() == null || authConfiguration.getRealm().equals("") || !authConfiguration.isEnabled()) {
            LOG.debug("No authentication needed for path {}", path);
            chain.doFilter(request, response);
            return;
        }

        HttpSession session = httpRequest.getSession(false);
        if (session != null) {
            Subject subject = (Subject) session.getAttribute("subject");

            // For Spring Security
            if (AuthSessionHelpers.isSpringSecurityEnabled()) {
                if (subject == null && httpRequest.getRemoteUser() != null) {
                    AuthSessionHelpers.setup(
                        session, new Subject(), httpRequest.getRemoteUser(), timeout);
                }
                chain.doFilter(request, response);
                return;
            }

            // Connecting from another Hawtio may have a different user authentication, so
            // let's check if the session user is the same as in the authorization header here
            if (AuthSessionHelpers.validate(httpRequest, session, subject)) {
                executeAs(request, response, chain, subject);
                return;
            }
        }

        LOG.debug("Doing authentication and authorization for path {}", path);

        AuthenticateResult result = new Authenticator(httpRequest, authConfiguration).authenticate(
            subject -> executeAs(request, response, chain, subject));

        HttpServletResponse httpResponse = (HttpServletResponse) response;
        switch (result) {
        case AUTHORIZED:
            // request was executed using the authenticated subject, nothing more to do
            break;
        case NOT_AUTHORIZED:
            ServletHelpers.doForbidden(httpResponse);
            break;
        case NO_CREDENTIALS:
            if (authConfiguration.isNoCredentials401()) {
                // return auth prompt 401
                ServletHelpers.doAuthPrompt(authConfiguration.getRealm(), httpResponse);
            } else {
                // return forbidden 403 so the browser login does not popup
                ServletHelpers.doForbidden(httpResponse);
            }
            break;
        }
    }

    private static void executeAs(final ServletRequest request, final ServletResponse response, final FilterChain chain, Subject subject) {
        try {
            Subject.doAs(subject, (PrivilegedExceptionAction<Object>) () -> {
                chain.doFilter(request, response);
                return null;
            });
        } catch (PrivilegedActionException e) {
            LOG.info("Failed to invoke action " + ((HttpServletRequest) request).getPathInfo() + " due to:", e);
        }
    }

    @Override
    public void destroy() {
        LOG.info("Destroying hawtio authentication filter");
    }
} public class LoginRedirectFilter implements Filter {

    private static final transient Logger LOG = LoggerFactory.getLogger(LoginRedirectFilter.class);

    private int timeout;
    private AuthenticationConfiguration authConfiguration;

    private final String[] unsecuredPaths;

    private Redirector redirector = new Redirector();

    public LoginRedirectFilter() {
        this(AuthenticationConfiguration.UNSECURED_PATHS);
    }

    public LoginRedirectFilter(String[] unsecuredPaths) {
        this.unsecuredPaths = unsecuredPaths;
    }

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        authConfiguration = AuthenticationConfiguration.getConfiguration(filterConfig.getServletContext());
        timeout = AuthSessionHelpers.getSessionTimeout(filterConfig.getServletContext());
        LOG.info("Hawtio loginRedirectFilter is using {} sec. HttpSession timeout", timeout);
    }

    @Override
    public void doFilter(final ServletRequest request, final ServletResponse response, final FilterChain chain) throws IOException, ServletException {
        LOG.trace("Applying {}", getClass().getSimpleName());

        HttpServletRequest httpRequest = (HttpServletRequest) request;
        HttpServletResponse httpResponse = (HttpServletResponse) response;
        HttpSession session = httpRequest.getSession(false);
        String path = httpRequest.getServletPath();

        if (isRedirectRequired(session, path, httpRequest)) {
            redirector.doRedirect(httpRequest, httpResponse, AuthenticationConfiguration.LOGIN_URL);
        } else {
            chain.doFilter(request, response);
        }
    }

    private boolean isRedirectRequired(HttpSession session, String path, HttpServletRequest request) {
        return authConfiguration.isEnabled()
            && !authConfiguration.isKeycloakEnabled()
            && !AuthSessionHelpers.isSpringSecurityEnabled()
            && !AuthSessionHelpers.isAuthenticated(session)
            && isSecuredPath(path)
            && !tryAuthenticateRequest(request, session);
    }

    boolean tryAuthenticateRequest(HttpServletRequest request, HttpSession session) {
        AuthenticateResult result = new Authenticator(request, authConfiguration).authenticate(
           subject -> {
               String username = AuthHelpers.getUsername(subject);
               LOG.info("Logging in user: {}", username);
               AuthSessionHelpers.setup(session != null ? session :
                  request.getSession(true), subject, username, timeout);
           });

        return result == AuthenticateResult.AUTHORIZED;
    }

    boolean isSecuredPath(String path) {
        return !Arrays.stream(unsecuredPaths).anyMatch(path::startsWith);
    }

    @Override
    public void destroy() {
    }

    public void setRedirector(Redirector redirector) {
        this.redirector = redirector;
    }
} public class LoginServlet extends HttpServlet {

    private static final long serialVersionUID = 187076436862364207L;

    private static final transient Logger LOG = LoggerFactory.getLogger(LoginServlet.class);

    private int timeout;
    private AuthenticationConfiguration authConfiguration;

    private Converters converters = new Converters();
    private JsonConvertOptions options = JsonConvertOptions.DEFAULT;

    private Redirector redirector = new Redirector();

    @Override
    public void init() {
        authConfiguration = AuthenticationConfiguration.getConfiguration(getServletContext());
        timeout = AuthSessionHelpers.getSessionTimeout(getServletContext());
        LOG.info("Hawtio login is using {} sec. HttpSession timeout", timeout);
    }

    /**
     * GET simply returns login.html
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        if (authConfiguration.isKeycloakEnabled()) {
            redirector.doRedirect(request, response, "/");
        } else {
            redirector.doForward(request, response, "/login.html");
        }
    }

    /**
     * POST with username/password tries authentication and returns result as JSON
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException {
        AuthSessionHelpers.clear(request, authConfiguration, true);

        JSONObject json = ServletHelpers.readObject(request.getReader());
        String username = (String) json.get("username");
        String password = (String) json.get("password");

        AuthenticateResult result = new Authenticator(request, authConfiguration, username, password).authenticate(
            subject -> {
                LOG.info("Logging in user: {}", AuthHelpers.getUsername(subject));
                AuthSessionHelpers.setup(
                    request.getSession(true), subject, username, timeout);
                sendResponse(response, subject);
            });

        switch (result) {
        case AUTHORIZED:
            // response was sent using the authenticated subject, nothing more to do
            break;
        case NOT_AUTHORIZED:
        case NO_CREDENTIALS:
            ServletHelpers.doForbidden(response);
            break;
        }
    }

    private void sendResponse(HttpServletResponse response, Subject subject) {
        response.setContentType("application/json");
        try (PrintWriter out = response.getWriter()) {
            Map<String, Object> answer = new HashMap<>();

            List<Object> principals = new ArrayList<>();
            for (Principal principal : subject.getPrincipals()) {
                Map<String, String> data = new HashMap<>();
                data.put("type", principal.getClass().getName());
                data.put("name", principal.getName());
                principals.add(data);
            }

            List<Object> credentials = new ArrayList<>();
            for (Object credential : subject.getPublicCredentials()) {
                Map<String, Object> data = new HashMap<>();
                data.put("type", credential.getClass().getName());
                data.put("credential", credential);
                credentials.add(data);
            }

            answer.put("principals", principals);
            answer.put("credentials", credentials);

            ServletHelpers.writeObject(converters, options, out, answer);
        } catch (IOException e) {
            LOG.error("Failed to send response", e);
        }
    }

    public void setRedirector(Redirector redirector) {
        this.redirector = redirector;
    }
} public class LogoutServlet extends HttpServlet {

    private static final long serialVersionUID = -3504832582691232812L;

    private static final transient Logger LOG = LoggerFactory.getLogger(LogoutServlet.class);

    private AuthenticationConfiguration authConfiguration;

    private Redirector redirector = new Redirector();

    @Override
    public void init() {
        authConfiguration = AuthenticationConfiguration.getConfiguration(getServletContext());
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.logout();
        if (AuthSessionHelpers.isSpringSecurityEnabled()) {
            AuthSessionHelpers.clear(request, authConfiguration, false);
            redirector.doRedirect(request, response, "/");
        } else {
            AuthSessionHelpers.clear(request, authConfiguration, true);
            redirector.doRedirect(request, response, AuthenticationConfiguration.LOGIN_URL);
        }
    }

    public void setRedirector(Redirector redirector) {
        this.redirector = redirector;
    }
} public class Redirector {

    public static final String HAWTIO_REDIRECT_SCHEME = "hawtio.redirect.scheme";

    private String scheme;
    private String applicationContextPath = "";

    public Redirector() {
        scheme = System.getProperty(HAWTIO_REDIRECT_SCHEME);
    }

    public void doRedirect(HttpServletRequest request, HttpServletResponse response, String path) throws IOException {
        String redirectUrl = "";

        if (scheme == null) {
            scheme = request.getServletContext().getInitParameter("scheme");
        }
        if (scheme != null) {
            redirectUrl = scheme + "://" + request.getServerName() + ":" + request.getServerPort();
        }

        redirectUrl += request.getContextPath() + applicationContextPath + path;

        response.sendRedirect(redirectUrl);
    }

    public void doForward(HttpServletRequest request, HttpServletResponse response, String path) throws ServletException, IOException {
        request.getRequestDispatcher(applicationContextPath + path).forward(request, response);
    }

    public void setApplicationContextPath(String applicationContextPath) {
        this.applicationContextPath = applicationContextPath;
    }
} public class SessionExpiryFilter implements Filter {

    private static final transient Logger LOG = LoggerFactory.getLogger(SessionExpiryFilter.class);

    public static final String ATTRIBUTE_LAST_ACCESS = "LastAccess";

    private static final List<String> IGNORED_PATHS = Collections.unmodifiableList(Arrays.asList("jolokia", "proxy"));

    private ServletContext context;
    private AuthenticationConfiguration authConfiguration;
    private int pathIndex;

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        context = filterConfig.getServletContext();
        authConfiguration = AuthenticationConfiguration.getConfiguration(context);

        String servletPath = (String) filterConfig.getServletContext().getAttribute(HawtioProperty.SERVLET_PATH);
        if (servletPath == null) {
            this.pathIndex = 0; // assume hawtio is served from root
        } else {
            this.pathIndex = Strings.webContextPath(servletPath).replaceAll("[^/]+", "").length();
        }
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        LOG.trace("Applying {}", getClass().getSimpleName());

        if (servletRequest instanceof HttpServletRequest
            && servletResponse instanceof HttpServletResponse) {
            process((HttpServletRequest) servletRequest, (HttpServletResponse) servletResponse, filterChain);
        } else {
            filterChain.doFilter(servletRequest, servletResponse);
        }
    }

    private void writeOk(HttpServletResponse response) throws IOException, ServletException {
        response.setContentType("text/html;charset=UTF-8");
        try (OutputStream out = response.getOutputStream()) {
            out.write("ok".getBytes());
            out.flush();
        }
    }

    private void updateLastAccess(HttpSession session, long now) {
        session.setAttribute(ATTRIBUTE_LAST_ACCESS, now);
        LOG.debug("Reset LastAccess to: {}", now);
    }

    private void process(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException {
        if (context.getAttribute(AuthenticationConfiguration.AUTHENTICATION_ENABLED) == null) {
            // most likely the authentication filter hasn't been started up yet, let this request through and it can be dealt with by the authentication filter
            chain.doFilter(request, response);
            return;
        }

        HttpSession session = request.getSession(false);
        boolean enabled = (boolean) context.getAttribute(AuthenticationConfiguration.AUTHENTICATION_ENABLED);
        final RelativeRequestUri uri = new RelativeRequestUri(request, pathIndex);
        LOG.debug("Accessing [{}], hawtio path is [{}]", request.getRequestURI(), uri.getUri());

        // pass along if it's the top-level context
        if (uri.getComponents().length == 0) {
            if (session != null) {
                long now = System.currentTimeMillis();
                updateLastAccess(session, now);
            }
            chain.doFilter(request, response);
            return;
        }

        String subContext = uri.getComponents()[0];
        if (session == null || session.getMaxInactiveInterval() < 0) {
            if (subContext.equals("refresh") && !enabled) {
                LOG.debug("Authentication disabled, received refresh response, responding with ok");
                writeOk(response);
            } else {
                chain.doFilter(request, response);
                /*
                if (!enabled) {
                    LOG.debug("Authentication disabled, allowing request");
                    chain.doFilter(request, response);
                } else if (request.getHeader(Authenticator.HEADER_AUTHORIZATION) != null) {
                    // there's no session, but we have request with authentication attempt
                    // let's pass it further the filter chain - if authentication will fail, user will get 403 anyway
                    chain.doFilter(request, response);
                } else {
                    if (noCredentials401 && subContext.equals("jolokia")) {
                        LOG.debug("Authentication enabled, noCredentials401 is true, allowing request for {}",
                            subContext);
                        chain.doFilter(request, response);
                    } else if (subContext.equals("jolokia") ||
                        subContext.equals("proxy") ||
                        subContext.equals("user") ||
                        subContext.equals("exportContext") ||
                        subContext.equals("contextFormatter") ||
                        subContext.equals("upload")) {
                        LOG.debug("Authentication enabled, denying request for {}", subContext);
                        ServletHelpers.doForbidden(response);
                    } else {
                        LOG.debug("Authentication enabled, but allowing request for {}", subContext);
                        chain.doFilter(request, response);
                    }
                }
                */
            }
            return;
        }

        int maxInactiveInterval = session.getMaxInactiveInterval();
        long now = System.currentTimeMillis();
        if (session.getAttribute(ATTRIBUTE_LAST_ACCESS) != null) {
            long lastAccess = (long) session.getAttribute(ATTRIBUTE_LAST_ACCESS);
            long remainder = (now - lastAccess) / 1000;
            LOG.debug("Session expiry: {}s, duration since last access: {}s", maxInactiveInterval, remainder);
            if (remainder > maxInactiveInterval) {
                LOG.info("Expiring session due to inactivity");
                session.invalidate();
                ServletHelpers.doForbidden(response);
                return;
            }
        }

        if (subContext.equals("refresh")) {
            updateLastAccess(session, now);
            writeOk(response);
            return;
        }

        LOG.debug("SubContext: {}", subContext);
        if (IGNORED_PATHS.contains(subContext) && session.getAttribute(ATTRIBUTE_LAST_ACCESS) != null) {
            LOG.debug("Not updating LastAccess");
        } else {
            updateLastAccess(session, now);
        }

        chain.doFilter(request, response);
    }

    @Override
    public void destroy() {
        // noop
    }
} public class KeycloakUserServlet extends UserServlet {

    private static final long serialVersionUID = 1734127369954899957L;

    private AuthenticationConfiguration authConfiguration;
    private boolean keycloakEnabled;

    @Override
    public void init() throws ServletException {
        super.init();
        authConfiguration = AuthenticationConfiguration.getConfiguration(getServletContext());
        keycloakEnabled = authConfiguration.isKeycloakEnabled();
    }

    @Override
    protected String getUsername(HttpServletRequest req, HttpServletResponse resp) {
        if (keycloakEnabled) {
            return getKeycloakUsername(req, resp);
        } else {
            return super.getUsername(req, resp);
        }
    }

    /**
     * With Keycloak integration, the Authorization header is available in the request to the UserServlet.
     */
    protected String getKeycloakUsername(final HttpServletRequest req, HttpServletResponse resp) {
        AtomicReference<String> username = new AtomicReference<>();
        new Authenticator(req, authConfiguration).authenticate(
            subject -> {
                username.set(AuthHelpers.getUsername(subject));

                // Start httpSession
                req.getSession(true);
            }
        );
        return username.get();
    }

} public class CORSFilter extends HttpHeaderFilter {

    @Override
    protected void addHeaders(HttpServletRequest request, HttpServletResponse response) {
        if (!allowAny()) {
            return;
        }
        if ("OPTIONS".equals(request.getMethod())) {
            response.addHeader("Access-Control-Request-Method", "GET, POST, PUT, DELETE");
            String headers = request.getHeader("Access-Control-Request-Headers");
            if (headers != null) {
                response.addHeader("Access-Control-Allow-Headers", headers);
            }
            response.addHeader("Access-Control-Max-Age", "" + TimeUnit.DAYS.toSeconds(1));
        }
        response.addHeader("Access-Control-Allow-Origin", "*");
    }

    protected boolean allowAny() {
        // TODO allow configuration...
        return true;
    }
} public class ContentSecurityPolicyFilter extends HttpHeaderFilter {

    private static final transient Logger LOG = LoggerFactory.getLogger(ContentSecurityPolicyFilter.class);

    private static String POLICY = "";
    private static final String POLICY_TEMPLATE =
        "default-src 'self'; " +
        "script-src 'self' 'unsafe-inline' 'unsafe-eval' %s; " +
        "style-src 'self' 'unsafe-inline'; " +
        "font-src 'self' data:; " +
        "img-src 'self' data:; " +
        "connect-src 'self' %s; " +
        "frame-src 'self' %s";

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        super.init(filterConfig);

        String keycloakConfigFile = getConfigParameter(KeycloakServlet.KEYCLOAK_CLIENT_CONFIG);
        if (System.getProperty(KeycloakServlet.HAWTIO_KEYCLOAK_CLIENT_CONFIG) != null) {
            keycloakConfigFile = System.getProperty(KeycloakServlet.HAWTIO_KEYCLOAK_CLIENT_CONFIG);
        }

        boolean addedKeycloakUrl = false;
        if (keycloakConfigFile != null && !keycloakConfigFile.trim().equals("")) {
            try (InputStream is = ServletHelpers.loadFile(keycloakConfigFile);
                BufferedReader reader = new BufferedReader(new InputStreamReader(is))) {
                JSONObject json = ServletHelpers.readObject(reader);
                String url = (String) json.get("url");
                URI uri = URI.create(url);
                LOG.info("Found Keycloak URL: {}", uri);
                String cspSrc = uri.getScheme() + "://" + uri.getHost();
                if (uri.getPort() >= 0) {
                    cspSrc += ":" + uri.getPort();
                }
                POLICY = String.format(POLICY_TEMPLATE, cspSrc, cspSrc, cspSrc);
                addedKeycloakUrl = true;
            } catch (IOException e) {
                LOG.error("Can't read keycloak configuration file", e);
            }
        }
        if (!addedKeycloakUrl) {
            POLICY = String.format(POLICY_TEMPLATE, "", "", "");
        }
    }

    @Override
    protected void addHeaders(HttpServletRequest request, HttpServletResponse response) {
        response.addHeader("Content-Security-Policy", POLICY);
    }
} public class FlightRecordingDownloadFacade implements Filter {

    private static final Pattern recordingPattern=Pattern.compile(".*exec/jdk.management.jfr:type=FlightRecorder/(downloadRecording\\(long\\)/)(\\d+).*");

    /**
     * Return whether the request might be for downloading a flight recording
     */
    private static boolean isFlightRecordingRequest(ServletRequest request){
        if( request instanceof HttpServletRequest) {
            HttpServletRequest req= (HttpServletRequest) request;
            if(!req.getMethod().equalsIgnoreCase("GET")) {
                return false;
            }
            return recordingPattern.matcher(req.getRequestURI()).find();
        }
        return false;
    }

    @Override
    public void init(FilterConfig filterConfig) {

    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response,
        FilterChain chain) throws IOException, ServletException {
        if(isFlightRecordingRequest(request)){
            downloadFlightRecording(request, response, chain);
        } else {
            chain.doFilter(request, response);
        }
    }

    private void downloadFlightRecording(ServletRequest request, ServletResponse response,
        FilterChain chain) throws IOException, ServletException {
        HttpServletRequest req=(HttpServletRequest)request;

        Matcher matcher = recordingPattern.matcher(req.getRequestURI());

        if(!matcher.find()){
            throw new ServletException("Unable to find flightrecorder information in URL " + req.getRequestURI());
        }

        String recordingNumber=matcher.group(2);
        String replacementPattern=matcher.group(1)+recordingNumber;

        //STEP 1: Open stream
        final long stream = openStream((HttpServletResponse) response, chain, req, recordingNumber, replacementPattern);

        ((HttpServletResponse) response).setHeader("Content-Disposition", "attachment; filename=\"recording" + recordingNumber + ".jfr\"");

        //Would expect all kinds of buffering in the stack, but writes were proven slow in some tests so buffer
        //just to be sure
        OutputStream destination=new BufferedOutputStream(response.getOutputStream());
        //STEP 2: Read stream until empty
        //noinspection StatementWithEmptyBody
        while(readData((HttpServletResponse) response, chain, req, replacementPattern, stream, destination)) {
        }

        try {
            //STEP 3: Close stream (best effort)
            chain.doFilter(new StandinRequest(req, replacementPattern, "closeStream(long)/"+stream), new DerivedResponse((HttpServletResponse) response));

        }catch (Exception ignore) {
        }


    }

    @SuppressWarnings("unchecked")
    private boolean readData(HttpServletResponse response, FilterChain chain, HttpServletRequest req,
        String replacementPattern, long stream, OutputStream destination) throws IOException, ServletException {
        DerivedResponse readResponse = new DerivedResponse(response);
        chain.doFilter(new StandinRequest(req, replacementPattern, "readStream(long)/"+ stream), readResponse);
        Object data=readResponse.interpretResponse();
        if(data==null){
            destination.flush();
            return false;
        }
        if(!(data instanceof JSONArray)) {
            throw new ServletException("Response did not contain expected data");
        }
        for (Number number:(Collection<Number>)data
        ) {
            destination.write(number.byteValue());
        }
        return true;
    }

    private long openStream(HttpServletResponse response, FilterChain chain, HttpServletRequest req,
        String recordingNumber, String replacementPattern) throws IOException, ServletException {
        DerivedResponse openResponse = new DerivedResponse(response);
        chain.doFilter(new StandinRequest(req,
            replacementPattern, "openStream(long,javax.management.openmbean.TabularData)/"+ recordingNumber
            +"/" + emptyMapArgument(req)), openResponse);
        Object streamRef = openResponse.interpretResponse();
        if(!(streamRef instanceof Number)) {
            throw new ServletException("Response did not contain stream reference");
        }
        return ((Number)streamRef).longValue();
    }

    private String emptyMapArgument(HttpServletRequest req) {
        //since proxy URLs must be valid, encode these characters
        //but for local jolokia use as is
        String emptyMap="{}";
        if("/proxy".equals(req.getServletPath())) {
            emptyMap="%7B%7D";
        }
        return emptyMap;
    }

    @Override
    public void destroy() {

    }

    static class StandinRequest extends HttpServletRequestWrapper {

        private final String replaceFrom;
        private final String replaceTo;

        /**
         * Constructs a request object wrapping the given request.
         */
        public StandinRequest(HttpServletRequest request, final String replaceFrom, final String replaceTo) {
            super(request);
            this.replaceFrom=replaceFrom;
            this.replaceTo=replaceTo;
        }

        private String replaceInPath(String servletPath) {
            return servletPath.replace(this.replaceFrom, this.replaceTo);
        }

        @Override
        public StringBuffer getRequestURL() {
            return new StringBuffer(replaceInPath(super.getRequestURL().toString()));
        }

        @Override
        public String getRequestURI() {
            return replaceInPath(super.getRequestURI());
        }

        @SuppressWarnings("deprecation")
        @Override
        public String getRealPath(String path) {
            return replaceInPath(super.getRealPath(path));
        }

        @Override
        public String getPathInfo() {
            return replaceInPath(super.getPathInfo());
        }

        //Prevent modification of the request
        @Override
        public void setAttribute(String name, Object o) {
        }

    }

    static class DerivedResponse extends HttpServletResponseWrapper {

        private final RecordingOutputStream output=new RecordingOutputStream();
        private int status;
        private String characterEncoding;

        public DerivedResponse(HttpServletResponse response) {
            super(response);
        }

        @Override
        public ServletOutputStream getOutputStream() {
            return this.output;
        }

        @Override
        public void setStatus(int sc) {
            this.status=sc;
        }

        @Override
        public void setBufferSize(int size) {
        }

        @Override
        public void setCharacterEncoding(String charset) {
            this.characterEncoding=charset;
        }

        //ignore these
        @Override
        public void setContentLength(int len) {
        }

        @Override
        public void setContentType(String type) {
        }

        Object interpretResponse() throws IOException {
            if(this.status / 100 > 2) {
                throw new IOException("Invalid response code " + this.status + " response: " + new String(this.output.getBytes()));
            }

            final ByteArrayInputStream bytes = new ByteArrayInputStream(this.output.getBytes());
            Reader reader;
            if(this.characterEncoding!=null) {
                reader=new InputStreamReader(bytes, this.characterEncoding);
            } else {
                reader=new InputStreamReader(bytes);
            }
            final JSONObject response;
            try {
                response = (JSONObject) new JSONParser()
                    .parse(reader);
                if(!(response.get("status") instanceof Number) || ((Number)response.get("status")).intValue() != 200) {
                    throw new IOException("Invalid jolokia response code " + response.get("status") + " response: " + new String(this.output.getBytes()));
                }
                return response.get("value");
            } catch (ParseException e) {
                throw new IOException("Unable to parse JSON response");
            }

        }
    }

    static class RecordingOutputStream extends ServletOutputStream {

        private final ByteArrayOutputStream recorder;

        RecordingOutputStream() {
            this.recorder=new ByteArrayOutputStream();
        }

        @Override
        public boolean isReady() {
            return true;
        }

        @Override
        public void setWriteListener(WriteListener writeListener) {
        }

        @Override
        public void write(int b) {
            this.recorder.write(b);
        }

        byte[] getBytes() {
            return this.recorder.toByteArray();
        }
    }

} public class XXSSProtectionFilter extends HttpHeaderFilter {

    @Override
    protected void addHeaders(HttpServletRequest request, HttpServletResponse response) {
        response.addHeader("X-XSS-Protection", "1");
    }
} public class ProxyServlet extends HttpServlet {

    private static final long serialVersionUID = 7792226114533360114L;

    private static final transient Logger LOG = LoggerFactory.getLogger(ProxyServlet.class);

    /* INIT PARAMETER NAME CONSTANTS */

    /**
     * A boolean parameter name to enable logging of input and target URLs to the servlet log.
     *
     * @deprecated Use SLF4J {@link Logger}
     */
    @Deprecated
    public static final String P_LOG = "log";

    /**
     * A boolean parameter name to enable forwarding of the client IP
     */
    public static final String P_FORWARDEDFOR = "forwardip";

    /**
     * Whether we accept self-signed SSL certificates
     */
    private static final String PROXY_ACCEPT_SELF_SIGNED_CERTS = "hawtio.proxyDisableCertificateValidation";
    private static final String PROXY_ACCEPT_SELF_SIGNED_CERTS_ENV = "PROXY_DISABLE_CERT_VALIDATION";

    public static final String PROXY_ALLOWLIST = "proxyAllowlist";
    public static final String LOCAL_ADDRESS_PROBING = "localAddressProbing";
    public static final String DISABLE_PROXY = "disableProxy";

    public static final String HAWTIO_PROXY_ALLOWLIST = "hawtio." + PROXY_ALLOWLIST;
    public static final String HAWTIO_LOCAL_ADDRESS_PROBING = "hawtio." + LOCAL_ADDRESS_PROBING;
    public static final String HAWTIO_DISABLE_PROXY = "hawtio." + DISABLE_PROXY;

    /* MISC */

    protected boolean enabled = true;

    protected boolean doLog = false;
    protected boolean doForwardIP = true;
    protected boolean acceptSelfSignedCerts = false;

    protected ProxyAllowlist allowlist;

    protected CloseableHttpClient proxyClient;
    private CookieStore cookieStore;

    @Override
    public String getServletInfo() {
        return "A proxy servlet by David Smiley, dsmiley@mitre.org";
    }

    @Override
    public void init(ServletConfig servletConfig) throws ServletException {
        super.init(servletConfig);

        ConfigManager config = (ConfigManager) getServletContext().getAttribute(ConfigManager.CONFIG_MANAGER);

        enabled = !config.getBoolean(DISABLE_PROXY, false);
        if (!enabled) {
            LOG.info("Proxy servlet is disabled");
            // proxy servlet is disabled so won't run any further initialisation
            return;
        }

        String allowlistStr = config.get(PROXY_ALLOWLIST, servletConfig.getInitParameter(PROXY_ALLOWLIST));
        boolean probeLocal = config.getBoolean(LOCAL_ADDRESS_PROBING, true);
        allowlist = new ProxyAllowlist(allowlistStr, probeLocal);

        String doForwardIPString = servletConfig.getInitParameter(P_FORWARDEDFOR);
        if (doForwardIPString != null) {
            this.doForwardIP = Boolean.parseBoolean(doForwardIPString);
        }

        String doLogStr = servletConfig.getInitParameter(P_LOG);
        if (doLogStr != null) {
            this.doLog = Boolean.parseBoolean(doLogStr);
        }

        cookieStore = new BasicCookieStore();
        HttpClientBuilder httpClientBuilder = HttpClients.custom()
            .setDefaultCookieStore(cookieStore)
            .useSystemProperties();

        if (System.getProperty(PROXY_ACCEPT_SELF_SIGNED_CERTS) != null) {
            acceptSelfSignedCerts = Boolean.parseBoolean(System.getProperty(PROXY_ACCEPT_SELF_SIGNED_CERTS));
        } else if (System.getenv(PROXY_ACCEPT_SELF_SIGNED_CERTS_ENV) != null) {
            acceptSelfSignedCerts = Boolean.parseBoolean(System.getenv(PROXY_ACCEPT_SELF_SIGNED_CERTS_ENV));
        }

        if (acceptSelfSignedCerts) {
            try {
                SSLContextBuilder builder = new SSLContextBuilder();
                builder.loadTrustMaterial(null, (X509Certificate[] x509Certificates, String s) -> true);
                SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(
                    builder.build(), SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
                httpClientBuilder.setSSLSocketFactory(sslsf);
            } catch (NoSuchAlgorithmException e) {
                throw new ServletException(e);
            } catch (KeyStoreException e) {
                throw new ServletException(e);
            } catch (KeyManagementException e) {
                throw new ServletException(e);
            }
        }

        proxyClient = httpClientBuilder.build();
    }

    @Override
    public void destroy() {
        try {
            if (proxyClient != null) {
                proxyClient.close();
            }
        } catch (IOException e) {
            log("While destroying servlet, shutting down httpclient: " + e, e);
            LOG.error("While destroying servlet, shutting down httpclient: " + e, e);
        }
        super.destroy();
    }

    @Override
    protected void service(HttpServletRequest servletRequest, HttpServletResponse servletResponse)
        throws ServletException, IOException {
        // returns if enabled or not so that Connect plugin can turn on/off itself
        if ("/enabled".equals(servletRequest.getPathInfo())) {
            ServletHelpers.sendJSONResponse(servletResponse, enabled);
            return;
        }

        if (!enabled) {
            servletResponse.setStatus(HttpServletResponse.SC_NOT_FOUND);
            return;
        }

        // Make the Request
        //note: we won't transfer the protocol version because I'm not sure it would truly be compatible
        ProxyAddress proxyAddress = parseProxyAddress(servletRequest);
        if (proxyAddress == null || proxyAddress.getFullProxyUrl() == null) {
            servletResponse.setStatus(HttpServletResponse.SC_NOT_FOUND);
            return;
        }
        // TODO Implement allowlist protection for Kubernetes services as well
        if (proxyAddress instanceof ProxyDetails) {
            ProxyDetails details = (ProxyDetails) proxyAddress;
            if (!allowlist.isAllowed(details)) {
                LOG.debug("Rejecting {}", proxyAddress);
                ServletHelpers.doForbidden(servletResponse, ForbiddenReason.HOST_NOT_ALLOWED);
                return;
            }
        }

        String method = servletRequest.getMethod();
        String proxyRequestUri = proxyAddress.getFullProxyUrl();

        URI targetUriObj;
        try {
            targetUriObj = new URI(proxyRequestUri);
        } catch (URISyntaxException e) {
            LOG.error("URL '{}' is not valid: {}", proxyRequestUri, e.getMessage());
            servletResponse.setStatus(HttpServletResponse.SC_NOT_FOUND);
            return;
        }

        HttpRequest proxyRequest;
        //spec: RFC 2616, sec 4.3: either of these two headers signal that there is a message body.
        if (servletRequest.getHeader(HttpHeaders.CONTENT_LENGTH) != null ||
            servletRequest.getHeader(HttpHeaders.TRANSFER_ENCODING) != null) {
            HttpEntityEnclosingRequest eProxyRequest = new BasicHttpEntityEnclosingRequest(method, proxyRequestUri);
            // Add the input entity (streamed)
            //  note: we don't bother ensuring we close the servletInputStream since the container handles it
            eProxyRequest.setEntity(new InputStreamEntity(servletRequest.getInputStream(), servletRequest.getContentLength()));
            proxyRequest = eProxyRequest;
        } else {
            proxyRequest = new BasicHttpRequest(method, proxyRequestUri);
        }

        copyRequestHeaders(servletRequest, proxyRequest, targetUriObj);

        String username = proxyAddress.getUserName();
        String password = proxyAddress.getPassword();

        if (Strings.isNotBlank(username) && Strings.isNotBlank(password)) {
            String encodedCreds = Base64.encodeBase64String((username + ":" + password).getBytes());
            proxyRequest.setHeader("Authorization", "Basic " + encodedCreds);
        }

        Header proxyAuthHeader = proxyRequest.getFirstHeader("Authorization");
        if (proxyAuthHeader != null) {
            String proxyAuth = proxyAuthHeader.getValue();
            // if remote jolokia credentials have changed, we have to clear session cookies in http-client
            HttpSession session = servletRequest.getSession();
            if (session != null) {
                String previousProxyCredentials = (String) session.getAttribute("proxy-credentials");
                if (previousProxyCredentials != null && !previousProxyCredentials.equals(proxyAuth)) {
                    cookieStore.clear();
                }
                session.setAttribute("proxy-credentials", proxyAuth);
            }
        }

        setXForwardedForHeader(servletRequest, proxyRequest);

        CloseableHttpResponse proxyResponse = null;
        int statusCode = 0;
        try {

            // Execute the request
            if (doLog) {
                log("proxy " + method + " uri: " + servletRequest.getRequestURI() + " -- " + proxyRequest.getRequestLine().getUri());
            }
            LOG.debug("proxy {} uri: {} -- {}", method, servletRequest.getRequestURI(), proxyRequest.getRequestLine().getUri());
            proxyResponse = proxyClient.execute(URIUtils.extractHost(targetUriObj), proxyRequest);

            // Process the response
            statusCode = proxyResponse.getStatusLine().getStatusCode();

            if (statusCode == 401 || statusCode == 403) {
                if (doLog) {
                    log("Authentication Failed on remote server " + proxyRequestUri);
                }
                LOG.debug("Authentication Failed on remote server {}", proxyRequestUri);
            } else if (doResponseRedirectOrNotModifiedLogic(servletRequest, servletResponse, proxyResponse, statusCode, targetUriObj)) {
                //the response is already "committed" now without any body to send
                //TODO copy response headers?
                return;
            }

            // Pass the response code. This method with the "reason phrase" is deprecated but it's the only way to pass the
            //  reason along too.
            //noinspection deprecation
            servletResponse.setStatus(statusCode, proxyResponse.getStatusLine().getReasonPhrase());

            copyResponseHeaders(proxyResponse, servletResponse);

            // Send the content to the client
            copyResponseEntity(proxyResponse, servletResponse);

        } catch (Exception e) {
            //abort request, according to best practice with HttpClient
            if (proxyRequest instanceof AbortableHttpRequest) {
                AbortableHttpRequest abortableHttpRequest = (AbortableHttpRequest) proxyRequest;
                abortableHttpRequest.abort();
            }
            // Exception needs to be suppressed for security reason
            LOG.debug("Proxy to " + proxyRequestUri + " failed", e);
            if (e instanceof ConnectException || e instanceof UnknownHostException) {
                // Target host refused connection or doesn't exist
                servletResponse.setStatus(HttpServletResponse.SC_NOT_FOUND);
            } else if (e instanceof ServletException) {
                // Redirect / Not Modified failed
                servletResponse.sendError(HttpServletResponse.SC_BAD_GATEWAY, e.getMessage());
            } else if (e instanceof SecurityException) {
                servletResponse.setHeader("WWW-Authenticate", "Basic");
                servletResponse.sendError(statusCode, e.getMessage());
            } else {
                servletResponse.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage());
            }

        } finally {
            if (proxyResponse != null) {
                // Make sure the entire entity was consumed
                EntityUtils.consumeQuietly(proxyResponse.getEntity());

                try {
                    proxyResponse.close();
                } catch (IOException e) {
                    LOG.error("Error closing proxy client response: {}", e.getMessage());
                }
            }
            //Note: Don't need to close servlet outputStream:
            // http://stackoverflow.com/questions/1159168/should-one-call-close-on-httpservletresponse-getoutputstream-getwriter
        }
    }

    protected ProxyAddress parseProxyAddress(HttpServletRequest servletRequest) {
        return new ProxyDetails(servletRequest);
    }

    protected boolean doResponseRedirectOrNotModifiedLogic(
        HttpServletRequest servletRequest, HttpServletResponse servletResponse,
        HttpResponse proxyResponse, int statusCode, URI targetUriObj)
        throws ServletException, IOException {
        // Check if the proxy response is a redirect
        // The following code is adapted from org.tigris.noodle.filters.CheckForRedirect
        if (statusCode >= HttpServletResponse.SC_MULTIPLE_CHOICES /* 300 */
            && statusCode < HttpServletResponse.SC_NOT_MODIFIED /* 304 */) {
            Header locationHeader = proxyResponse.getLastHeader(HttpHeaders.LOCATION);
            if (locationHeader == null) {
                throw new ServletException("Received status code: " + statusCode
                    + " but no " + HttpHeaders.LOCATION + " header was found in the response");
            }
            // Modify the redirect to go to this proxy servlet rather that the proxied host
            String locStr = rewriteUrlFromResponse(servletRequest, locationHeader.getValue(), targetUriObj.toString());

            servletResponse.sendRedirect(locStr);
            return true;
        }
        // 304 needs special handling.  See:
        // http://www.ics.uci.edu/pub/ietf/http/rfc1945.html#Code304
        // We get a 304 whenever passed an 'If-Modified-Since'
        // header and the data on disk has not changed; server
        // responds w/ a 304 saying I'm not going to send the
        // body because the file has not changed.
        if (statusCode == HttpServletResponse.SC_NOT_MODIFIED) {
            servletResponse.setIntHeader(HttpHeaders.CONTENT_LENGTH, 0);
            servletResponse.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
            return true;
        }
        return false;
    }

    /**
     * These are the "hop-by-hop" headers that should not be copied.
     * http://www.w3.org/Protocols/rfc2616/rfc2616-sec13.html
     * I use an HttpClient HeaderGroup class instead of Set<String> because this
     * approach does case insensitive lookup faster.
     */
    protected static final HeaderGroup hopByHopHeaders;

    static {
        hopByHopHeaders = new HeaderGroup();
        String[] headers = new String[] {
            "Connection", "Keep-Alive", "Proxy-Authenticate", "Proxy-Authorization",
            "TE", "Trailers", "Transfer-Encoding", "Upgrade", "Cookie", "Set-Cookie" };
        for (String header : headers) {
            hopByHopHeaders.addHeader(new BasicHeader(header, null));
        }
    }

    /**
     * Copy request headers from the servlet client to the proxy request.
     */
    protected void copyRequestHeaders(HttpServletRequest servletRequest, HttpRequest proxyRequest, URI targetUriObj) {
        // Get an Enumeration of all of the header names sent by the client
        Enumeration enumerationOfHeaderNames = servletRequest.getHeaderNames();
        while (enumerationOfHeaderNames.hasMoreElements()) {
            String headerName = (String) enumerationOfHeaderNames.nextElement();
            //Instead the content-length is effectively set via InputStreamEntity
            if (headerName.equalsIgnoreCase(HttpHeaders.CONTENT_LENGTH))
                continue;
            if (hopByHopHeaders.containsHeader(headerName))
                continue;

            Enumeration headers = servletRequest.getHeaders(headerName);
            while (headers.hasMoreElements()) {//sometimes more than one value
                String headerValue = (String) headers.nextElement();
                // In case the proxy host is running multiple virtual servers,
                // rewrite the Host header to ensure that we get content from
                // the correct virtual server
                if (headerName.equalsIgnoreCase(HttpHeaders.HOST)) {
                    HttpHost host = URIUtils.extractHost(targetUriObj);
                    if (host != null) {
                        headerValue = host.getHostName();
                        if (headerValue != null && host.getPort() != -1) {
                            headerValue += ":" + host.getPort();
                        }
                    }
                }
                proxyRequest.addHeader(headerName, headerValue);
            }
        }
    }

    private void setXForwardedForHeader(HttpServletRequest servletRequest,
                                        HttpRequest proxyRequest) {
        String headerName = "X-Forwarded-For";
        if (doForwardIP) {
            String newHeader = servletRequest.getRemoteAddr();
            String existingHeader = servletRequest.getHeader(headerName);
            if (existingHeader != null) {
                newHeader = existingHeader + ", " + newHeader;
            }
            proxyRequest.setHeader(headerName, newHeader);
        }
    }

    /**
     * Copy proxied response headers back to the servlet client.
     */
    protected void copyResponseHeaders(HttpResponse proxyResponse, HttpServletResponse servletResponse) {
        for (Header header : proxyResponse.getAllHeaders()) {
            if (hopByHopHeaders.containsHeader(header.getName()))
                continue;
            servletResponse.addHeader(header.getName(), header.getValue());
        }
    }

    /**
     * Copy response body data (the entity) from the proxy to the servlet client.
     */
    protected void copyResponseEntity(HttpResponse proxyResponse, HttpServletResponse servletResponse) throws IOException {
        HttpEntity entity = proxyResponse.getEntity();
        if (entity != null) {
            OutputStream servletOutputStream = servletResponse.getOutputStream();
            entity.writeTo(servletOutputStream);
        }
    }

    /**
     * For a redirect response from the target server, this translates {@code theUrl} to redirect to
     * and translates it to one the original client can use.
     */
    protected String rewriteUrlFromResponse(HttpServletRequest servletRequest, String theUrl, String targetUri) {
        //TODO document example paths
        if (theUrl.startsWith(targetUri)) {
            String curUrl = servletRequest.getRequestURL().toString();//no query
            String pathInfo = servletRequest.getPathInfo();
            if (pathInfo != null) {
                assert curUrl.endsWith(pathInfo);
                curUrl = curUrl.substring(0, curUrl.length() - pathInfo.length());//take pathInfo off
            }
            theUrl = curUrl + theUrl.substring(targetUri.length());
        }
        return theUrl;
    }

    /**
     * Encodes characters in the query or fragment part of the URI.
     * <p/>
     * <p>Unfortunately, an incoming URI sometimes has characters disallowed by the spec.  HttpClient
     * insists that the outgoing proxied request has a valid URI because it uses Java's {@link URI}.
     * To be more forgiving, we must escape the problematic characters.  See the URI class for the
     * spec.
     *
     * @param in example: name=value&foo=bar#fragment
     */
    protected static CharSequence encodeUriQuery(CharSequence in) {
        //Note that I can't simply use URI.java to encode because it will escape pre-existing escaped things.
        StringBuilder outBuf = null;
        Formatter formatter = null;
        for (int i = 0; i < in.length(); i++) {
            char c = in.charAt(i);
            boolean escape = true;
            if (c < 128) {
                if (asciiQueryChars.get((int) c)) {
                    escape = false;
                }
            } else if (!Character.isISOControl(c) && !Character.isSpaceChar(c)) {//not-ascii
                escape = false;
            }
            if (!escape) {
                if (outBuf != null)
                    outBuf.append(c);
            } else {
                //escape
                if (outBuf == null) {
                    outBuf = new StringBuilder(in.length() + 5 * 3);
                    outBuf.append(in, 0, i);
                    formatter = new Formatter(outBuf);
                }
                //leading %, 0 padded, width 2, capital hex
                formatter.format("%%%02X", (int) c);//TODO
            }
        }
        return outBuf != null ? outBuf : in;
    }

    protected static final BitSet asciiQueryChars;

    static {
        char[] c_unreserved = "_-!.~'()*".toCharArray();//plus alphanum
        char[] c_punct = ",;:$&+=".toCharArray();
        char[] c_reserved = "?/[]@".toCharArray();//plus punct

        asciiQueryChars = new BitSet(128);
        for (char c = 'a'; c <= 'z'; c++) asciiQueryChars.set((int) c);
        for (char c = 'A'; c <= 'Z'; c++) asciiQueryChars.set((int) c);
        for (char c = '0'; c <= '9'; c++) asciiQueryChars.set((int) c);
        for (char c : c_unreserved) asciiQueryChars.set((int) c);
        for (char c : c_punct) asciiQueryChars.set((int) c);
        for (char c : c_reserved) asciiQueryChars.set((int) c);

        asciiQueryChars.set((int) '%');//leave existing percent escapes in place
    }

}
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import javax.servlet.DispatcherType;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import io.hawt.system.ConfigManager;
import io.hawt.web.auth.AuthenticationConfiguration;
import io.hawt.web.auth.AuthenticationFilter;
import io.hawt.web.auth.LoginRedirectFilter;
import io.hawt.web.auth.LoginServlet;
import io.hawt.web.auth.LogoutServlet;
import io.hawt.web.auth.Redirector;
import io.hawt.web.auth.SessionExpiryFilter;
import io.hawt.web.auth.keycloak.KeycloakServlet;
import io.hawt.web.auth.keycloak.KeycloakUserServlet;
import io.hawt.web.filters.BaseTagHrefFilter;
import io.hawt.web.filters.CORSFilter;
import io.hawt.web.filters.CacheHeadersFilter;
import io.hawt.web.filters.ContentSecurityPolicyFilter;
import io.hawt.web.filters.FlightRecordingDownloadFacade;
import io.hawt.web.filters.PublicKeyPinningFilter;
import io.hawt.web.filters.StrictTransportSecurityFilter;
import io.hawt.web.filters.XContentTypeOptionsFilter;
import io.hawt.web.filters.XFrameOptionsFilter;
import io.hawt.web.filters.XXSSProtectionFilter;
import io.hawt.web.proxy.ProxyServlet;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.actuate.autoconfigure.jolokia.JolokiaEndpoint;
import org.springframework.boot.actuate.autoconfigure.jolokia.JolokiaEndpointAutoConfiguration;
import org.springframework.boot.actuate.autoconfigure.web.ManagementContextConfiguration;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.boot.web.servlet.ServletContextInitializer;
import org.springframework.boot.web.servlet.ServletListenerRegistrationBean;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.core.Ordered;
import org.springframework.web.servlet.handler.SimpleUrlHandlerMapping;
import org.springframework.web.servlet.mvc.AbstractUrlViewController;
import static io.hawt.web.filters.BaseTagHrefFilter.PARAM_APPLICATION_CONTEXT_PATH;
        filter.setFilter(new CORSFilter());
        filter.addUrlPatterns(hawtioPath + "/*");
        return filter;
    }

    @Bean
    public FilterRegistrationBean xframeOptionsFilter() {
        final FilterRegistrationBean<XFrameOptionsFilter> filter = new FilterRegistrationBean<>();
        filter.setFilter(new XFrameOptionsFilter());
        filter.addUrlPatterns(hawtioPath + "/*");
        return filter;
    }

    @Bean
    public FilterRegistrationBean xxssProtectionFilter() {
        final FilterRegistrationBean<XXSSProtectionFilter> filter = new FilterRegistrationBean<>();
        filter.setFilter(new XXSSProtectionFilter());
        filter.addUrlPatterns(hawtioPath + "/*");
        return filter;
    }

    @Bean
    public FilterRegistrationBean xContentTypeOptionsFilter() {
        final FilterRegistrationBean<XContentTypeOptionsFilter> filter = new FilterRegistrationBean<>();
        filter.setFilter(new XContentTypeOptionsFilter());
        filter.addUrlPatterns(hawtioPath + "/*");
        return filter;
    }

    @Bean
    public FilterRegistrationBean contentSecurityPolicyFilter() {
        final FilterRegistrationBean<ContentSecurityPolicyFilter> filter = new FilterRegistrationBean<>();
        filter.setFilter(new ContentSecurityPolicyFilter());
        filter.addUrlPatterns(hawtioPath + "/*");
        return filter;
    }

    @Bean
    public FilterRegistrationBean strictTransportSecurityFilter() {
        final FilterRegistrationBean<StrictTransportSecurityFilter> filter = new FilterRegistrationBean<>();
        filter.setFilter(new StrictTransportSecurityFilter());
        filter.addUrlPatterns(hawtioPath + "/*");
        return filter;
    }

    @Bean
    public FilterRegistrationBean publicKeyPinningFilter() {
        final FilterRegistrationBean<PublicKeyPinningFilter> filter = new FilterRegistrationBean<>();
        filter.setFilter(new PublicKeyPinningFilter());
        filter.addUrlPatterns(hawtioPath + "/*");
        return filter;
    }

    @Bean
    @ConditionalOnBean(JolokiaEndpoint.class)
    @ConditionalOnExposedEndpoint(name = "jolokia")
    public FilterRegistrationBean authenticationFilter(final EndpointPathResolver pathResolver) {
        final FilterRegistrationBean<AuthenticationFilter> filter = new FilterRegistrationBean<>();
        filter.setFilter(new AuthenticationFilter());
        filter.addUrlPatterns(pathResolver.resolveUrlMapping("jolokia", "*"));
        filter.setDispatcherTypes(DispatcherType.ERROR, DispatcherType.FORWARD, DispatcherType.REQUEST);
        return filter;
    }

    @Bean
    public FilterRegistrationBean loginRedirectFilter(final Redirector redirector) {
        final String[] unsecuredPaths = prependContextPath(AuthenticationConfiguration.UNSECURED_PATHS);
        final FilterRegistrationBean<LoginRedirectFilter> filter = new FilterRegistrationBean<>();
        final LoginRedirectFilter loginRedirectFilter = new LoginRedirectFilter(unsecuredPaths);
        loginRedirectFilter.setRedirector(redirector);
        filter.setFilter(loginRedirectFilter);
        filter.addUrlPatterns(hawtioPath + "/*");
        return filter;
    }

    @Bean
    public FilterRegistrationBean baseTagHrefFilter(final EndpointPathResolver pathResolver) {
        final FilterRegistrationBean<BaseTagHrefFilter> filter = new FilterRegistrationBean<>();
        final BaseTagHrefFilter baseTagHrefFilter = new BaseTagHrefFilter();
        filter.setFilter(baseTagHrefFilter);
        filter.addUrlPatterns(hawtioPath + "/");
        filter.addUrlPatterns(hawtioPath + "/index.html");
        filter.addUrlPatterns(hawtioPath + "/login.html");
        filter.setDispatcherTypes(DispatcherType.ERROR, DispatcherType.FORWARD, DispatcherType.REQUEST);
        filter.addInitParameter(PARAM_APPLICATION_CONTEXT_PATH, pathResolver.resolve("hawtio"));
        return filter;
    }

    @Bean
    public FilterRegistrationBean flightRecorderDownloadFacade(final EndpointPathResolver pathResolver) {
        final FilterRegistrationBean<FlightRecordingDownloadFacade> filter = new FilterRegistrationBean<>();
        filter.setFilter(new FlightRecordingDownloadFacade());
        filter.addUrlPatterns(hawtioPath + "/jolokia/*");
        filter.addUrlPatterns(hawtioPath + "/proxy/*");
        filter.setDispatcherTypes(DispatcherType.ERROR, DispatcherType.FORWARD, DispatcherType.REQUEST);
        return filter;
    }

    // -------------------------------------------------------------------------
    // Servlets
    // -------------------------------------------------------------------------

    // Jolokia agent servlet is provided by Spring Boot actuator

    @Bean
    public ServletRegistrationBean jolokiaProxyServlet() {
        return new ServletRegistrationBean<>(
            new ProxyServlet(),
            hawtioPath + "/proxy/*");
    }

    @Bean
    public ServletRegistrationBean userServlet() {
        return new ServletRegistrationBean<>(
            new KeycloakUserServlet(),
            hawtioPath + "/user/*");
    }

    @Bean
    public ServletRegistrationBean loginServlet(Redirector redirector) {
        LoginServlet loginServlet = new LoginServlet();