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.StringUtils;
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> {

	private final TenantRepository tenants;

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

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

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

	@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 (StringUtils.startsWith(uri, baseUrl)) {
				uri = uri.replace(baseUrl, "http://localhost:8080");
				log.trace("Getting local JWS keys from URI {}", uri);
			}
			return JWSAlgorithmFamilyJWSKeySelector.fromJWKSetURL(new URL(uri));
		} catch (Exception ex) {
			throw new IllegalArgumentException(ex);
		}
	}
}