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
This commit is contained in:
Giovanni Brethenoux authored and GitHub committed 2026-11-13 16:25:52 -04:00
1 parent eea61cd42a
commit 294ad9679f
3 files changed
+150 -6

No files matched your search

@@ -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<String> 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");
@@ -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<IdentitySource> 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) {
@@ -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<String, Object> 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<String, Object> 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);