fix(cognito): hide unknown users in password authentication (#8005) (#8103)

This commit is contained in:
jwoa95 authored and GitHub committed 2026-11-12 09:48:13 -04:00
1 parent c888c636b3
commit 13ab84ed9f
5 files changed
+164 -6

No files matched your search

+6
View File
@@ -538,6 +538,12 @@ empty list, matching AWS. It is enforced as if it had `ALLOW_REFRESH_TOKEN_AUTH`
the stored or returned value. A client that signs in with `USER_PASSWORD_AUTH`, `ADMIN_USER_PASSWORD_AUTH` or
`USER_AUTH` must list the matching `ALLOW_` value.
With the app client's `PreventUserExistenceErrors` set to `ENABLED`, password authentication
(`USER_PASSWORD_AUTH`, `ADMIN_USER_PASSWORD_AUTH` and the legacy `ADMIN_NO_SRP_AUTH`) returns
`NotAuthorizedException` with `Incorrect username or password` for both an unknown username and
an incorrect password. With `LEGACY`, or when the setting is omitted, an unknown username returns
`UserNotFoundException`. See [AWS's user-existence error behavior](https://docs.aws.amazon.com/cognito/latest/developerguide/cognito-user-pool-managing-errors.html).
## Custom Message Trigger
`CustomMessage` requests include the `{####}` code placeholder, the `{##Click Here##}`
@@ -732,7 +732,12 @@ final class CognitoAuthFlowHandler {
if (!"UserNotFoundException".equals(ae.getErrorCode())) throw ae;
user = tryUserMigration(pool, client, username, password, null, clientMetadata,
"UserMigration_Authentication");
if (user == null) throw ae;
if (user == null) {
if ("ENABLED".equals(client.getPreventUserExistenceErrors())) {
throw new AwsException("NotAuthorizedException", INCORRECT_CREDENTIALS, 400);
}
throw ae;
}
}
firePreAuthentication(pool, client, user, null, clientMetadata, false);
@@ -29,6 +29,7 @@ import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.NullAndEmptySource;
import org.junit.jupiter.params.provider.NullSource;
import org.junit.jupiter.params.provider.ValueSource;
import org.mockito.ArgumentCaptor;
import org.mockito.invocation.InvocationOnMock;
@@ -1895,11 +1896,14 @@ class CognitoLambdaTriggersTest {
verify(lambdaService, never()).invoke(anyString(), eq("arn:aws:lambda:::post"), any(byte[].class), any());
}
@Test
@ParameterizedTest
@NullSource
@ValueSource(strings = {"ENABLED", "LEGACY"})
@SuppressWarnings("unchecked")
void userMigrationCreatesAndAuthenticatesMissingUser() {
void userMigrationCreatesAndAuthenticatesMissingUser(String prevention) {
UserPool pool = createPoolWithLambdaConfig(Map.of("UserMigration", "arn:aws:lambda:::migrate"));
UserPoolClient client = createClient(pool);
client.setPreventUserExistenceErrors(prevention);
Map<String, Object> migrationResp = Map.of(
"userAttributes", Map.of(
@@ -1923,10 +1927,13 @@ class CognitoLambdaTriggersTest {
assertTrue(user.isEnabled());
}
@Test
void userMigrationLambdaErrorPropagatesUserNotFound() {
@ParameterizedTest
@NullSource
@ValueSource(strings = {"ENABLED", "LEGACY"})
void userMigrationLambdaErrorHonorsUserExistenceErrorSetting(String prevention) {
UserPool pool = createPoolWithLambdaConfig(Map.of("UserMigration", "arn:aws:lambda:::migrate"));
UserPoolClient client = createClient(pool);
client.setPreventUserExistenceErrors(prevention);
when(lambdaService.invoke(anyString(), eq("arn:aws:lambda:::migrate"), any(byte[].class), any()))
.thenReturn(lambdaError("Unhandled"));
@@ -1934,7 +1941,9 @@ class CognitoLambdaTriggersTest {
AwsException ex = assertThrows(AwsException.class, () ->
service.initiateAuth(client.getClientId(), "USER_PASSWORD_AUTH",
Map.of("USERNAME", "ghost", "PASSWORD", "x")));
assertEquals("UserNotFoundException", ex.getErrorCode());
boolean hidden = "ENABLED".equals(prevention);
assertEquals(hidden ? "NotAuthorizedException" : "UserNotFoundException", ex.getErrorCode());
assertEquals(hidden ? "Incorrect username or password" : "User not found", ex.getMessage());
}
@Test
@@ -0,0 +1,92 @@
package io.floci.aws.services.cognito;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.floci.aws.testing.RestAssuredJsonUtils;
import io.quarkus.test.junit.QuarkusTest;
import io.restassured.response.Response;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.CsvSource;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import static io.floci.aws.services.cognito.CognitoRestAssuredUtils.cognitoAction;
import static io.floci.aws.services.cognito.CognitoRestAssuredUtils.cognitoJson;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.notNullValue;
import static org.hamcrest.Matchers.nullValue;
@QuarkusTest
class CognitoPasswordUserExistenceIntegrationTest {
private static final ObjectMapper MAPPER = new ObjectMapper();
@BeforeAll
static void configureRestAssured() {
RestAssuredJsonUtils.configureAwsContentTypes();
}
@ParameterizedTest
@CsvSource({
"USER_PASSWORD_AUTH, ENABLED", "ADMIN_USER_PASSWORD_AUTH, ENABLED", "ADMIN_NO_SRP_AUTH, ENABLED",
"USER_PASSWORD_AUTH, LEGACY", "ADMIN_USER_PASSWORD_AUTH, LEGACY", "ADMIN_NO_SRP_AUTH, LEGACY",
"USER_PASSWORD_AUTH,", "ADMIN_USER_PASSWORD_AUTH,", "ADMIN_NO_SRP_AUTH,"
})
void passwordAuthHonorsUserExistenceErrorSetting(String flow, String prevention) throws Exception {
String poolId = cognitoJson("CreateUserPool", """
{"PoolName":"password-user-existence"}
""").path("UserPool").path("Id").asText();
try {
Map<String, Object> clientRequest = new LinkedHashMap<>(Map.of(
"UserPoolId", poolId, "ClientName", "password-client",
"ExplicitAuthFlows", List.of("ALLOW_USER_PASSWORD_AUTH", "ALLOW_ADMIN_USER_PASSWORD_AUTH")));
if (prevention != null) {
clientRequest.put("PreventUserExistenceErrors", prevention);
}
String clientId = cognitoJson("CreateUserPoolClient", MAPPER.writeValueAsString(clientRequest))
.path("UserPoolClient").path("ClientId").asText();
cognitoAction("AdminCreateUser", """
{"UserPoolId":"%s","Username":"alice","MessageAction":"SUPPRESS"}
""".formatted(poolId)).then().statusCode(200);
cognitoAction("AdminSetUserPassword", """
{"UserPoolId":"%s","Username":"alice","Password":"Perm1234!","Permanent":true}
""".formatted(poolId)).then().statusCode(200);
passwordAuth(poolId, clientId, flow, "alice", "wrong").then()
.statusCode(400)
.body("__type", equalTo("NotAuthorizedException"))
.body("message", equalTo("Incorrect username or password"))
.body("AuthenticationResult", nullValue());
boolean hidden = "ENABLED".equals(prevention);
passwordAuth(poolId, clientId, flow, "nobody", "wrong").then()
.statusCode(400)
.body("__type", equalTo(hidden ? "NotAuthorizedException" : "UserNotFoundException"))
.body("message", equalTo(hidden ? "Incorrect username or password" : "User not found"))
.body("AuthenticationResult", nullValue());
passwordAuth(poolId, clientId, flow, "alice", "Perm1234!").then()
.statusCode(200)
.body("AuthenticationResult.AccessToken", notNullValue());
} finally {
cognitoAction("DeleteUserPool", """
{"UserPoolId":"%s"}
""".formatted(poolId)).then().statusCode(200);
}
}
private static Response passwordAuth(String poolId, String clientId, String flow,
String username, String password) throws Exception {
Map<String, Object> request = new LinkedHashMap<>(Map.of(
"ClientId", clientId, "AuthFlow", flow,
"AuthParameters", Map.of("USERNAME", username, "PASSWORD", password)));
String action = "InitiateAuth";
if (!"USER_PASSWORD_AUTH".equals(flow)) {
request.put("UserPoolId", poolId);
action = "AdminInitiateAuth";
}
return cognitoAction(action, MAPPER.writeValueAsString(request));
}
}
@@ -622,6 +622,52 @@ class CognitoServiceTest {
assertEquals("USER_PASSWORD_AUTH flow not enabled for this client", exception.getMessage());
}
@ParameterizedTest
@ValueSource(strings = {"USER_PASSWORD_AUTH", "ADMIN_USER_PASSWORD_AUTH", "ADMIN_NO_SRP_AUTH"})
void passwordAuthHidesUnknownUsersWhenPreventUserExistenceErrorsIsEnabled(String flow) {
UserPool pool = createPoolAndUser();
UserPoolClient client = openClient(service, pool.getId(), "hidden-password-client", false);
client.setPreventUserExistenceErrors("ENABLED");
AwsException wrongPassword = assertThrows(AwsException.class, () -> passwordAuth(
pool, client, flow, "alice", "wrong"));
AwsException unknownUser = assertThrows(AwsException.class, () -> passwordAuth(
pool, client, flow, "nobody", "wrong"));
assertEquals("NotAuthorizedException", wrongPassword.getErrorCode());
assertEquals("Incorrect username or password", wrongPassword.getMessage());
assertEquals(wrongPassword.getErrorCode(), unknownUser.getErrorCode());
assertEquals(wrongPassword.getMessage(), unknownUser.getMessage());
assertEquals(wrongPassword.getHttpStatus(), unknownUser.getHttpStatus());
assertNotNull(passwordAuth(pool, client, flow, "alice", "Perm1234!").get("AuthenticationResult"));
}
@ParameterizedTest
@CsvSource({
"USER_PASSWORD_AUTH, LEGACY", "USER_PASSWORD_AUTH,",
"ADMIN_USER_PASSWORD_AUTH, LEGACY", "ADMIN_USER_PASSWORD_AUTH,",
"ADMIN_NO_SRP_AUTH, LEGACY", "ADMIN_NO_SRP_AUTH,"
})
void passwordAuthPreservesUnknownUserErrorsForLegacyClients(String flow, String prevention) {
UserPool pool = createPoolAndUser();
UserPoolClient client = openClient(service, pool.getId(), "legacy-password-client", false);
client.setPreventUserExistenceErrors(prevention);
AwsException unknownUser = assertThrows(AwsException.class, () -> passwordAuth(
pool, client, flow, "nobody", "wrong"));
assertEquals("UserNotFoundException", unknownUser.getErrorCode());
assertEquals("User not found", unknownUser.getMessage());
}
private Map<String, Object> passwordAuth(UserPool pool, UserPoolClient client, String flow,
String username, String password) {
Map<String, String> parameters = Map.of("USERNAME", username, "PASSWORD", password);
return "USER_PASSWORD_AUTH".equals(flow)
? service.initiateAuth(client.getClientId(), flow, parameters)
: service.adminInitiateAuth(pool.getId(), client.getClientId(), flow, parameters);
}
private static final List<String> ALL_AUTH_FLOWS = List.of("ALLOW_USER_PASSWORD_AUTH",
"ALLOW_ADMIN_USER_PASSWORD_AUTH", "ALLOW_USER_AUTH", "ALLOW_USER_SRP_AUTH", "ALLOW_CUSTOM_AUTH",
"ALLOW_REFRESH_TOKEN_AUTH");