diff --git a/src/main/java/io/github/hectorvent/floci/services/cognito/CognitoService.java b/src/main/java/io/github/hectorvent/floci/services/cognito/CognitoService.java index fddb185c81..2a228abba4 100644 --- a/src/main/java/io/github/hectorvent/floci/services/cognito/CognitoService.java +++ b/src/main/java/io/github/hectorvent/floci/services/cognito/CognitoService.java @@ -89,6 +89,7 @@ public class CognitoService implements ResourceProvider { private static final Logger LOG = Logger.getLogger(CognitoService.class); private static final ObjectMapper MAPPER = new ObjectMapper(); + private static final String INVALID_ACCESS_TOKEN_MESSAGE = "Invalid access token"; private static final String IDENTITIES_ATTRIBUTE = "identities"; @@ -1655,27 +1656,16 @@ public class CognitoService implements ResourceProvider { "1 validation error detected: Value at 'accessToken' failed to satisfy constraint: Member must not be null", 400); } - String username = extractUsernameFromToken(accessToken); - String poolId = extractPoolIdFromToken(accessToken); - String jti = extractJtiFromToken(accessToken); - - if (username == null || poolId == null || jti == null) { - throw new AwsException("NotAuthorizedException", "Invalid access token", 400); - } - - // A token that was already revoked (or issued before an earlier sign-out) cannot - // authorize a fresh sign-out. - validateTokenNotRevoked(jti, poolId, "access"); - Long iat = extractIatFromToken(accessToken); - validateUserNotGloballySignedOut(username, poolId, "access", iat != null ? iat : 0L); - + VerifiedAccessToken token = verifyAccessToken(accessToken); + String username = token.username(); + String poolId = token.poolId(); CognitoUser user; try { user = adminGetUser(poolId, username); } catch (AwsException e) { if ("UserNotFoundException".equals(e.getErrorCode()) || "ResourceNotFoundException".equals(e.getErrorCode())) { - throw new AwsException("NotAuthorizedException", "Invalid access token", 400); + throw new AwsException("NotAuthorizedException", INVALID_ACCESS_TOKEN_MESSAGE, 400); } throw e; } @@ -2455,18 +2445,9 @@ public class CognitoService implements ResourceProvider { } public void changePassword(String accessToken, String previousPassword, String proposedPassword) { - String username = extractUsernameFromToken(accessToken); - String poolId = extractPoolIdFromToken(accessToken); - String jti = extractJtiFromToken(accessToken); - - if (username == null || poolId == null) { - throw new AwsException("NotAuthorizedException", "Invalid access token", 400); - } - - validateTokenNotRevoked(jti, poolId, "access"); - validateOriginJtiNotRevoked(accessToken, poolId); - Long iat = extractIatFromToken(accessToken); - validateUserNotGloballySignedOut(username, poolId, "access", iat != null ? iat : 0L); + VerifiedAccessToken token = verifyAccessToken(accessToken); + String username = token.username(); + String poolId = token.poolId(); CognitoUser user = adminGetUser(poolId, username); if (user.getPasswordHash() != null && !user.getPasswordHash().equals(hashPassword(previousPassword))) { @@ -2521,18 +2502,9 @@ public class CognitoService implements ResourceProvider { } public Map getUser(String accessToken) { - String username = extractUsernameFromToken(accessToken); - String poolId = extractPoolIdFromToken(accessToken); - String jti = extractJtiFromToken(accessToken); - - if (username == null || poolId == null || jti == null) { - throw new AwsException("NotAuthorizedException", "Invalid access token", 400); - } - - validateTokenNotRevoked(jti, poolId, "access"); - validateOriginJtiNotRevoked(accessToken, poolId); - Long iat = extractIatFromToken(accessToken); - validateUserNotGloballySignedOut(username, poolId, "access", iat != null ? iat : 0L); + VerifiedAccessToken token = verifyAccessToken(accessToken); + String username = token.username(); + String poolId = token.poolId(); CognitoUser user = adminGetUser(poolId, username); Map result = new HashMap<>(); @@ -2544,18 +2516,18 @@ public class CognitoService implements ResourceProvider { } public Map getUserAttributeVerificationCode(String accessToken, String attributeName) { - String username = extractUsernameFromToken(accessToken); - String poolId = extractPoolIdFromToken(accessToken); - String jti = extractJtiFromToken(accessToken); - - if (username == null || poolId == null || jti == null) { - throw new AwsException("NotAuthorizedException", "Invalid Access Token", 400); + VerifiedAccessToken token; + try { + token = verifyAccessToken(accessToken); + } catch (AwsException e) { + if ("NotAuthorizedException".equals(e.getErrorCode()) + && INVALID_ACCESS_TOKEN_MESSAGE.equals(e.getMessage())) { + throw new AwsException("NotAuthorizedException", "Invalid Access Token", 400); + } + throw e; } - - validateTokenNotRevoked(jti, poolId, "access"); - validateOriginJtiNotRevoked(accessToken, poolId); - Long iat = extractIatFromToken(accessToken); - validateUserNotGloballySignedOut(username, poolId, "access", iat != null ? iat : 0L); + String username = token.username(); + String poolId = token.poolId(); if (!"email".equals(attributeName) && !"phone_number".equals(attributeName)) { throw new AwsException("InvalidParameterException", @@ -2595,18 +2567,9 @@ public class CognitoService implements ResourceProvider { } public void updateUserAttributes(String accessToken, Map attributes) { - String username = extractUsernameFromToken(accessToken); - String poolId = extractPoolIdFromToken(accessToken); - String jti = extractJtiFromToken(accessToken); - - if (username == null || poolId == null) { - throw new AwsException("NotAuthorizedException", "Invalid access token", 400); - } - - validateTokenNotRevoked(jti, poolId, "access"); - validateOriginJtiNotRevoked(accessToken, poolId); - Long iat = extractIatFromToken(accessToken); - validateUserNotGloballySignedOut(username, poolId, "access", iat != null ? iat : 0L); + VerifiedAccessToken token = verifyAccessToken(accessToken); + String username = token.username(); + String poolId = token.poolId(); String verificationStatusAttribute = attributes.containsKey("email_verified") ? "email_verified" @@ -2622,18 +2585,9 @@ public class CognitoService implements ResourceProvider { } public void deleteUserAttributes(String accessToken, List attributeNames) { - String username = extractUsernameFromToken(accessToken); - String poolId = extractPoolIdFromToken(accessToken); - String jti = extractJtiFromToken(accessToken); - - if (username == null || poolId == null) { - throw new AwsException("NotAuthorizedException", "Invalid access token", 400); - } - - validateTokenNotRevoked(jti, poolId, "access"); - validateOriginJtiNotRevoked(accessToken, poolId); - Long iat = extractIatFromToken(accessToken); - validateUserNotGloballySignedOut(username, poolId, "access", iat != null ? iat : 0L); + VerifiedAccessToken token = verifyAccessToken(accessToken); + String username = token.username(); + String poolId = token.poolId(); adminDeleteUserAttributes(poolId, username, attributeNames); } @@ -3600,32 +3554,91 @@ public class CognitoService implements ResourceProvider { return null; } - private String extractUsernameFromToken(String token) { + record VerifiedAccessToken(String username, String poolId, String subject) {} + + /** + * Verifies the Cognito access-token contract before any self-service operation uses its claims. + * The pool's persisted public key is the trust anchor; claims are never trusted before the + * signature, issuer, client, token-use, and lifetime checks succeed. + */ + VerifiedAccessToken verifyAccessToken(String token) { try { - String[] parts = token.split("\\."); - if (parts.length < 2) return null; - String payloadJson = new String(Base64.getUrlDecoder().decode(parts[1]), StandardCharsets.UTF_8); - // Simple extraction without full JSON parsing - return extractJsonField(payloadJson, "username"); + if (token == null || token.isBlank()) { + throw new IllegalArgumentException("missing token"); + } + String[] parts = token.split("\\.", -1); + if (parts.length != 3 || parts[0].isEmpty() || parts[1].isEmpty() || parts[2].isEmpty()) { + throw new IllegalArgumentException("malformed JWT"); + } + + JsonNode header = MAPPER.readTree(Base64.getUrlDecoder().decode(parts[0])); + JsonNode claims = MAPPER.readTree(Base64.getUrlDecoder().decode(parts[1])); + if (!"RS256".equals(header.path("alg").asText()) + || !"JWT".equalsIgnoreCase(header.path("typ").asText())) { + throw new IllegalArgumentException("unsupported JWT algorithm"); + } + + String issuer = textClaim(claims, "iss"); + String poolId = null; + if (issuer != null && issuer.startsWith(baseUrl + "/")) { + poolId = issuer.substring((baseUrl + "/").length()); + } + UserPool pool = poolId == null ? null : poolStore.get(poolId).orElse(null); + if (pool == null || !getIssuer(poolId).equals(issuer) + || !getSigningKeyId(pool).equals(textClaim(header, "kid"))) { + throw new IllegalArgumentException("invalid issuer or key"); + } + + Signature verifier = Signature.getInstance("SHA256withRSA"); + verifier.initVerify(getSigningPublicKey(pool)); + verifier.update((parts[0] + "." + parts[1]).getBytes(StandardCharsets.UTF_8)); + if (!verifier.verify(Base64.getUrlDecoder().decode(parts[2]))) { + throw new IllegalArgumentException("invalid signature"); + } + + String verifiedPoolId = poolId; + String username = textClaim(claims, "username"); + String subject = textClaim(claims, "sub"); + String jti = textClaim(claims, "jti"); + String clientId = textClaim(claims, "client_id"); + long issuedAt = requiredNumericClaim(claims, "iat"); + long expiresAt = requiredNumericClaim(claims, "exp"); + if (username == null || subject == null || jti == null || clientId == null + || !"access".equals(textClaim(claims, "token_use")) + || clientStore.get(clientId).filter(c -> verifiedPoolId.equals(c.getUserPoolId())).isEmpty() + || expiresAt <= System.currentTimeMillis() / 1000L) { + throw new IllegalArgumentException("invalid access-token claims"); + } + + String originJti = textClaim(claims, "origin_jti"); + validateTokenNotRevoked(jti, poolId, "access"); + if (originJti != null) { + validateTokenNotRevoked(originJti, poolId, "access"); + } + validateUserNotGloballySignedOut(username, poolId, "access", issuedAt); + return new VerifiedAccessToken(username, poolId, subject); + } catch (AwsException e) { + throw e; } catch (Exception e) { - return null; + LOG.debug("Access token verification failed", e); + throw new AwsException("NotAuthorizedException", INVALID_ACCESS_TOKEN_MESSAGE, 400); } } - private String extractPoolIdFromToken(String token) { - try { - String[] parts = token.split("\\."); - if (parts.length < 2) return null; - String payloadJson = new String(Base64.getUrlDecoder().decode(parts[1]), StandardCharsets.UTF_8); - String iss = extractJsonField(payloadJson, "iss"); - if (iss == null) return null; - int lastSlash = iss.lastIndexOf('/'); - return lastSlash >= 0 ? iss.substring(lastSlash + 1) : null; - } catch (Exception e) { - return null; - } + private static String textClaim(JsonNode claims, String name) { + JsonNode value = claims.path(name); + return value.isTextual() && !value.asText().isBlank() ? value.asText() : null; } + private static long requiredNumericClaim(JsonNode claims, String name) { + JsonNode value = claims.path(name); + if (!value.isIntegralNumber()) { + throw new IllegalArgumentException("missing numeric claim"); + } + return value.asLong(); + } + + private void validateGroupName(String groupName) { if (groupName == null || groupName.isBlank()) { throw new AwsException("InvalidParameterException", "GroupName is required", 400); @@ -3633,16 +3646,6 @@ public class CognitoService implements ResourceProvider { } - private String extractJsonField(String json, String field) { - String search = "\"" + field + "\":\""; - int start = json.indexOf(search); - if (start < 0) return null; - start += search.length(); - int end = json.indexOf('"', start); - if (end < 0) return null; - return json.substring(start, end); - } - private String userKey(String poolId, String username) { return poolId + "::" + username; } @@ -3682,52 +3685,7 @@ public class CognitoService implements ResourceProvider { return updated; } - /** - * Extract JWT ID (jti) claim from a JWT token. - */ - private String extractJtiFromToken(String token) { - try { - String[] parts = token.split("\\."); - if (parts.length < 2) return null; - String payloadJson = new String(Base64.getUrlDecoder().decode(parts[1]), StandardCharsets.UTF_8); - return extractJsonField(payloadJson, "jti"); - } catch (Exception e) { - return null; - } - } - private String extractOriginJtiFromToken(String token) { - try { - String[] parts = token.split("\\."); - if (parts.length < 2) return null; - String payloadJson = new String(Base64.getUrlDecoder().decode(parts[1]), StandardCharsets.UTF_8); - return extractJsonField(payloadJson, "origin_jti"); - } catch (Exception e) { - return null; - } - } - - private Long extractIatFromToken(String token) { - try { - String[] parts = token.split("\\."); - if (parts.length < 2) return null; - String payloadJson = new String(Base64.getUrlDecoder().decode(parts[1]), StandardCharsets.UTF_8); - String iatStr = extractJsonField(payloadJson, "iat"); - if (iatStr != null) { - return Long.parseLong(iatStr); - } - // In case the simple extractor doesn't work for numbers (it extracts strings between quotes usually) - // let's use MAPPER for this specific field - Map payload = MAPPER.readValue(payloadJson, new TypeReference<>() {}); - Object iat = payload.get("iat"); - if (iat instanceof Number n) { - return n.longValue(); - } - } catch (Exception e) { - return null; - } - return null; - } /** * Validate that a refresh token has not been revoked, including global user sign-out. @@ -3774,12 +3732,6 @@ public class CognitoService implements ResourceProvider { } } - private void validateOriginJtiNotRevoked(String accessToken, String poolId) { - String originJti = extractOriginJtiFromToken(accessToken); - if (originJti != null) { - validateTokenNotRevoked(originJti, poolId, "access"); - } - } /** * Check if a user has been globally signed out (affects all their tokens). @@ -4098,37 +4050,14 @@ public class CognitoService implements ResourceProvider { Boolean emailEnabled, Boolean emailPreferred) { - String username = extractUsernameFromToken(accessToken); - String poolId = extractPoolIdFromToken(accessToken); - String jti = extractJtiFromToken(accessToken); - - if (username == null || poolId == null || jti == null) { - throw new AwsException( - "NotAuthorizedException", - "Invalid access token", - 400 - ); - } - - validateTokenNotRevoked(jti, poolId, "access"); - validateOriginJtiNotRevoked(accessToken, poolId); - - Long iat = extractIatFromToken(accessToken); - - validateUserNotGloballySignedOut( - username, - poolId, - "access", - iat != null ? iat : 0L - ); - - CognitoUser user = adminGetUser(poolId, username); + VerifiedAccessToken token = verifyAccessToken(accessToken); + CognitoUser user = adminGetUser(token.poolId(), token.username()); updateEmailMfaPreference(user, emailEnabled, emailPreferred); user.setLastModifiedDate(System.currentTimeMillis() / 1000L); - userStore.put(userKey(poolId, user.getUsername()), user); + userStore.put(userKey(token.poolId(), user.getUsername()), user); } private void updateEmailMfaPreference( diff --git a/src/main/java/io/github/hectorvent/floci/services/cognito/CognitoUserInfoController.java b/src/main/java/io/github/hectorvent/floci/services/cognito/CognitoUserInfoController.java index a0b13a00c8..fd5eea9788 100644 --- a/src/main/java/io/github/hectorvent/floci/services/cognito/CognitoUserInfoController.java +++ b/src/main/java/io/github/hectorvent/floci/services/cognito/CognitoUserInfoController.java @@ -1,6 +1,5 @@ package io.github.hectorvent.floci.services.cognito; -import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.node.ObjectNode; import io.github.hectorvent.floci.core.common.AwsException; @@ -17,7 +16,6 @@ import jakarta.ws.rs.core.MediaType; import jakarta.ws.rs.core.Response; import org.jboss.logging.Logger; -import java.util.Base64; import java.util.List; import java.util.Map; @@ -27,12 +25,10 @@ import java.util.Map; * mocks alone are insufficient for OIDC clients that resolve a user's profile * via this endpoint. * - *

Floci is a local emulator, not a security boundary: the bearer token is - * parsed but not signature-verified. The {@code iss} claim determines which - * pool to look the user up in and {@code sub} identifies the user. Attributes - * are returned with their raw Cognito names (including the {@code custom:*} - * prefix) so downstream Jackson mappings such as - * {@code @JsonProperty("custom:my_attribute")} resolve correctly. + *

Bearer access tokens are verified by the shared Cognito service verifier before + * {@code iss} and {@code sub} are used to resolve the user. Attributes are returned + * with their raw Cognito names (including the {@code custom:*} prefix) so downstream + * Jackson mappings such as {@code @JsonProperty("custom:my_attribute")} resolve correctly. * *

The response shape mirrors real AWS Cognito: snake_case keys for OIDC * standard claims and string-valued {@code email_verified} / @@ -47,7 +43,6 @@ import java.util.Map; public class CognitoUserInfoController { private static final Logger LOG = Logger.getLogger(CognitoUserInfoController.class); - private static final TypeReference> CLAIM_MAP_TYPE = new TypeReference<>() {}; private final CognitoService cognitoService; private final ObjectMapper objectMapper; @@ -67,30 +62,16 @@ public class CognitoUserInfoController { return bearerError(401, "invalid_token", "Bearer token required"); } String token = authorization.substring(7).trim(); - String[] parts = token.split("\\."); - if (parts.length < 2) { - return bearerError(401, "invalid_token", "Malformed JWT"); - } - - Map claims; + CognitoService.VerifiedAccessToken verified; try { - byte[] payload = Base64.getUrlDecoder().decode(parts[1]); - claims = objectMapper.readValue(payload, CLAIM_MAP_TYPE); - } catch (Exception e) { - LOG.debug("Failed to decode JWT payload", e); - return bearerError(401, "invalid_token", "Cannot decode JWT payload"); + verified = cognitoService.verifyAccessToken(token); + } catch (AwsException e) { + LOG.debug("Access token verification failed", e); + return bearerError(401, "invalid_token", e.getMessage()); } - String sub = asString(claims.get("sub")); - String iss = asString(claims.get("iss")); - if (sub == null || iss == null) { - return bearerError(401, "invalid_token", "Missing sub or iss claim"); - } - - String poolId = poolIdFromIssuer(iss); - if (poolId == null) { - return bearerError(401, "invalid_token", "Cannot derive user pool from iss: " + iss); - } + String sub = verified.subject(); + String poolId = verified.poolId(); String domainPoolId = (String) requestContext.getProperty(CognitoCustomDomainFilter.POOL_PROPERTY); if (domainPoolId != null && !domainPoolId.equals(poolId)) { return bearerError(401, "invalid_token", "Token was not issued by the user pool of this domain"); @@ -135,25 +116,6 @@ public class CognitoUserInfoController { "preferred_username", "profile", "picture", "website", "gender", "birthdate", "zoneinfo", "locale", "updated_at", "address"); - private static String poolIdFromIssuer(String iss) { - // iss looks like http://localhost:4566/eu-central-1_abc123 (or, in real AWS, - // https://cognito-idp..amazonaws.com/) — the pool id is the - // last path segment. - int slash = iss.lastIndexOf('/'); - if (slash < 0 || slash == iss.length() - 1) { - return null; - } - String candidate = iss.substring(slash + 1); - return candidate.contains("_") ? candidate : null; - } - - private static String asString(Object value) { - if (value == null) { - return null; - } - String s = value.toString().trim(); - return s.isEmpty() ? null : s; - } private static void putIfPresent(ObjectNode body, String key, String value) { if (value != null && !value.isEmpty()) { diff --git a/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoServiceTest.java b/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoServiceTest.java index ed52882011..acb871ec61 100644 --- a/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoServiceTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoServiceTest.java @@ -1,6 +1,7 @@ package io.github.hectorvent.floci.services.cognito; import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import io.github.hectorvent.floci.config.TlsCertificateManager; @@ -15,6 +16,7 @@ import io.github.hectorvent.floci.services.cognito.model.CognitoGroup; import io.github.hectorvent.floci.services.cognito.model.CognitoUser; import io.github.hectorvent.floci.services.cognito.model.IdentityProvider; import io.github.hectorvent.floci.services.cognito.model.ResourceServerScope; +import io.github.hectorvent.floci.services.cognito.model.RevokedTokenInfo; import io.github.hectorvent.floci.services.cognito.model.UserPool; import io.github.hectorvent.floci.services.cognito.model.UserPoolClient; import io.github.hectorvent.floci.services.cognito.model.UserPoolDomain; @@ -54,6 +56,7 @@ class CognitoServiceTest { private CognitoService service; private InMemoryStorage userStore; private InMemoryStorage groupStore; + private InMemoryStorage revokedTokenStore; private RegionResolver regionResolver; private AcmService acmService; @@ -61,6 +64,7 @@ class CognitoServiceTest { void setUp() { userStore = new InMemoryStorage<>(); groupStore = new InMemoryStorage<>(); + revokedTokenStore = new InMemoryStorage<>(); regionResolver = new RegionResolver("us-east-1", "000000000000"); acmService = mock(AcmService.class); // Every certificate exists and is issued unless a test says otherwise. @@ -72,7 +76,7 @@ class CognitoServiceTest { new InMemoryStorage<>(), userStore, groupStore, - new InMemoryStorage<>(), // revokedTokenStore + revokedTokenStore, "http://localhost:4566", regionResolver, null, @@ -3140,6 +3144,75 @@ class CognitoServiceTest { assertEquals("migrated@example.com", user.getAttributes().get("email")); } + @Test + void selfServiceRejectsForgedAccessTokenClaims() throws Exception { + UserPool pool = createPoolAndUser(); + UserPoolClient client = service.createUserPoolClient( + pool.getId(), "self-service-client", false, false, List.of(), List.of()); + CognitoUser user = service.adminGetUser(pool.getId(), "alice"); + String valid = service.generateSignedJwt(user, pool, "access", client, null, null); + UserPool otherPool = service.createUserPool(Map.of("PoolName", "OtherPool"), "us-east-1"); + CognitoUser otherUser = service.adminCreateUser(otherPool.getId(), "alice", Map.of(), null); + UserPoolClient otherClient = service.createUserPoolClient( + otherPool.getId(), "other-client", false, false, List.of(), List.of()); + + String[] parts = valid.split("\\."); + String unsigned = Base64.getUrlEncoder().withoutPadding() + .encodeToString("{\"alg\":\"none\",\"typ\":\"JWT\"}".getBytes(StandardCharsets.UTF_8)) + + "." + parts[1] + "."; + assertInvalidAccessToken(unsigned, "alg=none"); + assertInvalidAccessToken(withClaim(valid, "username", "mallory"), "modified payload"); + assertInvalidAccessToken(withClaim(valid, "iss", service.getIssuer(otherPool.getId())), "wrong user pool"); + String wrongKey = withClaim(service.generateSignedJwt(otherUser, otherPool, "access", otherClient, null, null), + "iss", service.getIssuer(pool.getId())); + wrongKey = withClaim(wrongKey, "client_id", client.getClientId()); + assertInvalidAccessToken(wrongKey, "wrong signing key"); + assertInvalidAccessToken(withClaim(valid, "iss", "https://attacker.example/issuer"), "wrong issuer"); + assertInvalidAccessToken(withClaim(valid, "client_id", "not-a-client"), "wrong client"); + assertInvalidAccessToken(withClaim(valid, "token_use", "id"), "wrong token_use"); + assertInvalidAccessToken(withClaim(valid, "exp", 1), "expired token"); + + Map claims = MAPPER.readValue(jwtPayload(valid), new TypeReference<>() {}); + String jti = (String) claims.get("jti"); + long now = System.currentTimeMillis(); + revokedTokenStore.put("revoked:" + pool.getId() + ":" + jti, + new RevokedTokenInfo(jti, "access", user.getUsername(), pool.getId(), now, now / 1000L + 3600)); + assertInvalidAccessToken(valid, "revoked jti"); + } + + @Test + void everySelfServiceEntryPointRejectsInvalidAccessToken() { + UserPool pool = createPoolAndUser(); + UserPoolClient client = service.createUserPoolClient( + pool.getId(), "self-service-client", false, false, List.of(), List.of()); + CognitoUser user = service.adminGetUser(pool.getId(), "alice"); + String signed = service.generateSignedJwt(user, pool, "access", client, null, null); + String[] parts = signed.split("\\."); + String invalid = parts[0] + "." + parts[1] + ".tampered"; + + assertThrows(AwsException.class, () -> service.getUser(invalid)); + assertThrows(AwsException.class, () -> service.changePassword(invalid, "Perm1234!", "NewPass123!")); + assertThrows(AwsException.class, () -> service.updateUserAttributes(invalid, Map.of("email", "x@example.com"))); + assertThrows(AwsException.class, () -> service.deleteUserAttributes(invalid, List.of("email"))); + assertThrows(AwsException.class, () -> service.getUserAttributeVerificationCode(invalid, "email")); + assertThrows(AwsException.class, () -> service.globalSignOut(invalid)); + assertThrows(AwsException.class, () -> service.setUserMFAPreference(invalid, true, false)); + } + + private void assertInvalidAccessToken(String token, String reason) { + AwsException failure = assertThrows(AwsException.class, () -> service.getUser(token), reason); + assertEquals("NotAuthorizedException", failure.getErrorCode(), reason); + } + + private static String withClaim(String token, String name, Object value) throws Exception { + String[] parts = token.split("\\."); + Map claims = MAPPER.readValue(jwtPayload(token), new TypeReference<>() {}); + claims.put(name, value); + String payload = Base64.getUrlEncoder().withoutPadding() + .encodeToString(MAPPER.writeValueAsBytes(claims)); + return parts[0] + "." + payload + "." + parts[2]; + } + @Test void phoneAliasPoolTokenDoesNotLeakUuidAsEmailClaim() { UserPool pool = service.createUserPool(