AccessTokenAsParameterFilter.java

/*
 * Copyright 2023 Global Crop Diversity Trust
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.genesys.server.servlet.filter;

import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Arrays;
import java.util.Collections;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.genesys.blocks.tokenauth.spring.ApiTokenAuthenticationFilter;
import org.genesys.util.UrlUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.filter.OncePerRequestFilter;

import static org.eclipse.jetty.http.HttpCookie.SAME_SITE_LAX_COMMENT;
import static org.eclipse.jetty.http.HttpCookie.SAME_SITE_NONE_COMMENT;;

/**
 * Converts the API _access_token request parameter OR cookie to the "Authorization" HTTP request header if provided.
 *
 * @author Maxym Borodenko
 * @author Matija Obreza
 */
public class AccessTokenAsParameterFilter extends OncePerRequestFilter {

	public static final Logger LOG = LoggerFactory.getLogger(AccessTokenAsParameterFilter.class);

	private static final String ACCESS_TOKEN_COOKIE_PREFIX = "GENESYS_";
	private static final String ACCESS_TOKEN_PARAM_NAME = "_access_token";
	private static final String API_TOKEN_PARAM_NAME = "_api_token";

	@Value("${base.url}")
	private String baseUrl;

	private boolean cookieSecure;

	private String cookiePath;

	@Override
	public void afterPropertiesSet() throws ServletException {
		super.afterPropertiesSet();
		try {
			LOG.warn("Config base.url: {}", baseUrl);
			var siteUrl = UrlUtils.toCleanUrl(baseUrl);
			LOG.warn("Site URL: {}", siteUrl);
			cookiePath = siteUrl.getPath() + "/api";
			if (StringUtils.equalsIgnoreCase("https", siteUrl.getProtocol())) {
				LOG.warn("Cookies: Forcing secure cookies since we are on https");
				cookieSecure = true;
			} else if (StringUtils.equalsIgnoreCase("127.0.0.1", siteUrl.getHost())) {
				cookieSecure = true;
			} else if (StringUtils.equalsIgnoreCase("localhost", siteUrl.getHost())) {
				cookieSecure = true;
			} else if (StringUtils.endsWithIgnoreCase(".localhost", siteUrl.getHost())) {
				cookieSecure = true;
			} else {
				LOG.warn("Cookies: Forcing insecure cookies since we are on http");
				cookieSecure = false;
			}
		} catch (MalformedURLException e) {
			LOG.warn("Site URL: {}", baseUrl, e);
			throw new ServletException(e);
		}
	}

	@Override
	protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {

		String authorizationHeader = request.getHeader("Authorization");
		String accessToken = null;
		
		// Check if _api_token is present
		if (authorizationHeader == null) {
			String apiToken = StringUtils.defaultIfBlank(request.getParameter(API_TOKEN_PARAM_NAME), null);
			if (apiToken != null) {
				LOG.info("Applying API token as request parameter {}", API_TOKEN_PARAM_NAME);
				request = new CustomHeadersRequest(request);
				((CustomHeadersRequest) request).addHeader("Authorization", ApiTokenAuthenticationFilter.AUTHORIZATION_TYPE + " " + apiToken);
				filterChain.doFilter(request, response);
				return;
			}
		}

		// 1. Check if _access_token is present
		if (authorizationHeader == null) {
			// if (request.getQueryString().contains(ACCESS_TOKEN_PARAM_NAME.concat("="))) {
			// 	throw new InvalidApiUsageException(ACCESS_TOKEN_PARAM_NAME + " can only be used as a form parameter");
			// }
			accessToken = StringUtils.defaultIfBlank(request.getParameter(ACCESS_TOKEN_PARAM_NAME), null);
			if (accessToken != null) {
				LOG.info("Found access token as request parameter {}", ACCESS_TOKEN_PARAM_NAME);
			}
		}

		// 2. If not present in posted form, check for cookie
		// TODO Remove in 2023.3
		URL sourceUrl = null;
		try {
			sourceUrl = getRequestSource(request);
		} catch (MalformedURLException e) {
			LOG.debug("Could not obtain source URL: {}", e.getMessage());
		}

		String tokenCookieName = sourceUrl == null ? null : ACCESS_TOKEN_COOKIE_PREFIX + sourceUrl.getHost();
		// Find cookie by source host name (if available)
		var cookies = request.getCookies();
		Optional<Cookie> tokenCookie = cookies == null || tokenCookieName == null ? Optional.empty() : Arrays.stream(cookies).filter(cookie -> cookie.getName().equalsIgnoreCase(tokenCookieName)).findFirst();

		// If there's no Authorization header and no _access_token request parameter, then we use cookie value if available
		if (authorizationHeader == null && accessToken == null && tokenCookie.isPresent()) {
			LOG.info("Using access token from cookie {}", tokenCookieName);
			accessToken = StringUtils.defaultIfBlank(tokenCookie.get().getValue(), null);
		}

		// 3. Apply form or cookie token using CustomHeadersRequest only if Authorization header is missing
		if (authorizationHeader == null && StringUtils.isNotBlank(accessToken)) {
			LOG.debug("Applying access token from parameter/cookie");
			request = new CustomHeadersRequest(request);
			((CustomHeadersRequest) request).addHeader("Authorization", "Bearer " + accessToken);
		}

		// Register the "access_token" cookie if Authorization is provided (also as parameter)
		// TODO Remove in 2023.4
		var shouldAddCookie = (tokenCookieName != null && authorizationHeader != null && authorizationHeader.startsWith("Bearer ")) || accessToken != null;
		if (shouldAddCookie) {
			if (authorizationHeader != null && authorizationHeader.startsWith("Bearer ")) {
				LOG.debug("Applying Authorization header to cookie");
				accessToken = authorizationHeader.substring(7); // Remove "Bearer "
			}

			if (tokenCookie.isEmpty() || !tokenCookie.get().getValue().equals(accessToken)) {
				Cookie cookie = new Cookie(tokenCookieName, accessToken);
				if (cookieSecure) {
					cookie.setComment(SAME_SITE_NONE_COMMENT);
				} else {
					cookie.setComment(SAME_SITE_LAX_COMMENT);
				}
				cookie.setHttpOnly(true);
				cookie.setSecure(cookieSecure);
				cookie.setPath(cookiePath); // Only set cookie for /api
				// cookie.setMaxAge(-1); // Expire cookie when browser exits (default behavior)

				try {
					response.addCookie(cookie);
					LOG.info("Registered API cookie '{}' on {}{}", cookie.getName(), cookie.getDomain(), cookie.getPath());
				} catch (Throwable e) {
					LOG.error("Invalid cookie: {}. Value={}", e.getMessage(), cookie.getValue());
				}
			}
		}

		filterChain.doFilter(request, response);
	}

	private URL getRequestSource(HttpServletRequest request) throws MalformedURLException {
		String origin = request.getHeader("Origin");
		if (StringUtils.isNotBlank(origin)) {
			return new URL(origin);
		}

		String referrer = request.getHeader("Referer");
		if (StringUtils.isNotBlank(referrer)) {
			return new URL(referrer);
		}

		return null;
	}

	static class CustomHeadersRequest extends HttpServletRequestWrapper {
		private Map<String, String> customHeaders = new HashMap<>();

		public CustomHeadersRequest(HttpServletRequest request) {
			super(request);
		}

		public void addHeader(String name, String value) {
			customHeaders.put(name, value);
		}

		@Override
		public String getHeader(String name) {
			if (customHeaders.containsKey(name)) {
				return customHeaders.get(name);
			}
			return super.getHeader(name);
		}

		@Override
		public Enumeration<String> getHeaderNames() {
			List<String> names = Collections.list(super.getHeaderNames());
			names.addAll(customHeaders.keySet());
			return Collections.enumeration(names);
		}

		@Override
		public Enumeration<String> getHeaders(String name) {
			List<String> values = Collections.list(super.getHeaders(name));
			if (customHeaders.containsKey(name)) {
				values.add(customHeaders.get(name));
			}
			return Collections.enumeration(values);
		}
	}
}