Light, fluffy, and always free - The AWS Local Emulator alternative
fix(cognito): enforce user pool password policies (#2070)
Daniel Zwicker3aaf74520ead
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.javaindex 71603111a5..d9820713a4 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@@ -74,6 +74,8 @@ import static io.github.hectorvent.floci.core.common.ReservedTags.rejectUnknownR@ApplicationScopedpublic class CognitoService implements ResourceProvider {private static final int DEFAULT_REFRESH_TOKEN_VALIDITY_DAYS = 30;+ private static final String COGNITO_PASSWORD_SYMBOLS =+ "^$*.[]{}()?\"!@#%&/\\,><':;|_~`=+-";private static final Logger LOG = Logger.getLogger(CognitoService.class);private static final ObjectMapper MAPPER = new ObjectMapper();@@ -205,6 +207,7 @@ public class CognitoService implements ResourceProvider {pool.setClientIdOverride(getClientIdOverride(userPoolTags));pool.setClientSecretOverride(ReservedTags.extractOverrideCognitoClientSecret(userPoolTags));populateUserPool(pool, request);+ normalizePasswordPolicy(pool);ensureJwtSigningKeys(pool);ensureRefreshTokenSecret(pool);@@ -284,6 +287,41 @@ public class CognitoService implements ResourceProvider {LOG.infov("Added custom attributes to User Pool: {0}", userPoolId);}+ /**+ * Fills in AWS's per-field password policy defaults for a pool created with a+ * {@code PasswordPolicy} that has some fields unset: MinimumLength 8 (AWS's documented+ * complex-password recommendation; the field itself only documents a minimum of 6), the four+ * character-class requirements enabled, and TemporaryPasswordValidityDays 7 (the one default+ * the API reference states explicitly). "If you don't provide a value for an attribute,+ * Amazon Cognito sets it to its default value" (CreateUserPool).+ *+ * <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) {+ Map<String, Object> policies = pool.getPolicies();+ 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);+ passwordPolicy.putIfAbsent("RequireUppercase", true);+ passwordPolicy.putIfAbsent("RequireLowercase", true);+ passwordPolicy.putIfAbsent("RequireNumbers", true);+ passwordPolicy.putIfAbsent("RequireSymbols", true);+ passwordPolicy.putIfAbsent("TemporaryPasswordValidityDays", 7);+ normalized.put("PasswordPolicy", passwordPolicy);+ pool.setPolicies(normalized);+ }+@SuppressWarnings("unchecked")private void populateUserPool(UserPool pool, Map<String, Object> request) {if (request.containsKey("Policies")) pool.setPolicies((Map<String, Object>) request.get("Policies"));@@ -1195,10 +1233,17 @@ public class CognitoService implements ResourceProvider {public void adminResetUserPassword(String userPoolId, String username) {CognitoUser user = adminGetUser(userPoolId, username);+ UserPool pool = describeUserPool(userPoolId);+ String outgoingPasswordHash = user.getPasswordHash();user.setUserStatus("RESET_REQUIRED");user.setPasswordHash(null);user.setSrpVerifier(null);user.setSrpSalt(null);+ // Archive the outgoing password now that the current slot is actually clear, so+ // updatePasswordHistory retains a full PasswordHistorySize entries rather than n-1 --+ // otherwise the reset would itself age the oldest still-protected password out of the+ // window. A reset cannot be used to bypass PasswordHistorySize this way.+ updatePasswordHistory(pool, user, outgoingPasswordHash);user.setLastModifiedDate(System.currentTimeMillis() / 1000L);userStore.put(userKey(userPoolId, user.getUsername()), user);LOG.infov("Reset password for user {0} in pool {1}", user.getUsername(), userPoolId);@@ -2555,6 +2600,10 @@ public class CognitoService implements ResourceProvider {}private void updateUserPassword(CognitoUser user, String password) {+ UserPool pool = describeUserPool(user.getUserPoolId());+ validatePasswordAgainstPolicy(pool, user, password);+ String previousPasswordHash = user.getPasswordHash();+ String passwordHash = hashPassword(password);String saltHex = CognitoSrpHelper.generateSalt();String verifierHex = CognitoSrpHelper.computeVerifier(CognitoSrpHelper.extractPoolName(user.getUserPoolId()),@@ -2562,11 +2611,111 @@ public class CognitoService implements ResourceProvider {password,saltHex);- user.setPasswordHash(hashPassword(password));+ user.setPasswordHash(passwordHash);+ updatePasswordHistory(pool, user, previousPasswordHash);user.setSrpSalt(saltHex);user.setSrpVerifier(verifierHex);}+ @SuppressWarnings("unchecked")+ private void validatePasswordAgainstPolicy(UserPool pool, CognitoUser user, String password) {+ Map<String, Object> policies = pool.getPolicies();+ if (policies == null || !(policies.get("PasswordPolicy") instanceof Map<?, ?> rawPolicy)) {+ return;+ }++ Map<String, Object> policy = (Map<String, Object>) rawPolicy;+ boolean invalid = password == null+ || password.length() < policyInt(policy, "MinimumLength")+ || policyBoolean(policy, "RequireUppercase")+ && password.codePoints().noneMatch(Character::isUpperCase)+ || policyBoolean(policy, "RequireLowercase")+ && password.codePoints().noneMatch(Character::isLowerCase)+ || policyBoolean(policy, "RequireNumbers")+ && password.codePoints().noneMatch(Character::isDigit)+ || policyBoolean(policy, "RequireSymbols")+ && password.codePoints().noneMatch(+ codePoint -> COGNITO_PASSWORD_SYMBOLS.indexOf(codePoint) >= 0);++ if (invalid) {+ throw new AwsException(+ "InvalidPasswordException",+ "Password does not conform to the configured password policy.",+ 400+ );+ }++ String passwordHash = password == null ? "" : hashPassword(password);+ int historySize = policyInt(policy, "PasswordHistorySize");+ // AWS counts the current password as one of the `n` in PasswordHistorySize, so only+ // n-1 additional prior passwords are blocked alongside it: "users can't set a password+ // that matches any of n previous passwords, where n is PasswordHistorySize" together+ // with the documented max of "current password or any of up to 23 additional previous+ // passwords, for a maximum total of 24" (PasswordHistorySize's max value is 24). This+ // runs before any mutation, so a null current here means a prior admin reset left no+ // password occupying that slot — the full n entries in history are then still live,+ // not n-1 (mirrors the same condition in updatePasswordHistory).+ long historyCheckLimit = user.getPasswordHash() == null ? historySize : historySize - 1L;+ boolean reused = historySize > 0 && (passwordHash.equals(user.getPasswordHash())+ || user.getPasswordHistory().stream().limit(historyCheckLimit).anyMatch(passwordHash::equals));++ if (reused) {+ throw new AwsException(+ "PasswordHistoryPolicyViolationException",+ "Password matches a previously used password and does not comply with the "+ + "password history policy.",+ 400+ );+ }+ }++ @SuppressWarnings("unchecked")+ private void updatePasswordHistory(UserPool pool, CognitoUser user, String previousPasswordHash) {+ Map<String, Object> policies = pool.getPolicies();+ if (policies == null || !(policies.get("PasswordPolicy") instanceof Map<?, ?> rawPolicy)) {+ return;+ }++ int historySize = policyInt((Map<String, Object>) rawPolicy, "PasswordHistorySize");+ if (historySize <= 0) {+ return;+ }++ List<String> history = new ArrayList<>(user.getPasswordHistory());+ if (previousPasswordHash != null) {+ history.add(0, previousPasswordHash);+ }+ // Callers set the user's new current password hash (or null, for an admin reset that+ // clears it) before calling this, so the state read here already reflects it. A current+ // password occupies one of the n slots, leaving n-1 for history; a reset leaves none+ // occupied, so the freed slot goes to history until a new password takes it — otherwise+ // the outgoing password would fall out of the window a reset alone should not shrink.+ long retain = user.getPasswordHash() == null ? historySize : historySize - 1L;+ user.setPasswordHistory(history.stream().limit(Math.max(0, retain)).toList());+ }++ private int policyInt(Map<String, Object> policy, String key) {+ Object value = policy.get(key);+ if (value instanceof Number number) {+ return number.intValue();+ }+ if (value instanceof String stringValue) {+ try {+ return Integer.parseInt(stringValue);+ } catch (NumberFormatException ignored) {+ return 0;+ }+ }+ return 0;+ }++ private boolean policyBoolean(Map<String, Object> policy, String key) {+ Object value = policy.get(key);+ return value instanceof Boolean booleanValue+ ? booleanValue+ : Boolean.parseBoolean(String.valueOf(value));+ }+int getAccessTokenExpiresInSeconds(UserPoolClient client) {return resolveAccessTokenLifetimeSeconds(client);}diff --git a/src/main/java/io/github/hectorvent/floci/services/cognito/model/CognitoUser.java b/src/main/java/io/github/hectorvent/floci/services/cognito/model/CognitoUser.javaindex 7894d9d15d..91360ba691 100644--- a/src/main/java/io/github/hectorvent/floci/services/cognito/model/CognitoUser.java+++ b/src/main/java/io/github/hectorvent/floci/services/cognito/model/CognitoUser.java@@ -19,6 +19,7 @@ public class CognitoUser {private long creationDate;private long lastModifiedDate;private String passwordHash;+ private List<String> passwordHistory = new ArrayList<>();private boolean temporaryPassword;private List<String> groupNames = new ArrayList<>();private String srpSalt;@@ -56,6 +57,11 @@ public class CognitoUser {public String getPasswordHash() { return passwordHash; }public void setPasswordHash(String passwordHash) { this.passwordHash = passwordHash; }+ public List<String> getPasswordHistory() { return passwordHistory; }+ public void setPasswordHistory(List<String> passwordHistory) {+ this.passwordHistory = passwordHistory == null ? new ArrayList<>() : new ArrayList<>(passwordHistory);+ }+public boolean isTemporaryPassword() { return temporaryPassword; }public void setTemporaryPassword(boolean temporaryPassword) { this.temporaryPassword = temporaryPassword; }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.javaindex a8343f5e84..90c4cb3265 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@@ -342,6 +342,55 @@ class CognitoIntegrationTest {assertThat(destination, containsString("4567"));}+ @Test+ void signUpEnforcesTheConfiguredPasswordPolicy() throws Exception {+ JsonNode poolResponse = cognitoJson("CreateUserPool", """+ {+ "PoolName": "StrictPasswordPolicyPool",+ "Policies": {+ "PasswordPolicy": {+ "MinimumLength": 12,+ "RequireUppercase": true,+ "RequireLowercase": true,+ "RequireNumbers": true,+ "RequireSymbols": true,+ "PasswordHistorySize": 10+ }+ }+ }+ """);+ String strictPoolId = poolResponse.path("UserPool").path("Id").asText();++ JsonNode clientResponse = cognitoJson("CreateUserPoolClient", """+ {+ "UserPoolId": "%s",+ "ClientName": "strict-password-policy-client"+ }+ """.formatted(strictPoolId));+ String strictClientId = clientResponse.path("UserPoolClient").path("ClientId").asText();++ cognitoAction("SignUp", """+ {+ "ClientId": "%s",+ "Username": "invalid-password-user",+ "Password": "Short1!"+ }+ """.formatted(strictClientId))+ .then()+ .statusCode(400)+ .body("__type", org.hamcrest.Matchers.equalTo("InvalidPasswordException"));++ cognitoAction("SignUp", """+ {+ "ClientId": "%s",+ "Username": "valid-password-user",+ "Password": "ValidPassword1!"+ }+ """.formatted(strictClientId))+ .then()+ .statusCode(200);+ }+@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.javaindex df6ac368e6..47e428031c 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@@ -67,6 +67,23 @@ class CognitoServiceTest {return pool;}+ private UserPool createPoolWithStrictPasswordPolicy() {+ return service.createUserPool(Map.of(+ "PoolName", "StrictPasswordPool",+ "Policies", Map.of(+ "PasswordPolicy", Map.of(+ "MinimumLength", 12,+ "RequireUppercase", true,+ "RequireLowercase", true,+ "RequireNumbers", true,+ "RequireSymbols", true,+ "PasswordHistorySize", 10,+ "TemporaryPasswordValidityDays", 2+ )+ )+ ), "us-east-1");+ }+@Testvoid createUserPoolWithFullConfig() {List<Map<String, Object>> schema = List.of(@@ -88,10 +105,165 @@ class CognitoServiceTest {assertEquals("FullConfigPool", pool.getName());assertEquals("arn:aws:cognito-idp:us-east-1:000000000000:userpool/" + pool.getId(), pool.getArn());assertEquals(schema, pool.getSchemaAttributes());- assertEquals(policies, pool.getPolicies());+ // A supplied PasswordPolicy is normalized with AWS's defaults for the fields left unset+ // (MinimumLength here was explicit; the rest were not), matching what DescribeUserPool+ // returns on real Cognito for a policy submitted this way.+ Map<String, Object> expectedPasswordPolicy = new HashMap<>();+ expectedPasswordPolicy.put("MinimumLength", 12);+ expectedPasswordPolicy.put("RequireUppercase", true);+ expectedPasswordPolicy.put("RequireLowercase", true);+ expectedPasswordPolicy.put("RequireNumbers", true);+ expectedPasswordPolicy.put("RequireSymbols", true);+ expectedPasswordPolicy.put("TemporaryPasswordValidityDays", 7);+ assertEquals(Map.of("PasswordPolicy", expectedPasswordPolicy), pool.getPolicies());assertEquals(List.of("email"), pool.getUsernameAttributes());}+ @ParameterizedTest+ @CsvSource({+ "Short1!a",+ "lowercase123!",+ "UPPERCASE123!",+ "NoNumbersHere!",+ "NoSymbols1234",+ "NoSymbols 123"+ })+ void signUpRejectsPasswordsThatDoNotMatchTheUserPoolPolicy(String password) {+ UserPool pool = createPoolWithStrictPasswordPolicy();+ UserPoolClient client = service.createUserPoolClient(+ pool.getId(), "strict-client", false, false, List.of(), List.of());++ AwsException exception = assertThrows(AwsException.class, () ->+ service.signUp(client.getClientId(), "[email protected]", password, Map.of(+ "email", "[email protected]",+ "phone_number", "+4915112345678"+ )));++ assertEquals("InvalidPasswordException", exception.getErrorCode());+ }++ @Test+ void signUpAcceptsAPasswordThatMatchesTheUserPoolPolicy() {+ UserPool pool = createPoolWithStrictPasswordPolicy();+ UserPoolClient client = service.createUserPoolClient(+ pool.getId(), "strict-client", false, false, List.of(), List.of());++ CognitoUser user = service.signUp(+ client.getClientId(),+ "[email protected]",+ "ValidPassword1!",+ Map.of("email", "[email protected]", "phone_number", "+4915112345678")+ );++ assertEquals("[email protected]", user.getUsername());+ }++ @Test+ void passwordHistoryRejectsARecentlyUsedPassword() {+ UserPool pool = createPoolWithStrictPasswordPolicy();+ service.adminCreateUser(+ pool.getId(),+ "alice",+ Map.of("email", "[email protected]"),+ "InitialPass1!"+ );+ service.adminSetUserPassword(pool.getId(), "alice", "Replacement2!", true);++ AwsException exception = assertThrows(AwsException.class, () ->+ service.adminSetUserPassword(pool.getId(), "alice", "InitialPass1!", true));++ // AWS declares PasswordHistoryPolicyViolationException specifically for password reuse,+ // distinct from InvalidPasswordException for a password that fails the complexity rules.+ assertEquals("PasswordHistoryPolicyViolationException", exception.getErrorCode());+ assertEquals(400, exception.getHttpStatus());+ }++ @Test+ void passwordHistoryCountsTheCurrentPasswordAsOneOfN() {+ // PasswordHistorySize: 1 blocks the current password and nothing else — AWS counts the+ // 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))+ ), "us-east-1");+ service.adminCreateUser(pool.getId(), "alice", Map.of("email", "[email protected]"), "PasswordA1!");+ service.adminSetUserPassword(pool.getId(), "alice", "PasswordB1!", true);++ AwsException reuseOfCurrent = assertThrows(AwsException.class, () ->+ service.adminSetUserPassword(pool.getId(), "alice", "PasswordB1!", true));+ assertEquals("PasswordHistoryPolicyViolationException", reuseOfCurrent.getErrorCode());++ // Two changes back, real Cognito allows this at PasswordHistorySize: 1.+ assertDoesNotThrow(() -> service.adminSetUserPassword(pool.getId(), "alice", "PasswordA1!", true));+ }++ @Test+ void adminResetUserPasswordDoesNotBypassPasswordHistory() {+ UserPool pool = createPoolWithStrictPasswordPolicy();+ service.adminCreateUser(+ pool.getId(), "alice", Map.of("email", "[email protected]"), "InitialPass1!");+ service.adminSetUserPassword(pool.getId(), "alice", "Replacement2!", true);++ // Resetting must archive the outgoing password into history rather than discarding it,+ // or an admin reset becomes a way around PasswordHistorySize.+ service.adminResetUserPassword(pool.getId(), "alice");++ AwsException exception = assertThrows(AwsException.class, () ->+ service.adminSetUserPassword(pool.getId(), "alice", "Replacement2!", true));+ assertEquals("PasswordHistoryPolicyViolationException", exception.getErrorCode());+ }++ @Test+ void adminResetUserPasswordDoesNotShortenTheHistoryWindow() {+ // A reset clears the current password without replacing it, so the freed slot must go+ // to history, not be dropped: with PasswordHistorySize 2, Pass1 -> Pass2 -> Pass3 already+ // ages Pass1 out (only Pass3 + Pass2 are within the window) -- a reset right after must+ // 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))+ ), "us-east-1");+ service.adminCreateUser(pool.getId(), "alice", Map.of("email", "[email protected]"), "Pass1word!");+ service.adminSetUserPassword(pool.getId(), "alice", "Pass2word!", true);+ service.adminSetUserPassword(pool.getId(), "alice", "Pass3word!", true);++ service.adminResetUserPassword(pool.getId(), "alice");++ // Both passwords still within the window (Pass3 was current, Pass2 was the one prior)+ // must still be blocked immediately after the reset, before any new password is set.+ assertEquals("PasswordHistoryPolicyViolationException", assertThrows(AwsException.class, () ->+ service.adminSetUserPassword(pool.getId(), "alice", "Pass3word!", true)).getErrorCode());+ assertEquals("PasswordHistoryPolicyViolationException", assertThrows(AwsException.class, () ->+ service.adminSetUserPassword(pool.getId(), "alice", "Pass2word!", true)).getErrorCode());++ // Setting a new password re-occupies the current slot, so the window shrinks back to+ // n-1 in history and Pass2 (now two changes back) is free to reuse again.+ service.adminSetUserPassword(pool.getId(), "alice", "Pass4word!", true);+ assertDoesNotThrow(() -> service.adminSetUserPassword(pool.getId(), "alice", "Pass2word!", true));+ }++ @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 — and the unset RequireUppercase/Lowercase/Numbers+ // default to enabled too, the same "Cognito defaults" a console-created pool gets.+ UserPool pool = service.createUserPool(Map.of(+ "PoolName", "SymbolsOnlyPool",+ "Policies", Map.of("PasswordPolicy", Map.of("RequireSymbols", true))+ ), "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(), "[email protected]", "a!", Map.of(+ "email", "[email protected]", "phone_number", "+4915112345678")));+ assertEquals("InvalidPasswordException", exception.getErrorCode());++ assertDoesNotThrow(() -> service.signUp(+ client.getClientId(), "[email protected]", "Eightplus1!", Map.of(+ "email", "[email protected]", "phone_number", "+4915112345679")));+ }+@Testvoid createUserPoolWithOverrideIdUsesProvidedId() {UserPool pool = service.createUserPool(