mirror of
https://github.com/floci-io/floci.git
synced 2026-12-01 01:12:48 -05:00
feat(sts): verify web identity tokens from OIDC providers registered in IAM (#9217)
AssumeRoleWithWebIdentity verified only tokens from issuers Floci knows, such as its own EKS clusters, so a token from an OIDC provider registered with CreateOpenIDConnectProvider could not be verified. For a registered https issuer, the provider is read in the role's account, the token's key comes from the issuer's jwks_uri, and aud must name one of the provider's client IDs. An issuer whose keys cannot be fetched answers InvalidIdentityToken with AWS's message, and a token naming no key ID is refused with InvalidIdentityToken too. Closes #7942
This commit is contained in:
1 parent
b57af59bf8
commit
47e554680b
9 files changed
+401
-17
No files matched your search
@@ -82,6 +82,19 @@ public class WebIdentityTokenVerifier {
|
||||
.filter(iss -> iss != null && !iss.isBlank());
|
||||
}
|
||||
|
||||
/**
|
||||
* Reads the {@code kid} header without verifying the signature: the id of the issuer's key the
|
||||
* token names as its signer. Empty when {@code token} is not a JWT or names none.
|
||||
*/
|
||||
public Optional<String> peekKeyId(String token) {
|
||||
String[] parts = token == null ? new String[0] : token.split("\\.", -1);
|
||||
if (parts.length != 3) {
|
||||
return Optional.empty();
|
||||
}
|
||||
return decodeJson(parts[0]).map(header -> header.path("kid").asText(null))
|
||||
.filter(kid -> kid != null && !kid.isBlank());
|
||||
}
|
||||
|
||||
/**
|
||||
* Fully verifies {@code token}: RS256 signature against {@code publicKey}, {@code iss} equal to
|
||||
* {@code expectedIssuer}, {@code aud} containing {@code requiredAudience}, and {@code exp}/
|
||||
@@ -91,6 +104,15 @@ public class WebIdentityTokenVerifier {
|
||||
*/
|
||||
public WebIdentityToken verify(String token, RSAPublicKey publicKey, String expectedIssuer,
|
||||
String requiredAudience) throws InvalidTokenException {
|
||||
return verify(token, publicKey, expectedIssuer, List.of(requiredAudience));
|
||||
}
|
||||
|
||||
/**
|
||||
* As {@link #verify(String, RSAPublicKey, String, String)}, with {@code aud} holding at least one
|
||||
* of {@code acceptedAudiences}, the client IDs an IAM OIDC provider lists.
|
||||
*/
|
||||
public WebIdentityToken verify(String token, RSAPublicKey publicKey, String expectedIssuer,
|
||||
List<String> acceptedAudiences) throws InvalidTokenException {
|
||||
// Limit -1 keeps trailing empty segments, so an unsigned "header.payload." token is seen as
|
||||
// three parts and rejected by the algorithm check below rather than as malformed.
|
||||
String[] parts = token == null ? new String[0] : token.split("\\.", -1);
|
||||
@@ -120,9 +142,9 @@ public class WebIdentityTokenVerifier {
|
||||
}
|
||||
|
||||
List<String> audiences = readAudiences(claims);
|
||||
if (!audiences.contains(requiredAudience)) {
|
||||
if (audiences.stream().noneMatch(acceptedAudiences::contains)) {
|
||||
throw new InvalidTokenException("The web identity token audience does not include "
|
||||
+ requiredAudience);
|
||||
+ String.join(" or ", acceptedAudiences));
|
||||
}
|
||||
|
||||
verifyValidityWindow(claims);
|
||||
|
||||
@@ -187,6 +187,16 @@ public class JwtSignatureVerifier implements AutoCloseable {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The key {@code issuer} publishes under {@code kid}, read from its discovery document's
|
||||
* {@code jwks_uri}, or empty when it publishes none under that id.
|
||||
*
|
||||
* @throws JwtVerificationException if the discovery document or the key set cannot be fetched.
|
||||
*/
|
||||
public Optional<RSAPublicKey> signingKey(String issuer, String kid) throws JwtVerificationException {
|
||||
return Optional.ofNullable(resolveKey(issuer, kid));
|
||||
}
|
||||
|
||||
private RSAPublicKey resolveKey(String issuer, String kid) throws JwtVerificationException {
|
||||
CachedJwks cached = jwksCache.get(issuer);
|
||||
if (cached != null && !cached.isExpired()) {
|
||||
|
||||
@@ -5381,6 +5381,11 @@ public class IamService implements SessionAccountLookup, ResourceProvider {
|
||||
"OpenIDConnect Provider not found for arn " + arn, 404));
|
||||
}
|
||||
|
||||
/** The OIDC provider {@code accountId} stored under {@code arn}, or empty when it has registered none there. */
|
||||
public Optional<OpenIDConnectProvider> findOpenIDConnectProvider(String accountId, String arn) {
|
||||
return AccountAwareStorageBackend.getInAccount(oidcProviders, accountId, arn);
|
||||
}
|
||||
|
||||
public List<OpenIDConnectProvider> listOpenIDConnectProviders() {
|
||||
return oidcProviders.scan(k -> true);
|
||||
}
|
||||
|
||||
@@ -21,9 +21,11 @@ import io.floci.aws.core.common.SmithyValidationErrors;
|
||||
import io.floci.aws.core.common.WebIdentityToken;
|
||||
import io.floci.aws.core.common.WebIdentityTokenVerifier;
|
||||
import io.floci.aws.core.common.XmlBuilder;
|
||||
import io.floci.aws.services.apigatewayv2.JwtSignatureVerifier;
|
||||
import io.floci.aws.services.iam.model.DelegationRequest;
|
||||
import io.floci.aws.services.iam.model.IamPolicy;
|
||||
import io.floci.aws.services.iam.model.IamRole;
|
||||
import io.floci.aws.services.iam.model.OpenIDConnectProvider;
|
||||
import io.floci.aws.services.iam.model.OutboundWebIdentityFederation;
|
||||
import jakarta.enterprise.context.ApplicationScoped;
|
||||
import jakarta.inject.Inject;
|
||||
@@ -79,6 +81,7 @@ public class StsQueryHandler {
|
||||
private final WebIdentityTrustPolicyEvaluator webIdentityTrustEvaluator;
|
||||
private final WebIdentityTokenVerifier tokenVerifier;
|
||||
private final OidcIssuerKeyLookup oidcIssuerKeys;
|
||||
private final JwtSignatureVerifier registeredIssuerKeys;
|
||||
private final SAMLProviderService samlProviderService;
|
||||
private final SAMLTrustPolicyEvaluator samlTrustEvaluator;
|
||||
private final DelegationRequestService delegationRequestService;
|
||||
@@ -102,6 +105,7 @@ public class StsQueryHandler {
|
||||
WebIdentityTrustPolicyEvaluator webIdentityTrustEvaluator,
|
||||
WebIdentityTokenVerifier tokenVerifier,
|
||||
OidcIssuerKeyLookup oidcIssuerKeys,
|
||||
JwtSignatureVerifier registeredIssuerKeys,
|
||||
SAMLProviderService samlProviderService,
|
||||
SAMLTrustPolicyEvaluator samlTrustEvaluator,
|
||||
DelegationRequestService delegationRequestService,
|
||||
@@ -109,8 +113,8 @@ public class StsQueryHandler {
|
||||
WebIdentityTokenIssuer tokenIssuer,
|
||||
RequestContext requestContext) {
|
||||
this(iamService, accountResolver, regionResolver, config, trustPolicyEvaluator, webIdentityTrustEvaluator,
|
||||
tokenVerifier, oidcIssuerKeys, samlProviderService, samlTrustEvaluator, delegationRequestService,
|
||||
centralRootAccess, tokenIssuer, requestContext, Clock.systemUTC());
|
||||
tokenVerifier, oidcIssuerKeys, registeredIssuerKeys, samlProviderService, samlTrustEvaluator,
|
||||
delegationRequestService, centralRootAccess, tokenIssuer, requestContext, Clock.systemUTC());
|
||||
}
|
||||
|
||||
StsQueryHandler(IamService iamService, AccountResolver accountResolver, RegionResolver regionResolver,
|
||||
@@ -118,6 +122,7 @@ public class StsQueryHandler {
|
||||
WebIdentityTrustPolicyEvaluator webIdentityTrustEvaluator,
|
||||
WebIdentityTokenVerifier tokenVerifier,
|
||||
OidcIssuerKeyLookup oidcIssuerKeys,
|
||||
JwtSignatureVerifier registeredIssuerKeys,
|
||||
SAMLProviderService samlProviderService,
|
||||
SAMLTrustPolicyEvaluator samlTrustEvaluator,
|
||||
DelegationRequestService delegationRequestService,
|
||||
@@ -133,6 +138,7 @@ public class StsQueryHandler {
|
||||
this.webIdentityTrustEvaluator = webIdentityTrustEvaluator;
|
||||
this.tokenVerifier = tokenVerifier;
|
||||
this.oidcIssuerKeys = oidcIssuerKeys;
|
||||
this.registeredIssuerKeys = registeredIssuerKeys;
|
||||
this.samlProviderService = samlProviderService;
|
||||
this.samlTrustEvaluator = samlTrustEvaluator;
|
||||
this.delegationRequestService = delegationRequestService;
|
||||
@@ -815,7 +821,35 @@ public class StsQueryHandler {
|
||||
"The web identity token does not identify a trusted issuer.", AwsNamespaces.STS, 400))
|
||||
: WebIdentityOutcome.unverifiable();
|
||||
}
|
||||
Optional<IamRole> role = iamService.findRole(roleAccountId, roleName);
|
||||
String issuerKeyPrefix = stripScheme(issuer.get());
|
||||
// The provider is an IAM resource of the role's account, so it shares the role's partition.
|
||||
String oidcProviderArn = AwsArnUtils.Arn.global(
|
||||
AwsArnUtils.partitionOrDefault(role.map(IamRole::getArn).orElse(roleArn),
|
||||
regionResolver.getPartition()),
|
||||
"iam", roleAccountId, "oidc-provider/" + issuerKeyPrefix).toString();
|
||||
Optional<RSAPublicKey> key = oidcIssuerKeys.findVerificationKey(issuer.get());
|
||||
List<String> acceptedAudiences = List.of(STS_AUDIENCE);
|
||||
// IAM stores a provider's URL without its scheme and accepts only https, so only an https
|
||||
// issuer names one.
|
||||
Optional<OpenIDConnectProvider> provider = key.isPresent() || !config.services().iam().enforcementEnabled()
|
||||
|| !issuer.get().startsWith("https://")
|
||||
? Optional.empty() : iamService.findOpenIDConnectProvider(roleAccountId, oidcProviderArn);
|
||||
if (provider.isPresent()) {
|
||||
Optional<String> keyId = tokenVerifier.peekKeyId(token);
|
||||
if (keyId.isEmpty()) {
|
||||
return WebIdentityOutcome.deny(AwsQueryResponse.error("InvalidIdentityToken",
|
||||
"The web identity token names no signing key.", AwsNamespaces.STS, 400));
|
||||
}
|
||||
key = registeredIssuerKey(issuer.get(), keyId.get());
|
||||
if (key.isEmpty()) {
|
||||
return WebIdentityOutcome.deny(AwsQueryResponse.error("InvalidIdentityToken",
|
||||
"Couldn't retrieve verification key from your identity provider, please reference "
|
||||
+ "AssumeRoleWithWebIdentity documentation for requirements",
|
||||
AwsNamespaces.STS, 400));
|
||||
}
|
||||
acceptedAudiences = provider.get().getClientIdList();
|
||||
}
|
||||
if (key.isEmpty()) {
|
||||
return config.services().iam().enforcementEnabled()
|
||||
? WebIdentityOutcome.deny(AwsQueryResponse.error("InvalidIdentityToken",
|
||||
@@ -825,7 +859,7 @@ public class StsQueryHandler {
|
||||
|
||||
WebIdentityToken claims;
|
||||
try {
|
||||
claims = tokenVerifier.verify(token, key.get(), issuer.get(), STS_AUDIENCE);
|
||||
claims = tokenVerifier.verify(token, key.get(), issuer.get(), acceptedAudiences);
|
||||
} catch (WebIdentityTokenVerifier.ExpiredTokenException e) {
|
||||
LOG.debugv("Rejecting web identity token for role {0}: {1}", roleArn, e.getMessage());
|
||||
return WebIdentityOutcome.deny(AwsQueryResponse.error("ExpiredTokenException",
|
||||
@@ -838,16 +872,10 @@ public class StsQueryHandler {
|
||||
e.getMessage(), AwsNamespaces.STS, 400));
|
||||
}
|
||||
|
||||
Optional<IamRole> role = iamService.findRole(roleAccountId, roleName);
|
||||
if (role.isEmpty() || !IamService.roleArnMatches(roleArn, role.get())) {
|
||||
return WebIdentityOutcome.deny(accessDenied(roleArn));
|
||||
}
|
||||
|
||||
String issuerKeyPrefix = stripScheme(issuer.get());
|
||||
// The provider is an IAM resource of the role's account, so it shares the role's partition.
|
||||
String oidcProviderArn = AwsArnUtils.Arn.global(
|
||||
AwsArnUtils.partitionOrDefault(role.get().getArn(), regionResolver.getPartition()),
|
||||
"iam", roleAccountId, "oidc-provider/" + issuerKeyPrefix).toString();
|
||||
Map<String, List<String>> conditionClaims = Map.of(
|
||||
"sub", List.of(claims.subject()),
|
||||
"aud", claims.audiences());
|
||||
@@ -867,12 +895,28 @@ public class StsQueryHandler {
|
||||
accessDenied(AssumeRolePolicyEvaluator.TAG_SESSION_ACTION, roleArn));
|
||||
}
|
||||
|
||||
// verify() already required the audience list to contain STS_AUDIENCE.
|
||||
// verify() already required the audience list to hold one of the accepted audiences.
|
||||
String audience = claims.audiences().stream().filter(acceptedAudiences::contains).findFirst()
|
||||
.orElse(STS_AUDIENCE);
|
||||
return WebIdentityOutcome.allow(
|
||||
new VerifiedWebIdentity(claims.issuer(), claims.subject(), STS_AUDIENCE,
|
||||
new VerifiedWebIdentity(claims.issuer(), claims.subject(), audience,
|
||||
claims.principalTags(), claims.transitiveTagKeys()), role.get());
|
||||
}
|
||||
|
||||
/**
|
||||
* The key an issuer registered with {@code CreateOpenIDConnectProvider} publishes under
|
||||
* {@code keyId}, fetched from its {@code jwks_uri}. Empty when the keys cannot be fetched or
|
||||
* none carries that id, which AWS answers as {@code InvalidIdentityToken}.
|
||||
*/
|
||||
private Optional<RSAPublicKey> registeredIssuerKey(String issuer, String keyId) {
|
||||
try {
|
||||
return registeredIssuerKeys.signingKey(issuer, keyId);
|
||||
} catch (JwtSignatureVerifier.JwtVerificationException e) {
|
||||
LOG.debugv("Cannot fetch the keys of OIDC issuer {0}: {1}", issuer, e.getMessage());
|
||||
return Optional.empty();
|
||||
}
|
||||
}
|
||||
|
||||
private static String assumedRoleId(IamRole role, String sessionName) {
|
||||
String roleId = (role != null && role.getRoleId() != null) ? role.getRoleId() : ("AROA" + randomId(16));
|
||||
return roleId + ":" + sessionName;
|
||||
|
||||
Reference in new issue
Block a user