OAuthClientOriginCheckFilter.java

/*
 * Copyright 2018 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.blocks.security.component;

import java.io.IOException;
import java.util.Collections;
import java.util.List;
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.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.oauth2.jwt.Jwt;
import org.springframework.security.oauth2.server.resource.authentication.AbstractOAuth2TokenAuthenticationToken;
import org.springframework.web.filter.OncePerRequestFilter;

import lombok.extern.slf4j.Slf4j;

/**
 * Filter OAuth2 requests and check that Origin header matches what we have on
 * file.
 */
@Slf4j
public class OAuthClientOriginCheckFilter 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 AbstractOAuth2TokenAuthenticationToken<?>) {
			var oauthAuth = (AbstractOAuth2TokenAuthenticationToken<?>) authentication;
			if (!checkValidOrigin(request, oauthAuth)) {
				response.sendError(403, "Request origin not valid");
				return;
			}
		} else {
			log.debug("Authentication null for origin: {}", request.getHeader("Origin"));
		}
		filterChain.doFilter(request, response);
	}

	private boolean checkValidOrigin(HttpServletRequest request, AbstractOAuth2TokenAuthenticationToken<?> authAuth) {
		var token = (Jwt) authAuth.getToken();

		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));
			}
		}
		String reqOrigin = request.getHeader("Origin");
		String reqReferrer = request.getHeader("Referer"); // GET requests don't carry Origin?

		if (token != null) {
			boolean isGet = "get".equalsIgnoreCase(request.getMethod());
			List<String> claimAud = token.getClaim("aud");
			var clientId = claimAud.get(0);

			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 = (OAuthClient) clientDetailsService.loadClientByClientId(clientId); // This service use @Cacheable
		if (clientDetails == null) {
			throw new NullPointerException("No such client");
		}
		return clientDetails.getAllowedOrigins();
	}
}