mirror of
https://github.com/floci-io/floci.git
synced 2026-12-01 01:12:48 -05:00
fix(cognito): AWS-accurate UsernameAttributes pools — UUID username, alias sign-in, and token/revocation parity (#1849)
* feat: mint UUID username with mutable email alias for UsernameAttributes pools * fix(cognito): align token claims, alias-exists, read-attributes, and not-found status with AWS * fix(cognito): align token claims, alias-exists, read-attributes, not-found status, and canonical-username revocation with AWS * fix(cognito): accept canonical UUID on RESEND, harden migration sub-minting and email validation) * fix(cognito): AliasExistsException guard check * test(cloudformation): expect 400 for Cognito ResourceNotFoundException Align the post-deletion DescribeUserPool/DescribeUserPoolClient assertions with the AWS-accurate 400 status now returned for Cognito ResourceNotFoundException. * fix(cognito): bind CUSTOM_AUTH challenge USERNAME to the session user RespondToAuthChallenge validated SECRET_HASH against the caller-supplied USERNAME while resolving the user from the session, so the two were allowed to disagree. That reduced SECRET_HASH from a per-user binding to a bare proof-of-client-secret check, and let callers pass locally against requests real Cognito rejects. Resolve the supplied USERNAME the same way sign-in does and require it to match the session user; aliases still work since the caller may legitimately send the email while the session holds the UUID. Also compare SECRET_HASH with MessageDigest.isEqual instead of String.equals so the MAC comparison does not short-circuit on the first differing byte, matching the SRP path in CognitoSrpHelper.
This commit is contained in:
1 parent
5c45c146c7
commit
1ca19c722a
9 files changed
+1071
-81
No files matched your search
+3
-3
@@ -5706,7 +5706,7 @@ class CloudFormationIntegrationTest {
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(404);
|
||||
.statusCode(400);
|
||||
|
||||
given()
|
||||
.header("X-Amz-Target", "AWSCognitoIdentityProviderService.DescribeUserPoolClient")
|
||||
@@ -5715,7 +5715,7 @@ class CloudFormationIntegrationTest {
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(404);
|
||||
.statusCode(400);
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -5816,7 +5816,7 @@ class CloudFormationIntegrationTest {
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(404);
|
||||
.statusCode(400);
|
||||
}
|
||||
|
||||
@Test
|
||||
|
||||
+287
@@ -0,0 +1,287 @@
|
||||
package io.github.hectorvent.floci.services.cognito;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import io.github.hectorvent.floci.testing.RestAssuredJsonUtils;
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import io.restassured.response.Response;
|
||||
import org.junit.jupiter.api.BeforeAll;
|
||||
import org.junit.jupiter.api.MethodOrderer;
|
||||
import org.junit.jupiter.api.Order;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.TestMethodOrder;
|
||||
|
||||
import javax.crypto.Mac;
|
||||
import javax.crypto.spec.SecretKeySpec;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.Base64;
|
||||
import java.util.UUID;
|
||||
|
||||
import static io.github.hectorvent.floci.services.cognito.CognitoRestAssuredUtils.cognitoAction;
|
||||
import static io.github.hectorvent.floci.services.cognito.CognitoRestAssuredUtils.cognitoJson;
|
||||
import static org.hamcrest.Matchers.containsString;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertNotEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
/**
|
||||
* End-to-end (AWS wire protocol) coverage for a user pool created with
|
||||
* {@code UsernameAttributes = ["email"]}. Mirrors real Cognito: the canonical
|
||||
* {@code Username} is an immutable UUID equal to {@code sub}, the email is a mutable
|
||||
* sign-in alias, {@code SECRET_HASH} is validated against the sent USERNAME, and changing
|
||||
* the email rebinds sign-in without moving the username/sub.
|
||||
*/
|
||||
@QuarkusTest
|
||||
@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
|
||||
class CognitoAliasUsernameIntegrationTest {
|
||||
|
||||
private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();
|
||||
|
||||
private static final String EMAIL = "alias+" + UUID.randomUUID() + "@example.com";
|
||||
private static final String NEW_EMAIL = "changed+" + UUID.randomUUID() + "@example.com";
|
||||
private static final String PASSWORD = "Perm1234!";
|
||||
|
||||
private static String poolId;
|
||||
private static String clientId;
|
||||
private static String clientSecret;
|
||||
private static String uuidUsername;
|
||||
|
||||
@BeforeAll
|
||||
static void configureRestAssured() {
|
||||
RestAssuredJsonUtils.configureAwsContentTypes();
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(1)
|
||||
void adminCreateUserMintsUuidUsernameEqualToSub() throws Exception {
|
||||
JsonNode poolResponse = cognitoJson("CreateUserPool", """
|
||||
{
|
||||
"PoolName": "AliasEmailPool",
|
||||
"UsernameAttributes": ["email"],
|
||||
"AutoVerifiedAttributes": ["email"]
|
||||
}
|
||||
""");
|
||||
poolId = poolResponse.path("UserPool").path("Id").asText();
|
||||
|
||||
JsonNode clientResponse = cognitoJson("CreateUserPoolClient", """
|
||||
{
|
||||
"UserPoolId": "%s",
|
||||
"ClientName": "alias-client",
|
||||
"GenerateSecret": true,
|
||||
"ExplicitAuthFlows": [
|
||||
"ALLOW_USER_PASSWORD_AUTH",
|
||||
"ALLOW_ADMIN_USER_PASSWORD_AUTH",
|
||||
"ALLOW_REFRESH_TOKEN_AUTH"
|
||||
]
|
||||
}
|
||||
""".formatted(poolId));
|
||||
clientId = clientResponse.path("UserPoolClient").path("ClientId").asText();
|
||||
clientSecret = clientResponse.path("UserPoolClient").path("ClientSecret").asText();
|
||||
assertTrue(clientSecret != null && !clientSecret.isBlank(), "client secret must be generated");
|
||||
|
||||
JsonNode createResponse = cognitoJson("AdminCreateUser", """
|
||||
{
|
||||
"UserPoolId": "%s",
|
||||
"Username": "%s",
|
||||
"UserAttributes": [
|
||||
{ "Name": "email", "Value": "%s" },
|
||||
{ "Name": "email_verified", "Value": "true" }
|
||||
]
|
||||
}
|
||||
""".formatted(poolId, EMAIL, EMAIL));
|
||||
|
||||
JsonNode user = createResponse.path("User");
|
||||
uuidUsername = user.path("Username").asText();
|
||||
|
||||
assertTrue(isUuid(uuidUsername), "canonical Username must be a generated UUID, was: " + uuidUsername);
|
||||
assertNotEquals(EMAIL, uuidUsername, "Username must not be the email");
|
||||
assertEquals(uuidUsername, attribute(user.path("Attributes"), "sub"), "Username must equal sub");
|
||||
assertEquals(EMAIL, attribute(user.path("Attributes"), "email"), "email must be stored as an attribute");
|
||||
|
||||
cognitoAction("AdminSetUserPassword", """
|
||||
{
|
||||
"UserPoolId": "%s",
|
||||
"Username": "%s",
|
||||
"Password": "%s",
|
||||
"Permanent": true
|
||||
}
|
||||
""".formatted(poolId, EMAIL, PASSWORD))
|
||||
.then()
|
||||
.statusCode(200);
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(2)
|
||||
void listUsersReturnsUuidUsername() throws Exception {
|
||||
JsonNode response = cognitoJson("ListUsers", """
|
||||
{ "UserPoolId": "%s" }
|
||||
""".formatted(poolId));
|
||||
|
||||
JsonNode users = response.path("Users");
|
||||
assertEquals(1, users.size());
|
||||
assertEquals(uuidUsername, users.get(0).path("Username").asText());
|
||||
assertEquals(EMAIL, attribute(users.get(0).path("Attributes"), "email"));
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(3)
|
||||
void adminGetUserResolvesByUuidAndByEmailToUuid() throws Exception {
|
||||
JsonNode byUuid = cognitoJson("AdminGetUser", """
|
||||
{ "UserPoolId": "%s", "Username": "%s" }
|
||||
""".formatted(poolId, uuidUsername));
|
||||
assertEquals(uuidUsername, byUuid.path("Username").asText());
|
||||
|
||||
JsonNode byEmail = cognitoJson("AdminGetUser", """
|
||||
{ "UserPoolId": "%s", "Username": "%s" }
|
||||
""".formatted(poolId, EMAIL));
|
||||
assertEquals(uuidUsername, byEmail.path("Username").asText());
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(4)
|
||||
void signInByEmailAliasIssuesTokensWithUuidClaims() throws Exception {
|
||||
Response authResponse = initiateUserPasswordAuth(EMAIL);
|
||||
authResponse.then().statusCode(200);
|
||||
|
||||
String accessToken = authResponse.jsonPath().getString("AuthenticationResult.AccessToken");
|
||||
String idToken = authResponse.jsonPath().getString("AuthenticationResult.IdToken");
|
||||
|
||||
// AWS token split: access token has `username` (not `cognito:username`, not `email`).
|
||||
JsonNode access = decodeJwtPayload(accessToken);
|
||||
assertEquals(uuidUsername, access.path("sub").asText());
|
||||
assertEquals(uuidUsername, access.path("username").asText());
|
||||
assertTrue(access.path("cognito:username").isMissingNode(),
|
||||
"access token must not carry cognito:username (AWS emits it only in the id token)");
|
||||
assertTrue(access.path("email").isMissingNode(),
|
||||
"access token must not carry the email claim (AWS emits it only in the id token)");
|
||||
|
||||
// ID token has `cognito:username` and `email` (not `username`).
|
||||
JsonNode id = decodeJwtPayload(idToken);
|
||||
assertEquals(uuidUsername, id.path("sub").asText());
|
||||
assertEquals(uuidUsername, id.path("cognito:username").asText());
|
||||
assertEquals(EMAIL, id.path("email").asText());
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(5)
|
||||
void signInByUuidAlsoIssuesTokens() {
|
||||
initiateUserPasswordAuth(uuidUsername).then().statusCode(200)
|
||||
.body("AuthenticationResult.AccessToken", org.hamcrest.Matchers.notNullValue());
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(6)
|
||||
void secretHashValidatedAgainstSentUsername() {
|
||||
// USERNAME=email but SECRET_HASH computed over the UUID -> must be rejected.
|
||||
cognitoAction("InitiateAuth", """
|
||||
{
|
||||
"ClientId": "%s",
|
||||
"AuthFlow": "USER_PASSWORD_AUTH",
|
||||
"AuthParameters": {
|
||||
"USERNAME": "%s",
|
||||
"PASSWORD": "%s",
|
||||
"SECRET_HASH": "%s"
|
||||
}
|
||||
}
|
||||
""".formatted(clientId, EMAIL, PASSWORD, secretHash(uuidUsername)))
|
||||
.then()
|
||||
.statusCode(400)
|
||||
.body("__type", containsString("NotAuthorizedException"));
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(7)
|
||||
void emailChangeRebindsSignInAndKeepsUsernameAndSub() throws Exception {
|
||||
cognitoAction("AdminUpdateUserAttributes", """
|
||||
{
|
||||
"UserPoolId": "%s",
|
||||
"Username": "%s",
|
||||
"UserAttributes": [ { "Name": "email", "Value": "%s" } ]
|
||||
}
|
||||
""".formatted(poolId, uuidUsername, NEW_EMAIL))
|
||||
.then()
|
||||
.statusCode(200);
|
||||
|
||||
// New email now signs in.
|
||||
initiateUserPasswordAuth(NEW_EMAIL).then().statusCode(200)
|
||||
.body("AuthenticationResult.AccessToken", org.hamcrest.Matchers.notNullValue());
|
||||
|
||||
// Old email no longer resolves.
|
||||
cognitoAction("InitiateAuth", """
|
||||
{
|
||||
"ClientId": "%s",
|
||||
"AuthFlow": "USER_PASSWORD_AUTH",
|
||||
"AuthParameters": {
|
||||
"USERNAME": "%s",
|
||||
"PASSWORD": "%s",
|
||||
"SECRET_HASH": "%s"
|
||||
}
|
||||
}
|
||||
""".formatted(clientId, EMAIL, PASSWORD, secretHash(EMAIL)))
|
||||
.then()
|
||||
.statusCode(400)
|
||||
.body("__type", containsString("UserNotFoundException"));
|
||||
|
||||
// Immutable username / sub unchanged; email attribute updated.
|
||||
JsonNode user = cognitoJson("AdminGetUser", """
|
||||
{ "UserPoolId": "%s", "Username": "%s" }
|
||||
""".formatted(poolId, uuidUsername));
|
||||
assertEquals(uuidUsername, user.path("Username").asText());
|
||||
assertEquals(uuidUsername, attribute(user.path("UserAttributes"), "sub"));
|
||||
assertEquals(NEW_EMAIL, attribute(user.path("UserAttributes"), "email"));
|
||||
}
|
||||
|
||||
// ──────────────────────────── helpers ────────────────────────────
|
||||
|
||||
private static Response initiateUserPasswordAuth(String username) {
|
||||
return cognitoAction("InitiateAuth", """
|
||||
{
|
||||
"ClientId": "%s",
|
||||
"AuthFlow": "USER_PASSWORD_AUTH",
|
||||
"AuthParameters": {
|
||||
"USERNAME": "%s",
|
||||
"PASSWORD": "%s",
|
||||
"SECRET_HASH": "%s"
|
||||
}
|
||||
}
|
||||
""".formatted(clientId, username, PASSWORD, secretHash(username)));
|
||||
}
|
||||
|
||||
private static String secretHash(String username) {
|
||||
try {
|
||||
Mac mac = Mac.getInstance("HmacSHA256");
|
||||
mac.init(new SecretKeySpec(clientSecret.getBytes(StandardCharsets.UTF_8), "HmacSHA256"));
|
||||
byte[] sig = mac.doFinal((username + clientId).getBytes(StandardCharsets.UTF_8));
|
||||
return Base64.getEncoder().encodeToString(sig);
|
||||
} catch (Exception e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
}
|
||||
|
||||
private static boolean isUuid(String value) {
|
||||
try {
|
||||
UUID.fromString(value);
|
||||
return true;
|
||||
} catch (RuntimeException e) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
private static String attribute(JsonNode attributesArray, String name) {
|
||||
for (JsonNode attr : attributesArray) {
|
||||
if (name.equals(attr.path("Name").asText())) {
|
||||
return attr.path("Value").asText();
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
private static JsonNode decodeJwtPayload(String token) throws Exception {
|
||||
String[] parts = token.split("\\.");
|
||||
assertEquals(3, parts.length);
|
||||
String payload = parts[1];
|
||||
int pad = (4 - payload.length() % 4) % 4;
|
||||
payload += "=".repeat(pad);
|
||||
return OBJECT_MAPPER.readTree(Base64.getUrlDecoder().decode(payload));
|
||||
}
|
||||
}
|
||||
+2
-2
@@ -810,7 +810,7 @@ class CognitoIntegrationTest {
|
||||
}
|
||||
""".formatted(poolId))
|
||||
.then()
|
||||
.statusCode(404);
|
||||
.statusCode(400);
|
||||
}
|
||||
|
||||
// ── UpdateGroup & ListUsersInGroup ────────────────────────────────
|
||||
@@ -1440,7 +1440,7 @@ class CognitoIntegrationTest {
|
||||
}
|
||||
""".formatted(clientId, poolId))
|
||||
.then()
|
||||
.statusCode(404);
|
||||
.statusCode(400);
|
||||
}
|
||||
|
||||
@Test
|
||||
|
||||
+169
@@ -13,7 +13,10 @@ import io.github.hectorvent.floci.services.lambda.model.InvocationType;
|
||||
import io.github.hectorvent.floci.services.lambda.model.InvokeResult;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.mockito.ArgumentCaptor;
|
||||
|
||||
import javax.crypto.Mac;
|
||||
import javax.crypto.spec.SecretKeySpec;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.Base64;
|
||||
import java.util.HashMap;
|
||||
@@ -21,6 +24,7 @@ import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertNotEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertNotNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
@@ -719,4 +723,169 @@ class CognitoLambdaTriggersTest {
|
||||
assertEquals("DefineAuthChallenge trigger failed: DefineAuthChallenge trigger returned a non-object response",
|
||||
ex.getMessage());
|
||||
}
|
||||
|
||||
// =========================================================================
|
||||
// UsernameAttributes=email: triggers receive the canonical UUID as event.userName
|
||||
// =========================================================================
|
||||
|
||||
private UserPool createEmailAliasPoolWithLambdaConfig(Map<String, Object> lambdaConfig) {
|
||||
Map<String, Object> req = new HashMap<>();
|
||||
req.put("PoolName", "alias-trigger-pool");
|
||||
req.put("UsernameAttributes", List.of("email"));
|
||||
req.put("LambdaConfig", lambdaConfig);
|
||||
return service.createUserPool(req, "us-east-1");
|
||||
}
|
||||
|
||||
@Test
|
||||
void aliasPoolTriggerReceivesUuidUserNameAndEmailAttribute() throws Exception {
|
||||
UserPool pool = createEmailAliasPoolWithLambdaConfig(
|
||||
Map.of("PreAuthentication", "arn:aws:lambda:::pre"));
|
||||
UserPoolClient client = createClient(pool);
|
||||
|
||||
// Alias pool: the supplied value is the email; canonical username is a minted UUID == sub.
|
||||
CognitoUser user = service.adminCreateUser(pool.getId(), "person@example.com",
|
||||
Map.of("email", "person@example.com"), null);
|
||||
service.adminSetUserPassword(pool.getId(), "person@example.com", "Perm1234!", true);
|
||||
String uuid = user.getUsername();
|
||||
|
||||
when(lambdaService.invoke(anyString(), eq("arn:aws:lambda:::pre"), any(byte[].class), any()))
|
||||
.thenReturn(ok(Map.of()));
|
||||
|
||||
// Sign in with the email alias.
|
||||
service.initiateAuth(client.getClientId(), "USER_PASSWORD_AUTH",
|
||||
Map.of("USERNAME", "person@example.com", "PASSWORD", "Perm1234!"));
|
||||
|
||||
ArgumentCaptor<byte[]> payloadCaptor = ArgumentCaptor.forClass(byte[].class);
|
||||
verify(lambdaService, atLeastOnce())
|
||||
.invoke(anyString(), eq("arn:aws:lambda:::pre"), payloadCaptor.capture(), any());
|
||||
|
||||
Map<String, Object> event = MAPPER.readValue(payloadCaptor.getValue(), new TypeReference<>() {});
|
||||
assertEquals(uuid, event.get("userName"), "trigger event.userName must be the canonical UUID");
|
||||
assertNotEquals("person@example.com", event.get("userName"));
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
Map<String, Object> request = (Map<String, Object>) event.get("request");
|
||||
@SuppressWarnings("unchecked")
|
||||
Map<String, Object> userAttributes = (Map<String, Object>) request.get("userAttributes");
|
||||
assertEquals("person@example.com", userAttributes.get("email"),
|
||||
"trigger event.request.userAttributes.email must be the sign-in email");
|
||||
assertEquals(uuid, userAttributes.get("sub"));
|
||||
}
|
||||
|
||||
@Test
|
||||
@SuppressWarnings("unchecked")
|
||||
void aliasPoolCustomAuthEchoesUuidUsernameAndValidatesSecretHashAgainstSentValue() {
|
||||
Map<String, Object> req = new HashMap<>();
|
||||
req.put("PoolName", "alias-custom-pool");
|
||||
req.put("UsernameAttributes", List.of("email"));
|
||||
req.put("LambdaConfig", Map.of(
|
||||
"DefineAuthChallenge", "arn:aws:lambda:::define",
|
||||
"CreateAuthChallenge", "arn:aws:lambda:::create",
|
||||
"VerifyAuthChallengeResponse", "arn:aws:lambda:::verify"));
|
||||
UserPool pool = service.createUserPool(req, "us-east-1");
|
||||
UserPoolClient client = service.createUserPoolClient(
|
||||
pool.getId(), "c", true, false, List.of(), List.of());
|
||||
String secret = client.getClientSecret();
|
||||
assertNotNull(secret);
|
||||
|
||||
CognitoUser user = service.adminCreateUser(pool.getId(), "custom@example.com",
|
||||
Map.of("email", "custom@example.com"), null);
|
||||
service.adminSetUserPassword(pool.getId(), "custom@example.com", "Perm1234!", true);
|
||||
String uuid = user.getUsername();
|
||||
|
||||
when(lambdaService.invoke(anyString(), eq("arn:aws:lambda:::define"), any(byte[].class), any()))
|
||||
.thenReturn(ok(Map.of("challengeName", "CUSTOM_CHALLENGE")))
|
||||
.thenReturn(ok(Map.of("issueTokens", true)));
|
||||
when(lambdaService.invoke(anyString(), eq("arn:aws:lambda:::create"), any(byte[].class), any()))
|
||||
.thenReturn(ok(Map.of("publicChallengeParameters", Map.of("question", "q"),
|
||||
"privateChallengeParameters", Map.of("answer", "blue"))));
|
||||
when(lambdaService.invoke(anyString(), eq("arn:aws:lambda:::verify"), any(byte[].class), any()))
|
||||
.thenReturn(ok(Map.of("answerCorrect", true)));
|
||||
|
||||
// Round 1: sign in with the email alias.
|
||||
Map<String, Object> init = service.initiateAuth(client.getClientId(), "CUSTOM_AUTH",
|
||||
Map.of("USERNAME", "custom@example.com"));
|
||||
Map<String, String> challengeParams = (Map<String, String>) init.get("ChallengeParameters");
|
||||
// ChallengeParameters.USERNAME must echo the canonical UUID (as real AWS does), not the email.
|
||||
assertEquals(uuid, challengeParams.get("USERNAME"));
|
||||
assertNotEquals("custom@example.com", challengeParams.get("USERNAME"));
|
||||
String session = (String) init.get("Session");
|
||||
|
||||
// Round 2 with USERNAME=UUID but SECRET_HASH computed over the email -> rejected
|
||||
// (SECRET_HASH is validated against the sent USERNAME).
|
||||
AwsException ex = assertThrows(AwsException.class, () ->
|
||||
service.respondToAuthChallenge(client.getClientId(), "CUSTOM_CHALLENGE", session,
|
||||
Map.of("USERNAME", uuid, "ANSWER", "blue",
|
||||
"SECRET_HASH", secretHash(secret, "custom@example.com", client.getClientId()))));
|
||||
assertEquals("NotAuthorizedException", ex.getErrorCode());
|
||||
|
||||
// Round 2 with USERNAME=UUID and a matching SECRET_HASH over the UUID -> tokens issued.
|
||||
Map<String, Object> tokens = service.respondToAuthChallenge(client.getClientId(),
|
||||
"CUSTOM_CHALLENGE", session,
|
||||
Map.of("USERNAME", uuid, "ANSWER", "blue",
|
||||
"SECRET_HASH", secretHash(secret, uuid, client.getClientId())));
|
||||
assertNotNull(((Map<String, Object>) tokens.get("AuthenticationResult")).get("AccessToken"));
|
||||
}
|
||||
|
||||
@Test
|
||||
@SuppressWarnings("unchecked")
|
||||
void customAuthRejectsChallengeResponseUsernameThatIsNotTheSessionUser() {
|
||||
Map<String, Object> req = new HashMap<>();
|
||||
req.put("PoolName", "alias-custom-binding-pool");
|
||||
req.put("UsernameAttributes", List.of("email"));
|
||||
req.put("LambdaConfig", Map.of(
|
||||
"DefineAuthChallenge", "arn:aws:lambda:::define",
|
||||
"CreateAuthChallenge", "arn:aws:lambda:::create",
|
||||
"VerifyAuthChallengeResponse", "arn:aws:lambda:::verify"));
|
||||
UserPool pool = service.createUserPool(req, "us-east-1");
|
||||
UserPoolClient client = service.createUserPoolClient(
|
||||
pool.getId(), "c", true, false, List.of(), List.of());
|
||||
String secret = client.getClientSecret();
|
||||
assertNotNull(secret);
|
||||
|
||||
service.adminCreateUser(pool.getId(), "victim@example.com",
|
||||
Map.of("email", "victim@example.com"), null);
|
||||
CognitoUser other = service.adminCreateUser(pool.getId(), "other@example.com",
|
||||
Map.of("email", "other@example.com"), null);
|
||||
|
||||
when(lambdaService.invoke(anyString(), eq("arn:aws:lambda:::define"), any(byte[].class), any()))
|
||||
.thenReturn(ok(Map.of("challengeName", "CUSTOM_CHALLENGE")))
|
||||
.thenReturn(ok(Map.of("issueTokens", true)));
|
||||
when(lambdaService.invoke(anyString(), eq("arn:aws:lambda:::create"), any(byte[].class), any()))
|
||||
.thenReturn(ok(Map.of("publicChallengeParameters", Map.of("question", "q"),
|
||||
"privateChallengeParameters", Map.of("answer", "blue"))));
|
||||
when(lambdaService.invoke(anyString(), eq("arn:aws:lambda:::verify"), any(byte[].class), any()))
|
||||
.thenReturn(ok(Map.of("answerCorrect", true)));
|
||||
|
||||
Map<String, Object> init = service.initiateAuth(client.getClientId(), "CUSTOM_AUTH",
|
||||
Map.of("USERNAME", "victim@example.com"));
|
||||
String session = (String) init.get("Session");
|
||||
|
||||
// A SECRET_HASH that is valid for a *different* user must not satisfy the challenge:
|
||||
// the sent USERNAME has to resolve to the session's user, as it does in real Cognito.
|
||||
AwsException ex = assertThrows(AwsException.class, () ->
|
||||
service.respondToAuthChallenge(client.getClientId(), "CUSTOM_CHALLENGE", session,
|
||||
Map.of("USERNAME", other.getUsername(), "ANSWER", "blue",
|
||||
"SECRET_HASH", secretHash(secret, other.getUsername(), client.getClientId()))));
|
||||
assertEquals("NotAuthorizedException", ex.getErrorCode());
|
||||
|
||||
// The session user's own email alias still resolves to the session user, so it is accepted
|
||||
// even though the session was keyed off the canonical UUID.
|
||||
Map<String, Object> tokens = service.respondToAuthChallenge(client.getClientId(),
|
||||
"CUSTOM_CHALLENGE", session,
|
||||
Map.of("USERNAME", "victim@example.com", "ANSWER", "blue",
|
||||
"SECRET_HASH", secretHash(secret, "victim@example.com", client.getClientId())));
|
||||
assertNotNull(((Map<String, Object>) tokens.get("AuthenticationResult")).get("AccessToken"));
|
||||
}
|
||||
|
||||
private static String secretHash(String secret, String username, String clientId) {
|
||||
try {
|
||||
Mac mac = Mac.getInstance("HmacSHA256");
|
||||
mac.init(new SecretKeySpec(secret.getBytes(StandardCharsets.UTF_8), "HmacSHA256"));
|
||||
byte[] sig = mac.doFinal((username + clientId).getBytes(StandardCharsets.UTF_8));
|
||||
return Base64.getEncoder().encodeToString(sig);
|
||||
} catch (Exception e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1596,10 +1596,13 @@ class CognitoServiceTest {
|
||||
Map.of("PoolName", "TestPool", "UsernameAttributes", List.of("email")),
|
||||
"us-east-1"
|
||||
);
|
||||
service.adminCreateUser(pool.getId(), "bob", Map.of("email", "bob@example.com"), null);
|
||||
// UsernameAttributes=email pools mint a UUID username; the supplied email is the alias.
|
||||
CognitoUser created = service.adminCreateUser(pool.getId(), "bob@example.com",
|
||||
Map.of("email", "bob@example.com"), null);
|
||||
|
||||
CognitoUser found = service.adminGetUser(pool.getId(), "bob@example.com");
|
||||
assertEquals("bob", found.getUsername());
|
||||
assertEquals(created.getUsername(), found.getUsername());
|
||||
assertEquals(found.getAttributes().get("sub"), found.getUsername());
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -1608,10 +1611,12 @@ class CognitoServiceTest {
|
||||
Map.of("PoolName", "TestPool", "UsernameAttributes", List.of("phone_number")),
|
||||
"us-east-1"
|
||||
);
|
||||
service.adminCreateUser(pool.getId(), "bob", Map.of("phone_number", "+15551234567"), null);
|
||||
CognitoUser created = service.adminCreateUser(pool.getId(), "+15551234567",
|
||||
Map.of("phone_number", "+15551234567"), null);
|
||||
|
||||
CognitoUser found = service.adminGetUser(pool.getId(), "+15551234567");
|
||||
assertEquals("bob", found.getUsername());
|
||||
assertEquals(created.getUsername(), found.getUsername());
|
||||
assertEquals(found.getAttributes().get("sub"), found.getUsername());
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -2613,4 +2618,321 @@ class CognitoServiceTest {
|
||||
}
|
||||
}
|
||||
|
||||
// ──────── UsernameAttributes=email: immutable UUID username + mutable email alias ────────
|
||||
|
||||
private UserPool createEmailAliasPool() {
|
||||
Map<String, Object> req = new HashMap<>();
|
||||
req.put("PoolName", "EmailAliasPool");
|
||||
req.put("UsernameAttributes", List.of("email"));
|
||||
return service.createUserPool(req, "us-east-1");
|
||||
}
|
||||
|
||||
private static boolean isUuid(String value) {
|
||||
try {
|
||||
java.util.UUID.fromString(value);
|
||||
return true;
|
||||
} catch (RuntimeException e) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void emailAliasPoolMintsUuidUsernameEqualToSub() {
|
||||
UserPool pool = createEmailAliasPool();
|
||||
CognitoUser user = service.adminCreateUser(pool.getId(), "ew@gmail.com",
|
||||
new HashMap<>(Map.of("email", "ew@gmail.com")), null);
|
||||
|
||||
assertTrue(isUuid(user.getUsername()), "canonical username must be a generated UUID");
|
||||
assertEquals(user.getAttributes().get("sub"), user.getUsername(), "username must equal sub");
|
||||
assertNotEquals("ew@gmail.com", user.getUsername());
|
||||
assertEquals("ew@gmail.com", user.getAttributes().get("email"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void emailAliasPoolResolvesByUuidAndByEmail() {
|
||||
UserPool pool = createEmailAliasPool();
|
||||
CognitoUser created = service.adminCreateUser(pool.getId(), "a@b.com",
|
||||
new HashMap<>(Map.of("email", "a@b.com")), null);
|
||||
String uuid = created.getUsername();
|
||||
|
||||
assertEquals(uuid, service.adminGetUser(pool.getId(), uuid).getUsername());
|
||||
assertEquals(uuid, service.adminGetUser(pool.getId(), "a@b.com").getUsername());
|
||||
}
|
||||
|
||||
@Test
|
||||
void emailAliasPoolListUsersReturnsUuidUsername() {
|
||||
UserPool pool = createEmailAliasPool();
|
||||
CognitoUser created = service.adminCreateUser(pool.getId(), "list@b.com",
|
||||
new HashMap<>(Map.of("email", "list@b.com")), null);
|
||||
|
||||
List<CognitoUser> users = service.listUsers(pool.getId(), null);
|
||||
assertEquals(1, users.size());
|
||||
assertEquals(created.getUsername(), users.get(0).getUsername());
|
||||
assertTrue(isUuid(users.get(0).getUsername()));
|
||||
}
|
||||
|
||||
@Test
|
||||
void emailAliasPoolRejectsDuplicateEmail() {
|
||||
UserPool pool = createEmailAliasPool();
|
||||
service.adminCreateUser(pool.getId(), "dup@b.com",
|
||||
new HashMap<>(Map.of("email", "dup@b.com")), null);
|
||||
|
||||
AwsException ex = assertThrows(AwsException.class,
|
||||
() -> service.adminCreateUser(pool.getId(), "dup@b.com",
|
||||
new HashMap<>(Map.of("email", "dup@b.com")), null));
|
||||
assertEquals("UsernameExistsException", ex.getErrorCode());
|
||||
}
|
||||
|
||||
@Test
|
||||
void emailAliasPoolRejectsNonEmailUsername() {
|
||||
UserPool pool = createEmailAliasPool();
|
||||
AwsException ex = assertThrows(AwsException.class,
|
||||
() -> service.adminCreateUser(pool.getId(), "not-an-email", new HashMap<>(), null));
|
||||
assertEquals("InvalidParameterException", ex.getErrorCode());
|
||||
}
|
||||
|
||||
@Test
|
||||
void emailAliasPoolEmailChangeRebindsSignInAndKeepsSub() {
|
||||
UserPool pool = createEmailAliasPool();
|
||||
CognitoUser created = service.adminCreateUser(pool.getId(), "old@b.com",
|
||||
new HashMap<>(Map.of("email", "old@b.com")), null);
|
||||
String uuid = created.getUsername();
|
||||
String sub = created.getAttributes().get("sub");
|
||||
|
||||
service.adminUpdateUserAttributes(pool.getId(), uuid, Map.of("email", "new@b.com"));
|
||||
|
||||
assertEquals(uuid, service.adminGetUser(pool.getId(), "new@b.com").getUsername());
|
||||
AwsException ex = assertThrows(AwsException.class,
|
||||
() -> service.adminGetUser(pool.getId(), "old@b.com"));
|
||||
assertEquals("UserNotFoundException", ex.getErrorCode());
|
||||
|
||||
CognitoUser after = service.adminGetUser(pool.getId(), uuid);
|
||||
assertEquals(uuid, after.getUsername());
|
||||
assertEquals(sub, after.getAttributes().get("sub"));
|
||||
assertEquals("new@b.com", after.getAttributes().get("email"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void emailAliasPoolRejectsEmailChangeToTakenEmail() {
|
||||
UserPool pool = createEmailAliasPool();
|
||||
service.adminCreateUser(pool.getId(), "taken@b.com",
|
||||
new HashMap<>(Map.of("email", "taken@b.com")), null);
|
||||
CognitoUser second = service.adminCreateUser(pool.getId(), "mover@b.com",
|
||||
new HashMap<>(Map.of("email", "mover@b.com")), null);
|
||||
|
||||
AwsException ex = assertThrows(AwsException.class,
|
||||
() -> service.adminUpdateUserAttributes(pool.getId(), second.getUsername(),
|
||||
Map.of("email", "taken@b.com")));
|
||||
assertEquals("AliasExistsException", ex.getErrorCode());
|
||||
}
|
||||
|
||||
@Test
|
||||
void classicPoolKeepsLiteralUsername() {
|
||||
UserPool pool = service.createUserPool(Map.of("PoolName", "ClassicPool"), "us-east-1");
|
||||
CognitoUser user = service.adminCreateUser(pool.getId(), "bob",
|
||||
new HashMap<>(Map.of("email", "bob@example.com")), null);
|
||||
|
||||
assertEquals("bob", user.getUsername());
|
||||
assertNotEquals(user.getAttributes().get("sub"), user.getUsername());
|
||||
assertEquals("bob", service.adminGetUser(pool.getId(), "bob").getUsername());
|
||||
}
|
||||
|
||||
@Test
|
||||
void emailAliasPoolIgnoresCallerSuppliedSub() {
|
||||
UserPool pool = createEmailAliasPool();
|
||||
CognitoUser user = service.adminCreateUser(pool.getId(), "hijack@b.com",
|
||||
new HashMap<>(Map.of("email", "hijack@b.com", "sub", "attacker-controlled")), null);
|
||||
|
||||
assertNotEquals("attacker-controlled", user.getUsername());
|
||||
assertNotEquals("attacker-controlled", user.getAttributes().get("sub"));
|
||||
assertTrue(isUuid(user.getUsername()));
|
||||
assertEquals(user.getUsername(), user.getAttributes().get("sub"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void emailAliasPoolResendByUuidRefreshesUser() {
|
||||
UserPool pool = createEmailAliasPool();
|
||||
CognitoUser created = service.adminCreateUser(pool.getId(), "resend@example.com",
|
||||
new HashMap<>(Map.of("email", "resend@example.com")), "Temp123!", null);
|
||||
String uuid = created.getUsername();
|
||||
assertEquals("FORCE_CHANGE_PASSWORD", created.getUserStatus());
|
||||
|
||||
// RESEND addressed by the minted canonical UUID (not a valid email alias) must
|
||||
// refresh the invitation, not throw InvalidParameterException.
|
||||
CognitoUser resentByUuid = service.adminCreateUser(pool.getId(), uuid,
|
||||
new HashMap<>(), null, "RESEND");
|
||||
assertEquals(uuid, resentByUuid.getUsername(), "RESEND by UUID must return the same user");
|
||||
|
||||
// RESEND addressed by the email alias must keep working too.
|
||||
CognitoUser resentByAlias = service.adminCreateUser(pool.getId(), "resend@example.com",
|
||||
new HashMap<>(), null, "RESEND");
|
||||
assertEquals(uuid, resentByAlias.getUsername(), "RESEND by alias must return the same user");
|
||||
}
|
||||
|
||||
@Test
|
||||
void emailAliasPoolRejectsMalformedEmail() {
|
||||
UserPool pool = createEmailAliasPool();
|
||||
for (String bad : List.of("@", "a@", "notvalid@", "@domain.com")) {
|
||||
AwsException ex = assertThrows(AwsException.class,
|
||||
() -> service.adminCreateUser(pool.getId(), bad, new HashMap<>(), null),
|
||||
"malformed email must be rejected: " + bad);
|
||||
assertEquals("InvalidParameterException", ex.getErrorCode(),
|
||||
"malformed email must be rejected: " + bad);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void emailAliasPoolMigrationIgnoresLambdaSuppliedSub() {
|
||||
UserPool pool = createEmailAliasPool();
|
||||
Map<String, String> lambdaAttributes = new HashMap<>(Map.of(
|
||||
"email", "migrated@example.com", "sub", "attacker-controlled"));
|
||||
service.adminCreateMigratedUser(pool.getId(), "migrated@example.com", "Passw0rd!",
|
||||
lambdaAttributes, "CONFIRMED");
|
||||
|
||||
CognitoUser user = service.adminGetUser(pool.getId(), "migrated@example.com");
|
||||
assertNotEquals("attacker-controlled", user.getUsername());
|
||||
assertNotEquals("attacker-controlled", user.getAttributes().get("sub"));
|
||||
assertTrue(isUuid(user.getUsername()), "migrated canonical username must be a generated UUID");
|
||||
assertEquals(user.getUsername(), user.getAttributes().get("sub"), "username must equal sub");
|
||||
assertEquals("migrated@example.com", user.getAttributes().get("email"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void phoneAliasPoolTokenDoesNotLeakUuidAsEmailClaim() {
|
||||
UserPool pool = service.createUserPool(
|
||||
Map.of("PoolName", "PhonePool", "UsernameAttributes", List.of("phone_number")),
|
||||
"us-east-1");
|
||||
UserPoolClient client = service.createUserPoolClient(
|
||||
pool.getId(), "c", false, false, List.of(), List.of());
|
||||
CognitoUser user = service.adminCreateUser(pool.getId(), "+15551234567",
|
||||
new HashMap<>(Map.of("phone_number", "+15551234567")), null);
|
||||
|
||||
String idToken = service.generateSignedJwt(user, pool, "id", client, null, null);
|
||||
String segment = idToken.split("\\.")[1];
|
||||
int pad = (4 - segment.length() % 4) % 4;
|
||||
segment += "=".repeat(pad);
|
||||
String payload = new String(Base64.getUrlDecoder().decode(segment), StandardCharsets.UTF_8);
|
||||
|
||||
assertTrue(payload.contains("\"sub\":\"" + user.getUsername() + "\""));
|
||||
assertFalse(payload.contains("\"email\""),
|
||||
"no email claim must be emitted for a user without an email attribute: " + payload);
|
||||
}
|
||||
|
||||
@Test
|
||||
void accessAndIdTokensSplitClaimsLikeAws() {
|
||||
UserPool pool = service.createUserPool(Map.of("PoolName", "ClaimsPool"), "us-east-1");
|
||||
UserPoolClient client = service.createUserPoolClient(
|
||||
pool.getId(), "c", false, false, List.of(), List.of());
|
||||
CognitoUser user = service.adminCreateUser(pool.getId(), "claims@example.com",
|
||||
new HashMap<>(Map.of("email", "claims@example.com", "email_verified", "true")), null);
|
||||
|
||||
String access = jwtPayload(service.generateSignedJwt(user, pool, "access", client, null, null));
|
||||
String id = jwtPayload(service.generateSignedJwt(user, pool, "id", client, null, null));
|
||||
|
||||
// Access token: `username` + reserved scope; no user attributes, no cognito:username.
|
||||
assertTrue(access.contains("\"username\":\"" + user.getUsername() + "\""));
|
||||
assertTrue(access.contains("\"scope\":\"aws.cognito.signin.user.admin\""));
|
||||
assertFalse(access.contains("\"email\""), "access token must not carry email: " + access);
|
||||
assertFalse(access.contains("\"cognito:username\""),
|
||||
"access token must not carry cognito:username: " + access);
|
||||
|
||||
// ID token: `cognito:username` + email; no bare `username`.
|
||||
assertTrue(id.contains("\"cognito:username\":\"" + user.getUsername() + "\""));
|
||||
assertTrue(id.contains("\"email\":\"claims@example.com\""));
|
||||
assertFalse(id.contains("\"username\""), "id token must not carry a bare username claim: " + id);
|
||||
}
|
||||
|
||||
@Test
|
||||
void emailAliasPoolVerifiedDuplicateThrowsAliasExists() {
|
||||
UserPool pool = createEmailAliasPool();
|
||||
service.adminCreateUser(pool.getId(), "dupe@b.com",
|
||||
new HashMap<>(Map.of("email", "dupe@b.com", "email_verified", "true")), null);
|
||||
|
||||
AwsException ex = assertThrows(AwsException.class,
|
||||
() -> service.adminCreateUser(pool.getId(), "dupe@b.com",
|
||||
new HashMap<>(Map.of("email", "dupe@b.com", "email_verified", "true")), null));
|
||||
assertEquals("AliasExistsException", ex.getErrorCode());
|
||||
}
|
||||
|
||||
@Test
|
||||
void emailAliasPoolAliasExistsUsesExistingVerificationNotIncoming() {
|
||||
UserPool pool = createEmailAliasPool();
|
||||
// Existing owner holds a *verified* alias.
|
||||
service.adminCreateUser(pool.getId(), "owner@b.com",
|
||||
new HashMap<>(Map.of("email", "owner@b.com", "email_verified", "true")), null);
|
||||
|
||||
// The second create omits email_verified from its own payload. The exception
|
||||
// type must be driven by the existing owner's verified alias -> AliasExistsException.
|
||||
AwsException ex = assertThrows(AwsException.class,
|
||||
() -> service.adminCreateUser(pool.getId(), "owner@b.com",
|
||||
new HashMap<>(Map.of("email", "owner@b.com")), null));
|
||||
assertEquals("AliasExistsException", ex.getErrorCode());
|
||||
}
|
||||
|
||||
@Test
|
||||
void emailAliasPoolIncomingVerifiedFlagCannotForceAliasExists() {
|
||||
UserPool pool = createEmailAliasPool();
|
||||
// Existing owner's alias is *unverified*, so the alias is not reserved.
|
||||
service.adminCreateUser(pool.getId(), "unv@b.com",
|
||||
new HashMap<>(Map.of("email", "unv@b.com")), null);
|
||||
|
||||
// A caller-supplied email_verified=true must not upgrade the decision:
|
||||
// the existing owner is unverified -> UsernameExistsException, not AliasExistsException.
|
||||
AwsException ex = assertThrows(AwsException.class,
|
||||
() -> service.adminCreateUser(pool.getId(), "unv@b.com",
|
||||
new HashMap<>(Map.of("email", "unv@b.com", "email_verified", "true")), null));
|
||||
assertEquals("UsernameExistsException", ex.getErrorCode());
|
||||
}
|
||||
|
||||
@Test
|
||||
void emailAliasPoolForceAliasCreationReclaimsWithoutIncomingVerifiedFlag() {
|
||||
UserPool pool = createEmailAliasPool();
|
||||
CognitoUser first = service.adminCreateUser(pool.getId(), "reclaim@b.com",
|
||||
new HashMap<>(Map.of("email", "reclaim@b.com", "email_verified", "true")), null);
|
||||
|
||||
// ForceAliasCreation reclaim keys off the existing owner's verified alias and
|
||||
// must not require the caller to re-send email_verified in the new payload.
|
||||
CognitoUser second = service.adminCreateUser(pool.getId(), "reclaim@b.com",
|
||||
new HashMap<>(Map.of("email", "reclaim@b.com")), null, null, true);
|
||||
|
||||
assertNotEquals(first.getUsername(), second.getUsername());
|
||||
assertEquals(second.getUsername(), service.adminGetUser(pool.getId(), "reclaim@b.com").getUsername());
|
||||
assertNull(service.adminGetUser(pool.getId(), first.getUsername()).getAttributes().get("email"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void emailAliasPoolForceAliasCreationMigratesVerifiedAlias() {
|
||||
UserPool pool = createEmailAliasPool();
|
||||
CognitoUser first = service.adminCreateUser(pool.getId(), "move@b.com",
|
||||
new HashMap<>(Map.of("email", "move@b.com", "email_verified", "true")), null);
|
||||
|
||||
CognitoUser second = service.adminCreateUser(pool.getId(), "move@b.com",
|
||||
new HashMap<>(Map.of("email", "move@b.com", "email_verified", "true")), null, null, true);
|
||||
|
||||
assertNotEquals(first.getUsername(), second.getUsername());
|
||||
// The alias now resolves to the new user; the previous user lost it.
|
||||
assertEquals(second.getUsername(), service.adminGetUser(pool.getId(), "move@b.com").getUsername());
|
||||
assertNull(service.adminGetUser(pool.getId(), first.getUsername()).getAttributes().get("email"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void idTokenFiltersAttributesByReadAttributes() {
|
||||
UserPool pool = service.createUserPool(Map.of("PoolName", "ReadAttrPool"), "us-east-1");
|
||||
UserPoolClient client = service.createUserPoolClient(
|
||||
pool.getId(), "c", false, false, List.of(), List.of());
|
||||
client.setReadAttributes(List.of("email")); // readable: email only, not name
|
||||
CognitoUser user = service.adminCreateUser(pool.getId(), "reader@example.com",
|
||||
new HashMap<>(Map.of("email", "reader@example.com", "name", "Ada Lovelace")), null);
|
||||
|
||||
String id = jwtPayload(service.generateSignedJwt(user, pool, "id", client, null, null));
|
||||
assertTrue(id.contains("\"email\":\"reader@example.com\""), "readable attribute present: " + id);
|
||||
assertFalse(id.contains("\"name\""), "non-readable attribute must be filtered out: " + id);
|
||||
}
|
||||
|
||||
private static String jwtPayload(String token) {
|
||||
String segment = token.split("\\.")[1];
|
||||
int pad = (4 - segment.length() % 4) % 4;
|
||||
segment += "=".repeat(pad);
|
||||
return new String(Base64.getUrlDecoder().decode(segment), StandardCharsets.UTF_8);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user