feat(cognito): implement VerifyUserAttribute (#2018)

* feat(cognito): implement VerifyUserAttribute

* fix(cognito): align attribute verification with AWS

* fix(cognito): require access-token scope on VerifyUserAttribute

verifyUserAttribute() extracted username/pool/jti from the caller's token
but never checked token_use or scope, so a valid ID token could reach the
same code-consuming, attribute-mutating path as an access token. AWS
requires an access token carrying the aws.cognito.signin.user.admin scope
for this operation (API_VerifyUserAttribute.html).

Adds a token_use check (unconditional) and a scope check that only rejects
a token when it explicitly carries a scope list missing the required
scope. Most access tokens this simulator issues carry no scope claim at
all (scopes are only modeled through the V2 Pre-Token-Generation Lambda
override), so treating an absent claim as unrestricted keeps every normal
login flow working, while an access token with an explicit, non-conforming
scope list is now rejected.

Adds unit coverage for all three cases (ID token rejected, access token
missing the scope rejected, access token with the scope accepted) plus a
wire-level regression for the ID-token case.

* fix(cognito): scope consumed-code tombstone to attribute verification

VerificationCodeService.consume() retained a consumed-code tombstone for
every purpose, so a reused code answers ExpiredCodeException instead of
the original CodeMismatchException. That behavior was validated against a
real Cognito pool for VerifyUserAttribute, but the service is shared with
ConfirmSignUp (SIGNUP_CONFIRMATION) and ConfirmForgotPassword
(PASSWORD_RESET), so the same change silently altered their reused-code
error too, without the same validation.

Scopes the tombstone to EMAIL_ATTRIBUTE_VERIFICATION and
PHONE_ATTRIBUTE_VERIFICATION only. SIGNUP_CONFIRMATION and PASSWORD_RESET
go back to deleting on consume, restoring their original, previously
validated NOT_FOUND/CodeMismatchException behavior on reuse.

---------

Co-authored-by: Priamo Germosen <6233424+pgermosen@users.noreply.github.com>
This commit is contained in:
Daniel ZwickerandPriamo Germosen authored and GitHub committed 2026-09-14 11:05:25 -04:00
1 parent 166b13a82f
commit 36c3ee4e22
8 files changed
+689 -61

No files matched your search

@@ -104,6 +104,7 @@ public class CognitoJsonHandler {
case "ConfirmForgotPassword" -> handleConfirmForgotPassword(request);
case "GetUser" -> handleGetUser(request);
case "GetUserAttributeVerificationCode" -> handleGetUserAttributeVerificationCode(request);
case "VerifyUserAttribute" -> handleVerifyUserAttribute(request);
case "UpdateUserAttributes" -> handleUpdateUserAttributes(request);
case "DeleteUserAttributes" -> handleDeleteUserAttributes(request);
case "GlobalSignOut" -> handleGlobalSignOut(request);
@@ -1018,6 +1019,15 @@ public class CognitoJsonHandler {
return Response.ok(response).build();
}
private Response handleVerifyUserAttribute(JsonNode request) {
service.verifyUserAttribute(
request.path("AccessToken").asText(),
request.path("AttributeName").asText(),
request.path("Code").asText()
);
return Response.ok(objectMapper.createObjectNode()).build();
}
private Response handleUpdateUserAttributes(JsonNode request) {
Map<String, String> attrs = new HashMap<>();
request.path("UserAttributes").forEach(a -> attrs.put(a.path("Name").asText(), a.path("Value").asText()));
@@ -2594,6 +2594,48 @@ public class CognitoService implements ResourceProvider {
return response;
}
public void verifyUserAttribute(String accessToken, String attributeName, String code) {
VerifiedAccessToken token;
try {
token = verifyAccessToken(accessToken);
} catch (AwsException e) {
if ("NotAuthorizedException".equals(e.getErrorCode())
&& INVALID_ACCESS_TOKEN_MESSAGE.equals(e.getMessage())) {
throw new AwsException("NotAuthorizedException", "Invalid Access Token", 400);
}
throw e;
}
requireScope(accessToken, "aws.cognito.signin.user.admin");
String username = token.username();
String poolId = token.poolId();
if (!"email".equals(attributeName) && !"phone_number".equals(attributeName)) {
throw new AwsException("InvalidParameterException",
"Invalid attribute name. Only phone_number and email can be verified.", 400);
}
CognitoUser user = adminGetUser(poolId, username);
if (blankToNull(user.getAttributes().get(attributeName)) == null) {
throw new AwsException("InvalidParameterException",
"Unable to verify attribute: " + attributeName + " no value set to verify",
400);
}
VerificationCode.Purpose purpose = "email".equals(attributeName)
? VerificationCode.Purpose.EMAIL_ATTRIBUTE_VERIFICATION
: VerificationCode.Purpose.PHONE_ATTRIBUTE_VERIFICATION;
ensureVerificationWiring();
try {
verificationCodeService.consume(poolId, user.getUsername(), purpose, code);
} catch (VerificationCodeException e) {
throw mapVerificationCodeException(e);
}
user.getAttributes().put(attributeName + "_verified", "true");
user.setLastModifiedDate(System.currentTimeMillis() / 1000L);
userStore.put(userKey(poolId, user.getUsername()), user);
}
public void updateUserAttributes(String accessToken, Map<String, String> attributes) {
VerifiedAccessToken token = verifyAccessToken(accessToken);
String username = token.username();
@@ -3715,6 +3757,43 @@ public class CognitoService implements ResourceProvider {
/**
* Extracts the space-separated {@code scope} claim from an already-verified access token
* (call after {@link #verifyAccessToken}). {@code null} means no scope claim at all, which
* every token this simulator currently issues also is not the case for access tokens (see
* {@code generateSignedJwt}, which always sets a default scope) but a caller-suppressed
* scope list still needs to be tolerated as "no restriction modeled" rather than treated the
* same as an empty, restrictive list.
*/
private Set<String> extractScopesFromToken(String token) {
try {
String[] parts = token.split("\\.", -1);
JsonNode claims = MAPPER.readTree(Base64.getUrlDecoder().decode(parts[1]));
String scope = textClaim(claims, "scope");
if (scope == null || scope.isBlank()) return null;
Set<String> scopes = new HashSet<>();
for (String s : scope.split(" ")) {
if (!s.isBlank()) scopes.add(s);
}
return scopes;
} catch (Exception e) {
return null;
}
}
/**
* AWS requires an access token carrying the given scope for some operations (for example
* VerifyUserAttribute requires aws.cognito.signin.user.admin). Call after
* {@link #verifyAccessToken}, which already confirms the token is a valid, unexpired access
* token; this only adds the scope check on top.
*/
private void requireScope(String accessToken, String requiredScope) {
Set<String> scopes = extractScopesFromToken(accessToken);
if (scopes != null && !scopes.contains(requiredScope)) {
throw new AwsException("NotAuthorizedException", "Access Token does not have the required scope", 400);
}
}
/**
* Validate that a refresh token has not been revoked, including global user sign-out.
* Called from CognitoAuthFlowHandler for the REFRESH_TOKEN_AUTH flow.
@@ -86,9 +86,15 @@ public final class VerificationCodeService {
}
/**
* Validate a code. On success, marks it consumed and removes it. On any
* failure, throws {@link VerificationCodeException} with the specific
* {@link VerificationCodeException.Kind}.
* Validate a code. On success, marks it consumed. For the attribute-verification
* purposes, retains the tombstone until it expires or a new code replaces it, so a
* reused code answers {@code EXPIRED} rather than {@code NOT_FOUND}, validated against
* a real Cognito pool for {@code VerifyUserAttribute} (see CognitoServiceTest /
* CognitoAttributeVerificationIntegrationTest). {@link VerificationCode.Purpose#SIGNUP_CONFIRMATION}
* and {@link VerificationCode.Purpose#PASSWORD_RESET} keep the original delete-on-consume
* behavior instead, since that reuse case was never validated against real Cognito for
* {@code ConfirmSignUp} or {@code ConfirmForgotPassword}. On any failure, throws
* {@link VerificationCodeException} with the specific {@link VerificationCodeException.Kind}.
*
* <p>Note: not thread-safe under concurrent {@code consume()} of the same
* (poolId, username, purpose) key — two racing wrong-code calls may
@@ -101,17 +107,17 @@ public final class VerificationCodeService {
VerificationCode vc = store.get(key).orElseThrow(() -> new VerificationCodeException(
VerificationCodeException.Kind.NOT_FOUND,
"Invalid verification code provided, please try again"));
if (vc.isConsumed()) {
throw new VerificationCodeException(
VerificationCodeException.Kind.NOT_FOUND,
"Invalid verification code provided, please try again");
}
if (vc.isExpired(clock.instant())) {
store.delete(key);
throw new VerificationCodeException(
VerificationCodeException.Kind.EXPIRED,
"Invalid code provided, please request a code again");
}
if (vc.isConsumed()) {
throw new VerificationCodeException(
VerificationCodeException.Kind.EXPIRED,
"Invalid code provided, please request a code again");
}
if (vc.getAttemptsRemaining() <= 0) {
store.delete(key);
// AWS returns the generic invalid-code message here too, never the
@@ -136,7 +142,16 @@ public final class VerificationCodeService {
}
vc.markConsumed();
store.delete(key);
if (retainsConsumedTombstone(purpose)) {
store.put(key, vc);
} else {
store.delete(key);
}
}
private boolean retainsConsumedTombstone(VerificationCode.Purpose purpose) {
return purpose == VerificationCode.Purpose.EMAIL_ATTRIBUTE_VERIFICATION
|| purpose == VerificationCode.Purpose.PHONE_ATTRIBUTE_VERIFICATION;
}
/** Remove any active code for the (pool, user, purpose). Idempotent. */