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.genesys.spring.security;

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;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

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;

@Component
public class TenantJWSKeySelector
	implements JWTClaimsSetAwareJWSKeySelector<SecurityContext> {

	private Logger LOG = LoggerFactory.getLogger(TenantJWSKeySelector.class);

	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);
		}
	}
}