diff --git a/docs/services/eks.md b/docs/services/eks.md index 38f5811323..678c6bf031 100644 --- a/docs/services/eks.md +++ b/docs/services/eks.md @@ -245,7 +245,7 @@ When `sts:AssumeRoleWithWebIdentity` receives a token whose `iss` names an issue - `exp` / `nbf`, with 60s of clock-skew tolerance - the role's trust policy: `Principal.Federated` and the `Condition` block, comparing `oidc:sub` / `oidc:aud` with exact, case-sensitive equality -The response then carries the token's real claims in `SubjectFromWebIdentityToken`, `Provider`, and `Audience`. Failures return `InvalidIdentityToken` (400) for a bad token or `AccessDenied` (403) when the trust policy does not permit the subject. +The response then carries the token's real claims in `SubjectFromWebIdentityToken`, `Provider`, and `Audience`. Failures return `InvalidIdentityToken` (400) for a bad token, `ExpiredTokenException` (400) for an expired one, or `AccessDenied` (403) when the trust policy does not permit the subject. A token whose issuer Floci does not host is treated as opaque and accepted, since Floci cannot adjudicate a third-party provider. Validation is therefore automatic for Floci-issued tokens and requires no configuration flag. diff --git a/docs/services/sts.md b/docs/services/sts.md index c2b9c62b11..d48e416d0f 100644 --- a/docs/services/sts.md +++ b/docs/services/sts.md @@ -51,7 +51,7 @@ When the token's `iss` names a known Floci issuer, all of the following are enfo - `exp` / `nbf`, with 60s of clock-skew tolerance - the role's trust policy — `Principal.Federated` plus the `Condition` block, comparing `:sub` and `:aud` 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); a trust policy that does not permit the subject returns `AccessDenied` (403). +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 trust policy that does not permit the subject returns `AccessDenied` (403). By default, tokens from an issuer Floci does not host, or tokens that are not parseable JWTs, are treated as opaque and accepted for compatibility with existing workflows. When `FLOCI_SERVICES_IAM_ENFORCEMENT_ENABLED=true`, those tokens return `InvalidIdentityToken` because Floci cannot verify a third-party provider's signature. See [EKS](eks.md) for the full IRSA walkthrough and the token-minting endpoint. diff --git a/src/main/java/io/github/hectorvent/floci/core/common/WebIdentityTokenVerifier.java b/src/main/java/io/github/hectorvent/floci/core/common/WebIdentityTokenVerifier.java index 531698032a..46e02e9175 100644 --- a/src/main/java/io/github/hectorvent/floci/core/common/WebIdentityTokenVerifier.java +++ b/src/main/java/io/github/hectorvent/floci/core/common/WebIdentityTokenVerifier.java @@ -53,6 +53,17 @@ public class WebIdentityTokenVerifier { } } + /** + * Thrown when a token is past its {@code exp} claim. STS reports this as + * {@code ExpiredTokenException} rather than {@code InvalidIdentityToken}, so callers can tell + * a stale token apart from one that can never verify. + */ + public static class ExpiredTokenException extends InvalidTokenException { + public ExpiredTokenException(String message) { + super(message); + } + } + /** * Reads the {@code iss} claim without verifying the signature. Returns empty when {@code token} * is not a parseable JWT at all — the caller must reject it. @@ -123,7 +134,7 @@ public class WebIdentityTokenVerifier { throw new InvalidTokenException("The web identity token has no expiration claim"); } if (now > exp.asLong() + CLOCK_SKEW_SECONDS) { - throw new InvalidTokenException("The web identity token has expired"); + throw new ExpiredTokenException("The web identity token has expired"); } JsonNode nbf = claims.get("nbf"); diff --git a/src/main/java/io/github/hectorvent/floci/services/iam/StsQueryHandler.java b/src/main/java/io/github/hectorvent/floci/services/iam/StsQueryHandler.java index 5801b38b9d..9216e05a9d 100644 --- a/src/main/java/io/github/hectorvent/floci/services/iam/StsQueryHandler.java +++ b/src/main/java/io/github/hectorvent/floci/services/iam/StsQueryHandler.java @@ -274,6 +274,12 @@ public class StsQueryHandler { WebIdentityToken claims; try { claims = tokenVerifier.verify(token, key.get(), issuer.get(), STS_AUDIENCE); + } catch (WebIdentityTokenVerifier.ExpiredTokenException e) { + LOG.debugv("Rejecting web identity token for role {0}: {1}", roleArn, e.getMessage()); + return WebIdentityOutcome.deny(AwsQueryResponse.error("ExpiredTokenException", + "The web identity token that was passed is expired or is not valid. Get a new " + + "identity token from the identity provider and then retry the request.", + AwsNamespaces.STS, 400)); } catch (WebIdentityTokenVerifier.InvalidTokenException e) { LOG.debugv("Rejecting web identity token for role {0}: {1}", roleArn, e.getMessage()); return WebIdentityOutcome.deny(AwsQueryResponse.error("InvalidIdentityToken", diff --git a/src/test/java/io/github/hectorvent/floci/core/common/WebIdentityTokenVerifierTest.java b/src/test/java/io/github/hectorvent/floci/core/common/WebIdentityTokenVerifierTest.java index 3c87f8c755..d0a8eabe0d 100644 --- a/src/test/java/io/github/hectorvent/floci/core/common/WebIdentityTokenVerifierTest.java +++ b/src/test/java/io/github/hectorvent/floci/core/common/WebIdentityTokenVerifierTest.java @@ -167,8 +167,10 @@ class WebIdentityTokenVerifierTest { + "\"sub\":\"system:serviceaccount:my-namespace:my-service-account\"," + "\"exp\":" + expired + "}"); - WebIdentityTokenVerifier.InvalidTokenException thrown = assertThrows( - WebIdentityTokenVerifier.InvalidTokenException.class, + // The distinct subtype is what lets STS answer ExpiredTokenException instead of the + // generic InvalidIdentityToken it returns for every other verification failure. + WebIdentityTokenVerifier.ExpiredTokenException thrown = assertThrows( + WebIdentityTokenVerifier.ExpiredTokenException.class, () -> verifier.verify(token, (RSAPublicKey) keyPair.getPublic(), ISSUER, EksOidcService.STS_AUDIENCE)); assertTrue(thrown.getMessage().contains("expired")); diff --git a/src/test/java/io/github/hectorvent/floci/services/eks/EksIrsaEndToEndIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/eks/EksIrsaEndToEndIntegrationTest.java index 7e73ed3161..45042c914c 100644 --- a/src/test/java/io/github/hectorvent/floci/services/eks/EksIrsaEndToEndIntegrationTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/eks/EksIrsaEndToEndIntegrationTest.java @@ -7,6 +7,13 @@ import org.junit.jupiter.api.Order; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.TestMethodOrder; +import java.nio.charset.StandardCharsets; +import java.security.KeyFactory; +import java.security.PrivateKey; +import java.security.Signature; +import java.security.spec.PKCS8EncodedKeySpec; +import java.util.Base64; + import static io.restassured.RestAssured.given; import static org.hamcrest.Matchers.containsString; import static org.hamcrest.Matchers.equalTo; @@ -35,6 +42,12 @@ class EksIrsaEndToEndIntegrationTest { private static String issuer; private static String roleArn; + private final EksOidcService oidcService; + + EksIrsaEndToEndIntegrationTest(EksOidcService oidcService) { + this.oidcService = oidcService; + } + private static String issuerKeyPrefix() { return issuer.replaceFirst("^https://", ""); } @@ -96,6 +109,17 @@ class EksIrsaEndToEndIntegrationTest { .extract().path("token"); } + private PrivateKey clusterSigningKey() throws Exception { + String encoded = oidcService.ensureKey(CLUSTER, issuer).getPrivateKey(); + return KeyFactory.getInstance("RSA") + .generatePrivate(new PKCS8EncodedKeySpec(Base64.getDecoder().decode(encoded))); + } + + private static String base64Url(String value) { + return Base64.getUrlEncoder().withoutPadding() + .encodeToString(value.getBytes(StandardCharsets.UTF_8)); + } + private Response assumeRole(String token) { return given() .contentType(FORM) @@ -184,6 +208,29 @@ class EksIrsaEndToEndIntegrationTest { @Test @Order(8) + void expiredTokenReturnsExpiredTokenException() throws Exception { + // Signed with the cluster's own key so signature, issuer, and audience all pass and only the + // expiry can reject it. STS reports that case as ExpiredTokenException, distinct from the + // InvalidIdentityToken a caller cannot recover from by fetching a fresh token. + long expired = System.currentTimeMillis() / 1000 - 7200; + String header = base64Url("{\"alg\":\"RS256\",\"typ\":\"JWT\"}"); + String payload = base64Url("{\"iss\":\"" + issuer + "\",\"aud\":[\"sts.amazonaws.com\"]," + + "\"sub\":\"system:serviceaccount:" + NAMESPACE + ":" + SERVICE_ACCOUNT + "\"," + + "\"exp\":" + expired + "}"); + Signature signature = Signature.getInstance("SHA256withRSA"); + signature.initSign(clusterSigningKey()); + signature.update((header + "." + payload).getBytes(StandardCharsets.UTF_8)); + String token = header + "." + payload + "." + + Base64.getUrlEncoder().withoutPadding().encodeToString(signature.sign()); + + assumeRole(token) + .then() + .statusCode(400) + .body(containsString("ExpiredTokenException")); + } + + @Test + @Order(9) void opaqueThirdPartyTokenRemainsAccepted() { // Compatibility guarantee: Floci cannot adjudicate an issuer it does not host, so the // historical permissive behaviour is preserved rather than failing the call. @@ -195,7 +242,7 @@ class EksIrsaEndToEndIntegrationTest { } @Test - @Order(9) + @Order(10) void jwksAndDiscoveryEndpointsServeTheSigningKey() { given() .when() @@ -217,7 +264,7 @@ class EksIrsaEndToEndIntegrationTest { } @Test - @Order(10) + @Order(11) void mintRejectsMissingServiceAccount() { given() .contentType(JSON) @@ -229,7 +276,7 @@ class EksIrsaEndToEndIntegrationTest { } @Test - @Order(11) + @Order(12) void mintRejectsUnknownCluster() { given() .contentType(JSON) @@ -241,7 +288,7 @@ class EksIrsaEndToEndIntegrationTest { } @Test - @Order(12) + @Order(13) void deletingClusterDropsSigningKey() { given().when().delete("/clusters/" + CLUSTER).then().statusCode(200);