diff --git a/src/main/java/io/github/hectorvent/floci/services/cognito/CognitoService.java b/src/main/java/io/github/hectorvent/floci/services/cognito/CognitoService.java index 85f97cdfc0..f53bbcbbe7 100644 --- a/src/main/java/io/github/hectorvent/floci/services/cognito/CognitoService.java +++ b/src/main/java/io/github/hectorvent/floci/services/cognito/CognitoService.java @@ -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}. + * + *

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"). + * + *

{@code TemporaryPasswordValidityDays} defaults to 7 (the one default the API reference + * documents explicitly). * *

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. * *

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). - * - *

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 normalized = new HashMap<>(policies); Map passwordPolicy = new HashMap<>((Map) raw); - passwordPolicy.putIfAbsent("MinimumLength", 8); + validatePasswordPolicy(passwordPolicy); passwordPolicy.putIfAbsent("TemporaryPasswordValidityDays", 7); + Map normalized = new HashMap<>(policies); normalized.put("PasswordPolicy", passwordPolicy); pool.setPolicies(normalized); } + private void validatePasswordPolicy(Map 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 request) { - if (request.containsKey("Policies")) pool.setPolicies((Map) request.get("Policies")); + if (request.containsKey("Policies")) { + pool.setPolicies((Map) request.get("Policies")); + normalizePasswordPolicy(pool); + } if (request.containsKey("DeletionProtection")) pool.setDeletionProtection((String) request.get("DeletionProtection")); if (request.containsKey("LambdaConfig")) pool.setLambdaConfig((Map) request.get("LambdaConfig")); if (request.containsKey("Schema")) pool.setSchemaAttributes(prefixCustomSchemaAttributes((List>) 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 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 policy, String key) { Object value = policy.get(key); return value instanceof Boolean booleanValue diff --git a/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoIntegrationTest.java index c586ec9d05..9336605d88 100644 --- a/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoIntegrationTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoIntegrationTest.java @@ -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 { diff --git a/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoServiceTest.java b/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoServiceTest.java index 3786ff1cdd..0a07a6cc7d 100644 --- a/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoServiceTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoServiceTest.java @@ -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 policy = (Map) updated.getPolicies().get("PasswordPolicy"); + assertEquals(6, policy.get("MinimumLength")); + assertEquals(7, policy.get("TemporaryPasswordValidityDays")); } @Test