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>
This commit is contained in:
Daniel ZwickerandPriamo Germosen authored and GitHub committed 2026-08-31 13:09:58 -04:00
1 parent 62dbd9ddf9
commit 3aaf74520e
4 files changed
+378 -2

No files matched your search

@@ -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 {
@@ -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<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(), "alice@example.com", password, Map.of(
"email", "alice@example.com",
"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(),
"alice@example.com",
"ValidPassword1!",
Map.of("email", "alice@example.com", "phone_number", "+4915112345678")
);
assertEquals("alice@example.com", user.getUsername());
}
@Test
void passwordHistoryRejectsARecentlyUsedPassword() {
UserPool pool = createPoolWithStrictPasswordPolicy();
service.adminCreateUser(
pool.getId(),
"alice",
Map.of("email", "alice@example.com"),
"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", "alice@example.com"), "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", "alice@example.com"), "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", "alice@example.com"), "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(), "alice@example.com", "a!", Map.of(
"email", "alice@example.com", "phone_number", "+4915112345678")));
assertEquals("InvalidPasswordException", exception.getErrorCode());
assertDoesNotThrow(() -> service.signUp(
client.getClientId(), "bob@example.com", "Eightplus1!", Map.of(
"email", "bob@example.com", "phone_number", "+4915112345679")));
}
@Test
void createUserPoolWithOverrideIdUsesProvidedId() {
UserPool pool = service.createUserPool(