TenantJWSKeySelector.java

/*
 * Copyright 2022 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.gringlobal.oauth2.server;

import java.net.URL;
import java.security.Key;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.ConcurrentHashMap;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.Strings;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import com.nimbusds.jose.JWSHeader;
import com.nimbusds.jose.KeySourceException;
import com.nimbusds.jose.proc.JWSAlgorithmFamilyJWSKeySelector;
import com.nimbusds.jose.proc.JWSKeySelector;
import com.nimbusds.jose.proc.SecurityContext;
import com.nimbusds.jwt.JWTClaimsSet;
import com.nimbusds.jwt.proc.JWTClaimsSetAwareJWSKeySelector;

@Component
@Slf4j
public class TenantJWSKeySelector implements JWTClaimsSetAwareJWSKeySelector<SecurityContext>, InitializingBean {

	private final TenantRepository tenants;

	private final Map<String, JWSKeySelector<SecurityContext>> selectors = new ConcurrentHashMap<>();

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

	/**
	 * When we are the issuer, use internal URL to obtain JWSK
	 */
	@Value("${base.url.internal:http://localhost:8080}")
	private String baseUrlInternal;

	public TenantJWSKeySelector(TenantRepository tenants) {
		this.tenants = tenants;
	}

	/**
	 * Figure out the internal URL and fix it if necessary
	 */
	@Override
	public void afterPropertiesSet() throws Exception {
		var publicUrl = new URL(baseUrl);
		baseUrl = publicUrl.toString();
		var internalUrl = new URL(baseUrlInternal);
		if (Strings.CS.equals(internalUrl.getPath(), publicUrl.getPath())) {
			log.warn("Internal context path {} equals public context path {}", internalUrl.getPath(), publicUrl.getPath());
		} else {
			log.warn("Internal context path {} DOES NOT equal public context path {}", internalUrl.getPath(), publicUrl.getPath());
			internalUrl = new URL(internalUrl.getProtocol(), internalUrl.getHost(), internalUrl.getPort(), publicUrl.getPath());
		}
		baseUrlInternal = internalUrl.toString();
		log.warn("Using internal URL {} for JWKS", baseUrlInternal);
	}

	@Override
	public List<? extends Key> selectKeys(JWSHeader jwsHeader, JWTClaimsSet jwtClaimsSet, SecurityContext securityContext)
		throws KeySourceException {
		return this.selectors.computeIfAbsent(toTenant(jwtClaimsSet), this::fromTenant)
			.selectJWSKeys(jwsHeader, securityContext);
	}

	private String toTenant(JWTClaimsSet claimSet) {
		return (String) claimSet.getClaim("iss");
	}

	private JWSKeySelector<SecurityContext> fromTenant(String tenant) {
		log.trace("Getting JWSK selector for issuer {}", tenant);
		return Optional.ofNullable(this.tenants.findByIssuer(tenant))
			.map(cr -> cr.getProviderDetails().getJwkSetUri())
			.map(this::fromUri)
			.orElseThrow(() -> new IllegalArgumentException("unknown tenant"))
			;
	}

	private JWSKeySelector<SecurityContext> fromUri(String uri) {
		try {
			log.trace("Getting JWSK from URI {} (base={})", uri, baseUrl);
			if (Strings.CS.startsWith(uri, baseUrl)) {
				uri = uri.replace(baseUrl, baseUrlInternal);
				log.trace("Getting local JWS keys from URI {}", uri);
			}
			return JWSAlgorithmFamilyJWSKeySelector.fromJWKSetURL(new URL(uri));
		} catch (Exception ex) {
			throw new IllegalArgumentException(ex);
		}
	}
}