fix(cognito): validate PasswordPolicy MinimumLength and remove default of 8 (#4359)

* fix(cognito): validate PasswordPolicy MinimumLength and remove default of 8

When PasswordPolicy is supplied on CreateUserPool or UpdateUserPool, live Cognito evaluates an omitted MinimumLength as 0 and rejects it with InvalidParameterException against the constraint MinimumLength >= 6. It does not default MinimumLength to 8.

Remove the synthetic default of 8, enforce constraint validation on MinimumLength (6-99), TemporaryPasswordValidityDays (0-365), and PasswordHistorySize (0-24) when PasswordPolicy is provided, and keep documented default of 7 for TemporaryPasswordValidityDays.

Closes #4256

* fix(cognito): reject oversized password policy values

* fix(cognito): reject unparseable password policy integers
This commit is contained in:
Vũ Thế Huy authored and GitHub committed 2026-09-27 11:48:34 -04:00
1 parent 787538997f
commit 47ea463146
3 files changed
+305 -39

No files matched your search

@@ -47,6 +47,8 @@ import org.jspecify.annotations.Nullable;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.nio.charset.StandardCharsets;
import java.security.KeyFactory;
import java.security.KeyPair;
@@ -319,7 +321,6 @@ public class CognitoService implements ResourceProvider {
pool.setClientIdOverride(getClientIdOverride(userPoolTags));
pool.setClientSecretOverride(ReservedTags.extractOverrideCognitoClientSecret(userPoolTags));
populateUserPool(pool, request);
normalizePasswordPolicy(pool);
ensureJwtSigningKeys(pool);
ensureRefreshTokenSecret(pool);
@@ -399,32 +400,25 @@ public class CognitoService implements ResourceProvider {
}
/**
* Fills in AWS's per-field password policy defaults for a pool created with a
* {@code PasswordPolicy} that has some fields unset: TemporaryPasswordValidityDays 7 (the one
* default the API reference states explicitly) and MinimumLength 8 (AWS's documented
* complex-password recommendation; the field itself only documents a minimum of 6).
* "If you don't provide a value for an attribute, Amazon Cognito sets it to its default
* value" (CreateUserPool).
* Normalizes and validates a supplied {@code PasswordPolicy}.
*
* <p>On live Cognito, when {@code PasswordPolicy} is provided, {@code MinimumLength} must be
* between 6 and 99. If omitted, live Cognito evaluates it as 0 and rejects the request with
* {@code InvalidParameterException} ("Value '0' at 'policies.passwordPolicy.minimumLength'
* failed to satisfy constraint: Member must have value greater than or equal to 6").
*
* <p>{@code TemporaryPasswordValidityDays} defaults to 7 (the one default the API reference
* documents explicitly).
*
* <p>RequireUppercase, RequireLowercase, RequireNumbers and RequireSymbols are deliberately
* left alone. The API reference documents no default for any of them, and they are unboxed
* booleans in the Cognito model, so a client that wants one off cannot say so on the wire:
* aws-sdk-go-v2 emits each under {@code if v.RequireLowercase != false}. Absence therefore
* means "not required", which is what the live service reports back - the Terraform provider
* asserts require_numbers and require_uppercase read as false immediately after a create
* that set them to false. Defaulting them to enabled made every Terraform plan after a
* create show spurious drift, and over-enforced the policy on SignUp and
* AdminSetUserPassword. The all-enabled policy is the console's "Cognito defaults" mode,
* not an API default.
* left alone: absence means "not required", matching live Cognito and avoiding Terraform
* plan drift.
*
* <p>Deliberately does not fabricate a {@code PasswordPolicy} for a pool that supplies none
* at all — every other test and fixture in this codebase creates pools that way, relying on
* "no policy configured" meaning no password validation, and defaulting one into existence
* here would enforce it retroactively on all of them. Whether an unconfigured pool should
* get AWS's default policy is tracked separately (hectorvent's follow-up on #2066).
*
* <p>Scoped to creation only, not UpdateUserPool, whose partial-update semantics for a
* re-supplied PasswordPolicy are not verified here.
*/
@SuppressWarnings("unchecked")
private void normalizePasswordPolicy(UserPool pool) {
@@ -432,14 +426,83 @@ public class CognitoService implements ResourceProvider {
if (policies == null || !(policies.get("PasswordPolicy") instanceof Map<?, ?> raw)) {
return;
}
Map<String, Object> normalized = new HashMap<>(policies);
Map<String, Object> passwordPolicy = new HashMap<>((Map<String, Object>) raw);
passwordPolicy.putIfAbsent("MinimumLength", 8);
validatePasswordPolicy(passwordPolicy);
passwordPolicy.putIfAbsent("TemporaryPasswordValidityDays", 7);
Map<String, Object> normalized = new HashMap<>(policies);
normalized.put("PasswordPolicy", passwordPolicy);
pool.setPolicies(normalized);
}
private void validatePasswordPolicy(Map<String, Object> passwordPolicy) {
Object minLengthVal = passwordPolicy.get("MinimumLength");
if (minLengthVal == null) {
throw new AwsException(
"InvalidParameterException",
"1 validation error detected: Value '0' at 'policies.passwordPolicy.minimumLength' failed to satisfy constraint: Member must have value greater than or equal to 6",
400
);
}
BigInteger minLength = policyInteger(passwordPolicy, "MinimumLength", "minimumLength");
if (minLength.compareTo(BigInteger.valueOf(6)) < 0) {
throw new AwsException(
"InvalidParameterException",
"1 validation error detected: Value '" + minLengthVal + "' at 'policies.passwordPolicy.minimumLength' failed to satisfy constraint: Member must have value greater than or equal to 6",
400
);
}
if (minLength.compareTo(BigInteger.valueOf(99)) > 0) {
throw new AwsException(
"InvalidParameterException",
"1 validation error detected: Value '" + minLengthVal + "' at 'policies.passwordPolicy.minimumLength' failed to satisfy constraint: Member must have value less than or equal to 99",
400
);
}
if (passwordPolicy.containsKey("TemporaryPasswordValidityDays")) {
Object tempDaysVal = passwordPolicy.get("TemporaryPasswordValidityDays");
if (tempDaysVal != null) {
BigInteger tempDays = policyInteger(passwordPolicy, "TemporaryPasswordValidityDays",
"temporaryPasswordValidityDays");
if (tempDays.compareTo(BigInteger.ZERO) < 0) {
throw new AwsException(
"InvalidParameterException",
"1 validation error detected: Value '" + tempDaysVal + "' at 'policies.passwordPolicy.temporaryPasswordValidityDays' failed to satisfy constraint: Member must have value greater than or equal to 0",
400
);
}
if (tempDays.compareTo(BigInteger.valueOf(365)) > 0) {
throw new AwsException(
"InvalidParameterException",
"1 validation error detected: Value '" + tempDaysVal + "' at 'policies.passwordPolicy.temporaryPasswordValidityDays' failed to satisfy constraint: Member must have value less than or equal to 365",
400
);
}
}
}
if (passwordPolicy.containsKey("PasswordHistorySize")) {
Object historySizeVal = passwordPolicy.get("PasswordHistorySize");
if (historySizeVal != null) {
BigInteger historySize = policyInteger(passwordPolicy, "PasswordHistorySize", "passwordHistorySize");
if (historySize.compareTo(BigInteger.ZERO) < 0) {
throw new AwsException(
"InvalidParameterException",
"1 validation error detected: Value '" + historySizeVal + "' at 'policies.passwordPolicy.passwordHistorySize' failed to satisfy constraint: Member must have value greater than or equal to 0",
400
);
}
if (historySize.compareTo(BigInteger.valueOf(24)) > 0) {
throw new AwsException(
"InvalidParameterException",
"1 validation error detected: Value '" + historySizeVal + "' at 'policies.passwordPolicy.passwordHistorySize' failed to satisfy constraint: Member must have value less than or equal to 24",
400
);
}
}
}
}
private static String prefixedAttributeName(String name, boolean developerOnly) {
if (name.startsWith("custom:") || name.startsWith("dev:")) {
return name;
@@ -467,7 +530,10 @@ public class CognitoService implements ResourceProvider {
@SuppressWarnings("unchecked")
private void populateUserPool(UserPool pool, Map<String, Object> request) {
if (request.containsKey("Policies")) pool.setPolicies((Map<String, Object>) request.get("Policies"));
if (request.containsKey("Policies")) {
pool.setPolicies((Map<String, Object>) request.get("Policies"));
normalizePasswordPolicy(pool);
}
if (request.containsKey("DeletionProtection")) pool.setDeletionProtection((String) request.get("DeletionProtection"));
if (request.containsKey("LambdaConfig")) pool.setLambdaConfig((Map<String, Object>) request.get("LambdaConfig"));
if (request.containsKey("Schema")) pool.setSchemaAttributes(prefixCustomSchemaAttributes((List<Map<String, Object>>) request.get("Schema")));
@@ -4094,6 +4160,38 @@ public class CognitoService implements ResourceProvider {
return 0;
}
/**
* Reads a password policy integer without narrowing it, so range checks see the real value.
* A value that is not a whole-number type or string is rejected: falling back to zero would
* let it pass the 0-based ranges of {@code TemporaryPasswordValidityDays} and
* {@code PasswordHistorySize} and be stored as-is.
*/
private BigInteger policyInteger(Map<String, Object> policy, String key, String member) {
Object value = policy.get(key);
try {
if (value instanceof BigInteger integer) {
return integer;
}
if (value instanceof Number number) {
return new BigDecimal(number.toString()).toBigInteger();
}
if (value instanceof String stringValue) {
return new BigInteger(stringValue);
}
} catch (NumberFormatException e) {
throw notAnInteger(value, member);
}
throw notAnInteger(value, member);
}
private static AwsException notAnInteger(Object value, String member) {
return new AwsException(
"InvalidParameterException",
"1 validation error detected: Value '" + value + "' at 'policies.passwordPolicy." + member
+ "' failed to satisfy constraint: Member must be an integer",
400);
}
private boolean policyBoolean(Map<String, Object> policy, String key) {
Object value = policy.get(key);
return value instanceof Boolean booleanValue
@@ -539,6 +539,66 @@ class CognitoIntegrationTest {
assertFalse(policy.path("RequireSymbols").asBoolean());
}
@Test
void createUserPoolRejectsPasswordPolicyWithOmittedMinimumLength() {
given()
.header("X-Amz-Target", "AWSCognitoIdentityProviderService.CreateUserPool")
.contentType("application/x-amz-json-1.1")
.body("""
{
"PoolName": "InvalidMinLengthPool",
"Policies": {
"PasswordPolicy": {
"RequireUppercase": true
}
}
}
""")
.when()
.post("/")
.then()
.statusCode(400)
.body("__type", equalTo("InvalidParameterException"))
.body("message", containsString("policies.passwordPolicy.minimumLength"))
.body("message", containsString("Member must have value greater than or equal to 6"));
}
@Test
void updateUserPoolRejectsPasswordPolicyWithOmittedMinimumLength() throws Exception {
JsonNode created = cognitoJson("CreateUserPool", """
{
"PoolName": "ValidPoolToUpdate",
"Policies": {
"PasswordPolicy": {
"MinimumLength": 8
}
}
}
""");
String poolId = created.path("UserPool").path("Id").asText();
given()
.header("X-Amz-Target", "AWSCognitoIdentityProviderService.UpdateUserPool")
.contentType("application/x-amz-json-1.1")
.body("""
{
"UserPoolId": "%s",
"Policies": {
"PasswordPolicy": {
"RequireUppercase": true
}
}
}
""".formatted(poolId))
.when()
.post("/")
.then()
.statusCode(400)
.body("__type", equalTo("InvalidParameterException"))
.body("message", containsString("policies.passwordPolicy.minimumLength"))
.body("message", containsString("Member must have value greater than or equal to 6"));
}
@Test
@Order(7)
void confirmSignUpRequiresValidConfirmationCode() throws Exception {
@@ -452,7 +452,7 @@ class CognitoServiceTest {
// current password as one of the n, not an extra entry on top of n stored ones.
UserPool pool = service.createUserPool(Map.of(
"PoolName", "HistorySizeOnePool",
"Policies", Map.of("PasswordPolicy", Map.of("PasswordHistorySize", 1))
"Policies", Map.of("PasswordPolicy", Map.of("PasswordHistorySize", 1, "MinimumLength", 8))
), "us-east-1");
service.adminCreateUser(pool.getId(), "alice", Map.of("email", "alice@example.com"), "PasswordA1!");
service.adminSetUserPassword(pool.getId(), "alice", "PasswordB1!", true);
@@ -489,7 +489,7 @@ class CognitoServiceTest {
// not additionally age Pass2 out just because the current slot is temporarily empty.
UserPool pool = service.createUserPool(Map.of(
"PoolName", "ResetHistoryWindowPool",
"Policies", Map.of("PasswordPolicy", Map.of("PasswordHistorySize", 2))
"Policies", Map.of("PasswordPolicy", Map.of("PasswordHistorySize", 2, "MinimumLength", 8))
), "us-east-1");
service.adminCreateUser(pool.getId(), "alice", Map.of("email", "alice@example.com"), "Pass1word!");
service.adminSetUserPassword(pool.getId(), "alice", "Pass2word!", true);
@@ -511,26 +511,134 @@ class CognitoServiceTest {
}
@Test
void createUserPoolDefaultsAnUnsetMinimumLengthToEight() {
// A policy present but silent on MinimumLength gets AWS's default (8), not policyInt's
// fallback of 0 for an absent key. The character classes the policy did not ask for are
// not enforced: only RequireSymbols was set, so a password with no uppercase and no
// digit is accepted once it is long enough.
void createUserPoolRejectsPasswordPolicyWithUnsetMinimumLength() {
// When a PasswordPolicy is supplied without MinimumLength, live Cognito evaluates
// minimumLength as 0 and rejects it against the constraint MinimumLength >= 6.
AwsException exception = assertThrows(AwsException.class, () ->
service.createUserPool(Map.of(
"PoolName", "SymbolsOnlyPool",
"Policies", Map.of("PasswordPolicy", Map.of("RequireSymbols", true))
), "us-east-1"));
assertEquals("InvalidParameterException", exception.getErrorCode());
assertTrue(exception.getMessage().contains("policies.passwordPolicy.minimumLength"));
assertTrue(exception.getMessage().contains("Member must have value greater than or equal to 6"));
}
@Test
void createUserPoolRejectsMinimumLengthOutOfRange() {
AwsException tooShort = assertThrows(AwsException.class, () ->
service.createUserPool(Map.of(
"PoolName", "TooShortPool",
"Policies", Map.of("PasswordPolicy", Map.of("MinimumLength", 5))
), "us-east-1"));
assertEquals("InvalidParameterException", tooShort.getErrorCode());
assertTrue(tooShort.getMessage().contains("Member must have value greater than or equal to 6"));
AwsException tooLong = assertThrows(AwsException.class, () ->
service.createUserPool(Map.of(
"PoolName", "TooLongPool",
"Policies", Map.of("PasswordPolicy", Map.of("MinimumLength", 100))
), "us-east-1"));
assertEquals("InvalidParameterException", tooLong.getErrorCode());
assertTrue(tooLong.getMessage().contains("Member must have value less than or equal to 99"));
}
@Test
void createUserPoolRejectsOversizedMinimumLengthBeforeIntNarrowing() {
AwsException exception = assertThrows(AwsException.class, () ->
service.createUserPool(Map.of(
"PoolName", "OversizedMinimumLengthPool",
"Policies", Map.of("PasswordPolicy", Map.of("MinimumLength", 4_294_967_302L))
), "us-east-1"));
assertEquals("InvalidParameterException", exception.getErrorCode());
assertTrue(exception.getMessage().contains("Member must have value less than or equal to 99"));
}
@Test
void createUserPoolRejectsOversizedTemporaryPasswordValidityBeforeIntNarrowing() {
AwsException exception = assertThrows(AwsException.class, () ->
service.createUserPool(Map.of(
"PoolName", "OversizedTemporaryPasswordValidityPool",
"Policies", Map.of("PasswordPolicy", Map.of(
"MinimumLength", 8,
"TemporaryPasswordValidityDays", 4_294_967_302L))
), "us-east-1"));
assertEquals("InvalidParameterException", exception.getErrorCode());
assertTrue(exception.getMessage().contains("Member must have value less than or equal to 365"));
}
@Test
void createUserPoolRejectsOversizedPasswordHistorySizeBeforeIntNarrowing() {
AwsException exception = assertThrows(AwsException.class, () ->
service.createUserPool(Map.of(
"PoolName", "OversizedPasswordHistoryPool",
"Policies", Map.of("PasswordPolicy", Map.of(
"MinimumLength", 8,
"PasswordHistorySize", 4_294_967_302L))
), "us-east-1"));
assertEquals("InvalidParameterException", exception.getErrorCode());
assertTrue(exception.getMessage().contains("Member must have value less than or equal to 24"));
}
@Test
void createUserPoolRejectsUnparseableTemporaryPasswordValidity() {
for (Object value : new Object[] {Double.POSITIVE_INFINITY, Double.NaN, "abc", true}) {
AwsException exception = assertThrows(AwsException.class, () ->
service.createUserPool(Map.of(
"PoolName", "UnparseableTemporaryPasswordValidityPool",
"Policies", Map.of("PasswordPolicy", Map.of(
"MinimumLength", 8,
"TemporaryPasswordValidityDays", value))
), "us-east-1"), "value: " + value);
assertEquals("InvalidParameterException", exception.getErrorCode());
assertTrue(exception.getMessage().contains("Member must be an integer"), "value: " + value);
}
}
@Test
void createUserPoolRejectsUnparseablePasswordHistorySize() {
for (Object value : new Object[] {Double.POSITIVE_INFINITY, Double.NaN, "abc", true}) {
AwsException exception = assertThrows(AwsException.class, () ->
service.createUserPool(Map.of(
"PoolName", "UnparseablePasswordHistoryPool",
"Policies", Map.of("PasswordPolicy", Map.of(
"MinimumLength", 8,
"PasswordHistorySize", value))
), "us-east-1"), "value: " + value);
assertEquals("InvalidParameterException", exception.getErrorCode());
assertTrue(exception.getMessage().contains("Member must be an integer"), "value: " + value);
}
}
@Test
void updateUserPoolValidatesPasswordPolicy() {
UserPool pool = service.createUserPool(Map.of(
"PoolName", "SymbolsOnlyPool",
"Policies", Map.of("PasswordPolicy", Map.of("RequireSymbols", true))
"PoolName", "ValidPool",
"Policies", Map.of("PasswordPolicy", Map.of("MinimumLength", 8))
), "us-east-1");
UserPoolClient client = service.createUserPoolClient(
pool.getId(), "symbols-only-client", false, false, List.of(), List.of());
AwsException exception = assertThrows(AwsException.class, () ->
service.signUp(client.getClientId(), "alice@example.com", "a!", Map.of(
"email", "alice@example.com", "phone_number", "+4915112345678")));
assertEquals("InvalidPasswordException", exception.getErrorCode());
service.updateUserPool(Map.of(
"UserPoolId", pool.getId(),
"Policies", Map.of("PasswordPolicy", Map.of("RequireSymbols", true))
), "us-east-1"));
assertEquals("InvalidParameterException", exception.getErrorCode());
assertTrue(exception.getMessage().contains("policies.passwordPolicy.minimumLength"));
assertDoesNotThrow(() -> service.signUp(
client.getClientId(), "bob@example.com", "lowercase!", Map.of(
"email", "bob@example.com", "phone_number", "+4915112345679")));
assertDoesNotThrow(() -> service.updateUserPool(Map.of(
"UserPoolId", pool.getId(),
"Policies", Map.of("PasswordPolicy", Map.of("MinimumLength", 6))
), "us-east-1"));
UserPool updated = service.describeUserPool(pool.getId());
@SuppressWarnings("unchecked")
Map<String, Object> policy = (Map<String, Object>) updated.getPolicies().get("PasswordPolicy");
assertEquals(6, policy.get("MinimumLength"));
assertEquals(7, policy.get("TemporaryPasswordValidityDays"));
}
@Test