fix(cognito): reject undeclared custom user attributes (#7994) (#8124)

This commit is contained in:
jwoa95 authored and GitHub committed 2026-11-12 14:04:51 -04:00
1 parent 021e580a60
commit 5da8045bb2
9 files changed
+241 -6

No files matched your search

@@ -0,0 +1,130 @@
package com.floci.test;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.CsvSource;
import org.junit.jupiter.params.provider.ValueSource;
import software.amazon.awssdk.services.cognitoidentityprovider.CognitoIdentityProviderClient;
import software.amazon.awssdk.services.cognitoidentityprovider.model.AttributeDataType;
import software.amazon.awssdk.services.cognitoidentityprovider.model.AttributeType;
import software.amazon.awssdk.services.cognitoidentityprovider.model.AuthFlowType;
import software.amazon.awssdk.services.cognitoidentityprovider.model.ExplicitAuthFlowsType;
import software.amazon.awssdk.services.cognitoidentityprovider.model.InvalidParameterException;
import software.amazon.awssdk.services.cognitoidentityprovider.model.MessageActionType;
import software.amazon.awssdk.services.cognitoidentityprovider.model.SchemaAttributeType;
import java.util.List;
import java.util.Map;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
@DisplayName("Cognito custom attribute schema validation (issue #7994)")
class CognitoCustomAttributeSchemaTest {
private static final String PASSWORD = "Valid-password123!";
@ParameterizedTest
@CsvSource({
"AdminCreateUser, create", "AdminCreateUser, add",
"SignUp, create", "SignUp, add",
"AdminUpdateUserAttributes, create", "AdminUpdateUserAttributes, add",
"UpdateUserAttributes, create", "UpdateUserAttributes, add"
})
@DisplayName("All user writes reject undeclared attributes atomically and accept declared attributes")
void rejectsUndeclaredAttributesWithoutSavingAnyChanges(String action, String schemaSource) {
try (CognitoIdentityProviderClient cognito = TestFixtures.cognitoClient()) {
SchemaAttributeType known = SchemaAttributeType.builder().name("known")
.attributeDataType(AttributeDataType.STRING).mutable(true).build();
String poolId = cognito.createUserPool(b -> b.poolName(TestFixtures.uniqueName("custom-schema"))
.schema(schemaSource.equals("create") ? List.of(known) : List.of())).userPool().id();
try {
if (schemaSource.equals("add")) {
cognito.addCustomAttributes(b -> b.userPoolId(poolId).customAttributes(known));
}
String clientId = createClient(cognito, poolId);
cognito.adminCreateUser(b -> b.userPoolId(poolId).username("existing")
.messageAction(MessageActionType.SUPPRESS).userAttributes(
attribute("email", "original@example.com"), attribute("custom:known", "original")));
String accessToken = signIn(cognito, poolId, clientId);
List<AttributeType> original = cognito.adminGetUser(b -> b.userPoolId(poolId)
.username("existing")).userAttributes();
String username = action.equals("AdminCreateUser") || action.equals("SignUp") ? "new-user" : "existing";
List<AttributeType> invalid = List.of(attribute("email", "changed@example.com"),
attribute("custom:known", "changed"), attribute("custom:undeclared", "x"));
assertThatThrownBy(() -> write(cognito, action, poolId, clientId, username, accessToken, invalid))
.isInstanceOf(InvalidParameterException.class)
.hasMessageContaining("Attribute does not exist in the schema");
assertThat(cognito.adminGetUser(b -> b.userPoolId(poolId).username("existing")).userAttributes())
.containsExactlyInAnyOrderElementsOf(original);
assertThat(cognito.listUsers(b -> b.userPoolId(poolId)).users()).hasSize(1);
write(cognito, action, poolId, clientId, username, accessToken,
List.of(attribute("email", "changed@example.com"), attribute("custom:known", "changed")));
assertThat(cognito.adminGetUser(b -> b.userPoolId(poolId).username(username)).userAttributes())
.contains(attribute("custom:known", "changed"), attribute("email", "changed@example.com"));
} finally {
cognito.deleteUserPool(b -> b.userPoolId(poolId));
}
}
}
@ParameterizedTest
@ValueSource(strings = {"AdminCreateUser", "SignUp", "AdminUpdateUserAttributes", "UpdateUserAttributes"})
@DisplayName("A pool without a custom schema rejects custom attributes")
void rejectsCustomAttributesWhenNoSchemaWasDeclared(String action) {
try (CognitoIdentityProviderClient cognito = TestFixtures.cognitoClient()) {
String poolId = cognito.createUserPool(b -> b.poolName(TestFixtures.uniqueName("no-custom-schema")))
.userPool().id();
try {
String clientId = createClient(cognito, poolId);
cognito.adminCreateUser(b -> b.userPoolId(poolId).username("existing")
.messageAction(MessageActionType.SUPPRESS));
String accessToken = signIn(cognito, poolId, clientId);
String username = action.equals("AdminCreateUser") || action.equals("SignUp") ? "new-user" : "existing";
assertThatThrownBy(() -> write(cognito, action, poolId, clientId, username, accessToken,
List.of(attribute("custom:undeclared", "x"))))
.isInstanceOf(InvalidParameterException.class)
.hasMessageContaining("Attribute does not exist in the schema");
assertThat(cognito.listUsers(b -> b.userPoolId(poolId)).users()).hasSize(1);
assertThat(cognito.adminGetUser(b -> b.userPoolId(poolId).username("existing")).userAttributes())
.extracting(AttributeType::name).doesNotContain("custom:undeclared");
} finally {
cognito.deleteUserPool(b -> b.userPoolId(poolId));
}
}
}
private static String createClient(CognitoIdentityProviderClient cognito, String poolId) {
return cognito.createUserPoolClient(b -> b.userPoolId(poolId).clientName("custom-schema-client")
.explicitAuthFlows(ExplicitAuthFlowsType.ALLOW_USER_PASSWORD_AUTH)).userPoolClient().clientId();
}
private static String signIn(CognitoIdentityProviderClient cognito, String poolId, String clientId) {
cognito.adminSetUserPassword(b -> b.userPoolId(poolId).username("existing").password(PASSWORD).permanent(true));
return cognito.initiateAuth(b -> b.clientId(clientId).authFlow(AuthFlowType.USER_PASSWORD_AUTH)
.authParameters(Map.of("USERNAME", "existing", "PASSWORD", PASSWORD)))
.authenticationResult().accessToken();
}
private static AttributeType attribute(String name, String value) {
return AttributeType.builder().name(name).value(value).build();
}
private static void write(CognitoIdentityProviderClient cognito, String action, String poolId, String clientId,
String username, String accessToken, List<AttributeType> attributes) {
switch (action) {
case "AdminCreateUser" -> cognito.adminCreateUser(b -> b.userPoolId(poolId).username(username)
.messageAction(MessageActionType.SUPPRESS).userAttributes(attributes));
case "SignUp" -> cognito.signUp(b -> b.clientId(clientId).username(username).password(PASSWORD)
.userAttributes(attributes));
case "AdminUpdateUserAttributes" -> cognito.adminUpdateUserAttributes(b -> b.userPoolId(poolId)
.username(username).userAttributes(attributes));
case "UpdateUserAttributes" -> cognito.updateUserAttributes(b -> b.accessToken(accessToken)
.userAttributes(attributes));
default -> throw new IllegalArgumentException("Unknown action: " + action);
}
}
}
+9
View File
@@ -29,6 +29,15 @@ where `errorMessage` is taken verbatim from the function's error payload, as on
Sign-in by a disabled user fails with `NotAuthorizedException` (`User is disabled.`), as on AWS.
`AdminCreateUser`, `SignUp`, `AdminUpdateUserAttributes` and `UpdateUserAttributes` reject
`custom:` attributes that the user pool's schema does not declare with `InvalidParameterException`
and `Attribute does not exist in the schema.`. Declare custom attributes with `CreateUserPool`
or `AddCustomAttributes` before writing them. Validation runs before creating a user or changing
any attributes, so a rejected request does not save partial changes.
`NEW_PASSWORD_REQUIRED` responses, including custom SRP flows and administrative responses, also
validate custom attributes before changing the password or consuming the challenge session. An
undeclared attribute leaves both unchanged, so the client can correct the attributes and retry.
`CreateUserPool` supports overriding several values using user-pool tags **only** at creation time:
* `floci:override-id`, to pin the resulting `UserPool.Id`. Because a pinned id is caller-chosen it can be reused, which AWS never does. `DeleteUserPool` therefore deletes everything the pool owns (users, groups, app clients, resource servers, revoked token records and outstanding verification codes) so a pool recreated on the same id starts empty rather than inheriting the deleted pool's password hashes and client secrets.
* `floci:override-cognito-client-id`
@@ -572,21 +572,27 @@ final class CognitoAuthFlowHandler {
if (username == null || newPassword == null) {
throw new AwsException("InvalidParameterException", "USERNAME and NEW_PASSWORD are required", 400);
}
CognitoService.validateCustomAttributes(pool, newPasswordAttributes(responses));
service.adminSetUserPassword(pool.getId(), username, newPassword, true);
}
private CognitoUser applyNewPasswordAttributes(UserPool pool, Map<String, String> responses) {
String username = responses.get("USERNAME");
Map<String, String> attrUpdates = newPasswordAttributes(responses);
if (!attrUpdates.isEmpty()) {
service.adminUpdateUserAttributes(pool.getId(), username, attrUpdates);
}
return service.adminGetUser(pool.getId(), username);
}
private static Map<String, String> newPasswordAttributes(Map<String, String> responses) {
Map<String, String> attrUpdates = new HashMap<>();
for (Map.Entry<String, String> entry : responses.entrySet()) {
if (entry.getKey() != null && entry.getKey().startsWith("userAttributes.")) {
attrUpdates.put(entry.getKey().substring("userAttributes.".length()), entry.getValue());
}
}
if (!attrUpdates.isEmpty()) {
service.adminUpdateUserAttributes(pool.getId(), username, attrUpdates);
}
return service.adminGetUser(pool.getId(), username);
return attrUpdates;
}
// ──────────────────────────── USER_PASSWORD / REFRESH ────────────────────────────
@@ -2505,6 +2505,7 @@ public class CognitoService implements ResourceProvider {
resolvedAttributes.put("sub", canonicalUsername);
}
validateCustomAttributes(pool, resolvedAttributes);
validateEmailAttribute(resolvedAttributes, false);
CognitoUser user = new CognitoUser();
@@ -2822,6 +2823,7 @@ public class CognitoService implements ResourceProvider {
Map<String, String> clientMetadata, List<AttributeCodeMessage> messages) {
CognitoUser currentUser = adminGetUser(userPoolId, username);
UserPool pool = describeUserPool(userPoolId);
validateCustomAttributes(pool, attributes);
boolean stagesContactUpdate = attributes.entrySet().stream()
.anyMatch(attribute -> isVerifiableContactAttribute(attribute.getKey())
&& shouldVerifyAttribute(pool, attribute.getKey())
@@ -3566,6 +3568,7 @@ public class CognitoService implements ResourceProvider {
resolvedAttributes.put("sub", canonicalUsername);
}
validateCustomAttributes(pool, resolvedAttributes);
validateEmailAttribute(resolvedAttributes, false);
String key = userKey(userPoolId, canonicalUsername);
@@ -4630,6 +4633,7 @@ public class CognitoService implements ResourceProvider {
Map<String, String> clientMetadata, List<AttributeCodeMessage> messages) {
UserPool pool = describeUserPool(poolId);
CognitoUser currentUser = adminGetUser(poolId, username);
validateCustomAttributes(pool, attributes);
validateEmailAttribute(attributes, true);
// Validate every entry (alias availability) before mutating the user or issuing any
@@ -4729,6 +4733,17 @@ public class CognitoService implements ResourceProvider {
return deliveryDetails;
}
static void validateCustomAttributes(UserPool pool, Map<String, String> attributes) {
List<Map<String, Object>> schema = pool.getSchemaAttributes();
for (String name : attributes.keySet()) {
if (name != null && name.startsWith("custom:")
&& (schema == null || schema.stream().noneMatch(attribute -> name.equals(attribute.get("Name"))))) {
throw new AwsException("InvalidParameterException", "Attributes did not conform to the schema: "
+ name + ": Attribute does not exist in the schema.", 400);
}
}
}
private static void validateEmailAttribute(Map<String, String> attributes, boolean allowDeletion) {
if (attributes == null || !attributes.containsKey("email")) {
return;
@@ -253,6 +253,53 @@ class CognitoCustomSrpAuthTest {
}
}
@ParameterizedTest
@CsvSource({"false,false", "false,true", "true,false", "true,true"})
void undeclaredNewPasswordAttributesPreservePasswordAndSession(boolean custom, boolean admin) throws Exception {
temporaryPassword = true;
service.adminSetUserPassword(pool.getId(), USERNAME, PASSWORD, false);
service.addCustomAttributes(pool.getId(), List.of(
Map.of("Name", "declared", "AttributeDataType", "String", "Mutable", true)));
Map<String, Object> challenge;
if (custom) {
Map<String, Object> started = start(admin);
challenge = respond(admin, client.getClientId(), "PASSWORD_VERIFIER", started, proof(started));
} else {
client.setExplicitAuthFlows(List.of("ALLOW_USER_PASSWORD_AUTH", "ALLOW_ADMIN_USER_PASSWORD_AUTH"));
Map<String, String> parameters = Map.of("USERNAME", USERNAME, "PASSWORD", PASSWORD);
challenge = admin
? service.adminInitiateAuth(pool.getId(), client.getClientId(), "ADMIN_USER_PASSWORD_AUTH",
parameters, Map.of())
: service.initiateAuth(client.getClientId(), "USER_PASSWORD_AUTH", parameters);
}
assertEquals("NEW_PASSWORD_REQUIRED", challenge.get("ChallengeName"));
String originalHash = service.adminGetUser(pool.getId(), USERNAME).getPasswordHash();
Map<String, String> responses = new HashMap<>(Map.of("USERNAME", USERNAME, "NEW_PASSWORD", "Changed1234!",
"userAttributes.custom:undeclared", "invalid", "userAttributes.custom:declared", "valid"));
AwsException error = assertThrows(AwsException.class, () -> respond(admin, client.getClientId(),
"NEW_PASSWORD_REQUIRED", challenge, responses));
assertEquals("InvalidParameterException", error.getErrorCode());
assertTrue(error.getMessage().contains("Attribute does not exist in the schema"));
assertEquals(originalHash, service.adminGetUser(pool.getId(), USERNAME).getPasswordHash());
assertEquals("FORCE_CHANGE_PASSWORD", service.adminGetUser(pool.getId(), USERNAME).getUserStatus());
assertFalse(service.adminGetUser(pool.getId(), USERNAME).getAttributes().containsKey("custom:undeclared"));
assertFalse(service.adminGetUser(pool.getId(), USERNAME).getAttributes().containsKey("custom:declared"));
responses.remove("userAttributes.custom:undeclared");
Map<String, Object> next = respond(admin, client.getClientId(), "NEW_PASSWORD_REQUIRED", challenge, responses);
if (custom) {
assertEquals("CUSTOM_CHALLENGE", next.get("ChallengeName"));
} else {
assertNotNull(next.get("AuthenticationResult"));
}
assertEquals("valid", service.adminGetUser(pool.getId(), USERNAME).getAttributes().get("custom:declared"));
assertEquals("CONFIRMED", service.adminGetUser(pool.getId(), USERNAME).getUserStatus());
assertNotEquals(originalHash, service.adminGetUser(pool.getId(), USERNAME).getPasswordHash());
assertDenied(() -> respond(admin, client.getClientId(), "NEW_PASSWORD_REQUIRED", challenge, responses));
}
@Test
void rejectedCustomResponseDoesNotReplaceClientMetadata() throws Exception {
Map<String, Object> started = start(false);
@@ -94,7 +94,8 @@ class CognitoFederationServiceTest {
stateStore = new CognitoFederationStateStore(CLOCK);
federationService = new CognitoFederationService(
cognitoService, stateStore, new CognitoOidcClient(MAPPER), CLOCK);
pool = cognitoService.createUserPool(Map.of("PoolName", "FederationPool"), "us-east-1");
pool = cognitoService.createUserPool(Map.of("PoolName", "FederationPool", "Schema", List.of(
Map.of("Name", "note", "AttributeDataType", "String", "Mutable", true))), "us-east-1");
tokenStatus = 200;
tokenResponse = "{\"access_token\":\"provider-access-token\"}";
claimsStatus = 200;
@@ -2506,6 +2506,16 @@ class CognitoIntegrationTest {
""");
String delPoolId = poolResponse.path("UserPool").path("Id").asText();
cognitoAction("AddCustomAttributes", """
{
"UserPoolId": "%s",
"CustomAttributes": [
{ "Name": "age", "AttributeDataType": "String", "Mutable": true },
{ "Name": "gender", "AttributeDataType": "String", "Mutable": true }
]
}
""".formatted(delPoolId)).then().statusCode(200);
JsonNode clientResponse = cognitoJson("CreateUserPoolClient", """
{
"UserPoolId": "%s",
@@ -79,6 +79,19 @@ import static org.mockito.Mockito.*;
@Execution(ExecutionMode.CONCURRENT)
class CognitoServiceTest {
@Test
void adminUpdateUserAttributesRejectsUndeclaredCustomAttribute() {
UserPool pool = service.createUserPool(Map.of("PoolName", "CustomAttributeValidation"), "us-east-1");
service.adminCreateUser(pool.getId(), "alice", Map.of(), "TempPass1!");
AwsException error = assertThrows(AwsException.class, () -> service.adminUpdateUserAttributes(
pool.getId(), "alice", Map.of("custom:undeclared", "x")));
assertEquals("InvalidParameterException", error.getErrorCode());
assertTrue(error.getMessage().contains("Attribute does not exist in the schema"));
assertFalse(service.adminGetUser(pool.getId(), "alice").getAttributes().containsKey("custom:undeclared"));
}
private static final ObjectMapper MAPPER = new ObjectMapper();
/** What AWS's DescribeUserPool reports for a pool created without a SignInPolicy. */
private static final Map<String, Object> DEFAULT_SIGN_IN_POLICY =
@@ -2750,6 +2763,7 @@ class CognitoServiceTest {
mock(TlsCertificateManager.class));
UserPool pool = serviceWithVerification.createUserPool(Map.of(
"PoolName", "AdminPendingContactPool",
"Schema", List.of(Map.of("Name", "note", "AttributeDataType", "String", "Mutable", true)),
"AutoVerifiedAttributes", List.of("email", "phone_number"),
"UserAttributeUpdateSettings", Map.of(
"AttributesRequireVerificationBeforeUpdate", List.of("email", "phone_number"))),
@@ -42,7 +42,10 @@ class CognitoUserInfoIntegrationTest {
void createPoolClientAndUser() throws Exception {
JsonNode poolResponse = cognitoJson("CreateUserPool", """
{
"PoolName": "UserInfoPool"
"PoolName": "UserInfoPool",
"Schema": [
{ "Name": "tenant_id", "AttributeDataType": "String", "Mutable": true }
]
}
""");
poolId = poolResponse.path("UserPool").path("Id").asText();