From 294ad9679f4270798f4e35bd8a047d1742ae0d5c Mon Sep 17 00:00:00 2001 From: Giovanni Brethenoux <124669058+Giovannibthx@users.noreply.github.com> Date: Fri, 13 Nov 2026 21:25:52 +0100 Subject: [PATCH] fix(verifiedpermissions): accept tokens issued by Floci's own Cognito pools (#8133) * fix(verifiedpermissions): accept tokens issued by Floci's own Cognito pools * fix(verifiedpermissions): verify emulated pool tokens with Cognito's own check --- .../aws/services/cognito/CognitoService.java | 13 +++ .../VerifiedPermissionsTokenService.java | 63 +++++++++++++-- .../VerifiedPermissionsIntegrationTest.java | 80 +++++++++++++++++++ 3 files changed, 150 insertions(+), 6 deletions(-) diff --git a/src/main/java/io/floci/aws/services/cognito/CognitoService.java b/src/main/java/io/floci/aws/services/cognito/CognitoService.java index a0ed279f68..40fb21af31 100644 --- a/src/main/java/io/floci/aws/services/cognito/CognitoService.java +++ b/src/main/java/io/floci/aws/services/cognito/CognitoService.java @@ -6227,6 +6227,19 @@ public class CognitoService implements ResourceProvider { } } + /** + * The id of the Floci pool that issued and signed this token, after the same alg, issuer, kid + * and signature checks Cognito applies to its own tokens; empty when any of them fails. + */ + public Optional verifiedIssuingPoolId(String token) { + try { + return Optional.of(verifyJwtSignatureAndIssuer(token).poolId()); + } catch (Exception e) { + LOG.debug("Token not verified as issued by a Floci pool", e); + return Optional.empty(); + } + } + private VerifiedJwt verifyJwtSignatureAndIssuer(String token) throws Exception { if (token == null || token.isBlank()) { throw new IllegalArgumentException("missing token"); diff --git a/src/main/java/io/floci/aws/services/verifiedpermissions/VerifiedPermissionsTokenService.java b/src/main/java/io/floci/aws/services/verifiedpermissions/VerifiedPermissionsTokenService.java index 6a9bc27f34..e39ecfa8df 100644 --- a/src/main/java/io/floci/aws/services/verifiedpermissions/VerifiedPermissionsTokenService.java +++ b/src/main/java/io/floci/aws/services/verifiedpermissions/VerifiedPermissionsTokenService.java @@ -4,6 +4,8 @@ import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.node.ArrayNode; import com.fasterxml.jackson.databind.node.ObjectNode; +import io.floci.aws.core.common.AwsException; +import io.floci.aws.services.cognito.CognitoService; import io.floci.aws.services.verifiedpermissions.model.EntityIdentifier; import io.floci.aws.services.verifiedpermissions.model.IdentitySource; import jakarta.enterprise.context.ApplicationScoped; @@ -24,16 +26,19 @@ public class VerifiedPermissionsTokenService { private final CedarAuthorizationEvaluator evaluator; private final VerifiedPermissionsOidcSignatureVerifier signatureVerifier; private final ObjectMapper objectMapper; + private final CognitoService cognitoService; @Inject public VerifiedPermissionsTokenService(VerifiedPermissionsService service, CedarAuthorizationEvaluator evaluator, VerifiedPermissionsOidcSignatureVerifier signatureVerifier, - ObjectMapper objectMapper) { + ObjectMapper objectMapper, + CognitoService cognitoService) { this.service = service; this.evaluator = evaluator; this.signatureVerifier = signatureVerifier; this.objectMapper = objectMapper; + this.cognitoService = cognitoService; } public PreparedTokenRequest prepare(JsonNode request, String region) { @@ -72,13 +77,28 @@ public class VerifiedPermissionsTokenService { if (issuer == null || issuer.isBlank()) { throw VerifiedPermissionsService.validation("Token has no issuer claim."); } - IdentitySource source = service.identitySourcesForStore(store, region).stream() + List sources = service.identitySourcesForStore(store, region); + // A Cognito identity source names a pool. When that pool is one of Floci's own, its + // tokens carry Floci's issuer (CognitoService#getIssuer), not the AWS host stored in the + // source's configuration, and are verified against the pool's signing key here: the OIDC + // verifier only fetches public HTTPS JWKS, which an emulated pool never has. + IdentitySource local = sources.stream() + .filter(candidate -> issuer.equals(emulatedCognitoIssuer(candidate.configuration()))) + .findFirst().orElse(null); + IdentitySource source = local != null ? local : sources.stream() .filter(candidate -> issuer.equals(VerifiedPermissionsService.identityIssuer(candidate.configuration()))) .findFirst().orElseThrow(() -> VerifiedPermissionsService.validation("No identity source matches the token issuer.")); - try { - signatureVerifier.verify(token, issuer); - } catch (VerifiedPermissionsOidcSignatureVerifier.VerificationException e) { - throw VerifiedPermissionsService.validation("Token signature validation failed: " + e.getMessage()); + if (local != null) { + String poolId = cognitoPoolId(local.configuration()); + if (!cognitoService.verifiedIssuingPoolId(token).map(poolId::equals).orElse(false)) { + throw VerifiedPermissionsService.validation("Token signature validation failed."); + } + } else { + try { + signatureVerifier.verify(token, issuer); + } catch (VerifiedPermissionsOidcSignatureVerifier.VerificationException e) { + throw VerifiedPermissionsService.validation("Token signature validation failed: " + e.getMessage()); + } } validateTimes(claims); JsonNode configuration = source.configuration(); @@ -217,6 +237,37 @@ public class VerifiedPermissionsTokenService { }; } + /** The pool id of a Cognito identity source, or null for an OIDC one. */ + private static String cognitoPoolId(JsonNode configuration) { + JsonNode cognito = configuration.get("cognitoUserPoolConfiguration"); + if (cognito == null) { + return null; + } + String arn = cognito.path("userPoolArn").asText(""); + int slash = arn.indexOf("userpool/"); + return slash < 0 ? null : arn.substring(slash + "userpool/".length()); + } + + /** + * The issuer Floci's Cognito signs with for this source's pool, or null when the source does + * not name one of Floci's pools: the full ARN must match, not only the pool id. + */ + private String emulatedCognitoIssuer(JsonNode configuration) { + String poolId = cognitoPoolId(configuration); + if (poolId == null) { + return null; + } + String configuredArn = configuration.path("cognitoUserPoolConfiguration").path("userPoolArn").asText(); + try { + if (!configuredArn.equals(cognitoService.describeUserPool(poolId).getArn())) { + return null; + } + } catch (AwsException e) { + return null; + } + return cognitoService.getIssuer(poolId); + } + private JsonNode decodeClaims(String token) { String[] parts = token == null ? new String[0] : token.split("\\.", -1); if (parts.length != 3) { diff --git a/src/test/java/io/floci/aws/services/verifiedpermissions/VerifiedPermissionsIntegrationTest.java b/src/test/java/io/floci/aws/services/verifiedpermissions/VerifiedPermissionsIntegrationTest.java index 7f8dc60d46..8e17bf5332 100644 --- a/src/test/java/io/floci/aws/services/verifiedpermissions/VerifiedPermissionsIntegrationTest.java +++ b/src/test/java/io/floci/aws/services/verifiedpermissions/VerifiedPermissionsIntegrationTest.java @@ -1,6 +1,7 @@ package io.floci.aws.services.verifiedpermissions; import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import io.floci.aws.testing.RestAssuredJsonUtils; import io.floci.aws.testing.SidecarContainersProfile; @@ -314,6 +315,76 @@ class VerifiedPermissionsIntegrationTest { .then().statusCode(400).body("__type", containsString("ResourceNotFoundException")); } + @Test + void isAuthorizedWithToken_acceptsAccessTokensFromFlocisOwnCognitoPool() throws Exception { + JsonNode pool = cognito("CreateUserPool", "{\"PoolName\":\"avp-token-pool\"}"); + String poolId = pool.path("UserPool").path("Id").asText(); + String poolArn = pool.path("UserPool").path("Arn").asText(); + String clientId = cognito("CreateUserPoolClient", objectJson(Map.of( + "UserPoolId", poolId, "ClientName", "app", + "ExplicitAuthFlows", List.of("ALLOW_ADMIN_USER_PASSWORD_AUTH", "ALLOW_REFRESH_TOKEN_AUTH")))) + .path("UserPoolClient").path("ClientId").asText(); + cognito("AdminCreateUser", objectJson(Map.of( + "UserPoolId", poolId, "Username", "alice", "MessageAction", "SUPPRESS"))); + cognito("AdminSetUserPassword", objectJson(Map.of( + "UserPoolId", poolId, "Username", "alice", "Password", "Avp-Token-1!", "Permanent", true))); + String accessToken = cognito("AdminInitiateAuth", objectJson(Map.of( + "UserPoolId", poolId, "ClientId", clientId, "AuthFlow", "ADMIN_USER_PASSWORD_AUTH", + "AuthParameters", Map.of("USERNAME", "alice", "PASSWORD", "Avp-Token-1!")))) + .path("AuthenticationResult").path("AccessToken").asText(); + + String store = createStore("OFF", "DISABLED"); + givenAws("CreateIdentitySource", objectJson(Map.of( + "policyStoreId", store, "principalEntityType", "User", + "configuration", Map.of("cognitoUserPoolConfiguration", Map.of( + "userPoolArn", poolArn, + "clientIds", List.of(clientId)))))) + .then().statusCode(200); + givenAws("CreatePolicy", objectJson(Map.of("policyStoreId", store, "definition", Map.of( + "static", Map.of("statement", "permit(principal, action, resource);"))))) + .then().statusCode(200); + + // A source naming the same pool id in another account is not this pool: the token's + // issuer matches no source there. + String foreign = createStore("OFF", "DISABLED"); + givenAws("CreateIdentitySource", objectJson(Map.of( + "policyStoreId", foreign, "principalEntityType", "User", + "configuration", Map.of("cognitoUserPoolConfiguration", Map.of( + "userPoolArn", poolArn.replaceFirst(":\\d{12}:", ":999988887777:"), + "clientIds", List.of(clientId)))))) + .then().statusCode(200); + givenAws("CreatePolicy", objectJson(Map.of("policyStoreId", foreign, "definition", Map.of( + "static", Map.of("statement", "permit(principal, action, resource);"))))) + .then().statusCode(200); + + Map request = new LinkedHashMap<>(); + request.put("policyStoreId", store); + request.put("accessToken", accessToken); + request.put("action", Map.of("actionType", "Action", "actionId", "view")); + request.put("resource", Map.of("entityType", "Photo", "entityId", "p1")); + givenAws("IsAuthorizedWithToken", objectJson(request)) + .then().statusCode(200).body("decision", equalTo("ALLOW")); + + Map foreignRequest = new LinkedHashMap<>(request); + foreignRequest.put("policyStoreId", foreign); + givenAws("IsAuthorizedWithToken", objectJson(foreignRequest)) + .then().statusCode(400).body("__type", containsString("ValidationException")) + .body("message", containsString("issuer")); + + // Same issuer, signature broken: refused, never evaluated. + String[] parts = accessToken.split("\\."); + String flipped = (parts[2].charAt(0) == 'A' ? "B" : "A") + parts[2].substring(1); + request.put("accessToken", parts[0] + "." + parts[1] + "." + flipped); + givenAws("IsAuthorizedWithToken", objectJson(request)) + .then().statusCode(400).body("__type", containsString("ValidationException")) + .body("message", containsString("signature")); + + // Same issuer, empty header: a validation error, not a server error. + request.put("accessToken", "." + parts[1] + "." + parts[2]); + givenAws("IsAuthorizedWithToken", objectJson(request)) + .then().statusCode(400).body("__type", containsString("ValidationException")); + } + @Test void deletePolicyAndPolicyStore_areIdempotentForRetries() { String store = createStore("OFF", "DISABLED"); @@ -371,6 +442,15 @@ class VerifiedPermissionsIntegrationTest { .then().statusCode(400).body("__type", containsString("ValidationException")); } + /** A Cognito call signed for the same account as the policy store, as one real deployment makes them. */ + private static JsonNode cognito(String action, String body) throws JsonProcessingException { + String response = given().contentType("application/x-amz-json-1.1") + .header("Authorization", AUTH.replace("/verifiedpermissions/", "/cognito-idp/")) + .header("X-Amz-Target", "AWSCognitoIdentityProviderService." + action).body(body) + .when().post("/").then().statusCode(200).extract().asString(); + return new ObjectMapper().readTree(response); + } + private static String objectJson(Object value) { try { return new ObjectMapper().writeValueAsString(value);