diff --git a/.github/workflows/iam-data-drift.yml b/.github/workflows/iam-data-drift.yml index 76d985ffa8..5cd2ac733b 100644 --- a/.github/workflows/iam-data-drift.yml +++ b/.github/workflows/iam-data-drift.yml @@ -128,6 +128,9 @@ on: - 'tools/aws/sources/sts-session-tags.json' - 'tools/aws/fetch_sts_session_tags.py' - 'tools/aws/test_fetch_sts_session_tags.py' + - 'tools/aws/sources/sts-oidc-claim-keys.json' + - 'tools/aws/fetch_sts_oidc_claim_keys.py' + - 'tools/aws/test_fetch_sts_oidc_claim_keys.py' - 'tools/aws/fetch_secretsmanager_required_permissions.py' - 'tools/aws/sources/secretsmanager-required-permissions.json' - 'tools/aws/test_fetch_secretsmanager_required_permissions.py' diff --git a/Makefile b/Makefile index 312f4feca5..2ed048e32e 100644 --- a/Makefile +++ b/Makefile @@ -651,6 +651,8 @@ IAM_AUTHORIZED_ACTIONS_PATHS := src/main/resources/aws/iam-authorized-actions.js tools/aws/sources/sts-source-identity.json tools/aws/fetch_sts_source_identity.py \ tools/aws/test_fetch_sts_source_identity.py tools/aws/sources/sts-session-tags.json \ tools/aws/fetch_sts_session_tags.py tools/aws/test_fetch_sts_session_tags.py \ + tools/aws/sources/sts-oidc-claim-keys.json tools/aws/fetch_sts_oidc_claim_keys.py \ + tools/aws/test_fetch_sts_oidc_claim_keys.py \ tools/aws/sources/secretsmanager-required-permissions.json tools/aws/fetch_secretsmanager_required_permissions.py \ tools/aws/test_fetch_secretsmanager_required_permissions.py \ tools/aws/sources/lambda-response-permissions.json tools/aws/fetch_lambda_response_permissions.py \ diff --git a/docs/services/sts.md b/docs/services/sts.md index a9e0f14e99..3676f0a321 100644 --- a/docs/services/sts.md +++ b/docs/services/sts.md @@ -511,11 +511,18 @@ A federated trust policy's `Condition` is read by the condition engine every oth `ForAnyValue`), `...IfExists` and `Null` among them, with their usual reading of a key the request does not carry. Its context holds the assertion's claims under the Service Authorization Reference's `saml:` keys (`saml:aud`, `saml:sub`, `saml:iss`, `saml:namequalifier`), or the token's under its -issuer's prefix (`:sub`, `:aud`), each read under that prefix alone, -`sts:RoleSessionName`, the role's tags, the request tags and the source identity. `:aud` is -the one audience the token was accepted for, the one the response returns as `Audience`, wherever -the token's list names it: the Service Authorization Reference types the key `String`, a single -value. A key that is multivalued, as `aws:TagKeys` is, takes a set operator, as AWS says +issuer's prefix, each read under that prefix alone, `sts:RoleSessionName`, the role's tags, the +request tags and the source identity. The token's keys are those the IAM User Guide's Default mapping +gives, which it says to "use ... if your IdP is not listed in the tab options": `:sub`, +`:aud`, `:oaud`, `:amr` and `:email`, each read from the claim the +guide names, and absent where the token sets none. `:aud` is the one audience the token was +accepted for, the one the response returns as `Audience`: its `azp` where it sets one, as "AWS STS +will use the value in the azp claim as the aud claim", or else the one of its `aud` list the +provider lists, wherever the list names it, as the Service Authorization Reference types the key +`String`, a single value. `:oaud` is the token's `aud`, each audience its list names, whether +or not the token sets `azp`, and `:amr` each value of its `amr`. `webIdentityClaims` in the +generated `iam-authorized-actions.json` gives the mapping, from the guide's pages vendored by +`tools/aws/fetch_sts_oidc_claim_keys.py`. A key that is multivalued, as `aws:TagKeys` is, takes a set operator, as AWS says "multivalued context keys require a condition set operator", and a negated operator over an empty list of values holds, the NOR of no values. @@ -732,6 +739,11 @@ AssumeRoleWithSAML does not require the use of AWS security credentials", and so `SourceIdentity` attribute carrying several values or one outside botocore's type, and a token's `source_identity` claim that is not one such string, answer `InvalidIdentityToken` with a sentence of Floci's own: nothing published says what AWS answers. +- **A token's claims are read by the Default mapping alone, and for the trust policy alone.** The + IAM User Guide gives some identity providers a mapping of their own, GitHub's + `token.actions.githubusercontent.com:repository` or Amazon Cognito's `aud` read without `azp` + among them, which Floci does not read yet. The keys the guide marks available in session are not + carried into the session's later requests. ## Web Identity Validation (IRSA) @@ -741,9 +753,9 @@ When the token's `iss` names a known Floci issuer, all of the following are enfo - the RS256 signature, against the issuer's public key - `iss` matches that issuer exactly -- `aud` contains `sts.amazonaws.com` +- `aud` contains `sts.amazonaws.com`, or `azp` is `sts.amazonaws.com` where the token sets one - `exp` / `nbf`, with 60s of clock-skew tolerance -- the role's trust policy: `Principal.Federated` plus the `Condition` block, comparing `:sub`, `:aud` and `sts:RoleSessionName` (the request's `RoleSessionName`) with exact, **case-sensitive** equality (`StringEquals`, `StringNotEquals`, `StringLike`, and `StringNotLike` are supported) +- the role's trust policy: `Principal.Federated` plus the `Condition` block, comparing the token's claims under the keys described above (`:sub`, `:aud` and the rest of the IAM User Guide's Default mapping) and `sts:RoleSessionName` (the request's `RoleSessionName`) with exact, **case-sensitive** equality (`StringEquals`, `StringNotEquals`, `StringLike`, and `StringNotLike` are supported) 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). @@ -754,7 +766,7 @@ By default, tokens from an issuer Floci does not host, or tokens that are not pa 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 `/.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. +- `azp`, or `aud` where the token sets no `azp`, must hold one of the provider's client IDs, as "AWS STS will use the value in the azp claim as the aud claim", 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. diff --git a/src/main/java/io/floci/aws/core/common/WebIdentityToken.java b/src/main/java/io/floci/aws/core/common/WebIdentityToken.java index 88b53c658a..dc69b98a21 100644 --- a/src/main/java/io/floci/aws/core/common/WebIdentityToken.java +++ b/src/main/java/io/floci/aws/core/common/WebIdentityToken.java @@ -11,7 +11,8 @@ import java.util.Map; * * @param issuer the {@code iss} claim * @param subject the {@code sub} claim. For IRSA, {@code system:serviceaccount::} - * @param audiences the {@code aud} claim, normalized to a list (JWT allows string or array) + * @param audiences the claim the token's audience is read from, {@code aud} unless the verifier was given others + * ({@code azp} before {@code aud} for AWS STS), normalized to a list (JWT allows string or array) * @param principalTags the session tags the token passes, from either of the two claim formats * AWS publishes for them, and empty when it passes none * @param transitiveTagKeys the keys among those tags the token asks to set as transitive, from diff --git a/src/main/java/io/floci/aws/core/common/WebIdentityTokenVerifier.java b/src/main/java/io/floci/aws/core/common/WebIdentityTokenVerifier.java index 6159b6a8ea..cc68bef87f 100644 --- a/src/main/java/io/floci/aws/core/common/WebIdentityTokenVerifier.java +++ b/src/main/java/io/floci/aws/core/common/WebIdentityTokenVerifier.java @@ -39,6 +39,8 @@ public class WebIdentityTokenVerifier { /** Tolerance for clock drift between Floci and a token minted elsewhere. */ private static final long CLOCK_SKEW_SECONDS = 60; + /** The claim a JWT names its audiences in, RFC 7519's {@code aud}. */ + private static final String AUDIENCE_CLAIM = "aud"; /** * The namespace AWS publishes a token's session tags under, whichever format they take: the claim the generated * {@code iam-authorized-actions.json} gives AssumeRoleWithWebIdentity's session tags, from the IAM user guide's @@ -120,6 +122,17 @@ public class WebIdentityTokenVerifier { */ public WebIdentityToken verify(String token, RSAPublicKey publicKey, String expectedIssuer, List acceptedAudiences) throws InvalidTokenException { + return verify(token, publicKey, expectedIssuer, acceptedAudiences, List.of(AUDIENCE_CLAIM)); + } + + /** + * As {@link #verify(String, RSAPublicKey, String, List)}, the token's audience read from the first of + * {@code audienceClaims} the token sets ({@link #audienceClaim}): AWS STS reads it from {@code azp} where a + * token sets both, as the generated {@code iam-authorized-actions.json} gives it. + */ + public WebIdentityToken verify(String token, RSAPublicKey publicKey, String expectedIssuer, + List acceptedAudiences, List audienceClaims) + 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); @@ -148,7 +161,7 @@ public class WebIdentityTokenVerifier { + "OIDC provider: " + issuer); } - List audiences = readAudiences(claims); + List audiences = readAudiences(claims, audienceClaim(claims, audienceClaims)); if (audiences.stream().noneMatch(acceptedAudiences::contains)) { throw new InvalidTokenException("The web identity token audience does not include " + String.join(" or ", acceptedAudiences)); @@ -286,9 +299,17 @@ public class WebIdentityTokenVerifier { + " does not carry a single value"); } - private List readAudiences(JsonNode claims) { + /** + * The first of {@code audienceClaims} that {@code claims} sets, which the token's audience is read from, or null + * when it sets none of them. + */ + private static String audienceClaim(JsonNode claims, List audienceClaims) { + return audienceClaims.stream().filter(claims::hasNonNull).findFirst().orElse(null); + } + + private List readAudiences(JsonNode claims, String claim) { List audiences = new ArrayList<>(); - JsonNode aud = claims.get("aud"); + JsonNode aud = claim == null ? null : claims.get(claim); if (aud == null) { return audiences; } diff --git a/src/main/java/io/floci/aws/services/iam/IamAuthorizedActions.java b/src/main/java/io/floci/aws/services/iam/IamAuthorizedActions.java index 19d1416ea1..87bb778c14 100644 --- a/src/main/java/io/floci/aws/services/iam/IamAuthorizedActions.java +++ b/src/main/java/io/floci/aws/services/iam/IamAuthorizedActions.java @@ -17,6 +17,7 @@ import java.util.Locale; import java.util.Map; import java.util.Optional; import java.util.Set; +import java.util.regex.Pattern; /** * The IAM action AWS checks for an operation whose action is not the operation's own name, read once @@ -74,6 +75,8 @@ public final class IamAuthorizedActions { private static final Set KEPT_FOR_ITEM_CHECKS = Set.of("dynamodb:TransactGetItems"); private static final ObjectMapper MAPPER = JacksonConfig.jsonMapper(); + /** A JWT claim's name, and the name a condition key gives it after the issuer's host and path. */ + private static final Pattern CLAIM = Pattern.compile("[a-z][a-z0-9_]*"); /** * The file: the action of each operation it names, keyed by {@code :}, the actions of @@ -82,12 +85,37 @@ public final class IamAuthorizedActions { * {@code :@}, the operations whose action a request parameter chooses, and the * reference's spelling of an action named as its operation in another case, the actions each operation needs * beside its own when it sets a value, and those it needs on each entry it reads, keyed by - * {@code :}. + * {@code :}, and the condition keys a web identity token's claims are read as. */ record Table(Map actions, Set withoutResourceTypes, Set byMethod, Map byModel, Map versioned, Map spellings, Map> companions, Map> perEntry, - Map> returnedOnlyIf) { + Map> returnedOnlyIf, WebIdentityClaims webIdentityClaims) { + } + + /** + * How a web identity token's claims are read as the condition keys of a role's trust policy, as the IAM User + * Guide's Default mapping gives them for an identity provider it gives no mapping of its own: each key + * ({@code keys}), and the claims the token's audience is read from, the one AWS STS uses in place of the other + * first ({@code audience}): "AWS STS will use the value in the azp claim as the aud claim". + */ + public record WebIdentityClaims(List keys, List audience) { + } + + /** + * A condition key a web identity token's {@code claim} is read as, under the issuer's host and path, and the claim + * it is read from when that claim has no value, or null where the guide names none: "If no value is set for azp, + * the aud condition key maps to the aud claim". + */ + public record ClaimKey(String key, String claim, String otherwise) { + + /** + * Whether the key reads the claims a token's audience is read from, in their order, as the guide's {@code aud} + * reads {@code azp} and then {@code aud}: the key that holds the one audience the token was accepted for. + */ + public boolean readsAudience(List audience) { + return otherwise != null && audience.equals(List.of(claim, otherwise)); + } } /** @@ -255,6 +283,11 @@ public final class IamAuthorizedActions { .findFirst(); } + /** How a web identity token's claims are read as condition keys; no keys where the file gives none. */ + public static WebIdentityClaims webIdentityClaims() { + return Holder.TABLE.webIdentityClaims(); + } + /** The file's entries. */ static Table parse(InputStream in) throws IOException { JsonNode document = MAPPER.readTree(in); @@ -283,7 +316,36 @@ public final class IamAuthorizedActions { byMethod(document.path("authorizedByMethod")), byModel(document.path("authorizedByModel")), versioned(document.path("versioned")), spellings(document.path("spellings")), companions(document.path("companions")), perEntry(document.path("perEntry")), - returnedOnlyIf(document.path("returnedOnlyIf"))); + returnedOnlyIf(document.path("returnedOnlyIf")), webIdentityClaims(document.path("webIdentityClaims"))); + } + + /** The condition keys a web identity token's claims are read as, and the claims its audience is read from. */ + private static WebIdentityClaims webIdentityClaims(JsonNode claims) { + if (claims.isMissingNode()) { + return new WebIdentityClaims(List.of(), List.of()); + } + List keys = new ArrayList<>(); + Set seen = new HashSet<>(); + for (JsonNode row : claims.path("default")) { + String key = JsonNodes.asText(row.path("key"), ""); + String claim = JsonNodes.asText(row.path("claim"), ""); + String otherwise = JsonNodes.asText(row.path("otherwise"), null); + if (!CLAIM.matcher(key).matches() || !CLAIM.matcher(claim).matches() + || otherwise != null && !CLAIM.matcher(otherwise).matches() || !seen.add(key)) { + throw new IllegalStateException(RESOURCE_NAME + " gives webIdentityClaims the key " + row + + ", which is not a key named once with the claim it is read from"); + } + keys.add(new ClaimKey(key, claim, otherwise)); + } + List audience = claims.path("audience").valueStream().map(claim -> JsonNodes.asText(claim, "")) + .toList(); + if (keys.isEmpty() || audience.size() != 2 || audience.stream().anyMatch(claim -> !CLAIM.matcher(claim) + .matches()) || audience.get(0).equals(audience.get(1)) + || keys.stream().filter(key -> key.readsAudience(audience)).count() != 1) { + throw new IllegalStateException(RESOURCE_NAME + " gives webIdentityClaims " + claims + + ", which are not keys, one of them reading the two claims a token's audience is read from"); + } + return new WebIdentityClaims(List.copyOf(keys), audience); } /** Each namespace's operations' members returned only with an action, keyed {@code :}. */ diff --git a/src/main/java/io/floci/aws/services/iam/StsQueryHandler.java b/src/main/java/io/floci/aws/services/iam/StsQueryHandler.java index 0049494e8b..3ea9c0b940 100644 --- a/src/main/java/io/floci/aws/services/iam/StsQueryHandler.java +++ b/src/main/java/io/floci/aws/services/iam/StsQueryHandler.java @@ -1015,6 +1015,40 @@ public class StsQueryHandler { } } + /** + * The token's claims as the condition keys the generated {@code iam-authorized-actions.json} reads them as, the IAM + * User Guide's Default mapping, each named without the issuer's prefix: a key reads its claim, or the claim its row + * names when that claim has no value ("If no value is set for azp, the aud condition key maps to the aud claim"), + * and is absent where the token sets neither. The key reading the claims the token's audience is read from, in + * their order ({@link IamAuthorizedActions.ClaimKey#readsAudience}), holds the one audience the token was accepted + * for, whatever else the claim lists, as the Service Authorization Reference types the key String, where + * "multivalued context keys ... use an ArrayOf prefix". Any other key holds its claim's value, or each value of an + * array, whether or not the audience was read from that claim: {@code oaud} every audience the token's {@code aud} + * lists, and {@code amr}, which the guide says "is multivalued", each of its values. + */ + static Map> claimKeys(JsonNode payload, IamAuthorizedActions.WebIdentityClaims mapping, + String audience) { + Map> keys = new LinkedHashMap<>(); + for (IamAuthorizedActions.ClaimKey key : mapping.keys()) { + String claim = payload.hasNonNull(key.claim()) || key.otherwise() == null ? key.claim() : key.otherwise(); + List values = key.readsAudience(mapping.audience()) ? List.of(audience) + : claimValues(payload.path(claim)); + if (!values.isEmpty()) { + keys.put(key.key(), values); + } + } + return keys; + } + + /** A claim's value, or each value of an array claim, as text; none for a claim missing, null or an object. */ + private static List claimValues(JsonNode claim) { + if (claim.isArray()) { + return claim.valueStream().filter(value -> value.isValueNode() && !value.isNull()) + .map(JsonNodes::asText).toList(); + } + return claim.isValueNode() && !claim.isNull() ? List.of(JsonNodes.asText(claim)) : List.of(); + } + /** * Inspects {@code token} and decides whether it may assume {@code roleArn} as the session * {@code sessionName}, which the trust policy reads as {@code sts:RoleSessionName}. @@ -1064,9 +1098,10 @@ public class StsQueryHandler { : WebIdentityOutcome.unverifiable(); } + IamAuthorizedActions.WebIdentityClaims claimKeys = IamAuthorizedActions.webIdentityClaims(); WebIdentityToken claims; try { - claims = tokenVerifier.verify(token, key.get(), issuer.get(), acceptedAudiences); + claims = tokenVerifier.verify(token, key.get(), issuer.get(), acceptedAudiences, claimKeys.audience()); } catch (WebIdentityTokenVerifier.ExpiredTokenException e) { LOG.debugv("Rejecting web identity token for role {0}: {1}", roleArn, e.getMessage()); return WebIdentityOutcome.deny(AwsQueryResponse.error("ExpiredTokenException", @@ -1083,15 +1118,12 @@ public class StsQueryHandler { return WebIdentityOutcome.deny(accessDenied(roleArn)); } - // The audience the token was accepted for, which is the one value of the trust policy's aud key as it is of - // the response's Audience: the Service Authorization Reference types the key String, where "multivalued - // context keys ... use an ArrayOf prefix", and "AWS STS will use the value in the azp claim as the aud - // claim". verify() already required the audience list to hold one of the accepted audiences. + // The audience the token was accepted for, the response's Audience, read from the claim the generated table + // names first among those the token sets: "AWS STS will use the value in the azp claim as the aud claim". + // verify() already required it to be one of the accepted audiences. String audience = claims.audiences().stream().filter(acceptedAudiences::contains).findFirst() .orElse(STS_AUDIENCE); - Map> conditionClaims = Map.of( - "sub", List.of(claims.subject()), - "aud", List.of(audience)); + Map> conditionClaims = claimKeys(claims.claims(), claimKeys, audience); // The source identity the token sets, which the generated table says it carries in a claim of its own: // "include source identity in the https://aws.amazon.com/source_identity namespace in the token". The trust diff --git a/src/main/resources/aws/iam-authorized-actions.json b/src/main/resources/aws/iam-authorized-actions.json index 14b957b046..586ca4c631 100644 --- a/src/main/resources/aws/iam-authorized-actions.json +++ b/src/main/resources/aws/iam-authorized-actions.json @@ -2,7 +2,7 @@ "_source": { "generator": "tools/aws/regen_iam_authorized_actions.py", "reference": "https://servicereference.us-east-1.amazonaws.com/", - "retrieved": "2026-12-04", + "retrieved": "2026-12-05", "note": "make iam-authorized-actions-verify checks every entry against AWS." }, "authorizedActions": { @@ -2078,5 +2078,34 @@ } ] } + }, + "webIdentityClaims": { + "default": [ + { + "key": "amr", + "claim": "amr" + }, + { + "key": "aud", + "claim": "azp", + "otherwise": "aud" + }, + { + "key": "email", + "claim": "email" + }, + { + "key": "oaud", + "claim": "aud" + }, + { + "key": "sub", + "claim": "sub" + } + ], + "audience": [ + "azp", + "aud" + ] } } diff --git a/src/test/java/io/floci/aws/core/common/WebIdentityTokenVerifierTest.java b/src/test/java/io/floci/aws/core/common/WebIdentityTokenVerifierTest.java index 3eff979cdb..7996877184 100644 --- a/src/test/java/io/floci/aws/core/common/WebIdentityTokenVerifierTest.java +++ b/src/test/java/io/floci/aws/core/common/WebIdentityTokenVerifierTest.java @@ -155,6 +155,35 @@ class WebIdentityTokenVerifierTest { () -> verifier.verify(token, publicKey(), ISSUER, EksOidcService.STS_AUDIENCE)); } + /** + * Given the claims its audience is read from, the first the token sets is the audience: "AWS STS will use the + * value in the azp claim as the aud claim". A token whose {@code azp} is a client ID the provider lists is accepted + * whatever its {@code aud}, and one whose {@code azp} is not is refused though its {@code aud} is; one setting no + * {@code azp} is read by its {@code aud}. Without them, {@code aud} alone is read, as for an EKS Pod Identity + * token. + */ + @Test + void readsTheAudienceFromTheFirstOfTheClaimsItIsGivenThatTheTokenSets() throws Exception { + KeyPair keyPair = newKeyPair(); + RSAPublicKey key = (RSAPublicKey) keyPair.getPublic(); + List accepted = List.of(EksOidcService.STS_AUDIENCE); + List audienceClaims = List.of("azp", "aud"); + long now = System.currentTimeMillis() / 1000; + String byAzp = signRs256(keyPair.getPrivate(), "{\"iss\":\"" + ISSUER + "\",\"aud\":\"web-client\"," + + "\"azp\":\"" + EksOidcService.STS_AUDIENCE + "\",\"sub\":\"s\",\"exp\":" + (now + 3600) + "}"); + assertEquals(accepted, verifier.verify(byAzp, key, ISSUER, accepted, audienceClaims).audiences()); + assertThrows(WebIdentityTokenVerifier.InvalidTokenException.class, + () -> verifier.verify(byAzp, key, ISSUER, accepted)); + + String otherAzp = signRs256(keyPair.getPrivate(), claims("\"azp\":\"web-client\"")); + assertThrows(WebIdentityTokenVerifier.InvalidTokenException.class, + () -> verifier.verify(otherAzp, key, ISSUER, accepted, audienceClaims)); + assertEquals(accepted, verifier.verify(otherAzp, key, ISSUER, accepted).audiences()); + + String noAzp = signRs256(keyPair.getPrivate(), claims("\"iat\":" + now)); + assertEquals(accepted, verifier.verify(noAzp, key, ISSUER, accepted, audienceClaims).audiences()); + } + @Test void rejectsExpiredToken() throws Exception { // Signed with a locally generated key so the payload can carry an arbitrary past expiry; diff --git a/src/test/java/io/floci/aws/services/iam/IamAuthorizedActionsTest.java b/src/test/java/io/floci/aws/services/iam/IamAuthorizedActionsTest.java index eb99a12a7b..9f423ee385 100644 --- a/src/test/java/io/floci/aws/services/iam/IamAuthorizedActionsTest.java +++ b/src/test/java/io/floci/aws/services/iam/IamAuthorizedActionsTest.java @@ -114,6 +114,50 @@ class IamAuthorizedActionsTest { assertEquals(Map.of("memorydb:CreateACL", "memorydb:CreateAcl"), parsed.spellings()); } + /** + * The file reads a web identity token's claims as the IAM User Guide's Default mapping gives them, and its + * audience from {@code azp} before {@code aud}: "AWS STS will use the value in the azp claim as the aud claim". + */ + @Test + void theFileGivesTheDefaultMappingOfAWebIdentityTokensClaims() { + IamAuthorizedActions.WebIdentityClaims claims = IamAuthorizedActions.webIdentityClaims(); + assertEquals(List.of(new IamAuthorizedActions.ClaimKey("amr", "amr", null), + new IamAuthorizedActions.ClaimKey("aud", "azp", "aud"), + new IamAuthorizedActions.ClaimKey("email", "email", null), + new IamAuthorizedActions.ClaimKey("oaud", "aud", null), + new IamAuthorizedActions.ClaimKey("sub", "sub", null)), claims.keys()); + assertEquals(List.of("azp", "aud"), claims.audience()); + } + + @Test + void aMalformedWebIdentityClaimMappingIsRefused() throws IOException { + String base = "\"authorizedActions\": {\"sqs\": {\"A\": \"sqs:B\"}}, \"actionsWithoutResourceTypes\": {}, " + + "\"authorizedByMethod\": {}, "; + assertEquals(new IamAuthorizedActions.WebIdentityClaims(List.of(), List.of()), + IamAuthorizedActions.parse(json("{" + base.substring(0, base.length() - 2) + "}")).webIdentityClaims()); + for (String claims : List.of("{\"default\": [], \"audience\": [\"azp\", \"aud\"]}", + "{\"default\": [{\"key\": \"sub\", \"claim\": \"sub\"}], \"audience\": [\"aud\"]}", + "{\"default\": [{\"key\": \"sub\", \"claim\": \"sub\"}], \"audience\": [\"aud\", \"aud\"]}", + "{\"default\": [{\"key\": \"sub\"}], \"audience\": [\"azp\", \"aud\"]}", + "{\"default\": [{\"key\": \"Sub\", \"claim\": \"sub\"}], \"audience\": [\"azp\", \"aud\"]}", + "{\"default\": [{\"key\": \"sub\", \"claim\": \"sub\"}, {\"key\": \"sub\", \"claim\": \"aud\"}], " + + "\"audience\": [\"azp\", \"aud\"]}")) { + assertThrows(IllegalStateException.class, () -> IamAuthorizedActions.parse(json("{" + base + + "\"webIdentityClaims\": " + claims + "}")), claims); + } + // One key reads the audience claims in their order: the one holding the audience the token was accepted for. + String reader = "{\"key\": \"aud\", \"claim\": \"azp\", \"otherwise\": \"aud\"}"; + String sub = "{\"key\": \"sub\", \"claim\": \"sub\"}, "; + assertEquals(2, IamAuthorizedActions.parse(json("{" + base + "\"webIdentityClaims\": {\"default\": [" + sub + + reader + "], \"audience\": [\"azp\", \"aud\"]}}")).webIdentityClaims().keys().size()); + for (String rows : List.of(sub + "{\"key\": \"aud\", \"claim\": \"aud\"}", + sub + "{\"key\": \"aud\", \"claim\": \"aud\", \"otherwise\": \"azp\"}", + reader + ", " + reader.replace("\"key\": \"aud\"", "\"key\": \"oaud\""))) { + assertThrows(IllegalStateException.class, () -> IamAuthorizedActions.parse(json("{" + base + + "\"webIdentityClaims\": {\"default\": [" + rows + "], \"audience\": [\"azp\", \"aud\"]}}")), rows); + } + } + @Test void aMalformedModelVersionOrSpellingEntryIsRefused() { String base = "\"authorizedActions\": {\"sqs\": {\"A\": \"sqs:B\"}}, \"actionsWithoutResourceTypes\": {}, " diff --git a/src/test/java/io/floci/aws/services/iam/StsQueryHandlerTest.java b/src/test/java/io/floci/aws/services/iam/StsQueryHandlerTest.java index c7d3ef9d91..3c611e58a7 100644 --- a/src/test/java/io/floci/aws/services/iam/StsQueryHandlerTest.java +++ b/src/test/java/io/floci/aws/services/iam/StsQueryHandlerTest.java @@ -2,6 +2,7 @@ package io.floci.aws.services.iam; import io.floci.aws.config.EmulatorConfig; import io.floci.aws.core.common.AccountResolver; +import io.floci.aws.core.common.JacksonConfig; import io.floci.aws.core.common.OidcIssuerKeyLookup; import io.floci.aws.core.common.RegionResolver; import io.floci.aws.core.common.RequestContext; @@ -24,6 +25,7 @@ import org.junit.jupiter.params.provider.CsvSource; import org.junit.jupiter.params.provider.MethodSource; import org.junit.jupiter.params.provider.ValueSource; import org.mockito.ArgumentCaptor; +import tools.jackson.databind.JsonNode; import java.security.interfaces.RSAPublicKey; import java.time.Clock; @@ -667,6 +669,26 @@ class StsQueryHandlerTest { any(), eq("000000000000"), eq("test-session"), eq("AROA-test:test-session")); } + /** + * A token's claims are the keys the generated table's Default mapping gives them: each key its claim, or the claim + * its row names when that claim has no value, and none where the token sets neither. The key reading the audience + * claims holds the one audience the token was accepted for; any other its claim's value as text, or each value of + * an array, {@code oaud} every audience the token lists even where the audience was read from {@code aud}. + */ + @Test + void aWebIdentityTokensClaimsAreTheKeysTheGeneratedTableGivesThem() { + IamAuthorizedActions.WebIdentityClaims mapping = IamAuthorizedActions.webIdentityClaims(); + JsonNode hybrid = JacksonConfig.jsonMapper().readTree("{\"sub\":\"s\",\"aud\":\"web\",\"azp\":\"android\"," + + "\"amr\":[\"authenticated\",\"accounts.google.com\"],\"email\":\"a@example.test\"}"); + assertEquals(Map.of("sub", List.of("s"), "aud", List.of("android"), "oaud", List.of("web"), + "amr", List.of("authenticated", "accounts.google.com"), "email", List.of("a@example.test")), + StsQueryHandler.claimKeys(hybrid, mapping, "android")); + JsonNode listed = JacksonConfig.jsonMapper().readTree("{\"sub\":7,\"aud\":[\"other\",\"sts.amazonaws.com\"]}"); + assertEquals(Map.of("sub", List.of("7"), "aud", List.of("sts.amazonaws.com"), + "oaud", List.of("other", "sts.amazonaws.com")), + StsQueryHandler.claimKeys(listed, mapping, "sts.amazonaws.com")); + } + @Test void roleArnMatchesValidatesPartitionsAndPaths() { IamRole role = new IamRole(); @@ -1133,7 +1155,8 @@ 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), anyList())) + // The token's audience is read from the claims the generated table names, azp before aud. + when(verifier.verify(eq("jwt0"), any(), eq(issuer), anyList(), eq(List.of("azp", "aud")))) .thenReturn(new WebIdentityToken(issuer, "system:serviceaccount:default:app", List.of("sts.amazonaws.com"), Map.of("Project", "atlas"), List.of("Project"))); diff --git a/src/test/java/io/floci/aws/services/iam/StsRegisteredOidcProviderIntegrationTest.java b/src/test/java/io/floci/aws/services/iam/StsRegisteredOidcProviderIntegrationTest.java index 70b7873c6a..f53d490018 100644 --- a/src/test/java/io/floci/aws/services/iam/StsRegisteredOidcProviderIntegrationTest.java +++ b/src/test/java/io/floci/aws/services/iam/StsRegisteredOidcProviderIntegrationTest.java @@ -344,6 +344,76 @@ class StsRegisteredOidcProviderIntegrationTest { } } + /** + * A token's {@code oaud} key holds every audience its {@code aud} lists, whether or not it sets {@code azp}, while + * its {@code aud} key holds the one audience it was accepted for: a trust policy denying a token that lists another + * client refuses the token listing it beside the accepted one, and allows a token listing the accepted one alone. + */ + @Test + void theOriginalAudienceKeyHoldsEveryAudienceTheTokenLists() throws Exception { + String host = issuer.substring("https://".length()); + String federated = "\"Principal\":{\"Federated\":\"" + providerArn + "\"}," + + "\"Action\":\"sts:AssumeRoleWithWebIdentity\","; + String trust = "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Allow\"," + federated + + "\"Condition\":{\"StringEquals\":{\"" + host + ":aud\":\"sts.amazonaws.com\"}}}," + + "{\"Effect\":\"Deny\"," + federated + "\"Condition\":{\"ForAnyValue:StringEquals\":{\"" + host + + ":oaud\":\"web-client\"}}}]}"; + Role role = iam.createRole(b -> b.roleName("web-oaud-" + UUID.randomUUID().toString().substring(0, 8)) + .assumeRolePolicyDocument(trust)).role(); + try { + ObjectNode listing = objectMapper.createObjectNode(); + listing.putArray("aud").add("web-client").add("sts.amazonaws.com"); + StsException refused = assertThrows(StsException.class, () -> assume(role, token(issuer, + "sts.amazonaws.com", privateKey, KEY_ID, listing))); + assertEquals(403, refused.statusCode()); + assertEquals("sts.amazonaws.com", assume(role, token(issuer, "sts.amazonaws.com", privateKey)).audience()); + } finally { + iam.deleteRole(b -> b.roleName(role.roleName())); + } + } + + /** + * A token's claims are the keys the IAM User Guide's Default mapping gives them. A token setting {@code azp}, as a + * hybrid app's does, is accepted for that client ID, which the provider lists, whatever its {@code aud}, and its + * keys are those of the guide's example: "The azp field value matches the accounts.google.com:aud condition key + * value", while "the Google ID Token aud field value matches only the accounts.google.com:oaud condition key + * value". Its {@code email} is read as the claim gives it, and its {@code amr}, which the guide says "is + * multivalued", with a set operator. A token whose {@code azp} the provider does not list is refused though its + * {@code aud} is listed, and one passing another email is refused by the trust policy. + */ + @Test + void aTokensClaimsAreTheKeysTheGuidesDefaultMappingGivesThem() throws Exception { + String host = issuer.substring("https://".length()); + String trust = "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Allow\",\"Principal\":{" + + "\"Federated\":\"" + providerArn + "\"},\"Action\":\"sts:AssumeRoleWithWebIdentity\"," + + "\"Condition\":{\"StringEquals\":{\"" + host + ":aud\":\"sts.amazonaws.com\",\"" + host + + ":oaud\":\"web-client\",\"" + host + ":email\":\"dev@example.test\"}," + + "\"ForAnyValue:StringEquals\":{\"" + host + ":amr\":\"authenticated\"}}}]}"; + Role mapped = iam.createRole(b -> b.roleName("web-claims-" + UUID.randomUUID().toString().substring(0, 8)) + .assumeRolePolicyDocument(trust)).role(); + try { + assertEquals("sts.amazonaws.com", assume(mapped, token(issuer, "web-client", privateKey, KEY_ID, + claims("sts.amazonaws.com", "dev@example.test"))).audience()); + StsException otherAzp = assertThrows(StsException.class, () -> assume(mapped, token(issuer, + "sts.amazonaws.com", privateKey, KEY_ID, claims("web-client", "dev@example.test")))); + assertEquals("InvalidIdentityToken", otherAzp.awsErrorDetails().errorCode()); + StsException otherEmail = assertThrows(StsException.class, () -> assume(mapped, token(issuer, + "web-client", privateKey, KEY_ID, claims("sts.amazonaws.com", "ops@example.test")))); + assertEquals(403, otherEmail.statusCode()); + } finally { + iam.deleteRole(b -> b.roleName(mapped.roleName())); + } + } + + /** A hybrid app's claims: {@code azp}, an authenticated {@code amr} and {@code email}. */ + private ObjectNode claims(String azp, String email) { + ObjectNode claims = objectMapper.createObjectNode(); + claims.put("azp", azp); + claims.putArray("amr").add("authenticated").add("accounts.google.com"); + claims.put("email", email); + return claims; + } + private Role audienceRole(String host, String operator) { String trust = "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Allow\",\"Principal\":{" + "\"Federated\":\"" + providerArn + "\"},\"Action\":\"sts:AssumeRoleWithWebIdentity\"," diff --git a/tools/aws/fetch_sts_oidc_claim_keys.py b/tools/aws/fetch_sts_oidc_claim_keys.py new file mode 100644 index 0000000000..13cbe1c287 --- /dev/null +++ b/tools/aws/fetch_sts_oidc_claim_keys.py @@ -0,0 +1,205 @@ +#!/usr/bin/env python3 +"""Vendor how the IAM User Guide maps an OIDC token's claims to the condition keys a role's trust policy reads into +tools/aws/sources/sts-oidc-claim-keys.json, a source of the IAM authorized actions table. + +The IAM User Guide's page on condition keys has, under "Available keys for AWS OIDC federation", a Default tab, which +"lists the standard OIDC claims and how they map to AWS STS condition context keys in AWS", and says "Use this mapping if +your IdP is not listed in the tab options". Its table gives each key, the claim it is read from and whether it is +available in session: + + AWS STS condition key IdP JWT claim Available in session + amr amr Yes + aud azp Yes + If no value is set for azp, the aud condition key maps to the aud claim. + email email No + oaud aud No + sub sub Yes + + https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_iam-condition-keys.html#condition-keys-wif + +The page on creating an OIDC identity provider says which claim a token's audience, the client ID the provider is +registered with, is read from: + + If your OIDC identity provider is setting both aud and azp claims in the token, AWS STS will use the value in the + azp claim as the aud claim. + + https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_providers_create_oidc.html + +This script copies the tab's sentence, each row of its table and the provider page's sentence as they stand, with what +they name: a row's key, its claim, the claim the row's own sentence says the key is read from when that claim has no +value, and whether it is available in session; the claim the provider page names the audience and the one AWS STS uses +in its place. A page whose table has other columns, or that words either sentence otherwise, is refused, so a reworded +page fails rather than giving a key. Nothing in the output is written by hand. + +Run from anywhere in the repo: + python3 tools/aws/fetch_sts_oidc_claim_keys.py # rewrite the vendored file + python3 tools/aws/fetch_sts_oidc_claim_keys.py --verify # online: the file still says what the pages do +""" +from __future__ import annotations + +import argparse +import html +import json +import re +import sys +import urllib.request +from datetime import datetime, timezone +from pathlib import Path + +KEYS_PAGE = "https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_iam-condition-keys.html" +PROVIDER_PAGE = "https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_providers_create_oidc.html" +# The section of the condition keys page on OIDC federation, and the tab of it for an IdP no other tab names. +SECTION = "condition-keys-wif" +TAB = "default" +REPO_ROOT = Path(__file__).resolve().parents[2] +OUTPUT = REPO_ROOT / "tools/aws/sources/sts-oidc-claim-keys.json" + +# The table's columns, as the page heads them. +COLUMNS = ["AWS STS condition key", "IdP JWT claim", "Available in session"] +NAME_RE = re.compile(r"^[a-z][a-z0-9_]*$") +# The tab's sentence saying which IdPs its mapping is for. +APPLIES_RE = re.compile(r"^Use this mapping if your IdP is not listed in the tab options\.$") +# A row's sentence naming the claim its key is read from when the row's claim has no value. +OTHERWISE_RE = re.compile(r"^If no value is set for (?P[a-z][a-z0-9_]*), the (?P[a-z][a-z0-9_]*) condition " + r"key maps to the (?P[a-z][a-z0-9_]*) claim\.$") +# The provider page's sentence naming the claim AWS STS reads a token's audience from in place of another. +AUDIENCE_RE = re.compile(r"^If your OIDC identity provider is setting both (?P[a-z]+) and (?P[a-z]+) " + r"claims in the token, AWS STS will use the value in the (?P=preferred) claim as the " + r"(?P=claim) claim\.$") + + +def _text(fragment: str) -> str: + return re.sub(r"\s+", " ", html.unescape(re.sub(r"<[^>]+>", "", fragment))).strip() + + +def _paragraphs(fragment: str) -> list[str]: + """Each paragraph of the fragment as one line of text.""" + return [text for text in (_text(body) for body in re.findall(r"]*>(.*?)

", fragment, re.S)) if text] + + +def _sentences(paragraph: str) -> list[str]: + return [sentence for sentence in re.split(r"(?<=\.)\s+", paragraph) if sentence] + + +def tab(page: str) -> str: + """The tab's markup, up to the next tab of the section that is not a nested code example's.""" + section = re.search(r'\bid="' + re.escape(SECTION) + r'"(?P.*?)(?= re.Match: + found = [match for match in map(pattern.match, sentences) if match is not None] + if len(found) != 1: + raise ValueError(f"{page} no longer says in one sentence {what}: its wording changed") + return found[0] + + +def keys(markup: str) -> list[dict]: + """The rows of the tab's table: each key, its claim, the claim its sentence reads it from otherwise, and whether it + is available in session.""" + table = re.search(r"", markup, re.S) + if table is None: + raise ValueError(f"{KEYS_PAGE}'s {TAB} tab has no table: its layout changed") + header = [_text(cell) for cell in re.findall(r"]*>(.*?)", table.group(0), re.S)] + if header != COLUMNS: + raise ValueError(f"{KEYS_PAGE}'s {TAB} tab heads its table {header}, not {COLUMNS}") + rows = [] + for row in re.findall(r"(.*?)", table.group(0), re.S): + cells = [_paragraphs(cell) for cell in re.findall(r"]*>(.*?)", row, re.S)] + if not cells: + continue + if len(cells) != 3 or len(cells[0]) != 1 or len(cells[2]) != 1 or not 1 <= len(cells[1]) <= 2: + raise ValueError(f"{KEYS_PAGE}'s {TAB} tab has a row {cells} that is not a key, its claim and whether " + f"it is available in session") + key, claim, session = cells[0][0], cells[1][0], cells[2][0] + if not NAME_RE.match(key) or not NAME_RE.match(claim) or session not in ("Yes", "No"): + raise ValueError(f"{KEYS_PAGE}'s {TAB} tab maps '{key}' to '{claim}' in session '{session}', which is " + f"not a key, a claim and Yes or No") + entry = {"key": key, "claim": claim, "inSession": session == "Yes"} + if len(cells[1]) == 2: + otherwise = OTHERWISE_RE.match(cells[1][1]) + if otherwise is None or otherwise.group("claim") != claim or otherwise.group("key") != key: + raise ValueError(f"{KEYS_PAGE}'s {TAB} tab says of {key} '{cells[1][1]}', which no longer names " + f"the claim {key} is read from when {claim} has no value") + entry["otherwise"] = otherwise.group("otherwise") + entry["otherwiseSentence"] = otherwise.group(0) + rows.append(entry) + if not rows or len({row["key"] for row in rows}) != len(rows): + raise ValueError(f"{KEYS_PAGE}'s {TAB} tab gives no keys, or one twice: its layout changed") + return rows + + +def audience(page: str) -> dict: + """The claim the provider page names a token's audience, the one AWS STS uses in its place, and the sentence.""" + sentences = [sentence for paragraph in _paragraphs(page) for sentence in _sentences(paragraph)] + found = _one(AUDIENCE_RE, sentences, "which claim AWS STS reads a token's audience from", PROVIDER_PAGE) + return {"claim": found.group("claim"), "preferred": found.group("preferred"), "sentence": found.group(0)} + + +def build(keys_page: str, provider_page: str) -> dict: + markup = tab(keys_page) + sentences = [sentence for paragraph in _paragraphs(markup) for sentence in _sentences(paragraph)] + applies = _one(APPLIES_RE, sentences, f"which IdPs its {TAB} mapping is for", KEYS_PAGE) + return { + "_source": { + "pages": [f"{KEYS_PAGE}#{SECTION}", PROVIDER_PAGE], + "fetcher": str(Path(__file__).resolve().relative_to(REPO_ROOT)), + "retrieved": datetime.now(timezone.utc).strftime("%Y-%m-%d"), + "note": "The IAM User Guide's Default mapping of OIDC claims to condition keys, each row as the page gives " + "it, and its sentence naming the claim AWS STS reads a token's audience from, copied as they stand.", + }, + "default": {"sentence": applies.group(0), "keys": keys(markup)}, + "audience": audience(provider_page), + } + + +def fetch_url(url: str) -> str: + request = urllib.request.Request(url, headers={"User-Agent": "floci-tools"}) + with urllib.request.urlopen(request, timeout=60) as response: + return response.read().decode("utf-8") + + +def fetch_all(fetch=fetch_url) -> tuple[str, str]: + """The IAM User Guide's page on condition keys and its page on creating an OIDC identity provider.""" + return fetch(KEYS_PAGE), fetch(PROVIDER_PAGE) + + +def stale(vendored: dict, keys_page: str, provider_page: str) -> bool: + """Whether the pages now give something other than the vendored file, its date aside.""" + built = build(keys_page, provider_page) + return any(vendored.get(key) != built[key] for key in built if key != "_source") + + +def main(argv: list[str] | None = None, fetch=fetch_url) -> int: + parser = argparse.ArgumentParser(description=__doc__.splitlines()[0]) + parser.add_argument("--verify", action="store_true", help="online: the vendored file matches the pages") + args = parser.parse_args(argv) + try: + pages = fetch_all(fetch) + except OSError as e: + print(f"error: could not read the IAM User Guide ({e})", file=sys.stderr) + return 2 + if args.verify: + vendored = json.loads(OUTPUT.read_text(encoding="utf-8")) + if stale(vendored, *pages): + print(f"error: {OUTPUT.relative_to(REPO_ROOT)} no longer says what the IAM User Guide does: run " + f"tools/aws/fetch_sts_oidc_claim_keys.py and then make iam-authorized-actions-sync", file=sys.stderr) + return 1 + print(f"{OUTPUT.relative_to(REPO_ROOT)} matches the IAM User Guide") + return 0 + built = build(*pages) + OUTPUT.write_text(json.dumps(built, indent=2) + "\n", encoding="utf-8") + print(f"wrote {OUTPUT.relative_to(REPO_ROOT)} ({len(built['default']['keys'])} key(s))") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tools/aws/regen_iam_authorized_actions.py b/tools/aws/regen_iam_authorized_actions.py index abb2b05e82..8fd7cbfc46 100644 --- a/tools/aws/regen_iam_authorized_actions.py +++ b/tools/aws/regen_iam_authorized_actions.py @@ -85,6 +85,15 @@ provider (IdP) passing tags must have the sts:TagSession permission", for the ta `https://aws.amazon.com/SAML/Attributes/PrincipalTag:{TagKey}` attributes or the token's `https://aws.amazon.com/tags` claim pass, where the reference's action of the operation's name takes `aws:RequestTag/${TagKey}`. +A web identity token's claims are read as the condition keys of the role's trust policy, under the issuer's host and +path (`token.actions.githubusercontent.com:sub`), as the IAM user guide's page on condition keys maps them in its +Default tab, which it says to "use ... if your IdP is not listed in the tab options": each key, the claim it is read +from and, where the row's own sentence names one, the claim it is read from when that claim has no value ("If no value +is set for azp, the aud condition key maps to the aud claim"). The guide's page on creating an OIDC identity provider +names the claim the token's audience, which the provider's client IDs are checked against, is read from: "AWS STS will +use the value in the azp claim as the aud claim". Both are copied unchanged into +tools/aws/sources/sts-oidc-claim-keys.json by tools/aws/fetch_sts_oidc_claim_keys.py (`webIdentityClaims`). + CloudWatch's Prometheus-compatible PromQL endpoints are operations neither botocore nor the reference model. The CloudWatch user guide's "IAM permissions for PromQL" table gives each endpoint path's required actions, and each operation's page the paths its "Valid URIs" give, both copied unchanged into @@ -162,6 +171,10 @@ S3_REQUIRED = REPO_ROOT / "tools/aws/sources/s3-required-actions.json" SOURCE_IDENTITY = REPO_ROOT / "tools/aws/sources/sts-source-identity.json" # The IAM user guide's page on session tags, as tools/aws/fetch_sts_session_tags.py copies it. SESSION_TAGS = REPO_ROOT / "tools/aws/sources/sts-session-tags.json" +# The IAM user guide's Default mapping of OIDC claims to condition keys, and its sentence naming the claim a token's +# audience is read from, as tools/aws/fetch_sts_oidc_claim_keys.py copies them. +WEB_IDENTITY_CLAIMS = REPO_ROOT / "tools/aws/sources/sts-oidc-claim-keys.json" +CLAIM_RE = re.compile(r"^[a-z][a-z0-9_]*$") # The AWS Secrets Manager API reference's required permissions of each operation the Service Reference lists as # authorized by another of its actions, as tools/aws/fetch_secretsmanager_required_permissions.py copies them. REQUIRED_PERMISSIONS = REPO_ROOT / "tools/aws/sources/secretsmanager-required-permissions.json" @@ -601,6 +614,23 @@ def load_session_tags(source: Path = SESSION_TAGS) -> dict | None: return json.loads(source.read_text(encoding="utf-8")) if source.exists() else None +def load_web_identity_claims(source: Path = WEB_IDENTITY_CLAIMS) -> dict | None: + """The vendored IAM user guide's mapping of OIDC claims to condition keys, none when the file is missing.""" + return json.loads(source.read_text(encoding="utf-8")) if source.exists() else None + + +def web_identity_claims(source: dict | None) -> dict: + """The `webIdentityClaims` section, from the IAM user guide's pages (`source`, `load_web_identity_claims`): under + `default`, each condition key a token's claims are read as when the guide gives its issuer no tab of its own, the + claim it is read from, and the claim the row's sentence reads it from when that claim has no value (`otherwise`); + under `audience`, the claims a token's audience is read from, the one AWS STS uses in place of the other first.""" + if not source: + return {} + keys = [{"key": row["key"], "claim": row["claim"], + **({"otherwise": row["otherwise"]} if "otherwise" in row else {})} for row in source["default"]["keys"]] + return {"default": keys, "audience": [source["audience"]["preferred"], source["audience"]["claim"]]} + + def load_required_permissions(source: Path = REQUIRED_PERMISSIONS) -> dict | None: """The vendored API reference's required permissions, none when the file is missing.""" return json.loads(source.read_text(encoding="utf-8")) if source.exists() else None @@ -931,6 +961,7 @@ def build(documents: list[dict], provenance: str, routed: list[str], load_endpoint_permissions()), "perEntry": per_entry_actions(documents, load_required_permissions()), "returnedOnlyIf": returned_only_if(documents, load_response_permissions()), + "webIdentityClaims": web_identity_claims(load_web_identity_claims()), } @@ -1024,9 +1055,30 @@ def _section_problems(document: dict) -> list[str]: or not action_of(namespace, gate.get("action")) or not NAME_RE.match(str(gate.get("member"))): problems.append(f"returnedOnlyIf {namespace}:{operation} is not a response member and an " f"action of {namespace}") + claims = document.get("webIdentityClaims") + if claims is not None and not _web_identity_claims_hold(claims): + problems.append("webIdentityClaims is not each key with the claim it is read from, and the claims a token's " + "audience is read from, which one key reads") return problems +def _web_identity_claims_hold(claims: object) -> bool: + """Whether the web identity claims are keys named once, each with the claim it is read from and the one it falls + back to, and the two claims a token's audience is read from, which exactly one key reads in their order.""" + if not isinstance(claims, dict) or set(claims) != {"default", "audience"}: + return False + rows, audience = claims["default"], claims["audience"] + if not isinstance(rows, list) or not rows or not isinstance(audience, list) or len(audience) != 2 \ + or not all(isinstance(claim, str) and CLAIM_RE.match(claim) for claim in audience) \ + or audience[0] == audience[1]: + return False + if not all(isinstance(row, dict) and set(row) <= {"key", "claim", "otherwise"} and {"key", "claim"} <= set(row) + and all(isinstance(value, str) and CLAIM_RE.match(value) for value in row.values()) for row in rows): + return False + keys = [row["key"] for row in rows] + return len(set(keys)) == len(keys) and [[row["claim"], row.get("otherwise")] for row in rows].count(audience) == 1 + + def _companion_source_holds(namespace: str, companion: dict) -> bool: """Whether a companion names where its value comes from: a request member, or a SAML attribute or a token claim with the namespace's key the value is present in the request as.""" @@ -1228,6 +1280,13 @@ def main(argv: list[str] | None = None) -> int: f"{fetch_sts_session_tags.PAGE} does (run tools/aws/fetch_sts_session_tags.py)", file=sys.stderr) return 1 + claim_keys = load_web_identity_claims() + if args.source_dir is None and claim_keys is not None: + import fetch_sts_oidc_claim_keys + if fetch_sts_oidc_claim_keys.stale(claim_keys, *fetch_sts_oidc_claim_keys.fetch_all()): + print(f"error: {WEB_IDENTITY_CLAIMS.relative_to(REPO_ROOT)} no longer says what the IAM user " + f"guide does (run tools/aws/fetch_sts_oidc_claim_keys.py)", file=sys.stderr) + return 1 response_permissions = load_response_permissions() if args.source_dir is None and response_permissions is not None: import fetch_lambda_response_permissions @@ -1271,7 +1330,8 @@ def main(argv: list[str] | None = None) -> int: "companions": companions(documents, source_identity, None, session_tags, load_required_permissions(), endpoint_permissions), "perEntry": per_entry_actions(documents, load_required_permissions()), - "returnedOnlyIf": returned_only_if(documents, load_response_permissions())} + "returnedOnlyIf": returned_only_if(documents, load_response_permissions()), + "webIdentityClaims": web_identity_claims(claim_keys)} for section, value in sections.items(): if vendored_document.get(section, {}) != value: untrue.append(f"{section} differs from what AWS gives: expected {json.dumps(value)}") diff --git a/tools/aws/sources/sts-oidc-claim-keys.json b/tools/aws/sources/sts-oidc-claim-keys.json new file mode 100644 index 0000000000..3198dc0413 --- /dev/null +++ b/tools/aws/sources/sts-oidc-claim-keys.json @@ -0,0 +1,48 @@ +{ + "_source": { + "pages": [ + "https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_iam-condition-keys.html#condition-keys-wif", + "https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_providers_create_oidc.html" + ], + "fetcher": "tools/aws/fetch_sts_oidc_claim_keys.py", + "retrieved": "2026-12-05", + "note": "The IAM User Guide's Default mapping of OIDC claims to condition keys, each row as the page gives it, and its sentence naming the claim AWS STS reads a token's audience from, copied as they stand." + }, + "default": { + "sentence": "Use this mapping if your IdP is not listed in the tab options.", + "keys": [ + { + "key": "amr", + "claim": "amr", + "inSession": true + }, + { + "key": "aud", + "claim": "azp", + "inSession": true, + "otherwise": "aud", + "otherwiseSentence": "If no value is set for azp, the aud condition key maps to the aud claim." + }, + { + "key": "email", + "claim": "email", + "inSession": false + }, + { + "key": "oaud", + "claim": "aud", + "inSession": false + }, + { + "key": "sub", + "claim": "sub", + "inSession": true + } + ] + }, + "audience": { + "claim": "aud", + "preferred": "azp", + "sentence": "If your OIDC identity provider is setting both aud and azp claims in the token, AWS STS will use the value in the azp claim as the aud claim." + } +} diff --git a/tools/aws/test_fetch_sts_oidc_claim_keys.py b/tools/aws/test_fetch_sts_oidc_claim_keys.py new file mode 100644 index 0000000000..cadeb68994 --- /dev/null +++ b/tools/aws/test_fetch_sts_oidc_claim_keys.py @@ -0,0 +1,92 @@ +#!/usr/bin/env python3 +"""Tests for fetch_sts_oidc_claim_keys.py, on pages in the IAM User Guide's markup.""" +from __future__ import annotations + +import json + +import pytest + +import fetch_sts_oidc_claim_keys as f + +APPLIES = "Use this mapping if your IdP is not listed in the tab options." +OTHERWISE = ('If no value is set for azp, the aud\n' + ' condition key maps to the aud claim.') +AUDIENCE = ('If your OIDC identity provider is setting both aud and azp' + '\n claims in the token, AWS STS will use the value in the azp claim as ' + 'the\n aud claim.') +HEADER = "AWS STS condition keyIdP JWT claimAvailable in session" +ROWS = [("amr", "

amr

", "Yes"), ("aud", f"

azp

{OTHERWISE}

", "Yes"), ("sub", "

sub

", "Yes")] + + +def row(key: str, claim: str, session: str) -> str: + return (f'

{key}

{claim}' + f'

{session}

') + + +def keys_page(applies: str = APPLIES, header: str = HEADER, rows=ROWS, tab: str = "default", + section: str = "condition-keys-wif") -> str: + body = "".join(row(*each) for each in rows) + return (f'

Available keys for AWS OIDC federation

' + f'
Default

Default lists the standard OIDC claims. {applies}

' + f'{header}{body}
' + # A code example's own tabs, nested in the Default tab, which do not end it. + f'
JSON
{{}}
' + f'

More on the keys.

' + f'
AWS STS

Use this mapping if your IdP is not listed in the tab options.' + f'

{HEADER}{row("jti", "

jti

", "No")}
' + f'

More information

') + + +def provider_page(sentence: str = AUDIENCE) -> str: + return (f'

If your IdP JWT token includes the azp ' + f'claim, enter this value as the Audience value.

{sentence}

') + + +def test_the_default_tab_s_rows_and_the_audience_sentence_are_copied_as_the_pages_give_them(): + built = f.build(keys_page(), provider_page()) + assert built["default"] == {"sentence": APPLIES, "keys": [ + {"key": "amr", "claim": "amr", "inSession": True}, + {"key": "aud", "claim": "azp", "inSession": True, "otherwise": "aud", + "otherwiseSentence": "If no value is set for azp, the aud condition key maps to the aud claim."}, + {"key": "sub", "claim": "sub", "inSession": True}]} + assert built["audience"] == {"claim": "aud", "preferred": "azp", "sentence": "If your OIDC identity provider is " + "setting both aud and azp claims in the token, AWS STS will use the value in the azp " + "claim as the aud claim."} + + +@pytest.mark.parametrize("arguments, problem", [ + ({"section": "condition-keys-oidc"}, "has no section condition-keys-wif"), + ({"tab": "standard"}, "has no default tab"), + ({"applies": "Use this mapping for any IdP."}, "which IdPs its default mapping is for"), + ({"header": "KeyClaim"}, "heads its table"), + ({"rows": [("amr", "

amr

", "Sometimes")]}, "not a key, a claim and Yes or No"), + ({"rows": [("amr", "

amr

a

b

", "Yes")]}, "is not a key, its claim"), + ({"rows": [("aud", f"

azp

{OTHERWISE.replace('maps to', 'is')}

", "Yes")]}, "no longer names"), + ({"rows": [("oaud", f"

azp

{OTHERWISE}

", "No")]}, "no longer names"), + ({"rows": [("sub", "

sub

", "Yes"), ("sub", "

aud

", "No")]}, "gives no keys, or one twice"), +]) +def test_a_reworded_keys_page_is_refused(arguments, problem): + with pytest.raises(ValueError, match=problem): + f.build(keys_page(**arguments), provider_page()) + + +def test_a_reworded_provider_page_is_refused(): + with pytest.raises(ValueError, match="which claim AWS STS reads a token's audience from"): + f.build(keys_page(), provider_page(AUDIENCE.replace("azp claim as", "aud claim as"))) + with pytest.raises(ValueError, match="which claim AWS STS reads a token's audience from"): + f.build(keys_page(), provider_page(AUDIENCE + "

" + AUDIENCE)) + + +def test_stale_compares_everything_but_the_date(): + built = f.build(keys_page(), provider_page()) + assert not f.stale(dict(built, _source={"retrieved": "2000-01-01"}), keys_page(), provider_page()) + assert f.stale(built, keys_page(rows=ROWS[:2]), provider_page()) + + +def test_the_vendored_file_is_what_its_fetcher_writes(): + vendored = json.loads(f.OUTPUT.read_text(encoding="utf-8")) + assert [(entry["key"], entry["claim"], entry.get("otherwise")) for entry in vendored["default"]["keys"]] == [ + ("amr", "amr", None), ("aud", "azp", "aud"), ("email", "email", None), ("oaud", "aud", None), + ("sub", "sub", None)] + assert (vendored["audience"]["claim"], vendored["audience"]["preferred"]) == ("aud", "azp") + assert vendored["_source"]["fetcher"] == "tools/aws/fetch_sts_oidc_claim_keys.py" diff --git a/tools/aws/test_regen_iam_authorized_actions.py b/tools/aws/test_regen_iam_authorized_actions.py index 9603ae7bcd..2c4ba9a780 100644 --- a/tools/aws/test_regen_iam_authorized_actions.py +++ b/tools/aws/test_regen_iam_authorized_actions.py @@ -1066,3 +1066,50 @@ def test_both_pages_give_a_federated_operation_its_companions_source_identity_fi found = r.companions([document], FEDERATED_PAGE, STS_REQUESTS, SESSION_TAGS_PAGE)["sts"] assert [companion["action"] for companion in found["AssumeRoleWithSAML"]] == [ "sts:SetSourceIdentity", "sts:TagSession"] + + +# --------------------------------------------------------------------------- # +# webIdentityClaims: a web identity token's claims as the keys of a trust policy +# --------------------------------------------------------------------------- # +CLAIM_KEYS = { + "default": {"sentence": "Use this mapping if your IdP is not listed in the tab options.", "keys": [ + {"key": "amr", "claim": "amr", "inSession": True}, + {"key": "aud", "claim": "azp", "inSession": True, "otherwise": "aud", + "otherwiseSentence": "If no value is set for azp, the aud condition key maps to the aud claim."}, + {"key": "oaud", "claim": "aud", "inSession": False}]}, + "audience": {"claim": "aud", "preferred": "azp", "sentence": "If your OIDC identity provider is setting both aud " + "and azp claims in the token, AWS STS will use the value in the azp claim as the aud claim."}, +} + + +def test_a_web_identity_token_s_claims_are_the_keys_the_guide_maps_them_to(): + assert r.web_identity_claims(CLAIM_KEYS) == { + "default": [{"key": "amr", "claim": "amr"}, {"key": "aud", "claim": "azp", "otherwise": "aud"}, + {"key": "oaud", "claim": "aud"}], + "audience": ["azp", "aud"]} + assert r.web_identity_claims(None) == {} + + +@pytest.mark.parametrize("broken", [ + {"default": [], "audience": ["azp", "aud"]}, + {"default": [{"key": "sub", "claim": "sub"}]}, + {"default": [{"key": "sub", "claim": "sub"}], "audience": ["aud", "aud"]}, + {"default": [{"key": "sub", "claim": "sub", "inSession": True}], "audience": ["azp", "aud"]}, + {"default": [{"key": "sub"}], "audience": ["azp", "aud"]}, + {"default": [{"key": "sub", "claim": "Sub"}], "audience": ["azp", "aud"]}, + {"default": [{"key": "sub", "claim": "sub"}, {"key": "sub", "claim": "aud"}], "audience": ["azp", "aud"]}, + # A key that is no name is refused, not hashed. + {"default": [{"key": [], "claim": "sub"}, {"key": "aud", "claim": "azp", "otherwise": "aud"}], + "audience": ["azp", "aud"]}, + # Exactly one key reads the audience claims, in their order. + {"default": [{"key": "aud", "claim": "aud"}], "audience": ["azp", "aud"]}, + {"default": [{"key": "aud", "claim": "aud", "otherwise": "azp"}], "audience": ["azp", "aud"]}, + {"default": [{"key": "aud", "claim": "azp", "otherwise": "aud"}, {"key": "oaud", "claim": "azp", "otherwise": "aud"}], + "audience": ["azp", "aud"]}, +]) +def test_the_built_document_carries_the_vendored_mapping_and_a_malformed_one_is_refused(broken): + document = r.build(ANCHOR_SERVICES, "a test", []) + assert document["webIdentityClaims"] == r.web_identity_claims(r.load_web_identity_claims()) + assert r.validate(document, []) == [] + assert ("webIdentityClaims is not each key with the claim it is read from, and the claims a token's audience is " + "read from, which one key reads") in r.validate(dict(document, webIdentityClaims=broken), [])