feat(cognito): support pending user attribute verification (#2531)

* feat(cognito): support pending attribute verification

* fix(cognito): omit UserAttributeUpdateSettings when a pool never configured it

DescribeUserPool/CreateUserPool/UpdateUserPool always serialized
UserAttributeUpdateSettings as an empty object for pools that never set it,
where AWS omits absent optional members entirely. UserPoolAddOns right above
it already handles this correctly (an unconfigured pool omits the key rather
than returning {} or null, confirmed by Terraform re-planning the block into
and out of existence); UserAttributeUpdateSettings now follows the same
pattern.

* test(cognito): replace var with explicit AWS SDK response types

AGENTS.md's Types and names rule bans var in local declarations; the compat
test used it for four locals whose concrete AWS SDK type is the thing under
review here (CodeDeliveryDetailsType, UpdateUserAttributesResponse).

---------

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:50:16 -04:00
1 parent 52bafb7e5c
commit a03c4d6160
8 files changed
+545 -37

No files matched your search

@@ -1031,9 +1031,10 @@ public class CognitoJsonHandler {
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()));
service.updateUserAttributes(request.path("AccessToken").asText(), attrs);
List<Map<String, Object>> deliveryDetails = service.updateUserAttributes(
request.path("AccessToken").asText(), attrs);
ObjectNode response = objectMapper.createObjectNode();
response.putArray("CodeDeliveryDetailsList");
response.set("CodeDeliveryDetailsList", objectMapper.valueToTree(deliveryDetails));
return Response.ok(response).build();
}
@@ -1111,6 +1112,11 @@ public class CognitoJsonHandler {
}
node.set("UsernameConfiguration", objectMapper.valueToTree(p.getUsernameConfiguration() != null ? p.getUsernameConfiguration() : new HashMap<>()));
node.set("AccountRecoverySetting", objectMapper.valueToTree(p.getAccountRecoverySetting() != null ? p.getAccountRecoverySetting() : new HashMap<>()));
// Same reasoning as UserPoolAddOns above: an unconfigured pool omits this optional
// member entirely rather than returning an empty object.
if (p.getUserAttributeUpdateSettings() != null && !p.getUserAttributeUpdateSettings().isEmpty()) {
node.set("UserAttributeUpdateSettings", objectMapper.valueToTree(p.getUserAttributeUpdateSettings()));
}
node.put("UserPoolTier", p.getUserPoolTier() != null ? p.getUserPoolTier() : "ESSENTIALS");
return node;
@@ -373,9 +373,39 @@ public class CognitoService implements ResourceProvider {
if (request.containsKey("UserPoolAddOns")) pool.setUserPoolAddOns((Map<String, Object>) request.get("UserPoolAddOns"));
if (request.containsKey("UsernameConfiguration")) pool.setUsernameConfiguration((Map<String, Object>) request.get("UsernameConfiguration"));
if (request.containsKey("AccountRecoverySetting")) pool.setAccountRecoverySetting((Map<String, Object>) request.get("AccountRecoverySetting"));
if (request.containsKey("UserAttributeUpdateSettings")) {
pool.setUserAttributeUpdateSettings(validateUserAttributeUpdateSettings(
(Map<String, Object>) request.get("UserAttributeUpdateSettings")));
}
if (request.containsKey("UserPoolTier")) pool.setUserPoolTier((String) request.get("UserPoolTier"));
}
private Map<String, Object> validateUserAttributeUpdateSettings(Map<String, Object> settings) {
if (settings == null || settings.isEmpty()) {
return new HashMap<>();
}
Object rawAttributes = settings.get("AttributesRequireVerificationBeforeUpdate");
if (!(rawAttributes instanceof List<?> attributes)) {
throw new AwsException("InvalidParameterException",
"AttributesRequireVerificationBeforeUpdate must be a list", 400);
}
LinkedHashSet<String> normalized = new LinkedHashSet<>();
for (Object attribute : attributes) {
String name = String.valueOf(attribute);
if (!"email".equals(name) && !"phone_number".equals(name)) {
throw new AwsException("InvalidParameterException",
"AttributesRequireVerificationBeforeUpdate only supports email and phone_number", 400);
}
normalized.add(name);
}
Map<String, Object> result = new LinkedHashMap<>();
result.put("AttributesRequireVerificationBeforeUpdate", new ArrayList<>(normalized));
return result;
}
public UserPool describeUserPool(String id) {
UserPool pool = poolStore.get(id)
.orElseThrow(() -> userPoolNotFound(id));
@@ -2564,7 +2594,7 @@ public class CognitoService implements ResourceProvider {
CognitoUser user = adminGetUser(poolId, username);
UserPool pool = describeUserPool(poolId);
String destination = blankToNull(user.getAttributes().get(attributeName));
String destination = attributeVerificationDestination(user, attributeName);
if (destination == null) {
throw new AwsException("InvalidParameterException",
"email".equals(attributeName)
@@ -2581,7 +2611,7 @@ public class CognitoService implements ResourceProvider {
try {
String code = verificationCodeService.issue(poolId, user.getUsername(),
purpose, Duration.ofHours(24));
messageDispatcher.dispatch(pool, user, purpose, code, List.of(deliveryMedium));
dispatchAttributeVerificationCode(pool, user, attributeName, destination, purpose, code);
} catch (VerificationCodeException e) {
throw mapVerificationCodeException(e);
}
@@ -2614,16 +2644,19 @@ public class CognitoService implements ResourceProvider {
"Invalid attribute name. Only phone_number and email can be verified.", 400);
}
CognitoUser user = adminGetUser(poolId, username);
if (blankToNull(user.getAttributes().get(attributeName)) == null) {
CognitoUser user = MAPPER.convertValue(
adminGetUser(poolId, username), CognitoUser.class);
if (attributeVerificationDestination(user, 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;
VerificationCode.Purpose purpose = verificationPurpose(attributeName);
String pendingValue = blankToNull(user.getPendingAttributes().get(attributeName));
if (pendingValue != null) {
ensureAliasAvailable(describeUserPool(poolId), user, attributeName, pendingValue);
}
ensureVerificationWiring();
try {
verificationCodeService.consume(poolId, user.getUsername(), purpose, code);
@@ -2631,12 +2664,16 @@ public class CognitoService implements ResourceProvider {
throw mapVerificationCodeException(e);
}
if (pendingValue != null) {
user.getAttributes().put(attributeName, pendingValue);
user.getPendingAttributes().remove(attributeName);
}
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) {
public List<Map<String, Object>> updateUserAttributes(String accessToken, Map<String, String> attributes) {
VerifiedAccessToken token = verifyAccessToken(accessToken);
String username = token.username();
String poolId = token.poolId();
@@ -2651,7 +2688,76 @@ public class CognitoService implements ResourceProvider {
400);
}
adminUpdateUserAttributes(poolId, username, attributes);
UserPool pool = describeUserPool(poolId);
CognitoUser currentUser = adminGetUser(poolId, username);
// Validate every entry (alias availability) before mutating the user or issuing any
// verification code. Otherwise a later entry failing leaves an earlier entry's code
// live against a user record that was never actually updated, and the request's
// attribute order would silently change what gets left behind.
for (Map.Entry<String, String> attribute : attributes.entrySet()) {
String attributeName = attribute.getKey();
String value = attribute.getValue();
if (isVerifiableContactAttribute(attributeName) && blankToNull(value) != null) {
ensureAliasAvailable(pool, currentUser, attributeName, value);
}
}
CognitoUser updatedUser = MAPPER.convertValue(currentUser, CognitoUser.class);
List<Map<String, Object>> deliveryDetails = new ArrayList<>();
try {
for (Map.Entry<String, String> attribute : attributes.entrySet()) {
String attributeName = attribute.getKey();
String value = attribute.getValue();
if (blankToNull(value) == null) {
// AWS: "To delete an attribute from the user, submit the attribute in
// your API request with a blank value."
updatedUser.getAttributes().remove(attributeName);
updatedUser.getAttributes().remove(attributeName + "_verified");
updatedUser.getPendingAttributes().remove(attributeName);
continue;
}
if (!isVerifiableContactAttribute(attributeName)) {
updatedUser.getAttributes().put(attributeName, value);
continue;
}
VerificationCode.Purpose purpose = verificationPurpose(attributeName);
ensureVerificationWiring();
String verificationCode = verificationCodeService.issue(
poolId, currentUser.getUsername(), purpose, Duration.ofHours(24));
dispatchAttributeVerificationCode(pool, currentUser, attributeName, value,
purpose, verificationCode);
if (requiresVerificationBeforeUpdate(pool, attributeName)) {
updatedUser.getPendingAttributes().put(attributeName, value);
} else {
updatedUser.getAttributes().put(attributeName, value);
updatedUser.getAttributes().put(attributeName + "_verified", "false");
updatedUser.getPendingAttributes().remove(attributeName);
}
Map<String, Object> detail = new LinkedHashMap<>();
detail.put("AttributeName", attributeName);
detail.put("DeliveryMedium", deliveryMedium(attributeName));
detail.put("Destination", maskAttributeDestination(attributeName, value));
deliveryDetails.add(detail);
}
} catch (VerificationCodeException e) {
throw mapVerificationCodeException(e);
} catch (AwsException e) {
throw e;
} catch (RuntimeException e) {
throw new AwsException("CodeDeliveryFailureException",
"Failed to deliver verification code", 400);
}
updatedUser.setLastModifiedDate(System.currentTimeMillis() / 1000L);
userStore.put(userKey(poolId, updatedUser.getUsername()), updatedUser);
return deliveryDetails;
}
public void deleteUserAttributes(String accessToken, List<String> attributeNames) {
@@ -3916,6 +4022,66 @@ public class CognitoService implements ResourceProvider {
return "revoked:" + poolId + ":" + jti;
}
private boolean isVerifiableContactAttribute(String attributeName) {
return "email".equals(attributeName) || "phone_number".equals(attributeName);
}
private VerificationCode.Purpose verificationPurpose(String attributeName) {
return "email".equals(attributeName)
? VerificationCode.Purpose.EMAIL_ATTRIBUTE_VERIFICATION
: VerificationCode.Purpose.PHONE_ATTRIBUTE_VERIFICATION;
}
private String deliveryMedium(String attributeName) {
return "email".equals(attributeName) ? "EMAIL" : "SMS";
}
private String maskAttributeDestination(String attributeName, String destination) {
return "email".equals(attributeName)
? maskEmail(destination)
: maskPhoneNumber(destination);
}
private String attributeVerificationDestination(CognitoUser user, String attributeName) {
String pending = blankToNull(user.getPendingAttributes().get(attributeName));
return pending != null ? pending : blankToNull(user.getAttributes().get(attributeName));
}
private boolean requiresVerificationBeforeUpdate(UserPool pool, String attributeName) {
Object configured = pool.getUserAttributeUpdateSettings()
.get("AttributesRequireVerificationBeforeUpdate");
return configured instanceof List<?> attributes && attributes.contains(attributeName);
}
private void dispatchAttributeVerificationCode(UserPool pool, CognitoUser user,
String attributeName, String destination,
VerificationCode.Purpose purpose, String code) {
CognitoUser deliveryUser = MAPPER.convertValue(user, CognitoUser.class);
deliveryUser.getAttributes().put(attributeName, destination);
messageDispatcher.dispatch(pool, deliveryUser, purpose, code,
List.of(deliveryMedium(attributeName)));
}
private void ensureAliasAvailable(UserPool pool, CognitoUser currentUser,
String attributeName, String value) {
boolean aliasAttribute = pool.getAliasAttributes().contains(attributeName);
boolean usernameAttribute = pool.getUsernameAttributes().contains(attributeName);
if (!aliasAttribute && !usernameAttribute) {
return;
}
String prefix = pool.getId() + "::";
boolean conflict = userStore.scan(key -> key.startsWith(prefix)).stream()
.filter(candidate -> !candidate.getUsername().equals(currentUser.getUsername()))
.filter(candidate -> value.equals(candidate.getAttributes().get(attributeName)))
.anyMatch(candidate -> !aliasAttribute
|| isActiveAliasAttribute(candidate, attributeName));
if (conflict) {
throw new AwsException("AliasExistsException",
"An account with the given " + attributeName + " already exists", 400);
}
}
private void ensureVerificationWiring() {
if (verificationCodeService == null || messageDispatcher == null) {
throw new IllegalStateException("Verification services are not configured");
@@ -16,6 +16,7 @@ public class CognitoUser {
private String userStatus; // UNCONFIRMED, CONFIRMED, ARCHIVED, COMPROMISED, UNKNOWN, RESET_REQUIRED, FORCE_CHANGE_PASSWORD
private boolean enabled;
private Map<String, String> attributes = new HashMap<>();
private Map<String, String> pendingAttributes = new HashMap<>();
private long creationDate;
private long lastModifiedDate;
private String passwordHash;
@@ -49,6 +50,13 @@ public class CognitoUser {
public Map<String, String> getAttributes() { return attributes; }
public void setAttributes(Map<String, String> attributes) { this.attributes = attributes; }
public Map<String, String> getPendingAttributes() { return pendingAttributes; }
public void setPendingAttributes(Map<String, String> pendingAttributes) {
this.pendingAttributes = pendingAttributes == null
? new HashMap<>()
: new HashMap<>(pendingAttributes);
}
public long getCreationDate() { return creationDate; }
public void setCreationDate(long creationDate) { this.creationDate = creationDate; }
@@ -46,6 +46,7 @@ public class UserPool {
private Map<String, Object> userPoolAddOns = new HashMap<>();
private Map<String, Object> usernameConfiguration = new HashMap<>();
private Map<String, Object> accountRecoverySetting = new HashMap<>();
private Map<String, Object> userAttributeUpdateSettings = new HashMap<>();
private String userPoolTier = "ESSENTIALS";
private String clientIdOverride = null;
@@ -160,6 +161,13 @@ public class UserPool {
public Map<String, Object> getAccountRecoverySetting() { return accountRecoverySetting; }
public void setAccountRecoverySetting(Map<String, Object> accountRecoverySetting) { this.accountRecoverySetting = accountRecoverySetting; }
public Map<String, Object> getUserAttributeUpdateSettings() { return userAttributeUpdateSettings; }
public void setUserAttributeUpdateSettings(Map<String, Object> userAttributeUpdateSettings) {
this.userAttributeUpdateSettings = userAttributeUpdateSettings == null
? new HashMap<>()
: new HashMap<>(userAttributeUpdateSettings);
}
public String getUserPoolTier() { return userPoolTier; }
public void setUserPoolTier(String userPoolTier) { this.userPoolTier = userPoolTier; }