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

@@ -7,12 +7,17 @@ import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import software.amazon.awssdk.services.cognitoidentityprovider.CognitoIdentityProviderClient;
import software.amazon.awssdk.services.cognitoidentityprovider.model.AliasAttributeType;
import software.amazon.awssdk.services.cognitoidentityprovider.model.AttributeType;
import software.amazon.awssdk.services.cognitoidentityprovider.model.AuthFlowType;
import software.amazon.awssdk.services.cognitoidentityprovider.model.CodeDeliveryDetailsType;
import software.amazon.awssdk.services.cognitoidentityprovider.model.CodeMismatchException;
import software.amazon.awssdk.services.cognitoidentityprovider.model.ExpiredCodeException;
import software.amazon.awssdk.services.cognitoidentityprovider.model.ExplicitAuthFlowsType;
import software.amazon.awssdk.services.cognitoidentityprovider.model.MessageActionType;
import software.amazon.awssdk.services.cognitoidentityprovider.model.UpdateUserAttributesResponse;
import software.amazon.awssdk.services.cognitoidentityprovider.model.UserNotFoundException;
import software.amazon.awssdk.services.cognitoidentityprovider.model.VerifiedAttributeType;
import java.net.URI;
import java.net.URLEncoder;
@@ -68,41 +73,22 @@ class CognitoVerifyUserAttributeTest {
poolId = cognito.createUserPool(b -> b.poolName("verify-attribute-" + UUID.randomUUID()))
.userPool()
.id();
String clientId = cognito.createUserPoolClient(b -> b
.userPoolId(poolId)
.clientName("verify-attribute-client")
.explicitAuthFlows(ExplicitAuthFlowsType.ALLOW_USER_PASSWORD_AUTH))
.userPoolClient()
.clientId();
String clientId = createClient();
String username = "verify-" + UUID.randomUUID();
String email = username + "@example.com";
String phoneNumber = "+1555" + ThreadLocalRandom.current().nextLong(1_000_000, 10_000_000);
cognito.adminCreateUser(b -> b
.userPoolId(poolId)
.username(username)
.messageAction(MessageActionType.SUPPRESS)
.userAttributes(
AttributeType.builder().name("email").value(email).build(),
AttributeType.builder().name("phone_number").value(phoneNumber).build()));
cognito.adminSetUserPassword(b -> b
.userPoolId(poolId)
.username(username)
.password(PASSWORD)
.permanent(true));
createConfirmedUser(username,
AttributeType.builder().name("email").value(email).build(),
AttributeType.builder().name("phone_number").value(phoneNumber).build());
String accessToken = cognito.initiateAuth(b -> b
.clientId(clientId)
.authFlow(AuthFlowType.USER_PASSWORD_AUTH)
.authParameters(Map.of("USERNAME", username, "PASSWORD", PASSWORD)))
.authenticationResult()
.accessToken();
String accessToken = authenticate(clientId, username);
clearInspectionEndpoint("/_aws/ses");
clearInspectionEndpoint("/_aws/sns");
var emailDelivery = cognito.getUserAttributeVerificationCode(b -> b
CodeDeliveryDetailsType emailDelivery = cognito.getUserAttributeVerificationCode(b -> b
.accessToken(accessToken)
.attributeName("email"))
.codeDeliveryDetails();
@@ -111,7 +97,7 @@ class CognitoVerifyUserAttributeTest {
assertThat(emailDelivery.destination()).isEqualTo("v***@e***");
String emailCode = fetchLatestSesVerificationCode(email);
var phoneDelivery = cognito.getUserAttributeVerificationCode(b -> b
CodeDeliveryDetailsType phoneDelivery = cognito.getUserAttributeVerificationCode(b -> b
.accessToken(accessToken)
.attributeName("phone_number"))
.codeDeliveryDetails();
@@ -173,6 +159,141 @@ class CognitoVerifyUserAttributeTest {
assertThat(userAttribute(username, "phone_number_verified")).isEqualTo("true");
}
@Test
void requiredEmailUpdateStaysPendingUntilVerification() throws Exception {
poolId = cognito.createUserPool(b -> b
.poolName("pending-email-update-" + UUID.randomUUID())
.aliasAttributes(AliasAttributeType.EMAIL)
.autoVerifiedAttributes(VerifiedAttributeType.EMAIL)
.userAttributeUpdateSettings(s -> s
.attributesRequireVerificationBeforeUpdate(VerifiedAttributeType.EMAIL)))
.userPool()
.id();
String clientId = createClient();
String username = "pending-email-" + UUID.randomUUID();
String oldEmail = "old+" + UUID.randomUUID() + "@example.com";
String newEmail = "new+" + UUID.randomUUID() + "@example.com";
createConfirmedUser(username,
AttributeType.builder().name("email").value(oldEmail).build(),
AttributeType.builder().name("email_verified").value("true").build());
String accessToken = authenticate(clientId, oldEmail);
clearInspectionEndpoint("/_aws/ses");
UpdateUserAttributesResponse update = cognito.updateUserAttributes(b -> b
.accessToken(accessToken)
.userAttributes(AttributeType.builder().name("email").value(newEmail).build()));
assertThat(update.codeDeliveryDetailsList()).singleElement().satisfies(delivery -> {
assertThat(delivery.attributeName()).isEqualTo("email");
assertThat(delivery.deliveryMediumAsString()).isEqualTo("EMAIL");
assertThat(delivery.destination()).isEqualTo(maskedEmail(newEmail));
});
String code = fetchLatestSesVerificationCode(newEmail);
assertThat(userAttribute(username, "email")).isEqualTo(oldEmail);
assertThat(userAttribute(username, "email_verified")).isEqualTo("true");
assertThat(authenticate(clientId, oldEmail)).isNotBlank();
assertAliasRejected(clientId, newEmail);
assertThatThrownBy(() -> cognito.verifyUserAttribute(b -> b
.accessToken(accessToken)
.attributeName("email")
.code(differentCode(code))))
.isInstanceOf(CodeMismatchException.class);
assertThat(userAttribute(username, "email")).isEqualTo(oldEmail);
assertThat(userAttribute(username, "email_verified")).isEqualTo("true");
assertThat(authenticate(clientId, oldEmail)).isNotBlank();
assertAliasRejected(clientId, newEmail);
cognito.verifyUserAttribute(b -> b
.accessToken(accessToken)
.attributeName("email")
.code(code));
assertThat(userAttribute(username, "email")).isEqualTo(newEmail);
assertThat(userAttribute(username, "email_verified")).isEqualTo("true");
assertAliasRejected(clientId, oldEmail);
assertThat(authenticate(clientId, newEmail)).isNotBlank();
}
@Test
void nonRequiredPhoneUpdateIsImmediateAndUnverifiedUntilVerification() throws Exception {
poolId = cognito.createUserPool(b -> b
.poolName("immediate-phone-update-" + UUID.randomUUID())
.aliasAttributes(AliasAttributeType.PHONE_NUMBER)
.autoVerifiedAttributes(VerifiedAttributeType.PHONE_NUMBER))
.userPool()
.id();
String clientId = createClient();
String username = "immediate-phone-" + UUID.randomUUID();
String oldPhone = "+15550001111";
String newPhone = "+15550002222";
createConfirmedUser(username,
AttributeType.builder().name("phone_number").value(oldPhone).build(),
AttributeType.builder().name("phone_number_verified").value("true").build());
String accessToken = authenticate(clientId, oldPhone);
clearInspectionEndpoint("/_aws/sns");
UpdateUserAttributesResponse update = cognito.updateUserAttributes(b -> b
.accessToken(accessToken)
.userAttributes(AttributeType.builder().name("phone_number").value(newPhone).build()));
assertThat(update.codeDeliveryDetailsList()).singleElement().satisfies(delivery -> {
assertThat(delivery.attributeName()).isEqualTo("phone_number");
assertThat(delivery.deliveryMediumAsString()).isEqualTo("SMS");
assertThat(delivery.destination()).isEqualTo(maskedPhoneNumber(newPhone));
});
String code = fetchLatestSnsVerificationCode(newPhone);
assertThat(userAttribute(username, "phone_number")).isEqualTo(newPhone);
assertThat(userAttribute(username, "phone_number_verified")).isEqualTo("false");
assertAliasRejected(clientId, oldPhone);
assertAliasRejected(clientId, newPhone);
cognito.verifyUserAttribute(b -> b
.accessToken(accessToken)
.attributeName("phone_number")
.code(code));
assertThat(userAttribute(username, "phone_number_verified")).isEqualTo("true");
assertAliasRejected(clientId, oldPhone);
assertThat(authenticate(clientId, newPhone)).isNotBlank();
}
private String createClient() {
return cognito.createUserPoolClient(b -> b
.userPoolId(poolId)
.clientName("verify-attribute-client")
.explicitAuthFlows(ExplicitAuthFlowsType.ALLOW_USER_PASSWORD_AUTH))
.userPoolClient()
.clientId();
}
private void createConfirmedUser(String username, AttributeType... attributes) {
cognito.adminCreateUser(b -> b
.userPoolId(poolId)
.username(username)
.messageAction(MessageActionType.SUPPRESS)
.userAttributes(attributes));
cognito.adminSetUserPassword(b -> b
.userPoolId(poolId)
.username(username)
.password(PASSWORD)
.permanent(true));
}
private String authenticate(String clientId, String username) {
return cognito.initiateAuth(b -> b
.clientId(clientId)
.authFlow(AuthFlowType.USER_PASSWORD_AUTH)
.authParameters(Map.of("USERNAME", username, "PASSWORD", PASSWORD)))
.authenticationResult()
.accessToken();
}
private void assertAliasRejected(String clientId, String alias) {
assertThatThrownBy(() -> authenticate(clientId, alias))
.isInstanceOf(UserNotFoundException.class);
}
private String userAttribute(String username, String attributeName) {
return cognito.adminGetUser(b -> b.userPoolId(poolId).username(username))
.userAttributes()
@@ -232,6 +353,11 @@ class CognitoVerifyUserAttributeTest {
return "000000".equals(code) ? "000001" : "000000";
}
private static String maskedEmail(String email) {
int at = email.indexOf('@');
return email.charAt(0) + "***@" + email.charAt(at + 1) + "***";
}
private static String maskedPhoneNumber(String phoneNumber) {
return "+" + "*".repeat(phoneNumber.length() - 5)
+ phoneNumber.substring(phoneNumber.length() - 4);
+21
View File
@@ -192,6 +192,27 @@ further divergences, both deliberate:
|--------|-------------|
| ListUsers | Lists users stored in a user pool. |
## User Attribute Update Verification
`CreateUserPool`, `UpdateUserPool`, and `DescribeUserPool` support
`UserAttributeUpdateSettings.AttributesRequireVerificationBeforeUpdate` for
`email` and `phone_number`.
For attributes listed in this setting, `UpdateUserAttributes` keeps the existing
verified value and sign-in alias active while the new value is pending. It sends
a verification code to the pending destination and returns the corresponding
entry in `CodeDeliveryDetailsList`. A successful `VerifyUserAttribute` promotes
the pending value, switches the alias, and sets the matching `*_verified`
attribute to `true`.
Without the setting, `UpdateUserAttributes` replaces the value immediately and
sets the matching `*_verified` attribute to `false` until verification succeeds.
A verification code is still sent to the replacement value, but Cognito no
longer retains or exposes the old value. For alias attributes, the old alias is
removed immediately and the replacement becomes usable for sign-in only after
successful verification. Incorrect or expired codes don't promote a pending
value or change its verified state.
### Groups
| Action | Description |
@@ -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; }
@@ -357,6 +357,51 @@ class CognitoAttributeVerificationIntegrationTest {
.body("message", equalTo("Invalid Access Token"));
}
@Test
@Order(13)
void userAttributeUpdateSettingsRoundTripThroughCreateUpdateAndDescribe() throws Exception {
JsonNode created = cognitoJson("CreateUserPool", """
{
"PoolName": "AttributeUpdateSettingsRoundTrip",
"UserAttributeUpdateSettings": {
"AttributesRequireVerificationBeforeUpdate": ["email", "phone_number"]
}
}
""");
String configuredPoolId = created.path("UserPool").path("Id").asText();
cognitoAction("DescribeUserPool", """
{
"UserPoolId": "%s"
}
""".formatted(configuredPoolId))
.then()
.statusCode(200)
.body("UserPool.UserAttributeUpdateSettings.AttributesRequireVerificationBeforeUpdate",
equalTo(java.util.List.of("email", "phone_number")));
cognitoAction("UpdateUserPool", """
{
"UserPoolId": "%s",
"UserAttributeUpdateSettings": {
"AttributesRequireVerificationBeforeUpdate": ["phone_number"]
}
}
""".formatted(configuredPoolId))
.then()
.statusCode(200);
cognitoAction("DescribeUserPool", """
{
"UserPoolId": "%s"
}
""".formatted(configuredPoolId))
.then()
.statusCode(200)
.body("UserPool.UserAttributeUpdateSettings.AttributesRequireVerificationBeforeUpdate",
equalTo(java.util.List.of("phone_number")));
}
private static void clearInspectionEndpoint(String path) {
given()
.delete(path)
@@ -22,7 +22,9 @@ import io.github.hectorvent.floci.services.cognito.model.UserPoolClient;
import io.github.hectorvent.floci.services.cognito.model.UserPoolDomain;
import io.github.hectorvent.floci.services.cognito.verification.CognitoMessageDispatcher;
import io.github.hectorvent.floci.services.cognito.verification.VerificationCode;
import io.github.hectorvent.floci.services.cognito.verification.VerificationCodeException;
import io.github.hectorvent.floci.services.cognito.verification.VerificationCodeService;
import org.mockito.ArgumentCaptor;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Nested;
import org.junit.jupiter.api.Test;
@@ -1589,6 +1591,132 @@ class CognitoServiceTest {
.getAttributes().get(verificationStatusAttribute));
}
@Test
@SuppressWarnings("unchecked")
void expiredPendingEmailCodeLeavesActiveAttributeAndVerifiedFlagUnchanged() {
VerificationCodeService verificationCodeService = mock(VerificationCodeService.class);
CognitoMessageDispatcher messageDispatcher = mock(CognitoMessageDispatcher.class);
when(verificationCodeService.issue(any(), any(),
eq(VerificationCode.Purpose.EMAIL_ATTRIBUTE_VERIFICATION), any()))
.thenReturn("123456");
CognitoService serviceWithVerification = new CognitoService(
new InMemoryStorage<>(),
new InMemoryStorage<>(),
new InMemoryStorage<>(),
new InMemoryStorage<>(),
new InMemoryStorage<>(),
new InMemoryStorage<>(),
new InMemoryStorage<>(),
new InMemoryStorage<>(),
"http://localhost:4566",
regionResolver,
null,
acmService,
verificationCodeService,
messageDispatcher,
mock(TlsCertificateManager.class));
UserPool pool = serviceWithVerification.createUserPool(Map.of(
"PoolName", "PendingEmailExpiryPool",
"AutoVerifiedAttributes", List.of("email"),
"UserAttributeUpdateSettings", Map.of(
"AttributesRequireVerificationBeforeUpdate", List.of("email"))),
"us-east-1");
UserPoolClient client = serviceWithVerification.createUserPoolClient(
pool.getId(), "pending-email-expiry-client", false, false, List.of(), List.of());
serviceWithVerification.adminCreateUser(pool.getId(), "alice", Map.of(
"email", "old@example.com",
"email_verified", "true"), "TempPass1!");
serviceWithVerification.adminSetUserPassword(
pool.getId(), "alice", "Permanent1!", true);
Map<String, Object> authResult = serviceWithVerification.initiateAuth(
client.getClientId(), "USER_PASSWORD_AUTH",
Map.of("USERNAME", "alice", "PASSWORD", "Permanent1!"));
String accessToken = (String) ((Map<String, Object>) authResult.get("AuthenticationResult"))
.get("AccessToken");
serviceWithVerification.updateUserAttributes(
accessToken, Map.of("email", "new@example.com"));
doThrow(new VerificationCodeException(
VerificationCodeException.Kind.EXPIRED,
"Invalid code provided, please request code again"))
.when(verificationCodeService)
.consume(pool.getId(), "alice",
VerificationCode.Purpose.EMAIL_ATTRIBUTE_VERIFICATION, "123456");
AwsException error = assertThrows(AwsException.class,
() -> serviceWithVerification.verifyUserAttribute(accessToken, "email", "123456"));
assertEquals("ExpiredCodeException", error.getErrorCode());
CognitoUser unchanged = serviceWithVerification.adminGetUser(pool.getId(), "alice");
assertEquals("old@example.com", unchanged.getAttributes().get("email"));
assertEquals("true", unchanged.getAttributes().get("email_verified"));
assertEquals("new@example.com", unchanged.getPendingAttributes().get("email"));
}
@Test
@SuppressWarnings("unchecked")
void verificationCodeForRequiredEmailUpdateUsesPendingDestination() {
VerificationCodeService verificationCodeService = mock(VerificationCodeService.class);
CognitoMessageDispatcher messageDispatcher = mock(CognitoMessageDispatcher.class);
when(verificationCodeService.issue(any(), any(),
eq(VerificationCode.Purpose.EMAIL_ATTRIBUTE_VERIFICATION), any()))
.thenReturn("123456");
CognitoService serviceWithVerification = new CognitoService(
new InMemoryStorage<>(),
new InMemoryStorage<>(),
new InMemoryStorage<>(),
new InMemoryStorage<>(),
new InMemoryStorage<>(),
new InMemoryStorage<>(),
new InMemoryStorage<>(),
new InMemoryStorage<>(),
"http://localhost:4566",
regionResolver,
null,
acmService,
verificationCodeService,
messageDispatcher,
mock(TlsCertificateManager.class));
UserPool pool = serviceWithVerification.createUserPool(Map.of(
"PoolName", "PendingEmailDeliveryPool",
"AutoVerifiedAttributes", List.of("email"),
"UserAttributeUpdateSettings", Map.of(
"AttributesRequireVerificationBeforeUpdate", List.of("email"))),
"us-east-1");
UserPoolClient client = serviceWithVerification.createUserPoolClient(
pool.getId(), "pending-email-delivery-client", false, false, List.of(), List.of());
serviceWithVerification.adminCreateUser(pool.getId(), "alice", Map.of(
"email", "old@example.com",
"email_verified", "true"), "TempPass1!");
serviceWithVerification.adminSetUserPassword(
pool.getId(), "alice", "Permanent1!", true);
Map<String, Object> authResult = serviceWithVerification.initiateAuth(
client.getClientId(), "USER_PASSWORD_AUTH",
Map.of("USERNAME", "alice", "PASSWORD", "Permanent1!"));
String accessToken = (String) ((Map<String, Object>) authResult.get("AuthenticationResult"))
.get("AccessToken");
serviceWithVerification.updateUserAttributes(
accessToken, Map.of("email", "new@example.com"));
clearInvocations(messageDispatcher);
Map<String, Object> delivery = serviceWithVerification
.getUserAttributeVerificationCode(accessToken, "email");
assertEquals("n***@e***", delivery.get("Destination"));
ArgumentCaptor<CognitoUser> deliveryUser = ArgumentCaptor.forClass(CognitoUser.class);
verify(messageDispatcher).dispatch(
eq(pool), deliveryUser.capture(),
eq(VerificationCode.Purpose.EMAIL_ATTRIBUTE_VERIFICATION),
eq("123456"), eq(List.of("EMAIL")));
assertEquals("new@example.com", deliveryUser.getValue().getAttributes().get("email"));
assertEquals("old@example.com",
serviceWithVerification.adminGetUser(pool.getId(), "alice").getAttributes().get("email"));
}
@Test
@SuppressWarnings("unchecked")
void jwtSubMatchesStoredSubAttribute() {