feat(cognito): add GetUserAttributeVerificationCode support (#1898)

* feat(cognito): issue attribute verification codes in CognitoService

* feat(cognito): dispatch GetUserAttributeVerificationCode in CognitoJsonHandler

* test(cognito): add GetUserAttributeVerificationCode happy path

* test(cognito): cover invalid token and unverifiable attribute errors

* docs(cognito): document GetUserAttributeVerificationCode

* fix(cognito): key attribute verification codes per attribute

* fix(cognito): match AWS error messages for GetUserAttributeVerificationCode

Real Cognito returns "Invalid Access Token", "Invalid attribute name.
Only phone_number and email can be verified.", and attribute-specific
"User does not have a valid registered email address" / "...phone
number" messages, per AWS-parity comparison in PR #1898 review.

* fix(cognito): match AWS destination masking format for verification codes

Real Cognito masks as "z***@b***" for email (first char of local part
and domain, three asterisks, no TLD retained) and "+********8920" for
phone (leading "+", asterisks, last four digits kept), per AWS-parity
comparison in PR #1898 review. Applies to both attribute-verification
and forgot-password/account-recovery delivery masking, which share
these helpers.

* test(cognito): assert exact AWS-parity error messages and mask format

Tighten GetUserAttributeVerificationCode assertions from loose
containsString checks to the exact wording and masking AWS returns,
so a regression in either silently drifting from AWS again is caught.

* test(cognito): cover re-issuing verification code for a verified attribute

AWS permits requesting a fresh GetUserAttributeVerificationCode code
for an attribute that is already verified, as long as its value has
not changed. Nothing in the current issuance path checks the
*_verified flag, so this locks in that AWS-parity behavior.

* style(cognito): drop redundant comment in attribute verification test

The method name already conveys the AWS behavior being tested, per
AGENTS.md's guidance to prefer self-explanatory code over comments.
This commit is contained in:
Feyikemi Ogunsanya authored and GitHub committed 2026-08-17 00:27:15 -05:00
1 parent 25b46e28ad
commit 24cdabb257
5 files changed
+339 -19

No files matched your search

@@ -81,6 +81,7 @@ public class CognitoJsonHandler {
case "ForgotPassword" -> handleForgotPassword(request);
case "ConfirmForgotPassword" -> handleConfirmForgotPassword(request);
case "GetUser" -> handleGetUser(request);
case "GetUserAttributeVerificationCode" -> handleGetUserAttributeVerificationCode(request);
case "UpdateUserAttributes" -> handleUpdateUserAttributes(request);
case "DeleteUserAttributes" -> handleDeleteUserAttributes(request);
case "GlobalSignOut" -> handleGlobalSignOut(request);
@@ -629,6 +630,19 @@ public class CognitoJsonHandler {
return Response.ok(objectMapper.valueToTree(result)).build();
}
private Response handleGetUserAttributeVerificationCode(JsonNode request) {
Map<String, Object> deliveryDetails = service.getUserAttributeVerificationCode(
request.path("AccessToken").asText(),
request.path("AttributeName").asText()
);
ObjectNode response = objectMapper.createObjectNode();
ObjectNode delivery = response.putObject("CodeDeliveryDetails");
delivery.put("AttributeName", (String) deliveryDetails.get("AttributeName"));
delivery.put("DeliveryMedium", (String) deliveryDetails.get("DeliveryMedium"));
delivery.put("Destination", (String) deliveryDetails.get("Destination"));
return Response.ok(response).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()));
@@ -1565,6 +1565,57 @@ public class CognitoService {
return result;
}
public Map<String, Object> getUserAttributeVerificationCode(String accessToken, String attributeName) {
String username = extractUsernameFromToken(accessToken);
String poolId = extractPoolIdFromToken(accessToken);
String jti = extractJtiFromToken(accessToken);
if (username == null || poolId == null || jti == null) {
throw new AwsException("NotAuthorizedException", "Invalid Access Token", 400);
}
validateTokenNotRevoked(jti, poolId, "access");
validateOriginJtiNotRevoked(accessToken, poolId);
Long iat = extractIatFromToken(accessToken);
validateUserNotGloballySignedOut(username, poolId, "access", iat != null ? iat : 0L);
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);
UserPool pool = describeUserPool(poolId);
String destination = blankToNull(user.getAttributes().get(attributeName));
if (destination == null) {
throw new AwsException("InvalidParameterException",
"email".equals(attributeName)
? "User does not have a valid registered email address"
: "User does not have a valid registered phone number",
400);
}
String deliveryMedium = "email".equals(attributeName) ? "EMAIL" : "SMS";
VerificationCode.Purpose purpose = "email".equals(attributeName)
? VerificationCode.Purpose.EMAIL_ATTRIBUTE_VERIFICATION
: VerificationCode.Purpose.PHONE_ATTRIBUTE_VERIFICATION;
ensureVerificationWiring();
try {
String code = verificationCodeService.issue(poolId, user.getUsername(),
purpose, Duration.ofHours(24));
messageDispatcher.dispatch(pool, user, purpose, code, List.of(deliveryMedium));
} catch (VerificationCodeException e) {
throw mapVerificationCodeException(e);
}
Map<String, Object> response = new LinkedHashMap<>();
response.put("AttributeName", attributeName);
response.put("DeliveryMedium", deliveryMedium);
response.put("Destination",
"email".equals(attributeName) ? maskEmail(destination) : maskPhoneNumber(destination));
return response;
}
public void updateUserAttributes(String accessToken, Map<String, String> attributes) {
String username = extractUsernameFromToken(accessToken);
String poolId = extractPoolIdFromToken(accessToken);
@@ -2802,34 +2853,21 @@ public class CognitoService {
if (at <= 0 || at == email.length() - 1) {
return "****";
}
String local = email.substring(0, at);
String domain = email.substring(at + 1);
return maskSegment(local) + "@" + maskDomain(domain);
return email.charAt(0) + "***@" + email.charAt(at + 1) + "***";
}
private String maskPhoneNumber(String phoneNumber) {
if (phoneNumber.length() <= 4) {
return "*".repeat(phoneNumber.length());
}
if (phoneNumber.charAt(0) == '+') {
return "+" + "*".repeat(Math.max(0, phoneNumber.length() - 5))
+ phoneNumber.substring(phoneNumber.length() - 4);
}
return "*".repeat(phoneNumber.length() - 4)
+ phoneNumber.substring(phoneNumber.length() - 4);
}
private String maskDomain(String domain) {
int dot = domain.lastIndexOf('.');
if (dot <= 0 || dot == domain.length() - 1) {
return maskSegment(domain);
}
return maskSegment(domain.substring(0, dot)) + domain.substring(dot);
}
private String maskSegment(String value) {
if (value.length() <= 1) {
return "*";
}
return value.charAt(0) + "*".repeat(Math.max(1, value.length() - 1));
}
private String blankToNull(String value) {
if (value == null || value.isBlank()) {
return null;
@@ -19,7 +19,10 @@ public final class VerificationCode {
SIGNUP_CONFIRMATION,
PASSWORD_RESET,
SMS_MFA,
ATTRIBUTE_VERIFICATION
// Attribute verification is keyed per attribute so email and phone_number codes
// rate-limit and overwrite independently, matching AWS.
EMAIL_ATTRIBUTE_VERIFICATION,
PHONE_ATTRIBUTE_VERIFICATION
}
private final String userPoolId;