ApiTokenOriginCheckFilter.java

/*
 * Copyright 2024 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.spring.security;

import java.io.IOException;
import java.util.Collections;
import java.util.Set;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.genesys.blocks.oauth.model.OAuthClient;
import org.genesys.blocks.oauth.service.OAuthClientService;
import org.genesys.blocks.tokenauth.spring.ApiTokenAuthenticationToken;
import org.genesys.blocks.tokenauth.spring.ApiTokenDetailsService.ApiTokenClientDetails;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.filter.OncePerRequestFilter;

import lombok.extern.slf4j.Slf4j;

/**
 * Filter requests that use API-Token authentication and check that the Origin header matches what we have on
 * file for the OAuth client (when the API-Token represents a client).
 */
@Slf4j
public class ApiTokenOriginCheckFilter extends OncePerRequestFilter {

	@Autowired
	private OAuthClientService clientDetailsService;

	@Override
	protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
		throws ServletException, IOException {
		Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
		if (authentication instanceof ApiTokenAuthenticationToken) {
			var apiTokenAuth = (ApiTokenAuthenticationToken) authentication;
			var authDetails = apiTokenAuth.getDetails();
			if (authDetails instanceof ApiTokenClientDetails) {
				var clientDetails = (ApiTokenClientDetails) authDetails;
				if (!checkValidOrigin(request, clientDetails)) {
					response.sendError(403, "Request origin not valid");
					return;
				}
			}
		} else {
			log.debug("Not authenticated by ApiToken for origin: {}", request.getHeader("Origin"));
		}
		filterChain.doFilter(request, response);
	}

	private boolean checkValidOrigin(HttpServletRequest request, ApiTokenClientDetails clientDetails) {

		if (log.isTraceEnabled()) { // Keep this, it's expensive
			log.trace(request.getRequestURI());
			for (String headerName : Collections.list(request.getHeaderNames())) {
				log.trace(">> {}: {}", headerName, request.getHeader(headerName));
			}
		}
		boolean isGet = "get".equalsIgnoreCase(request.getMethod());
		String reqOrigin = request.getHeader("Origin");
		String reqReferrer = request.getHeader("Referer"); // GET requests don't carry Origin?

		if (clientDetails != null) {
			var clientId = clientDetails.getUsername();

			try {
				Set<String> allowedOrigins = getAllowedOrigins(clientId);

				if (!allowedOrigins.isEmpty()) {
					if (reqOrigin == null && reqReferrer == null) {
						log.info("No origin/referrer header in request. Denying.");
						return false;
					}
					for (String allowedOrigin : allowedOrigins) {
						if (reqOrigin != null && reqOrigin.startsWith(allowedOrigin)) {
							log.debug("Origin match: {} for {}", reqOrigin, allowedOrigin);
							return true;
						}

						if ((isGet || reqOrigin == null) && reqReferrer != null && reqReferrer.startsWith(allowedOrigin)) {
							log.debug("Referrer match: {} for {}", reqReferrer, allowedOrigin);
							return true;
						}
					}
					// No declared origins match
					log.info("No origin/referrer match: {} or {} in {}", reqOrigin, reqReferrer, allowedOrigins);
					return false;
				} else {
					if (reqOrigin != null || reqReferrer != null) {
						log.info("{} may not be used from browsers. Denying.", clientId);
						return false;
					}
					return true;
				}
			} catch (Throwable e) {
				log.warn("Error loading client origins: {}", e.getMessage());
			}
		}
		log.debug("Allowing request with Origin: {}", reqOrigin);
		return true;
	}

	private Set<String> getAllowedOrigins(String clientId) {
		OAuthClient clientDetails = clientDetailsService.loadClientByClientId(clientId); // This service use @Cacheable
		if (clientDetails == null) {
			throw new NullPointerException("No such client");
		}
		return clientDetails.getAllowedOrigins();
	}
}