mirror of
https://github.com/floci-io/floci.git
synced 2026-12-01 01:12:48 -05:00
feat(sts): vend a signed web identity token for the calling identity (#6517)
GetWebIdentityToken is the last operation the pinned STS model publishes and Floci did not dispatch, which takes STS to 11 of 11. It answers "a signed JSON Web Token (JWT) that represents the calling Amazon Web Services identity", signed by STS and verifiable against the keys the issuer publishes. The issuer is IAM's. Outbound web identity federation mints one issuer URL per account, so the token names it as iss and the operation reads the switch behind it: while the feature is off the answer is OutboundWebIdentityFederationDisabledException, not the FeatureDisabled the IAM getter answers. SessionDurationEscalationException is the other refusal with a published trigger, for a caller on temporary credentials asking for a token that would outlive its own session, "beyond what was granted when the session was originally created". JWTPayloadSizeExceededException is modelled and nothing published says what the maximum payload is, so no size is invented here to refuse a request with. A temporary credential with no live session behind it is refused as expired rather than read as a caller that cannot be identified. IamEnforcementFilter answers ExpiredTokenException for one and it never reaches the operation, but with enforcement off, or in the window between that check and this one, the session lookup comes back empty and the caller would fall to the account root ARN this file hands an unresolvable caller, as GetCallerIdentity does. A token is not a request: its subject is signed and outlives the call, so a session already gone does not get one that speaks for the account, while an unknown long-term key keeps the stand-in. The filter's wording is shared rather than copied a second time. The declared constraints are read ahead of all of it, as #6402 put them elsewhere in this package: Audience required and 1 to 10 members of 1 to 1000 characters, SigningAlgorithm required at a fixed length of 5, DurationSeconds 60 to 3600 defaulting to 300, and Tags at most 50 with its keys and values held to their own lengths and pattern. A member sent empty is a member that is present, breaking its length rather than reading as absent, and a list member's violation names the index the request sent rather than the number it reads as, which is what #6478 settled. The claim layout is the IAM User Guide's. The standard OIDC claims sit at the top level, iss, aud, sub, iat, exp and jti, with the caller's ARN as the subject, and the custom claims are nested under the https://sts.amazonaws.com/ namespace the guide names: aws_account for the account the token was asked for, source_region for the region it was asked from, and the request's tags under request_tags. "All these claims may not be present in a token at the same time", so the organization, principal tag and session context claims the guide also lists are left out rather than invented, and request_tags is absent from a token whose request named none. The nesting is also what keeps a tag off a claim STS sets, a tag named exp being a key under request_tags rather than the claim that chooses the token's lifetime. Two answers are readings and docs/services/sts.md says so. The model publishes no enum for SigningAlgorithm, only the fixed length, so a five-character value that is neither RS256 nor ES384 is answered with this package's enum violation over the two values the reference names. The global endpoint refusal borrows the wording AWS publishes for AssumeRoot, the note for this operation giving none of its own. Signing goes through a new core.common helper rather than a third copy of the assembly: Cognito and EKS each already sign a JWT, and EksOidcService moves onto it here. ES384 signs through the JDK's P1363 variant, so the signature is the raw R || S pair JWS defines rather than the DER sequence a default ECDSA signer returns. Each account's key is minted on first use per algorithm and stored, so a restart does not invalidate a token already handed out. Eleven tests over the wire, including the claim set with the namespaced account and region, both signature shapes by their exact lengths, the tags arriving under request_tags rather than as claims of their own, the ceiling the caller's own session puts on a token, the refusal for a session already gone, and the constraints read while the feature is off. Beside them, a unit test verifies a minted token against the public half of the stored key for both algorithms, a length being no evidence of what was signed, and holds that one token's signature does not verify over another's claims; and the handler test takes the session ceiling to its own boundary on a fixed clock, where a token ending exactly with the session is issued, one ending a second later is refused, and nothing is minted on the refusal. What is not here is the other half: nothing publishes the verification key yet, so the discovery documents the issuer URL would host are not served, and the docs say that plainly.
This commit is contained in:
1 parent
56196fec1c
commit
4c55ec6b77
12 files changed
+1214
-26
No files matched your search
@@ -8,6 +8,7 @@ import io.github.hectorvent.floci.core.common.WebIdentityToken;
|
||||
import io.github.hectorvent.floci.core.common.WebIdentityTokenVerifier;
|
||||
import io.github.hectorvent.floci.services.iam.model.DelegationRequest;
|
||||
import io.github.hectorvent.floci.services.iam.model.IamRole;
|
||||
import io.github.hectorvent.floci.services.iam.model.OutboundWebIdentityFederation;
|
||||
import io.github.hectorvent.floci.testing.PartitionMatrix;
|
||||
import io.github.hectorvent.floci.testing.PartitionMatrix.PartitionCase;
|
||||
import jakarta.ws.rs.core.HttpHeaders;
|
||||
@@ -36,6 +37,7 @@ import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertNotEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.anyList;
|
||||
import static org.mockito.ArgumentMatchers.anyMap;
|
||||
import static org.mockito.ArgumentMatchers.anyString;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
@@ -88,6 +90,13 @@ class StsQueryHandlerTest {
|
||||
|
||||
private static StsQueryHandler newHandler(IamService iamService, RegionResolver regionResolver,
|
||||
Clock clock, DelegationRequestService delegation) {
|
||||
return newHandler(iamService, regionResolver, clock, delegation,
|
||||
mock(WebIdentityTokenIssuer.class));
|
||||
}
|
||||
|
||||
private static StsQueryHandler newHandler(IamService iamService, RegionResolver regionResolver,
|
||||
Clock clock, DelegationRequestService delegation,
|
||||
WebIdentityTokenIssuer tokenIssuer) {
|
||||
EmulatorConfig config = mock(EmulatorConfig.class);
|
||||
EmulatorConfig.ServicesConfig services = mock(EmulatorConfig.ServicesConfig.class);
|
||||
EmulatorConfig.IamServiceConfig iam = mock(EmulatorConfig.IamServiceConfig.class);
|
||||
@@ -108,6 +117,7 @@ class StsQueryHandlerTest {
|
||||
mock(SAMLTrustPolicyEvaluator.class),
|
||||
delegation,
|
||||
mock(CentralRootAccess.class),
|
||||
tokenIssuer,
|
||||
clock);
|
||||
}
|
||||
|
||||
@@ -143,6 +153,91 @@ class StsQueryHandlerTest {
|
||||
}
|
||||
}
|
||||
|
||||
/** The account's federation state with the feature on, which the operation reads the issuer from. */
|
||||
private static OutboundWebIdentityFederation enabledFederation() {
|
||||
OutboundWebIdentityFederation federation = new OutboundWebIdentityFederation();
|
||||
federation.setEnabled(true);
|
||||
federation.setIssuerIdentifier("https://sts.us-east-1.amazonaws.com/000000000000");
|
||||
return federation;
|
||||
}
|
||||
|
||||
/**
|
||||
* A caller on temporary credentials "cannot use this operation to extend the lifetime of a
|
||||
* session beyond what was granted when the session was originally created", so the ceiling on
|
||||
* a web identity token is the session's own expiration. The boundary is that instant itself: a
|
||||
* token ending exactly with the session is issued, and one ending a second later is not, which
|
||||
* is why the clock is fixed here rather than read. A long-term caller has no session to
|
||||
* escalate, so only the duration's own 3600 holds it.
|
||||
*/
|
||||
@ParameterizedTest
|
||||
@CsvSource({"ASIASESSION, 299, 200", "ASIASESSION, 300, 200", "ASIASESSION, 301, 403",
|
||||
"ASIASESSION, 3600, 403", "AKIALONGTERM, 3600, 200"})
|
||||
void aWebIdentityTokenCannotOutliveTheCallersSession(String accessKeyId, String duration,
|
||||
int expectedStatus) {
|
||||
Instant now = Instant.parse("2026-01-01T00:00:00Z");
|
||||
IamService iamService = mock(IamService.class);
|
||||
when(iamService.findEnabledOutboundWebIdentityFederation())
|
||||
.thenReturn(Optional.of(enabledFederation()));
|
||||
when(iamService.findSessionExpiration("ASIASESSION"))
|
||||
.thenReturn(Optional.of(now.plusSeconds(300)));
|
||||
WebIdentityTokenIssuer tokenIssuer = mock(WebIdentityTokenIssuer.class);
|
||||
when(tokenIssuer.mint(any(), anyString(), anyString(), anyList(), any(), any(), any()))
|
||||
.thenReturn("header.claims.signature");
|
||||
StsQueryHandler handler = newHandler(iamService, new RegionResolver(REGION, "000000000000"),
|
||||
Clock.fixed(now, ZoneOffset.UTC), mock(DelegationRequestService.class),
|
||||
tokenIssuer);
|
||||
setCaller(handler, accessKeyId, "-");
|
||||
|
||||
MultivaluedMap<String, String> params = new MultivaluedHashMap<>();
|
||||
params.putSingle("Audience.member.1", "app");
|
||||
params.putSingle("SigningAlgorithm", "RS256");
|
||||
params.putSingle("DurationSeconds", duration);
|
||||
Response response = handler.handle("GetWebIdentityToken", params);
|
||||
|
||||
String body = (String) response.getEntity();
|
||||
assertEquals(expectedStatus, response.getStatus(), body);
|
||||
if (expectedStatus == 403) {
|
||||
assertTrue(body.contains("<Code>SessionDurationEscalationException</Code>"), body);
|
||||
assertTrue(body.contains("You cannot use this operation to extend the lifetime of a"
|
||||
+ " session beyond what was granted when the session was originally created."),
|
||||
body);
|
||||
verifyNoInteractions(tokenIssuer);
|
||||
} else {
|
||||
verify(tokenIssuer).mint(any(), anyString(), anyString(), anyList(), any(), any(),
|
||||
any());
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* A temporary credential the session store no longer knows is refused as expired rather than
|
||||
* minted for. The lookup comes back empty for a session that has gone, which would otherwise
|
||||
* fall through to the account root ARN this file hands a caller it cannot resolve, and a
|
||||
* token's subject is signed and outlives the request that asked for it.
|
||||
*/
|
||||
@Test
|
||||
void aTemporaryCredentialWithNoLiveSessionIsRefusedRatherThanSignedAsRoot() {
|
||||
IamService iamService = mock(IamService.class);
|
||||
when(iamService.findEnabledOutboundWebIdentityFederation())
|
||||
.thenReturn(Optional.of(enabledFederation()));
|
||||
WebIdentityTokenIssuer tokenIssuer = mock(WebIdentityTokenIssuer.class);
|
||||
StsQueryHandler handler = newHandler(iamService, new RegionResolver(REGION, "000000000000"),
|
||||
Clock.fixed(Instant.parse("2026-01-01T00:00:00Z"), ZoneOffset.UTC),
|
||||
mock(DelegationRequestService.class), tokenIssuer);
|
||||
setCaller(handler, "ASIAGONE", "-");
|
||||
|
||||
MultivaluedMap<String, String> params = new MultivaluedHashMap<>();
|
||||
params.putSingle("Audience.member.1", "app");
|
||||
params.putSingle("SigningAlgorithm", "RS256");
|
||||
Response response = handler.handle("GetWebIdentityToken", params);
|
||||
|
||||
String body = (String) response.getEntity();
|
||||
assertEquals(403, response.getStatus(), body);
|
||||
assertTrue(body.contains("<Code>ExpiredTokenException</Code>"), body);
|
||||
assertTrue(body.contains("The security token included in the request has expired."), body);
|
||||
assertFalse(body.contains(":root"), body);
|
||||
verifyNoInteractions(tokenIssuer);
|
||||
}
|
||||
|
||||
private static void setCaller(StsQueryHandler handler, String headerKey, String queryKey) {
|
||||
handler.headers = mock(HttpHeaders.class);
|
||||
if (!"-".equals(headerKey)) {
|
||||
@@ -662,7 +757,8 @@ 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),
|
||||
mock(DelegationRequestService.class), mock(CentralRootAccess.class));
|
||||
mock(DelegationRequestService.class), mock(CentralRootAccess.class),
|
||||
mock(WebIdentityTokenIssuer.class));
|
||||
MultivaluedMap<String, String> params = new MultivaluedHashMap<>();
|
||||
params.putSingle("RoleArn", requestedRoleArn);
|
||||
params.putSingle("RoleSessionName", "app");
|
||||
|
||||
+353
@@ -0,0 +1,353 @@
|
||||
package io.github.hectorvent.floci.services.iam;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import io.restassured.response.ExtractableResponse;
|
||||
import io.restassured.response.Response;
|
||||
import io.restassured.specification.RequestSpecification;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.util.Base64;
|
||||
|
||||
import static io.restassured.RestAssured.given;
|
||||
import static org.hamcrest.Matchers.containsString;
|
||||
import static org.hamcrest.Matchers.equalTo;
|
||||
import static org.hamcrest.Matchers.matchesPattern;
|
||||
import static org.hamcrest.Matchers.not;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertNotNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
/**
|
||||
* {@code GetWebIdentityToken} over the wire: the signed JWT it answers with, the switch it reads,
|
||||
* and the constraints it is held to.
|
||||
*
|
||||
* <p>The token is checked here by decoding it rather than by verifying its signature, no endpoint
|
||||
* publishing the verification key yet, that being the other half of the feature. What is checked
|
||||
* instead is the shape a verifier depends on, including the one detail an ECDSA JWS is easy to get
|
||||
* wrong: the signature is the raw {@code R || S} pair, 96 bytes for P-384, rather than the
|
||||
* variable-length DER sequence the JDK's default ECDSA signer returns. That the signature verifies
|
||||
* at all, against the key the issuer stored and over the claims it was made for, is
|
||||
* {@link WebIdentityTokenIssuerTest}, which reaches the key through the store.
|
||||
*
|
||||
* <p>The feature switch is account-level and shared, so each test sets the state it needs first.
|
||||
*/
|
||||
@QuarkusTest
|
||||
class WebIdentityTokenIntegrationTest {
|
||||
|
||||
private static final String IAM_AUTH =
|
||||
"AWS4-HMAC-SHA256 Credential=test/20261025/us-east-1/iam/aws4_request";
|
||||
private static final String STS_AUTH =
|
||||
"AWS4-HMAC-SHA256 Credential=test/20261025/us-east-1/sts/aws4_request";
|
||||
|
||||
private static final String TOKEN =
|
||||
"GetWebIdentityTokenResponse.GetWebIdentityTokenResult.WebIdentityToken";
|
||||
private static final String EXPIRATION =
|
||||
"GetWebIdentityTokenResponse.GetWebIdentityTokenResult.Expiration";
|
||||
/** A violation is read off the message rather than the body, which escapes its quotes. */
|
||||
private static final String CODE = "ErrorResponse.Error.Code";
|
||||
private static final String MESSAGE = "ErrorResponse.Error.Message";
|
||||
private static final String ISSUER = "GetOutboundWebIdentityFederationInfoResponse"
|
||||
+ ".GetOutboundWebIdentityFederationInfoResult.IssuerIdentifier";
|
||||
/** The namespace the IAM User Guide nests the identity claims and the request's tags under. */
|
||||
private static final String CLAIM_NAMESPACE = "https://sts.amazonaws.com/";
|
||||
|
||||
private static final ObjectMapper MAPPER = new ObjectMapper();
|
||||
|
||||
private static RequestSpecification iam(String action) {
|
||||
return given().header("Authorization", IAM_AUTH).formParam("Action", action);
|
||||
}
|
||||
|
||||
private static RequestSpecification sts(String action) {
|
||||
return given().header("Authorization", STS_AUTH).formParam("Action", action);
|
||||
}
|
||||
|
||||
/** One audience and RS256, which is the shape the Reference's own sample request sends. */
|
||||
private static RequestSpecification token(String algorithm) {
|
||||
return sts("GetWebIdentityToken")
|
||||
.formParam("Audience.member.1", "app")
|
||||
.formParam("SigningAlgorithm", algorithm);
|
||||
}
|
||||
|
||||
/** The same request, signed as the session {@code GetSessionToken} handed out. */
|
||||
private static RequestSpecification session(String accessKeyId) {
|
||||
return given()
|
||||
.header("Authorization", "AWS4-HMAC-SHA256 Credential=" + accessKeyId
|
||||
+ "/20261025/us-east-1/sts/aws4_request")
|
||||
.formParam("Action", "GetWebIdentityToken")
|
||||
.formParam("Audience.member.1", "app")
|
||||
.formParam("SigningAlgorithm", "RS256");
|
||||
}
|
||||
|
||||
/** Enables the feature if it is off, and answers with the account's issuer either way. */
|
||||
private static String enabledIssuer() {
|
||||
iam("EnableOutboundWebIdentityFederation").when().post("/");
|
||||
return iam("GetOutboundWebIdentityFederationInfo")
|
||||
.when().post("/").then().statusCode(200).extract().path(ISSUER);
|
||||
}
|
||||
|
||||
private static void disableFederation() {
|
||||
iam("DisableOutboundWebIdentityFederation").when().post("/");
|
||||
}
|
||||
|
||||
private static JsonNode part(String jwt, int index) throws Exception {
|
||||
return MAPPER.readTree(Base64.getUrlDecoder().decode(jwt.split("\\.", -1)[index]));
|
||||
}
|
||||
|
||||
private static byte[] signature(String jwt) {
|
||||
return Base64.getUrlDecoder().decode(jwt.split("\\.", -1)[2]);
|
||||
}
|
||||
|
||||
/**
|
||||
* "The token contains standard JWT claims such as subject, audience, expiration time", the
|
||||
* audience being the one the request named, and the issuer the one IAM minted for the account.
|
||||
* The default duration is 300 seconds, and {@code Expiration} names the same instant as
|
||||
* {@code exp}. Beside them sit the identity claims the guide nests under its own namespace,
|
||||
* the account the token was asked for and the region it was asked from, and no
|
||||
* {@code request_tags} where the request named no tags.
|
||||
*/
|
||||
@Test
|
||||
void aTokenCarriesTheStandardClaimsAndTheAccountsIssuer() throws Exception {
|
||||
String issuer = enabledIssuer();
|
||||
|
||||
String jwt = token("RS256").when().post("/").then().statusCode(200)
|
||||
.body(EXPIRATION, matchesPattern("\\d{4}-\\d{2}-\\d{2}T.*Z"))
|
||||
.extract().path(TOKEN);
|
||||
|
||||
JsonNode header = part(jwt, 0);
|
||||
assertEquals("RS256", header.path("alg").asText());
|
||||
assertEquals("JWT", header.path("typ").asText());
|
||||
assertTrue(header.path("kid").asText().matches("[0-9a-f]{32}"), header.toString());
|
||||
|
||||
JsonNode claims = part(jwt, 1);
|
||||
assertEquals(issuer, claims.path("iss").asText());
|
||||
assertEquals(1, claims.path("aud").size(), claims.toString());
|
||||
assertEquals("app", claims.path("aud").get(0).asText());
|
||||
assertTrue(claims.path("sub").asText().matches("arn:aws[a-z-]*:iam::\\d{12}:.+"),
|
||||
claims.toString());
|
||||
assertEquals(300, claims.path("exp").asLong() - claims.path("iat").asLong());
|
||||
assertNotNull(claims.path("jti").asText());
|
||||
assertEquals(256, signature(jwt).length, "RS256 signs with the 2048-bit account key");
|
||||
|
||||
JsonNode identity = claims.path(CLAIM_NAMESPACE);
|
||||
assertTrue(identity.path("aws_account").asText().matches("\\d{12}"), claims.toString());
|
||||
assertEquals("us-east-1", identity.path("source_region").asText(), claims.toString());
|
||||
assertTrue(identity.path("request_tags").isMissingNode(),
|
||||
"a request that named no tags carries no request_tags claim");
|
||||
}
|
||||
|
||||
/**
|
||||
* {@code ES384} is "ECDSA using P-384 curve with SHA-384", and JWS defines that signature as
|
||||
* the raw {@code R || S} pair: two 48-byte halves for P-384. A DER sequence would be close to
|
||||
* this length and would verify nowhere.
|
||||
*/
|
||||
@Test
|
||||
void anEs384TokenSignsWithTheRawPairJwsDefines() throws Exception {
|
||||
enabledIssuer();
|
||||
|
||||
String jwt = token("ES384").when().post("/").then().statusCode(200).extract().path(TOKEN);
|
||||
|
||||
assertEquals("ES384", part(jwt, 0).path("alg").asText());
|
||||
assertEquals(96, signature(jwt).length, "ES384 is R || S over P-384, not DER");
|
||||
}
|
||||
|
||||
/**
|
||||
* Request tags "appear under the request_tags field in the token", which the guide nests under
|
||||
* the same namespace as the identity claims. That nesting is also what keeps a tag named after
|
||||
* a claim STS sets out of it: such a tag is a key under {@code request_tags}, so it cannot
|
||||
* lengthen the token's own life.
|
||||
*/
|
||||
@Test
|
||||
void tagsBecomeRequestTagsUnderTheNamespaceRatherThanClaimsOfTheirOwn() throws Exception {
|
||||
enabledIssuer();
|
||||
|
||||
String jwt = token("RS256")
|
||||
.formParam("Tags.member.1.Key", "Team")
|
||||
.formParam("Tags.member.1.Value", "platform")
|
||||
.formParam("Tags.member.2.Key", "exp")
|
||||
.formParam("Tags.member.2.Value", "99999999999")
|
||||
.when().post("/").then().statusCode(200).extract().path(TOKEN);
|
||||
|
||||
JsonNode claims = part(jwt, 1);
|
||||
JsonNode requestTags = claims.path(CLAIM_NAMESPACE).path("request_tags");
|
||||
assertEquals("platform", requestTags.path("Team").asText(), claims.toString());
|
||||
assertEquals("99999999999", requestTags.path("exp").asText(),
|
||||
"a tag named after a claim is a request tag, not that claim");
|
||||
assertTrue(claims.path("Team").isMissingNode(), "a tag is not a claim of its own");
|
||||
assertEquals(300, claims.path("exp").asLong() - claims.path("iat").asLong(),
|
||||
"the request's own exp tag does not become the expiry");
|
||||
}
|
||||
|
||||
/**
|
||||
* The duration is 60 to 3600, and {@code Expiration} is "determined by adding the
|
||||
* DurationSeconds value to the time the token was issued".
|
||||
*/
|
||||
@Test
|
||||
void theDurationIsHeldToItsRangeAndSetsTheExpiry() throws Exception {
|
||||
enabledIssuer();
|
||||
|
||||
ExtractableResponse<Response> issued = token("RS256").formParam("DurationSeconds", "3600")
|
||||
.when().post("/").then().statusCode(200).extract();
|
||||
JsonNode claims = part(issued.path(TOKEN), 1);
|
||||
assertEquals(3600, claims.path("exp").asLong() - claims.path("iat").asLong());
|
||||
assertEquals(claims.path("exp").asLong(),
|
||||
Instant.parse(issued.path(EXPIRATION)).getEpochSecond(),
|
||||
"Expiration names the instant the exp claim does");
|
||||
|
||||
token("RS256").formParam("DurationSeconds", "59").when().post("/").then().statusCode(400)
|
||||
.body(containsString("ValidationError"))
|
||||
.body(containsString("Member must have value greater than or equal to 60"));
|
||||
token("RS256").formParam("DurationSeconds", "3601").when().post("/").then().statusCode(400)
|
||||
.body(containsString("Member must have value less than or equal to 3600"));
|
||||
}
|
||||
|
||||
/** The feature's own refusal, which is not IAM's {@code FeatureDisabled} 404. */
|
||||
@Test
|
||||
void theSwitchBeingOffIsTheOperationsOwnRefusal() {
|
||||
disableFederation();
|
||||
|
||||
token("RS256").when().post("/").then().statusCode(403)
|
||||
.body(CODE, equalTo("OutboundWebIdentityFederationDisabledException"))
|
||||
.body(MESSAGE, containsString("The outbound web identity federation feature is not"
|
||||
+ " enabled for this account."))
|
||||
.body(not(containsString("FeatureDisabled")));
|
||||
|
||||
enabledIssuer();
|
||||
}
|
||||
|
||||
/**
|
||||
* The validation layer runs ahead of the operation, so a request that breaks a declared
|
||||
* constraint is the 400 even where the feature the operation reads is off.
|
||||
*/
|
||||
@Test
|
||||
void theDeclaredConstraintsAreReadAheadOfTheSwitch() {
|
||||
disableFederation();
|
||||
|
||||
sts("GetWebIdentityToken").formParam("SigningAlgorithm", "RS256")
|
||||
.when().post("/").then().statusCode(400)
|
||||
.body(CODE, equalTo("ValidationError"))
|
||||
.body(MESSAGE, equalTo("1 validation error detected: Value null at 'audience' failed"
|
||||
+ " to satisfy constraint: Member must not be null"))
|
||||
.body(not(containsString("OutboundWebIdentityFederationDisabled")));
|
||||
|
||||
enabledIssuer();
|
||||
}
|
||||
|
||||
/**
|
||||
* Both required members are reported together when both are absent, and a member sent empty is
|
||||
* a member that is present, so it breaks the minimum length of 1 rather than reading as absent.
|
||||
*/
|
||||
@Test
|
||||
void theRequiredMembersAndTheirBoundsAreReportedTogether() {
|
||||
enabledIssuer();
|
||||
|
||||
sts("GetWebIdentityToken").when().post("/").then().statusCode(400)
|
||||
.body(MESSAGE, equalTo("2 validation errors detected: Value null at 'audience' failed"
|
||||
+ " to satisfy constraint: Member must not be null; Value null at"
|
||||
+ " 'signingAlgorithm' failed to satisfy constraint: Member must not be"
|
||||
+ " null"));
|
||||
|
||||
sts("GetWebIdentityToken")
|
||||
.formParam("Audience.member.1", "")
|
||||
.formParam("SigningAlgorithm", "RS256")
|
||||
.when().post("/").then().statusCode(400)
|
||||
.body(MESSAGE, containsString("Value '' at 'audience.1.member' failed to satisfy"
|
||||
+ " constraint: Member must have length greater than or equal to 1"));
|
||||
|
||||
RequestSpecification eleven = sts("GetWebIdentityToken")
|
||||
.formParam("SigningAlgorithm", "RS256");
|
||||
for (int audience = 1; audience <= 11; audience++) {
|
||||
eleven.formParam("Audience.member." + audience, "app" + audience);
|
||||
}
|
||||
eleven.when().post("/").then().statusCode(400)
|
||||
.body(MESSAGE, containsString("Value at 'audience' failed to satisfy constraint:"
|
||||
+ " Member must have length less than or equal to 10"));
|
||||
}
|
||||
|
||||
/**
|
||||
* {@code jwtAlgorithmType} publishes a fixed length of 5 and no enum, so the length is the
|
||||
* declared constraint and the two values the Reference names are read from it.
|
||||
*/
|
||||
@Test
|
||||
void aSigningAlgorithmIsHeldToItsLengthAndThenToTheTwoValues() {
|
||||
enabledIssuer();
|
||||
|
||||
token("RS25").when().post("/").then().statusCode(400)
|
||||
.body(MESSAGE, containsString("Value 'RS25' at 'signingAlgorithm' failed to satisfy"
|
||||
+ " constraint: Member must have length greater than or equal to 5"));
|
||||
|
||||
token("HS256").when().post("/").then().statusCode(400)
|
||||
.body(MESSAGE, containsString("Value 'HS256' at 'signingAlgorithm' failed to satisfy"
|
||||
+ " constraint: Member must satisfy enum value set: [RS256, ES384]"));
|
||||
}
|
||||
|
||||
/**
|
||||
* The session ceiling against a real session rather than a stubbed one: {@code GetSessionToken}
|
||||
* hands out credentials that expire, and a token asked for past that instant is refused.
|
||||
* {@code StsQueryHandlerTest} holds the boundary itself on a fixed clock; what this adds is
|
||||
* that the expiration is found through the session the caller is actually on.
|
||||
*/
|
||||
@Test
|
||||
void aTokenIsRefusedWhereItWouldOutliveTheCallersOwnSession() throws Exception {
|
||||
enabledIssuer();
|
||||
String sessionKey = sts("GetSessionToken").formParam("DurationSeconds", "900")
|
||||
.when().post("/").then().statusCode(200)
|
||||
.extract().path("GetSessionTokenResponse.GetSessionTokenResult.Credentials.AccessKeyId");
|
||||
|
||||
session(sessionKey).formParam("DurationSeconds", "3600")
|
||||
.when().post("/").then().statusCode(403)
|
||||
.body(CODE, equalTo("SessionDurationEscalationException"))
|
||||
.body(MESSAGE, containsString("You cannot use this operation to extend the lifetime"
|
||||
+ " of a session beyond what was granted when the session was originally"
|
||||
+ " created."));
|
||||
|
||||
String jwt = session(sessionKey).formParam("DurationSeconds", "60")
|
||||
.when().post("/").then().statusCode(200).extract().path(TOKEN);
|
||||
JsonNode claims = part(jwt, 1);
|
||||
assertEquals(60, claims.path("exp").asLong() - claims.path("iat").asLong(),
|
||||
"a token inside the session is issued for what it asked for");
|
||||
}
|
||||
|
||||
/**
|
||||
* The same refusal over the wire for a session key nothing issued, which reaches the operation
|
||||
* because enforcement is off here: no token is minted, and none names the account root.
|
||||
*/
|
||||
@Test
|
||||
void aSessionKeyWithNoSessionBehindItIsRefusedAsExpired() {
|
||||
enabledIssuer();
|
||||
|
||||
session("ASIANOSUCHSESSION001").when().post("/").then().statusCode(403)
|
||||
.body(CODE, equalTo("ExpiredTokenException"))
|
||||
.body(MESSAGE, equalTo("The security token included in the request has expired."))
|
||||
.body(not(containsString(":root")));
|
||||
}
|
||||
|
||||
/** A {@code Tag} declares its key and its value required, and each carries its own shape. */
|
||||
@Test
|
||||
void aTagIsHeldToItsOwnMembers() {
|
||||
enabledIssuer();
|
||||
|
||||
token("RS256").formParam("Tags.member.1.Key", "Team")
|
||||
.when().post("/").then().statusCode(400)
|
||||
.body(MESSAGE, containsString("Value null at 'tags.1.member.value' failed to satisfy"
|
||||
+ " constraint: Member must not be null"));
|
||||
|
||||
token("RS256")
|
||||
.formParam("Tags.member.1.Key", "Team?")
|
||||
.formParam("Tags.member.1.Value", "platform")
|
||||
.when().post("/").then().statusCode(400)
|
||||
.body(MESSAGE, containsString("at 'tags.1.member.key' failed to satisfy constraint:"
|
||||
+ " Member must satisfy regular expression pattern"));
|
||||
|
||||
RequestSpecification fiftyOne = token("RS256");
|
||||
for (int tag = 1; tag <= 51; tag++) {
|
||||
fiftyOne.formParam("Tags.member." + tag + ".Key", "Key" + tag)
|
||||
.formParam("Tags.member." + tag + ".Value", "value" + tag);
|
||||
}
|
||||
fiftyOne.when().post("/").then().statusCode(400)
|
||||
.body(MESSAGE, containsString("Value at 'tags' failed to satisfy constraint: Member"
|
||||
+ " must have length less than or equal to 50"));
|
||||
}
|
||||
}
|
||||
+145
@@ -0,0 +1,145 @@
|
||||
package io.github.hectorvent.floci.services.iam;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import io.github.hectorvent.floci.core.storage.InMemoryStorage;
|
||||
import io.github.hectorvent.floci.core.storage.StorageBackend;
|
||||
import io.github.hectorvent.floci.services.iam.model.WebIdentityTokenKey;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.EnumSource;
|
||||
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.security.KeyFactory;
|
||||
import java.security.PublicKey;
|
||||
import java.security.Signature;
|
||||
import java.security.spec.X509EncodedKeySpec;
|
||||
import java.time.Instant;
|
||||
import java.util.Base64;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertNotEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
/**
|
||||
* What the wire test cannot check: that a token verifies against the key the issuer stored. Nothing
|
||||
* publishes that key yet, that being the other half of the feature, so this reaches it through the
|
||||
* store the issuer is built with.
|
||||
*
|
||||
* <p>The JCA names are spelled out here rather than read off
|
||||
* {@link WebIdentityTokenIssuer.Algorithm}, which is the point of the exercise: a signature that
|
||||
* stopped being the raw {@code R || S} pair JWS defines would fail this verifier rather than
|
||||
* follow the change into it.
|
||||
*/
|
||||
class WebIdentityTokenIssuerTest {
|
||||
|
||||
private static final String ISSUER = "https://sts.us-east-1.amazonaws.com/000000000000";
|
||||
private static final String SUBJECT = "arn:aws:iam::000000000000:user/token-holder";
|
||||
private static final Instant ISSUED_AT = Instant.parse("2026-01-01T00:00:00Z");
|
||||
private static final WebIdentityTokenIssuer.CustomClaims CUSTOM_CLAIMS =
|
||||
new WebIdentityTokenIssuer.CustomClaims("000000000000", "us-east-1", Map.of());
|
||||
|
||||
private static final ObjectMapper MAPPER = new ObjectMapper();
|
||||
|
||||
private StorageBackend<String, WebIdentityTokenKey> keyStore;
|
||||
private WebIdentityTokenIssuer issuer;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
keyStore = new InMemoryStorage<>();
|
||||
issuer = new WebIdentityTokenIssuer(keyStore, MAPPER);
|
||||
}
|
||||
|
||||
private String mint(WebIdentityTokenIssuer.Algorithm algorithm, long seconds) {
|
||||
return issuer.mint(algorithm, ISSUER, SUBJECT, List.of("app"), CUSTOM_CLAIMS,
|
||||
ISSUED_AT, ISSUED_AT.plusSeconds(seconds));
|
||||
}
|
||||
|
||||
private static String segment(String jwt, int index) {
|
||||
return jwt.split("\\.", -1)[index];
|
||||
}
|
||||
|
||||
private static String signingInput(String jwt) {
|
||||
return jwt.substring(0, jwt.lastIndexOf('.'));
|
||||
}
|
||||
|
||||
private static byte[] signature(String jwt) {
|
||||
return Base64.getUrlDecoder().decode(segment(jwt, 2));
|
||||
}
|
||||
|
||||
private static String keyId(String jwt) throws Exception {
|
||||
return MAPPER.readTree(Base64.getUrlDecoder().decode(segment(jwt, 0)))
|
||||
.path("kid").asText();
|
||||
}
|
||||
|
||||
private static String keyAlgorithm(WebIdentityTokenIssuer.Algorithm algorithm) {
|
||||
return algorithm == WebIdentityTokenIssuer.Algorithm.RS256 ? "RSA" : "EC";
|
||||
}
|
||||
|
||||
private static String signatureAlgorithm(WebIdentityTokenIssuer.Algorithm algorithm) {
|
||||
return algorithm == WebIdentityTokenIssuer.Algorithm.RS256
|
||||
? "SHA256withRSA"
|
||||
: "SHA384withECDSAinP1363Format";
|
||||
}
|
||||
|
||||
/** Verifies a signature over the bytes given, against the stored public half of the key. */
|
||||
private boolean verifies(WebIdentityTokenIssuer.Algorithm algorithm, String signingInput,
|
||||
byte[] signature) throws Exception {
|
||||
WebIdentityTokenKey key = keyStore.get(algorithm.name()).orElseThrow();
|
||||
PublicKey publicKey = KeyFactory.getInstance(keyAlgorithm(algorithm)).generatePublic(
|
||||
new X509EncodedKeySpec(Base64.getDecoder().decode(key.getPublicKey())));
|
||||
Signature verifier = Signature.getInstance(signatureAlgorithm(algorithm));
|
||||
verifier.initVerify(publicKey);
|
||||
verifier.update(signingInput.getBytes(StandardCharsets.US_ASCII));
|
||||
return verifier.verify(signature);
|
||||
}
|
||||
|
||||
/** The token is signed over its own header and claims by the key stored for its algorithm. */
|
||||
@ParameterizedTest
|
||||
@EnumSource(WebIdentityTokenIssuer.Algorithm.class)
|
||||
void aTokenVerifiesAgainstTheKeyTheIssuerStored(WebIdentityTokenIssuer.Algorithm algorithm)
|
||||
throws Exception {
|
||||
String jwt = mint(algorithm, 300);
|
||||
|
||||
assertTrue(verifies(algorithm, signingInput(jwt), signature(jwt)),
|
||||
algorithm + " must verify against the key the issuer stored");
|
||||
}
|
||||
|
||||
/**
|
||||
* The signature covers the claims it was made over, so one token's signature does not carry
|
||||
* another's claim set. A signature of the right length but over the wrong bytes passes a
|
||||
* length check and fails here.
|
||||
*/
|
||||
@ParameterizedTest
|
||||
@EnumSource(WebIdentityTokenIssuer.Algorithm.class)
|
||||
void aSignatureDoesNotCoverAnotherTokensClaims(WebIdentityTokenIssuer.Algorithm algorithm)
|
||||
throws Exception {
|
||||
String jwt = mint(algorithm, 300);
|
||||
String longer = mint(algorithm, 3600);
|
||||
assertNotEquals(segment(jwt, 1), segment(longer, 1));
|
||||
|
||||
String swapped = segment(jwt, 0) + "." + segment(longer, 1);
|
||||
|
||||
assertFalse(verifies(algorithm, swapped, signature(jwt)),
|
||||
algorithm + " must not verify a claim set it did not sign");
|
||||
}
|
||||
|
||||
/**
|
||||
* One key per algorithm, minted on first use and stored rather than held in memory, so a
|
||||
* restart does not invalidate a token already handed out.
|
||||
*/
|
||||
@Test
|
||||
void theKeyIsMintedOncePerAlgorithmAndStored() throws Exception {
|
||||
String first = mint(WebIdentityTokenIssuer.Algorithm.RS256, 300);
|
||||
String second = mint(WebIdentityTokenIssuer.Algorithm.RS256, 300);
|
||||
String other = mint(WebIdentityTokenIssuer.Algorithm.ES384, 300);
|
||||
|
||||
assertEquals(keyId(first), keyId(second));
|
||||
assertNotEquals(keyId(first), keyId(other));
|
||||
assertEquals(keyId(first), keyStore.get("RS256").orElseThrow().getKeyId());
|
||||
assertEquals(keyId(other), keyStore.get("ES384").orElseThrow().getKeyId());
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user