From 3aaf74520eadd2c0a71ec84b2ab06a1b406f2f80 Mon Sep 17 00:00:00 2001
From: Daniel Zwicker <500483+dzwicker@users.noreply.github.com>
Date: Mon, 31 Aug 2026 19:09:58 +0200
Subject: [PATCH] fix(cognito): enforce user pool password policies (#2070)
* fix(cognito): enforce user pool password policies
Closes #2066
* fix(cognito): close remaining password-policy review gaps on #2066
Addresses the three items left open on this PR's review:
- Password reuse now raises PasswordHistoryPolicyViolationException
instead of InvalidPasswordException, matching the shape AWS declares
for it on AdminSetUserPassword, ChangePassword, ConfirmForgotPassword,
RespondToAuthChallenge and AdminRespondToAuthChallenge (all funnel
through updateUserPassword here).
- Fixed the off-by-one in PasswordHistorySize: AWS counts the current
password as one of the n, so only n-1 prior passwords are blocked
alongside it, not n. Both the check and what gets retained in history
are corrected together.
- adminResetUserPassword no longer bypasses PasswordHistorySize: it now
archives the outgoing password hash before clearing it, the same way
an ordinary password update does.
- CreateUserPool now fills in AWS's per-field password policy defaults
(MinimumLength 8, all four character-class requirements, Temporary-
PasswordValidityDays 7) for any field left unset in a supplied
PasswordPolicy. Deliberately scoped to a policy that is present but
partial, not to a pool with no PasswordPolicy at all -- every other
pool-creating test in this codebase relies on that meaning no
validation, and defaulting one into existence would enforce it on
all of them retroactively. The broader "no Policies at all" case
stays a separate follow-up.
New tests: passwordHistoryCountsTheCurrentPasswordAsOneOfN,
adminResetUserPasswordDoesNotBypassPasswordHistory,
createUserPoolDefaultsAnUnsetMinimumLengthToEight. Updated
passwordHistoryRejectsARecentlyUsedPassword's assertion for the new
exception code, and createUserPoolWithFullConfig's expectation for the
normalized policy shape.
* fix(cognito): stop admin reset from shrinking the password-history window
greptile caught a real bug in the previous commit: updatePasswordHistory
always capped retained history at PasswordHistorySize - 1, on the
assumption that a current password always occupies one of the n slots.
That's true for an ordinary password change, but not for
adminResetUserPassword, which clears the current password without
replacing it -- so capping at n-1 there dropped the oldest still-
protected entry a reset alone should not age out.
Both updatePasswordHistory and validatePasswordAgainstPolicy now check
whether a current password hash exists at the moment they run (the
mutation callers apply before archiving/checking) to decide whether n
or n-1 entries are live. adminResetUserPassword is reordered so the
hash is actually cleared before archival runs, matching what the check
now expects.
New test: adminResetUserPasswordDoesNotShortenTheHistoryWindow, which
pins the exact PasswordHistorySize: 2 / three-password / reset scenario
greptile's finding described, including that the window correctly
shrinks back to n-1 once a new password re-occupies the current slot.
---------
Co-authored-by: Priamo Germosen <6233424+pgermosen@users.noreply.github.com>
---
.../services/cognito/CognitoService.java | 151 ++++++++++++++-
.../services/cognito/model/CognitoUser.java | 6 +
.../cognito/CognitoIntegrationTest.java | 49 +++++
.../services/cognito/CognitoServiceTest.java | 174 +++++++++++++++++-
4 files changed, 378 insertions(+), 2 deletions(-)
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 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
@ApplicationScoped
public 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).
+ *
+ *
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) {
+ Map policies = pool.getPolicies();
+ 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);
+ 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 request) {
if (request.containsKey("Policies")) pool.setPolicies((Map) 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 policies = pool.getPolicies();
+ if (policies == null || !(policies.get("PasswordPolicy") instanceof Map, ?> rawPolicy)) {
+ return;
+ }
+
+ Map policy = (Map) 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 policies = pool.getPolicies();
+ if (policies == null || !(policies.get("PasswordPolicy") instanceof Map, ?> rawPolicy)) {
+ return;
+ }
+
+ int historySize = policyInt((Map) rawPolicy, "PasswordHistorySize");
+ if (historySize <= 0) {
+ return;
+ }
+
+ List 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 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 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.java
index 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 passwordHistory = new ArrayList<>();
private boolean temporaryPassword;
private List 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 getPasswordHistory() { return passwordHistory; }
+ public void setPasswordHistory(List 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.java
index 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.java
index 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");
+ }
+
@Test
void createUserPoolWithFullConfig() {
List