mirror of
https://github.com/floci-io/floci.git
synced 2026-11-23 14:10:49 -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
@@ -126,6 +126,46 @@ Standalone `TagResource` rejects reserved `floci:*` keys. `ListTagsForResource`
|
||||
- It validates requested OAuth scopes against the app client's `AllowedOAuthScopes` and the pool's registered resource-server scopes.
|
||||
- It advertises the prefixed token endpoint in `/{userPoolId}/.well-known/openid-configuration`.
|
||||
|
||||
## Sign-in Identifiers (`UsernameAttributes`)
|
||||
|
||||
Floci follows real Cognito semantics for pools created with `UsernameAttributes` (e.g.
|
||||
`--username-attributes email`):
|
||||
|
||||
- `AdminCreateUser`/`SignUp` accept the email (or phone number) as the sign-in value, but the
|
||||
**canonical `Username` is an auto-generated, immutable UUID equal to `sub`**. The supplied email is
|
||||
stored as a mutable alias attribute.
|
||||
- `ListUsers`, `AdminGetUser` and Lambda trigger `event.userName` all report the **UUID**, never the
|
||||
email; the email lives in the `email` attribute and in `event.request.userAttributes.email`.
|
||||
- Sign-in resolves by the **current** email alias **or** the UUID. `SECRET_HASH` is validated against
|
||||
the exact `USERNAME` value sent: `Base64(HMAC-SHA256(USERNAME + clientId, clientSecret))`.
|
||||
- In `CUSTOM_AUTH` / SRP flows, `ChallengeParameters.USERNAME` echoes the **UUID** (as real AWS does);
|
||||
the `RespondToAuthChallenge` `SECRET_HASH` is validated against the `USERNAME` sent that round. That
|
||||
`USERNAME` must still resolve to the session's user — the UUID or any of its current aliases — and a
|
||||
value naming a different user is rejected with `NotAuthorizedException`.
|
||||
- `AdminUpdateUserAttributes` can change the email; afterwards sign-in works with the new email and
|
||||
fails with the old one, while `Username`/`sub` stay fixed.
|
||||
- Duplicate email/phone on `AdminCreateUser`: `UsernameExistsException` when the incoming alias is
|
||||
unverified, `AliasExistsException` when it is verified (`email_verified=true`); pass
|
||||
`ForceAliasCreation=true` to migrate a verified alias off the previous owner. On
|
||||
`AdminUpdateUserAttributes`, changing to an in-use alias throws `AliasExistsException`.
|
||||
|
||||
Pools **without** `UsernameAttributes` (classic pools, and pools using `AliasAttributes`) keep the
|
||||
literal `Username` you supply, unchanged.
|
||||
|
||||
### Token claims
|
||||
|
||||
Floci mirrors AWS's access-token / ID-token split:
|
||||
|
||||
- **Access token:** `sub`, `username` (the UUID), `scope` (`aws.cognito.signin.user.admin` for API
|
||||
sign-in), `client_id`, `cognito:groups`, `jti`/`origin_jti`. It does **not** carry `cognito:username`
|
||||
or user attributes like `email`.
|
||||
- **ID token:** `sub`, `cognito:username`, `aud`, and readable user attributes (`email`,
|
||||
`email_verified`, `phone_number`, `custom:*`, ...). Attribute claims are filtered by the app client's
|
||||
`ReadAttributes` (an unset/empty list means all attributes are readable).
|
||||
|
||||
Not-found errors (`ResourceNotFoundException`, `UserNotFoundException`) return HTTP `400`, matching the
|
||||
Cognito JSON protocol.
|
||||
|
||||
## Configuration
|
||||
|
||||
| Variable | Default | Description |
|
||||
|
||||
+22
-5
@@ -14,6 +14,7 @@ import io.github.hectorvent.floci.services.lambda.model.InvokeResult;
|
||||
import org.jboss.logging.Logger;
|
||||
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.security.MessageDigest;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Base64;
|
||||
import java.util.HashMap;
|
||||
@@ -320,11 +321,22 @@ final class CognitoAuthFlowHandler {
|
||||
} catch (Exception e) {
|
||||
throw new AwsException("InternalErrorException", "SECRET_HASH computation failed", 500);
|
||||
}
|
||||
if (!expected.equals(provided)) {
|
||||
if (!MessageDigest.isEqual(expected.getBytes(StandardCharsets.UTF_8),
|
||||
provided.getBytes(StandardCharsets.UTF_8))) {
|
||||
throw new AwsException("NotAuthorizedException", "SECRET_HASH does not match", 400);
|
||||
}
|
||||
}
|
||||
|
||||
private String resolveToCanonicalUsername(UserPool pool, String username) {
|
||||
try {
|
||||
return service.adminGetUser(pool.getId(), username).getUsername();
|
||||
} catch (AwsException e) {
|
||||
LOG.debugv("Could not resolve USERNAME {0} in pool {1}: {2}",
|
||||
username, pool.getId(), e.getMessage());
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
// ──────────────────────────── SRP ────────────────────────────
|
||||
|
||||
private Map<String, Object> handleUserSrpAuth(UserPool pool, UserPoolClient client,
|
||||
@@ -448,7 +460,7 @@ final class CognitoAuthFlowHandler {
|
||||
}
|
||||
|
||||
CustomAuthSession state =
|
||||
new CustomAuthSession(pool.getId(), username, client.getClientId());
|
||||
new CustomAuthSession(pool.getId(), user.getUsername(), client.getClientId());
|
||||
state.clientMetadata = clientMetadata == null ? Map.of() : clientMetadata;
|
||||
|
||||
Map<String, Object> defineResp = defineAuthChallenge(pool, client, user, state);
|
||||
@@ -466,7 +478,7 @@ final class CognitoAuthFlowHandler {
|
||||
state.currentChallengeName = challengeName;
|
||||
|
||||
Map<String, String> publicParams = new HashMap<>();
|
||||
publicParams.put("USERNAME", username);
|
||||
publicParams.put("USERNAME", user.getUsername());
|
||||
for (Map.Entry<String, String> e : authParameters.entrySet()) {
|
||||
if (!"USERNAME".equals(e.getKey()) && !"SRP_A".equals(e.getKey())) {
|
||||
publicParams.putIfAbsent(e.getKey(), e.getValue());
|
||||
@@ -475,7 +487,7 @@ final class CognitoAuthFlowHandler {
|
||||
applyCreateResponse(state, challengeName,
|
||||
createAuthChallenge(pool, client, user, state, challengeName), publicParams);
|
||||
|
||||
String sessionToken = buildSessionToken(pool.getId(), username, client.getClientId());
|
||||
String sessionToken = buildSessionToken(pool.getId(), user.getUsername(), client.getClientId());
|
||||
customAuthSessions.put(sessionToken, state);
|
||||
|
||||
Map<String, Object> result = new HashMap<>();
|
||||
@@ -503,9 +515,14 @@ final class CognitoAuthFlowHandler {
|
||||
if (answer == null || answer.isBlank()) {
|
||||
throw new AwsException("InvalidParameterException", "ANSWER is required", 400);
|
||||
}
|
||||
validateSecretHash(client, responses, state.username);
|
||||
|
||||
String suppliedUsername = responses.getOrDefault("USERNAME", state.username);
|
||||
validateSecretHash(client, responses, suppliedUsername);
|
||||
|
||||
CognitoUser user = service.adminGetUser(pool.getId(), state.username);
|
||||
if (!user.getUsername().equals(resolveToCanonicalUsername(pool, suppliedUsername))) {
|
||||
throw new AwsException("NotAuthorizedException", "Invalid session for the user.", 400);
|
||||
}
|
||||
|
||||
boolean answerCorrect = verifyAuthChallenge(pool, client, user, state, answer);
|
||||
if (!state.history.isEmpty()) {
|
||||
|
||||
@@ -354,7 +354,8 @@ public class CognitoJsonHandler {
|
||||
request.path("Username").asText(),
|
||||
attrs,
|
||||
tempPassword,
|
||||
messageAction
|
||||
messageAction,
|
||||
request.path("ForceAliasCreation").asBoolean(false)
|
||||
);
|
||||
ObjectNode response = objectMapper.createObjectNode();
|
||||
response.set("User", userToNode(user));
|
||||
|
||||
@@ -300,7 +300,7 @@ public class CognitoService {
|
||||
|
||||
public UserPool describeUserPool(String id) {
|
||||
UserPool pool = poolStore.get(id)
|
||||
.orElseThrow(() -> new AwsException("ResourceNotFoundException", "User pool not found", 404));
|
||||
.orElseThrow(() -> new AwsException("ResourceNotFoundException", "User pool not found", 400));
|
||||
boolean generatedKeys = ensureJwtSigningKeys(pool);
|
||||
boolean generatedSecret = ensureRefreshTokenSecret(pool);
|
||||
if (generatedKeys || generatedSecret) {
|
||||
@@ -490,9 +490,9 @@ public class CognitoService {
|
||||
|
||||
public UserPoolClient describeUserPoolClient(String userPoolId, String clientId) {
|
||||
UserPoolClient client = clientStore.get(clientId)
|
||||
.orElseThrow(() -> new AwsException("ResourceNotFoundException", "User pool client not found", 404));
|
||||
.orElseThrow(() -> new AwsException("ResourceNotFoundException", "User pool client not found", 400));
|
||||
if (!client.getUserPoolId().equals(userPoolId)) {
|
||||
throw new AwsException("ResourceNotFoundException", "User pool client not found", 404);
|
||||
throw new AwsException("ResourceNotFoundException", "User pool client not found", 400);
|
||||
}
|
||||
return client;
|
||||
}
|
||||
@@ -502,7 +502,7 @@ public class CognitoService {
|
||||
}
|
||||
|
||||
public void deleteUserPoolClient(String clientId) {
|
||||
clientStore.get(clientId).orElseThrow(() -> new AwsException("ResourceNotFoundException", "User pool client not found", 404));
|
||||
clientStore.get(clientId).orElseThrow(() -> new AwsException("ResourceNotFoundException", "User pool client not found", 400));
|
||||
clientStore.delete(clientId);
|
||||
}
|
||||
|
||||
@@ -668,18 +668,18 @@ public class CognitoService {
|
||||
|
||||
public List<UserPoolClientSecret> listUserPoolClientSecrets(String userPoolId, String clientId) {
|
||||
UserPoolClient client = clientStore.get(clientId)
|
||||
.orElseThrow(() -> new AwsException("ResourceNotFoundException", "User pool client not found", 404));
|
||||
.orElseThrow(() -> new AwsException("ResourceNotFoundException", "User pool client not found", 400));
|
||||
if (!client.getUserPoolId().equals(userPoolId)) {
|
||||
throw new AwsException("ResourceNotFoundException", "User pool client not found", 404);
|
||||
throw new AwsException("ResourceNotFoundException", "User pool client not found", 400);
|
||||
}
|
||||
return client.getUserPoolClientSecrets();
|
||||
}
|
||||
|
||||
public UserPoolClientSecret addUserPoolClientSecret(String clientId, String clientSecret, String userPoolId) {
|
||||
UserPoolClient client = clientStore.get(clientId)
|
||||
.orElseThrow(() -> new AwsException("ResourceNotFoundException", "User pool client not found", 404));
|
||||
.orElseThrow(() -> new AwsException("ResourceNotFoundException", "User pool client not found", 400));
|
||||
if (!client.getUserPoolId().equals(userPoolId)) {
|
||||
throw new AwsException("ResourceNotFoundException", "User pool client not found", 404);
|
||||
throw new AwsException("ResourceNotFoundException", "User pool client not found", 400);
|
||||
}
|
||||
|
||||
if (client.getUserPoolClientSecrets().size() >= 2) {
|
||||
@@ -706,16 +706,16 @@ public class CognitoService {
|
||||
|
||||
public void deleteUserPoolClientSecret(String clientId, String clientSecretId, String userPoolId) {
|
||||
UserPoolClient client = clientStore.get(clientId)
|
||||
.orElseThrow(() -> new AwsException("ResourceNotFoundException", "User pool client not found", 404));
|
||||
.orElseThrow(() -> new AwsException("ResourceNotFoundException", "User pool client not found", 400));
|
||||
if (!client.getUserPoolId().equals(userPoolId)) {
|
||||
throw new AwsException("ResourceNotFoundException", "User pool client not found", 404);
|
||||
throw new AwsException("ResourceNotFoundException", "User pool client not found", 400);
|
||||
}
|
||||
|
||||
UserPoolClientSecret userPoolClientSecret = client.getUserPoolClientSecrets().stream()
|
||||
.filter(s -> s.getClientSecretId().equals(clientSecretId))
|
||||
.findFirst()
|
||||
.orElseThrow(() -> new AwsException(
|
||||
"ResourceNotFoundException", "Client secret does not exist", 404));
|
||||
"ResourceNotFoundException", "Client secret does not exist", 400));
|
||||
|
||||
if (client.getUserPoolClientSecrets().size() <= 1) {
|
||||
throw new AwsException(
|
||||
@@ -760,7 +760,7 @@ public class CognitoService {
|
||||
public ResourceServer describeResourceServer(String userPoolId, String identifier) {
|
||||
describeUserPool(userPoolId);
|
||||
return resourceServerStore.get(resourceServerKey(userPoolId, identifier))
|
||||
.orElseThrow(() -> new AwsException("ResourceNotFoundException", "Resource server not found", 404));
|
||||
.orElseThrow(() -> new AwsException("ResourceNotFoundException", "Resource server not found", 400));
|
||||
}
|
||||
|
||||
public List<ResourceServer> listResourceServers(String userPoolId) {
|
||||
@@ -814,13 +814,33 @@ public class CognitoService {
|
||||
Map<String, String> attributes,
|
||||
String temporaryPassword,
|
||||
String messageAction) {
|
||||
describeUserPool(userPoolId);
|
||||
String key = userKey(userPoolId, username);
|
||||
return adminCreateUser(userPoolId, username, attributes, temporaryPassword, messageAction, false);
|
||||
}
|
||||
|
||||
public CognitoUser adminCreateUser(String userPoolId,
|
||||
String username,
|
||||
Map<String, String> attributes,
|
||||
String temporaryPassword,
|
||||
String messageAction,
|
||||
boolean forceAliasCreation) {
|
||||
UserPool pool = describeUserPool(userPoolId);
|
||||
boolean resend = "RESEND".equalsIgnoreCase(messageAction);
|
||||
boolean aliasPool = usesAliasUsernames(pool);
|
||||
|
||||
Map<String, String> resolvedAttributes = attributes == null
|
||||
? new HashMap<>() : new HashMap<>(attributes);
|
||||
|
||||
CognitoUser existing = userStore.get(userKey(userPoolId, username)).orElse(null);
|
||||
String aliasAttribute = null;
|
||||
if (aliasPool && existing == null) {
|
||||
aliasAttribute = aliasAttributeForValue(pool, username);
|
||||
existing = findUserByAlias(userPoolId, aliasAttribute, username);
|
||||
}
|
||||
|
||||
if (resend) {
|
||||
CognitoUser existing = userStore.get(key)
|
||||
.orElseThrow(() -> new AwsException("UserNotFoundException", "User not found", 404));
|
||||
if (existing == null) {
|
||||
throw new AwsException("UserNotFoundException", "User not found", 400);
|
||||
}
|
||||
if (!"FORCE_CHANGE_PASSWORD".equals(existing.getUserStatus())) {
|
||||
final String userStateExceptionMessage = """
|
||||
User is in %s state and cannot be resent an invitation.
|
||||
@@ -828,21 +848,39 @@ public class CognitoService {
|
||||
throw new AwsException("UnsupportedUserStateException", userStateExceptionMessage, 400);
|
||||
}
|
||||
existing.setLastModifiedDate(System.currentTimeMillis() / 1000L);
|
||||
userStore.put(key, existing);
|
||||
LOG.infov("Resent invitation for user {0} in pool {1}", username, userPoolId);
|
||||
userStore.put(userKey(userPoolId, existing.getUsername()), existing);
|
||||
LOG.infov("Resent invitation for user {0} in pool {1}", existing.getUsername(), userPoolId);
|
||||
return existing;
|
||||
}
|
||||
|
||||
if (userStore.get(key).isPresent()) {
|
||||
throw new AwsException("UsernameExistsException", "User already exists", 400);
|
||||
if (existing != null) {
|
||||
boolean existingAliasVerified = aliasAttribute != null
|
||||
&& "true".equalsIgnoreCase(existing.getAttributes().get(aliasAttribute + "_verified"));
|
||||
if (existingAliasVerified) {
|
||||
if (!forceAliasCreation) {
|
||||
throw new AwsException("AliasExistsException",
|
||||
"An account with the given " + aliasAttribute + " already exists.", 400);
|
||||
}
|
||||
existing.getAttributes().remove(aliasAttribute);
|
||||
existing.getAttributes().put(aliasAttribute + "_verified", "false");
|
||||
existing.setLastModifiedDate(System.currentTimeMillis() / 1000L);
|
||||
userStore.put(userKey(userPoolId, existing.getUsername()), existing);
|
||||
} else {
|
||||
throw new AwsException("UsernameExistsException", "User already exists", 400);
|
||||
}
|
||||
}
|
||||
|
||||
String canonicalUsername = username;
|
||||
if (aliasPool) {
|
||||
resolvedAttributes.put(aliasAttribute, username);
|
||||
canonicalUsername = UUID.randomUUID().toString();
|
||||
resolvedAttributes.put("sub", canonicalUsername);
|
||||
}
|
||||
|
||||
CognitoUser user = new CognitoUser();
|
||||
user.setUsername(username);
|
||||
user.setUsername(canonicalUsername);
|
||||
user.setUserPoolId(userPoolId);
|
||||
if (attributes != null) {
|
||||
user.getAttributes().putAll(attributes);
|
||||
}
|
||||
user.getAttributes().putAll(resolvedAttributes);
|
||||
|
||||
// Ensure sub attribute is present
|
||||
if (!user.getAttributes().containsKey("sub")) {
|
||||
@@ -855,22 +893,37 @@ public class CognitoService {
|
||||
user.setUserStatus("FORCE_CHANGE_PASSWORD");
|
||||
}
|
||||
|
||||
userStore.put(key, user);
|
||||
LOG.infov("Created user {0} in pool {1}", username, userPoolId);
|
||||
userStore.put(userKey(userPoolId, canonicalUsername), user);
|
||||
LOG.infov("Created user {0} in pool {1}", canonicalUsername, userPoolId);
|
||||
return user;
|
||||
}
|
||||
|
||||
void adminCreateMigratedUser(String userPoolId, String username, String password,
|
||||
Map<String, String> attributes, String finalUserStatus) {
|
||||
describeUserPool(userPoolId);
|
||||
String key = userKey(userPoolId, username);
|
||||
UserPool pool = describeUserPool(userPoolId);
|
||||
boolean aliasPool = usesAliasUsernames(pool);
|
||||
|
||||
CognitoUser user = userStore.get(key).orElseGet(CognitoUser::new);
|
||||
user.setUsername(username);
|
||||
user.setUserPoolId(userPoolId);
|
||||
if (attributes != null) {
|
||||
user.getAttributes().putAll(attributes);
|
||||
Map<String, String> resolvedAttributes = attributes == null
|
||||
? new HashMap<>() : new HashMap<>(attributes);
|
||||
|
||||
CognitoUser existing;
|
||||
String canonicalUsername;
|
||||
if (aliasPool) {
|
||||
String aliasAttribute = aliasAttributeForValue(pool, username);
|
||||
resolvedAttributes.put(aliasAttribute, username);
|
||||
existing = findUserByAlias(userPoolId, aliasAttribute, username);
|
||||
canonicalUsername = existing != null ? existing.getUsername() : UUID.randomUUID().toString();
|
||||
resolvedAttributes.put("sub", canonicalUsername);
|
||||
} else {
|
||||
canonicalUsername = username;
|
||||
existing = userStore.get(userKey(userPoolId, username)).orElse(null);
|
||||
}
|
||||
String key = userKey(userPoolId, canonicalUsername);
|
||||
|
||||
CognitoUser user = existing != null ? existing : new CognitoUser();
|
||||
user.setUsername(canonicalUsername);
|
||||
user.setUserPoolId(userPoolId);
|
||||
user.getAttributes().putAll(resolvedAttributes);
|
||||
if (!user.getAttributes().containsKey("sub")) {
|
||||
user.getAttributes().put("sub", UUID.randomUUID().toString());
|
||||
}
|
||||
@@ -883,7 +936,7 @@ public class CognitoService {
|
||||
user.setLastModifiedDate(System.currentTimeMillis() / 1000L);
|
||||
|
||||
userStore.put(key, user);
|
||||
LOG.infov("Migrated user {0} into pool {1} (status={2})", username, userPoolId, user.getUserStatus());
|
||||
LOG.infov("Migrated user {0} into pool {1} (status={2})", canonicalUsername, userPoolId, user.getUserStatus());
|
||||
}
|
||||
|
||||
public void adminUserGlobalSignOut(String userPoolId, String username) {
|
||||
@@ -891,9 +944,9 @@ public class CognitoService {
|
||||
CognitoUser user = adminGetUser(userPoolId, username);
|
||||
|
||||
// Revoke all tokens for this user
|
||||
revokeAllUserTokens(userPoolId, username);
|
||||
revokeAllUserTokens(userPoolId, user.getUsername());
|
||||
|
||||
LOG.infov("AdminUserGlobalSignOut: revoked all tokens for user {0} in pool {1}", username, userPoolId);
|
||||
LOG.infov("AdminUserGlobalSignOut: revoked all tokens for user {0} in pool {1}", user.getUsername(), userPoolId);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -921,10 +974,9 @@ public class CognitoService {
|
||||
Long iat = extractIatFromToken(accessToken);
|
||||
validateUserNotGloballySignedOut(username, poolId, "access", iat != null ? iat : 0L);
|
||||
|
||||
// Confirm the pool and user actually exist before mutating the revocation store,
|
||||
// matching the implicit validation AWS performs and the adminUserGlobalSignOut counterpart.
|
||||
CognitoUser user;
|
||||
try {
|
||||
adminGetUser(poolId, username);
|
||||
user = adminGetUser(poolId, username);
|
||||
} catch (AwsException e) {
|
||||
if ("UserNotFoundException".equals(e.getErrorCode())
|
||||
|| "ResourceNotFoundException".equals(e.getErrorCode())) {
|
||||
@@ -933,20 +985,21 @@ public class CognitoService {
|
||||
throw e;
|
||||
}
|
||||
|
||||
// Revoke all of the user's issued tokens (access, ID, refresh).
|
||||
revokeAllUserTokens(poolId, username);
|
||||
revokeAllUserTokens(poolId, user.getUsername());
|
||||
|
||||
LOG.infov("GlobalSignOut: revoked all tokens for user {0} in pool {1}", username, poolId);
|
||||
LOG.infov("GlobalSignOut: revoked all tokens for user {0} in pool {1}", user.getUsername(), poolId);
|
||||
}
|
||||
|
||||
public CognitoUser adminGetUser(String userPoolId, String username) {
|
||||
UserPool pool = poolStore.get(userPoolId).orElseThrow(
|
||||
() -> new AwsException("ResourceNotFoundException", "User pool not found", 400));
|
||||
LinkedHashSet<CognitoUser> matches = new LinkedHashSet<>();
|
||||
userStore.get(userKey(userPoolId, username)).ifPresent(matches::add);
|
||||
LinkedHashMap<String, CognitoUser> matches = new LinkedHashMap<>();
|
||||
userStore.get(userKey(userPoolId, username))
|
||||
.ifPresent(u -> matches.put(u.getUsername(), u));
|
||||
String prefix = userPoolId + "::";
|
||||
matches.addAll(userStore.scan(k -> k.startsWith(prefix)).stream()
|
||||
.filter(u -> matchesAliasOrUsernameAttribute(pool, u, username)).toList());
|
||||
userStore.scan(k -> k.startsWith(prefix)).stream()
|
||||
.filter(u -> matchesAliasOrUsernameAttribute(pool, u, username))
|
||||
.forEach(u -> matches.putIfAbsent(u.getUsername(), u));
|
||||
if (matches.isEmpty()) {
|
||||
throw new AwsException("UserNotFoundException", "User not found", 400);
|
||||
}
|
||||
@@ -954,7 +1007,7 @@ public class CognitoService {
|
||||
throw new AwsException("InvalidParameterException",
|
||||
"Multiple users found for the supplied username", 400);
|
||||
}
|
||||
return matches.getFirst();
|
||||
return matches.values().iterator().next();
|
||||
}
|
||||
|
||||
public void adminDeleteUser(String userPoolId, String username) {
|
||||
@@ -981,6 +1034,20 @@ public class CognitoService {
|
||||
|
||||
public void adminUpdateUserAttributes(String userPoolId, String username, Map<String, String> attributes) {
|
||||
CognitoUser user = adminGetUser(userPoolId, username);
|
||||
UserPool pool = describeUserPool(userPoolId);
|
||||
if (usesAliasUsernames(pool)) {
|
||||
for (String aliasAttribute : pool.getUsernameAttributes()) {
|
||||
String newValue = attributes.get(aliasAttribute);
|
||||
if (newValue == null || newValue.equals(user.getAttributes().get(aliasAttribute))) {
|
||||
continue;
|
||||
}
|
||||
CognitoUser other = findUserByAlias(userPoolId, aliasAttribute, newValue);
|
||||
if (other != null && !other.getUsername().equals(user.getUsername())) {
|
||||
throw new AwsException("AliasExistsException",
|
||||
"An account with the given " + aliasAttribute + " already exists.", 400);
|
||||
}
|
||||
}
|
||||
}
|
||||
user.getAttributes().putAll(attributes);
|
||||
user.setLastModifiedDate(System.currentTimeMillis() / 1000L);
|
||||
userStore.put(userKey(userPoolId, user.getUsername()), user);
|
||||
@@ -1165,7 +1232,7 @@ public class CognitoService {
|
||||
validateGroupName(groupName);
|
||||
return groupStore.get(groupKey(userPoolId, groupName))
|
||||
.orElseThrow(() -> new AwsException("ResourceNotFoundException",
|
||||
"Group not found: " + groupName, 404));
|
||||
"Group not found: " + groupName, 400));
|
||||
}
|
||||
|
||||
public List<CognitoGroup> listGroups(String userPoolId) {
|
||||
@@ -1256,19 +1323,30 @@ public class CognitoService {
|
||||
String userPoolId = client.getUserPoolId();
|
||||
UserPool pool = describeUserPool(userPoolId);
|
||||
|
||||
String key = userKey(userPoolId, username);
|
||||
if (userStore.get(key).isPresent()) {
|
||||
boolean aliasPool = usesAliasUsernames(pool);
|
||||
Map<String, String> resolvedAttributes = attributes == null
|
||||
? new HashMap<>() : new HashMap<>(attributes);
|
||||
String canonicalUsername = username;
|
||||
if (aliasPool) {
|
||||
String aliasAttribute = aliasAttributeForValue(pool, username);
|
||||
if (findUserByAlias(userPoolId, aliasAttribute, username) != null) {
|
||||
throw new AwsException("UsernameExistsException", "User already exists", 400);
|
||||
}
|
||||
resolvedAttributes.put(aliasAttribute, username);
|
||||
canonicalUsername = UUID.randomUUID().toString();
|
||||
resolvedAttributes.put("sub", canonicalUsername);
|
||||
} else if (userStore.get(userKey(userPoolId, username)).isPresent()) {
|
||||
throw new AwsException("UsernameExistsException", "User already exists", 400);
|
||||
}
|
||||
|
||||
String key = userKey(userPoolId, canonicalUsername);
|
||||
|
||||
CognitoUser user = new CognitoUser();
|
||||
user.setUsername(username);
|
||||
user.setUsername(canonicalUsername);
|
||||
user.setUserPoolId(userPoolId);
|
||||
updateUserPassword(user, password);
|
||||
user.setUserStatus("UNCONFIRMED");
|
||||
if (attributes != null) {
|
||||
user.getAttributes().putAll(attributes);
|
||||
}
|
||||
user.getAttributes().putAll(resolvedAttributes);
|
||||
|
||||
// Ensure sub attribute is present (required by PreSignUp event)
|
||||
if (!user.getAttributes().containsKey("sub")) {
|
||||
@@ -1506,7 +1584,7 @@ public class CognitoService {
|
||||
|
||||
public Map<String, Object> forgotPassword(String clientId, String username) {
|
||||
UserPoolClient client = clientStore.get(clientId)
|
||||
.orElseThrow(() -> new AwsException("ResourceNotFoundException", "Client not found", 404));
|
||||
.orElseThrow(() -> new AwsException("ResourceNotFoundException", "Client not found", 400));
|
||||
CognitoUser user = adminGetUser(client.getUserPoolId(), username);
|
||||
UserPool pool = describeUserPool(client.getUserPoolId());
|
||||
ensureVerificationWiring();
|
||||
@@ -1530,7 +1608,7 @@ public class CognitoService {
|
||||
|
||||
public void confirmForgotPassword(String clientId, String username, String confirmationCode, String newPassword) {
|
||||
UserPoolClient client = clientStore.get(clientId)
|
||||
.orElseThrow(() -> new AwsException("ResourceNotFoundException", "Client not found", 404));
|
||||
.orElseThrow(() -> new AwsException("ResourceNotFoundException", "Client not found", 400));
|
||||
CognitoUser user = adminGetUser(client.getUserPoolId(), username);
|
||||
ensureVerificationWiring();
|
||||
try {
|
||||
@@ -1652,7 +1730,7 @@ public class CognitoService {
|
||||
|
||||
public Map<String, Object> issueClientCredentialsToken(String clientId, String clientSecret, String scope) {
|
||||
UserPoolClient client = clientStore.get(clientId)
|
||||
.orElseThrow(() -> new AwsException("ResourceNotFoundException", "Client not found", 404));
|
||||
.orElseThrow(() -> new AwsException("ResourceNotFoundException", "Client not found", 400));
|
||||
UserPool pool = describeUserPool(client.getUserPoolId());
|
||||
validateClientAllowsClientCredentials(client);
|
||||
validateClientSecret(client, clientSecret);
|
||||
@@ -1693,7 +1771,7 @@ public class CognitoService {
|
||||
|
||||
UserPoolClient findClientById(String clientId) {
|
||||
return clientStore.get(clientId)
|
||||
.orElseThrow(() -> new AwsException("ResourceNotFoundException", "Client not found", 404));
|
||||
.orElseThrow(() -> new AwsException("ResourceNotFoundException", "Client not found", 400));
|
||||
}
|
||||
|
||||
public Map<String, Object> getTokensFromRefreshToken(String clientId, String refreshToken) {
|
||||
@@ -1701,7 +1779,7 @@ public class CognitoService {
|
||||
throw new AwsException("InvalidParameterException", "RefreshToken is required", 400);
|
||||
}
|
||||
UserPoolClient client = clientStore.get(clientId)
|
||||
.orElseThrow(() -> new AwsException("ResourceNotFoundException", "Client not found", 404));
|
||||
.orElseThrow(() -> new AwsException("ResourceNotFoundException", "Client not found", 400));
|
||||
String[] parts = parseRefreshToken(refreshToken);
|
||||
if (parts == null) {
|
||||
throw new AwsException("NotAuthorizedException", "Invalid refresh token", 400);
|
||||
@@ -1780,6 +1858,13 @@ public class CognitoService {
|
||||
return; // Nothing keyed to revoke (legacy token); revocation is idempotent.
|
||||
}
|
||||
|
||||
try {
|
||||
username = adminGetUser(poolId, username).getUsername();
|
||||
} catch (AwsException e) {
|
||||
LOG.debugv("RevokeToken: user {0} not resolvable in pool {1} ({2}); using token-embedded username",
|
||||
username, poolId, e.getErrorCode());
|
||||
}
|
||||
|
||||
long nowMs = System.currentTimeMillis();
|
||||
long expiresAtSeconds = nowMs / 1000L + (365L * 24L * 60L * 60L);
|
||||
RevokedTokenInfo info = new RevokedTokenInfo(familyId, "refresh", username, poolId, nowMs, expiresAtSeconds);
|
||||
@@ -1813,7 +1898,6 @@ public class CognitoService {
|
||||
|
||||
Map<String, Object> claims = new LinkedHashMap<>();
|
||||
String sub = user.getAttributes().getOrDefault("sub", user.getUsername());
|
||||
String email = user.getAttributes().getOrDefault("email", user.getUsername());
|
||||
claims.put("sub", sub);
|
||||
claims.put("event_id", UUID.randomUUID().toString());
|
||||
claims.put("token_use", type);
|
||||
@@ -1821,10 +1905,13 @@ public class CognitoService {
|
||||
claims.put("iss", getIssuer(pool.getId()));
|
||||
claims.put("exp", now + lifetimeSeconds);
|
||||
claims.put("iat", now);
|
||||
claims.put("username", user.getUsername());
|
||||
claims.put("email", email);
|
||||
claims.put("cognito:username", user.getUsername());
|
||||
|
||||
if ("access".equals(type)) {
|
||||
claims.put("username", user.getUsername());
|
||||
claims.put("scope", "aws.cognito.signin.user.admin");
|
||||
} else if ("id".equals(type)) {
|
||||
claims.put("cognito:username", user.getUsername());
|
||||
}
|
||||
|
||||
// Add JWT ID (jti) claim for token revocation support
|
||||
String jti = UUID.randomUUID().toString();
|
||||
claims.put("jti", jti);
|
||||
@@ -1842,7 +1929,7 @@ public class CognitoService {
|
||||
claims.put("cognito:groups", new ArrayList<>(user.getGroupNames()));
|
||||
}
|
||||
if ("id".equals(type)) {
|
||||
addUserAttributeClaims(claims, user);
|
||||
addUserAttributeClaims(claims, user, client);
|
||||
}
|
||||
|
||||
applyClaimsOverride(claims, override, type);
|
||||
@@ -1850,12 +1937,18 @@ public class CognitoService {
|
||||
return signJwt(header, encodeJsonBase64Url(claims), getSigningPrivateKey(pool));
|
||||
}
|
||||
|
||||
private static void addUserAttributeClaims(Map<String, Object> claims, CognitoUser user) {
|
||||
private static void addUserAttributeClaims(Map<String, Object> claims, CognitoUser user,
|
||||
UserPoolClient client) {
|
||||
// AWS: "Your user's ID token only contains claims that correspond to the readable
|
||||
// attributes." An unset/empty ReadAttributes list means all attributes are readable.
|
||||
List<String> readable = client == null ? null : client.getReadAttributes();
|
||||
boolean filterByReadable = readable != null && !readable.isEmpty();
|
||||
for (Map.Entry<String, String> e : user.getAttributes().entrySet()) {
|
||||
String name = e.getKey();
|
||||
String value = e.getValue();
|
||||
if (name == null || name.isEmpty() || value == null) continue;
|
||||
if (claims.containsKey(name)) continue;
|
||||
if (filterByReadable && !isReadableAttribute(name, readable)) continue;
|
||||
switch (name) {
|
||||
case "email_verified", "phone_number_verified" -> claims.put(name, Boolean.parseBoolean(value));
|
||||
case "updated_at" -> {
|
||||
@@ -1870,6 +1963,18 @@ public class CognitoService {
|
||||
}
|
||||
}
|
||||
|
||||
private static boolean isReadableAttribute(String name, List<String> readable) {
|
||||
if (readable.contains(name)) {
|
||||
return true;
|
||||
}
|
||||
// The verification flags travel with their base attribute's read permission.
|
||||
return switch (name) {
|
||||
case "email_verified" -> readable.contains("email");
|
||||
case "phone_number_verified" -> readable.contains("phone_number");
|
||||
default -> false;
|
||||
};
|
||||
}
|
||||
|
||||
private static void applyClaimsOverride(Map<String, Object> claims, ClaimsOverride override, String tokenType) {
|
||||
if (override == null) return;
|
||||
boolean isAccess = "access".equals(tokenType);
|
||||
@@ -2824,6 +2929,55 @@ public class CognitoService {
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* True when the pool is configured with {@code UsernameAttributes} (email and/or
|
||||
* phone_number). Such pools mint an immutable, opaque username (a UUID equal to
|
||||
* {@code sub}) and treat the caller-supplied email/phone as a mutable sign-in alias.
|
||||
* Classic pools (no {@code UsernameAttributes}) keep the caller-supplied username verbatim.
|
||||
*/
|
||||
private boolean usesAliasUsernames(UserPool pool) {
|
||||
List<String> attributes = pool.getUsernameAttributes();
|
||||
return attributes != null && !attributes.isEmpty();
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolves which alias attribute ("email"/"phone_number") a supplied sign-in value maps
|
||||
* to for an alias-configured pool, mirroring AWS's format validation. Throws
|
||||
* {@code InvalidParameterException} when the value matches none of the pool's
|
||||
* {@code UsernameAttributes}.
|
||||
*/
|
||||
private String aliasAttributeForValue(UserPool pool, String value) {
|
||||
List<String> usernameAttributes = pool.getUsernameAttributes();
|
||||
boolean allowsEmail = usernameAttributes.contains("email");
|
||||
boolean allowsPhone = usernameAttributes.contains("phone_number");
|
||||
if (value != null) {
|
||||
if (allowsEmail && value.matches("[^@\\s]+@[^@\\s]+\\.[^@\\s]+")) {
|
||||
return "email";
|
||||
}
|
||||
if (allowsPhone && value.matches("\\+[0-9]{1,15}")) {
|
||||
return "phone_number";
|
||||
}
|
||||
}
|
||||
String expected;
|
||||
if (allowsEmail && allowsPhone) {
|
||||
expected = "Username should be either an email or a phone number.";
|
||||
} else if (allowsPhone) {
|
||||
expected = "Username should be a phone number.";
|
||||
} else {
|
||||
expected = "Username should be an email.";
|
||||
}
|
||||
throw new AwsException("InvalidParameterException", expected, 400);
|
||||
}
|
||||
|
||||
/** Finds the single user in a pool whose {@code aliasAttr} equals {@code aliasValue}, or null. */
|
||||
private CognitoUser findUserByAlias(String poolId, String aliasAttr, String aliasValue) {
|
||||
String prefix = poolId + "::";
|
||||
return userStore.scan(k -> k.startsWith(prefix)).stream()
|
||||
.filter(u -> aliasValue.equals(u.getAttributes().get(aliasAttr)))
|
||||
.findFirst()
|
||||
.orElse(null);
|
||||
}
|
||||
|
||||
private List<String> accountRecoveryMechanisms(UserPool pool) {
|
||||
Map<String, Object> setting = pool.getAccountRecoverySetting();
|
||||
if (setting == null) {
|
||||
|
||||
+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