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
@@ -1235,7 +1235,7 @@ When `sts:AssumeRoleWithWebIdentity` receives a token whose `iss` names an issue
|
||||
|
||||
The response then carries the token's real claims in `SubjectFromWebIdentityToken`, `Provider`, and `Audience`. Failures return `InvalidIdentityToken` (400) for a bad token, `ExpiredTokenException` (400) for an expired one, or `AccessDenied` (403) when the trust policy does not permit the subject.
|
||||
|
||||
A token whose issuer Floci does not host is treated as opaque and accepted, since Floci cannot adjudicate a third-party provider. Validation is therefore automatic for Floci-issued tokens and requires no configuration flag.
|
||||
With IAM enforcement off, a token whose issuer Floci does not host is treated as opaque and accepted. With it on, such a token is verified against the issuer's published keys when the role's account registered the issuer as an OIDC provider, and refused otherwise (see [STS](sts.md#issuers-registered-in-iam)). Validation is automatic for Floci-issued tokens and requires no configuration flag.
|
||||
|
||||
### OIDC discovery endpoints
|
||||
|
||||
|
||||
+13
-1
@@ -621,7 +621,19 @@ When the token's `iss` names a known Floci issuer, all of the following are enfo
|
||||
|
||||
The response carries the token's real claims in `SubjectFromWebIdentityToken`, `Provider`, and `Audience`. A bad token returns `InvalidIdentityToken` (400), an expired one returns `ExpiredTokenException` (400), and a role that does not exist or a trust policy that does not permit the subject returns `AccessDenied` (403).
|
||||
|
||||
By default, tokens from an issuer Floci does not host, or tokens that are not parseable JWTs, are treated as opaque and accepted for compatibility with existing workflows, provided the target role exists in IAM. When `FLOCI_SERVICES_IAM_ENFORCEMENT_ENABLED=true`, those tokens return `InvalidIdentityToken` because Floci cannot verify a third-party provider's signature. See [EKS](eks.md) for the full IRSA walkthrough and the token-minting endpoint.
|
||||
By default, tokens from an issuer Floci does not host, or tokens that are not parseable JWTs, are treated as opaque and accepted for compatibility with existing workflows, provided the target role exists in IAM. See [EKS](eks.md) for the full IRSA walkthrough and the token-minting endpoint.
|
||||
|
||||
### Issuers registered in IAM
|
||||
|
||||
When `FLOCI_SERVICES_IAM_ENFORCEMENT_ENABLED=true`, a token from an issuer Floci does not host is verified when the role's account registered that issuer with `CreateOpenIDConnectProvider`, as IAM verifies it (a self-hosted provider, a SPIFFE/SPIRE OIDC discovery provider, a CI system):
|
||||
|
||||
- Floci reads `<issuer>/.well-known/openid-configuration`, fetches the key set at its `jwks_uri`, and verifies the signature with the key named by the token's `kid`. The key set is cached for 10 minutes and fetched again when a token names a key it does not hold.
|
||||
- `aud` must hold one of the provider's client IDs, and `Audience` in the response is that client ID. The other checks are the ones listed above.
|
||||
- When the key set cannot be fetched, or it holds no key with the token's `kid`, the call returns `InvalidIdentityToken` (400) with "Couldn't retrieve verification key from your identity provider, please reference AssumeRoleWithWebIdentity documentation for requirements". A token with no `kid` also returns `InvalidIdentityToken`.
|
||||
- Only an `https://` issuer matches a provider, as IAM accepts only `https://` provider URLs.
|
||||
- The issuer is fetched as API Gateway fetches a JWT authorizer's issuer: over HTTPS, trusting the JVM's roots and the CAs Floci trusts for its own outbound HTTPS, and refusing a private or local address unless `FLOCI_SECURITY_ALLOW_PRIVATE_JWT_TARGETS=true`. The provider's thumbprints are not compared.
|
||||
|
||||
A token from an issuer that is neither hosted by Floci nor registered in the role's account returns `InvalidIdentityToken`. With enforcement off, Floci fetches nothing and accepts such tokens as described above.
|
||||
|
||||
## Examples
|
||||
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -109,6 +109,18 @@ class JwtSignatureVerifierTest {
|
||||
verifier.verify(token, issuer); // does not throw
|
||||
}
|
||||
|
||||
@Test
|
||||
void signingKeyIsThePublishedKeyWithTheTokensKid() throws Exception {
|
||||
Optional<RSAPublicKey> key = verifier.signingKey(issuer, "test-key-1");
|
||||
|
||||
assertEquals(publicKey.getModulus(), key.orElseThrow().getModulus());
|
||||
}
|
||||
|
||||
@Test
|
||||
void signingKeyIsEmptyWhenNoPublishedKeyHasTheKid() throws Exception {
|
||||
assertTrue(verifier.signingKey(issuer, "unknown-kid").isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
void rejectsATokenSignedWithADifferentKey() throws Exception {
|
||||
KeyPairGenerator gen = KeyPairGenerator.getInstance("RSA");
|
||||
|
||||
@@ -7,6 +7,7 @@ import io.floci.aws.core.common.RegionResolver;
|
||||
import io.floci.aws.core.common.RequestContext;
|
||||
import io.floci.aws.core.common.WebIdentityToken;
|
||||
import io.floci.aws.core.common.WebIdentityTokenVerifier;
|
||||
import io.floci.aws.services.apigatewayv2.JwtSignatureVerifier;
|
||||
import io.floci.aws.services.iam.model.DelegationRequest;
|
||||
import io.floci.aws.services.iam.model.IamRole;
|
||||
import io.floci.aws.services.iam.model.OutboundWebIdentityFederation;
|
||||
@@ -122,6 +123,7 @@ class StsQueryHandlerTest {
|
||||
mock(WebIdentityTrustPolicyEvaluator.class),
|
||||
mock(WebIdentityTokenVerifier.class),
|
||||
mock(OidcIssuerKeyLookup.class),
|
||||
mock(JwtSignatureVerifier.class),
|
||||
mock(SAMLProviderService.class),
|
||||
mock(SAMLTrustPolicyEvaluator.class),
|
||||
delegation,
|
||||
@@ -1131,7 +1133,7 @@ class StsQueryHandlerTest {
|
||||
when(iamService.findRole("000000000000", "web-role")).thenReturn(Optional.of(role));
|
||||
WebIdentityTokenVerifier verifier = mock(WebIdentityTokenVerifier.class);
|
||||
when(verifier.peekIssuer("jwt0")).thenReturn(Optional.of(issuer));
|
||||
when(verifier.verify(eq("jwt0"), any(), eq(issuer), anyString()))
|
||||
when(verifier.verify(eq("jwt0"), any(), eq(issuer), anyList()))
|
||||
.thenReturn(new WebIdentityToken(issuer, "system:serviceaccount:default:app",
|
||||
List.of("sts.amazonaws.com"), Map.of("Project", "atlas"),
|
||||
List.of("Project")));
|
||||
@@ -1145,7 +1147,7 @@ class StsQueryHandlerTest {
|
||||
|
||||
StsQueryHandler handler = new StsQueryHandler(iamService, mock(AccountResolver.class),
|
||||
new RegionResolver(REGION, "000000000000"), config, mock(AssumeRolePolicyEvaluator.class),
|
||||
trust, verifier, keys, mock(SAMLProviderService.class), mock(SAMLTrustPolicyEvaluator.class),
|
||||
trust, verifier, keys, mock(JwtSignatureVerifier.class), mock(SAMLProviderService.class), mock(SAMLTrustPolicyEvaluator.class),
|
||||
mock(DelegationRequestService.class), mock(CentralRootAccess.class),
|
||||
mock(WebIdentityTokenIssuer.class), new RequestContext());
|
||||
MultivaluedMap<String, String> params = new MultivaluedHashMap<>();
|
||||
|
||||
+277
@@ -0,0 +1,277 @@
|
||||
package io.floci.aws.services.iam;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.databind.node.ObjectNode;
|
||||
import io.floci.aws.core.common.Base64Url;
|
||||
import io.floci.aws.core.common.RequestScopes;
|
||||
import io.floci.aws.services.apigatewayv2.JwtSignatureVerifier;
|
||||
import io.floci.aws.services.iam.model.IamRole;
|
||||
import io.floci.aws.services.iam.model.OpenIDConnectProvider;
|
||||
import io.floci.aws.testing.SignedIamEnforcementProfile;
|
||||
import io.floci.aws.testing.SignedIamUsers;
|
||||
import io.quarkus.test.InjectMock;
|
||||
import io.quarkus.test.common.http.TestHTTPResource;
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import io.quarkus.test.junit.TestProfile;
|
||||
import jakarta.inject.Inject;
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import software.amazon.awssdk.auth.credentials.AnonymousCredentialsProvider;
|
||||
import software.amazon.awssdk.auth.credentials.AwsBasicCredentials;
|
||||
import software.amazon.awssdk.auth.credentials.StaticCredentialsProvider;
|
||||
import software.amazon.awssdk.regions.Region;
|
||||
import software.amazon.awssdk.services.iam.IamClient;
|
||||
import software.amazon.awssdk.services.iam.model.Role;
|
||||
import software.amazon.awssdk.services.sts.StsClient;
|
||||
import software.amazon.awssdk.services.sts.model.AssumeRoleWithWebIdentityResponse;
|
||||
import software.amazon.awssdk.services.sts.model.StsException;
|
||||
|
||||
import java.net.URI;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.security.GeneralSecurityException;
|
||||
import java.security.KeyPair;
|
||||
import java.security.KeyPairGenerator;
|
||||
import java.security.Signature;
|
||||
import java.security.interfaces.RSAPrivateKey;
|
||||
import java.security.interfaces.RSAPublicKey;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.UUID;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
/**
|
||||
* {@code AssumeRoleWithWebIdentity} with a token from an issuer registered through
|
||||
* {@code CreateOpenIDConnectProvider}: "The JSON Web Key Set (JWKS) endpoint where IAM gets your
|
||||
* public keys" verifies it (IAM User Guide, Create an OpenID Connect (OIDC) identity provider in IAM).
|
||||
*
|
||||
* <p>The issuer's published keys are the network boundary, so the verifier that fetches them is
|
||||
* mocked; {@code JwtSignatureVerifierTest} covers the fetch itself.
|
||||
*/
|
||||
@QuarkusTest
|
||||
@TestProfile(SignedIamEnforcementProfile.class)
|
||||
class StsRegisteredOidcProviderIntegrationTest {
|
||||
|
||||
private static final String KEY_ID = "registered-key";
|
||||
private static final String SUBJECT = "repro";
|
||||
|
||||
private final ObjectMapper objectMapper = new ObjectMapper();
|
||||
private final List<String> sessions = new ArrayList<>();
|
||||
|
||||
@TestHTTPResource("/")
|
||||
URI endpoint;
|
||||
|
||||
@Inject
|
||||
IamService iamService;
|
||||
|
||||
@InjectMock
|
||||
JwtSignatureVerifier issuerKeys;
|
||||
|
||||
private RSAPrivateKey privateKey;
|
||||
private RSAPublicKey publicKey;
|
||||
private String issuer;
|
||||
private String providerArn;
|
||||
private SignedIamUsers.User admin;
|
||||
private IamClient iam;
|
||||
private StsClient sts;
|
||||
private Role role;
|
||||
|
||||
@BeforeEach
|
||||
void registerTheIssuer() throws Exception {
|
||||
KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA");
|
||||
generator.initialize(2048);
|
||||
KeyPair pair = generator.generateKeyPair();
|
||||
privateKey = (RSAPrivateKey) pair.getPrivate();
|
||||
publicKey = (RSAPublicKey) pair.getPublic();
|
||||
String host = "issuer-" + UUID.randomUUID().toString().substring(0, 8) + ".example.test";
|
||||
issuer = "https://" + host;
|
||||
|
||||
admin = SignedIamUsers.createUser(endpoint, "web-registered-", "admin",
|
||||
"{\"Statement\":{\"Effect\":\"Allow\",\"Action\":\"*\",\"Resource\":\"*\"}}");
|
||||
iam = IamClient.builder().endpointOverride(endpoint).region(Region.US_EAST_1)
|
||||
.credentialsProvider(StaticCredentialsProvider.create(AwsBasicCredentials.create(
|
||||
admin.accessKeyId(), admin.secretAccessKey()))).build();
|
||||
sts = StsClient.builder().endpointOverride(endpoint).region(Region.US_EAST_1)
|
||||
.credentialsProvider(AnonymousCredentialsProvider.create()).build();
|
||||
providerArn = iam.createOpenIDConnectProvider(b -> b.url(issuer).clientIDList("sts.amazonaws.com")
|
||||
.thumbprintList("0000000000000000000000000000000000000000")).openIDConnectProviderArn();
|
||||
String trust = "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Allow\",\"Principal\":{\"Federated\":\""
|
||||
+ providerArn + "\"},\"Action\":\"sts:AssumeRoleWithWebIdentity\",\"Condition\":{\"StringEquals\":{\""
|
||||
+ host + ":sub\":\"" + SUBJECT + "\"}}}]}";
|
||||
role = iam.createRole(b -> b.roleName("web-registered-" + UUID.randomUUID().toString().substring(0, 8))
|
||||
.assumeRolePolicyDocument(trust)).role();
|
||||
when(issuerKeys.signingKey(issuer, KEY_ID)).thenReturn(Optional.of(publicKey));
|
||||
}
|
||||
|
||||
@AfterEach
|
||||
void removeTheIssuer() throws Exception {
|
||||
try {
|
||||
for (String session : sessions) {
|
||||
iamService.unregisterSession("000000000000", session);
|
||||
}
|
||||
if (role != null) {
|
||||
iam.deleteRole(b -> b.roleName(role.roleName()));
|
||||
}
|
||||
} finally {
|
||||
try {
|
||||
if (providerArn != null) {
|
||||
iam.deleteOpenIDConnectProvider(b -> b.openIDConnectProviderArn(providerArn));
|
||||
}
|
||||
} finally {
|
||||
try {
|
||||
if (sts != null) {
|
||||
sts.close();
|
||||
}
|
||||
if (iam != null) {
|
||||
iam.close();
|
||||
}
|
||||
} finally {
|
||||
if (admin != null) {
|
||||
admin.close();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void tokenFromTheRegisteredIssuerAssumesTheRole() throws Exception {
|
||||
AssumeRoleWithWebIdentityResponse response = assume(token(issuer, "sts.amazonaws.com", privateKey));
|
||||
|
||||
assertEquals(SUBJECT, response.subjectFromWebIdentityToken());
|
||||
assertEquals(issuer, response.provider());
|
||||
assertEquals("sts.amazonaws.com", response.audience());
|
||||
}
|
||||
|
||||
@Test
|
||||
void tokenSignedWithAnotherKeyIsRefused() throws Exception {
|
||||
RSAPrivateKey forged = (RSAPrivateKey) KeyPairGenerator.getInstance("RSA").generateKeyPair().getPrivate();
|
||||
|
||||
StsException error = assertThrows(StsException.class,
|
||||
() -> assume(token(issuer, "sts.amazonaws.com", forged)));
|
||||
|
||||
assertEquals("InvalidIdentityToken", error.awsErrorDetails().errorCode());
|
||||
assertEquals(400, error.statusCode());
|
||||
}
|
||||
|
||||
@Test
|
||||
void tokenForAnAudienceTheProviderDoesNotListIsRefused() throws Exception {
|
||||
StsException error = assertThrows(StsException.class,
|
||||
() -> assume(token(issuer, "another-client", privateKey)));
|
||||
|
||||
assertEquals("InvalidIdentityToken", error.awsErrorDetails().errorCode());
|
||||
}
|
||||
|
||||
@Test
|
||||
void tokenFromAnIssuerWithoutAProviderIsRefused() throws Exception {
|
||||
String unregistered = "https://unregistered-" + UUID.randomUUID().toString().substring(0, 8) + ".example.test";
|
||||
when(issuerKeys.signingKey(unregistered, KEY_ID)).thenReturn(Optional.of(publicKey));
|
||||
|
||||
StsException error = assertThrows(StsException.class,
|
||||
() -> assume(token(unregistered, "sts.amazonaws.com", privateKey)));
|
||||
|
||||
assertEquals("InvalidIdentityToken", error.awsErrorDetails().errorCode());
|
||||
assertEquals("The web identity token issuer is not trusted.", error.awsErrorDetails().errorMessage());
|
||||
}
|
||||
|
||||
@Test
|
||||
void tokenWithoutAKeyIdIsRefusedAsAnInvalidToken() throws Exception {
|
||||
StsException error = assertThrows(StsException.class,
|
||||
() -> assume(token(issuer, "sts.amazonaws.com", privateKey, null)));
|
||||
|
||||
assertEquals("InvalidIdentityToken", error.awsErrorDetails().errorCode());
|
||||
assertEquals(400, error.statusCode());
|
||||
}
|
||||
|
||||
@Test
|
||||
void plainHttpIssuerDoesNotMatchTheHttpsProvider() throws Exception {
|
||||
String plainIssuer = "http://" + issuer.substring("https://".length());
|
||||
when(issuerKeys.signingKey(plainIssuer, KEY_ID)).thenReturn(Optional.of(publicKey));
|
||||
|
||||
StsException error = assertThrows(StsException.class,
|
||||
() -> assume(token(plainIssuer, "sts.amazonaws.com", privateKey)));
|
||||
|
||||
assertEquals("InvalidIdentityToken", error.awsErrorDetails().errorCode());
|
||||
}
|
||||
|
||||
@Test
|
||||
void issuerWhoseKeysCannotBeFetchedAnswersInvalidIdentityToken() throws Exception {
|
||||
when(issuerKeys.signingKey(issuer, KEY_ID))
|
||||
.thenThrow(new JwtSignatureVerifier.JwtVerificationException("connection refused"));
|
||||
|
||||
StsException error = assertThrows(StsException.class,
|
||||
() -> assume(token(issuer, "sts.amazonaws.com", privateKey)));
|
||||
|
||||
assertEquals("InvalidIdentityToken", error.awsErrorDetails().errorCode());
|
||||
assertEquals(400, error.statusCode());
|
||||
assertEquals("Couldn't retrieve verification key from your identity provider, please reference "
|
||||
+ "AssumeRoleWithWebIdentity documentation for requirements", error.awsErrorDetails().errorMessage());
|
||||
}
|
||||
|
||||
@Test
|
||||
void roleInAnotherAccountIsVerifiedByThatAccountsProvider() throws Exception {
|
||||
String otherAccount = "111122223333";
|
||||
String host = issuer.substring("https://".length());
|
||||
String otherRoleName = "web-registered-other-" + UUID.randomUUID().toString().substring(0, 8);
|
||||
OpenIDConnectProvider otherProvider = RequestScopes.callAs(otherAccount, () -> iamService
|
||||
.createOpenIDConnectProvider(issuer, List.of("sts.amazonaws.com"),
|
||||
List.of("0000000000000000000000000000000000000000"), Map.of()));
|
||||
String trust = "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Allow\",\"Principal\":{\"Federated\":\""
|
||||
+ otherProvider.getArn() + "\"},\"Action\":\"sts:AssumeRoleWithWebIdentity\",\"Condition\":{\"StringEquals\":{\""
|
||||
+ host + ":sub\":\"" + SUBJECT + "\"}}}]}";
|
||||
IamRole otherRole = RequestScopes.callAs(otherAccount, () -> iamService.createRole(otherRoleName, "/", trust,
|
||||
null, 3600, Map.of()));
|
||||
String token = token(issuer, "sts.amazonaws.com", privateKey);
|
||||
try {
|
||||
AssumeRoleWithWebIdentityResponse response = sts.assumeRoleWithWebIdentity(b -> b
|
||||
.roleArn(otherRole.getArn()).roleSessionName("registered").webIdentityToken(token));
|
||||
iamService.unregisterSession(otherAccount, response.credentials().accessKeyId());
|
||||
|
||||
assertEquals(SUBJECT, response.subjectFromWebIdentityToken());
|
||||
} finally {
|
||||
RequestScopes.callAs(otherAccount, () -> {
|
||||
iamService.deleteRole(otherRoleName);
|
||||
iamService.deleteOpenIDConnectProvider(otherProvider.getArn());
|
||||
return null;
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
private AssumeRoleWithWebIdentityResponse assume(String token) {
|
||||
AssumeRoleWithWebIdentityResponse response = sts.assumeRoleWithWebIdentity(b -> b.roleArn(role.arn())
|
||||
.roleSessionName("registered").webIdentityToken(token));
|
||||
sessions.add(response.credentials().accessKeyId());
|
||||
return response;
|
||||
}
|
||||
|
||||
private String token(String tokenIssuer, String audience, RSAPrivateKey signingKey)
|
||||
throws GeneralSecurityException {
|
||||
return token(tokenIssuer, audience, signingKey, KEY_ID);
|
||||
}
|
||||
|
||||
private String token(String tokenIssuer, String audience, RSAPrivateKey signingKey, String keyId)
|
||||
throws GeneralSecurityException {
|
||||
ObjectNode header = objectMapper.createObjectNode();
|
||||
header.put("alg", "RS256");
|
||||
header.put("typ", "JWT");
|
||||
if (keyId != null) {
|
||||
header.put("kid", keyId);
|
||||
}
|
||||
ObjectNode payload = objectMapper.createObjectNode();
|
||||
payload.put("iss", tokenIssuer);
|
||||
payload.put("sub", SUBJECT);
|
||||
payload.put("aud", audience);
|
||||
payload.put("exp", System.currentTimeMillis() / 1000 + 3600);
|
||||
String signingInput = Base64Url.encode(header.toString().getBytes(StandardCharsets.UTF_8)) + "."
|
||||
+ Base64Url.encode(payload.toString().getBytes(StandardCharsets.UTF_8));
|
||||
Signature signature = Signature.getInstance("SHA256withRSA");
|
||||
signature.initSign(signingKey);
|
||||
signature.update(signingInput.getBytes(StandardCharsets.UTF_8));
|
||||
return signingInput + "." + Base64Url.encode(signature.sign());
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user