fix(cognito): surface sign-in denials with the exception classes Cognito uses (#5223)

* fix(cognito): surface sign-in denials with the exception classes Cognito uses

A disabled user was rejected with UserNotConfirmedException ("User is disabled");
Cognito returns NotAuthorizedException with "User is disabled.". A PreAuthentication
trigger that returned an error payload surfaced as NotAuthorizedException; Cognito
returns UserLambdaValidationException with "PreAuthentication failed with error
<errorMessage>.", the same mapping floci already applied to PreSignUp on
AdminCreateUser. PreSignUp on SignUp is aligned the same way (it reported
NotAuthorizedException "PreSignUp trigger denied signup: ...").

The five duplicated eligibility checks now share requireSignInEligible /
requireEnabled, and the three blocking triggers share blockingTriggerFailure.
Integration tests that pass against AWS failed on these two codes.

* test(cognito): cover trigger invocation failures and assert the SDK exception classes

PreAuthentication and PreSignUp now get cases for an uninvokable function
(UnexpectedLambdaException) and a malformed response
(InvalidLambdaResponseException). A new sdk-test-java compat test asserts
NotAuthorizedException for a disabled user and UserLambdaValidationException
for a PreAuthentication trigger that raises, through the AWS SDK v2 client.

* test(cognito): drop the em-dash from the compat test display name
This commit is contained in:
danielxoi authored and GitHub committed 2026-10-06 23:28:03 -04:00
1 parent 8a1d1ddcd3
commit bcfb9c786c
8 files changed
+486 -47

No files matched your search

@@ -251,7 +251,7 @@ class CognitoLambdaTriggersTest {
AwsException ex = assertThrows(AwsException.class, () ->
service.initiateAuth(client.getClientId(), "USER_PASSWORD_AUTH",
Map.of("USERNAME", "alice", "PASSWORD", "Perm1234!")));
assertEquals("NotAuthorizedException", ex.getErrorCode());
assertEquals("UserLambdaValidationException", ex.getErrorCode());
assertEquals("PreAuthentication failed with error Unhandled.", ex.getMessage());
}
@@ -275,7 +275,7 @@ class CognitoLambdaTriggersTest {
}
});
assertEquals("NotAuthorizedException", ex.getErrorCode());
assertEquals("UserLambdaValidationException", ex.getErrorCode());
assertEquals("PreAuthentication failed with error Email not verified.", ex.getMessage());
}
@@ -298,10 +298,84 @@ class CognitoLambdaTriggersTest {
service.initiateAuth(client.getClientId(), "USER_PASSWORD_AUTH",
Map.of("USERNAME", "alice", "PASSWORD", "Perm1234!")));
assertEquals("NotAuthorizedException", ex.getErrorCode());
assertEquals("UserLambdaValidationException", ex.getErrorCode());
assertEquals("PreAuthentication failed with error Unhandled.", ex.getMessage());
}
@ParameterizedTest
@ValueSource(booleans = {false, true})
void preAuthenticationUninvokableFunctionIsAnUnexpectedLambdaException(boolean adminAuth) {
UserPool pool = createPoolWithLambdaConfig(Map.of("PreAuthentication", "arn:aws:lambda:::pre"));
seedUser(pool, "alice", "Perm1234!");
UserPoolClient client = createClient(pool);
when(lambdaService.invoke(anyString(), eq("arn:aws:lambda:::pre"), any(byte[].class), any()))
.thenThrow(new AwsException("ResourceNotFoundException",
"Function not found: arn:aws:lambda:::pre", 404));
AwsException ex = assertThrows(AwsException.class, () -> {
if (adminAuth) {
service.adminInitiateAuth(pool.getId(), client.getClientId(), "ADMIN_USER_PASSWORD_AUTH",
Map.of("USERNAME", "alice", "PASSWORD", "Perm1234!"));
} else {
service.initiateAuth(client.getClientId(), "USER_PASSWORD_AUTH",
Map.of("USERNAME", "alice", "PASSWORD", "Perm1234!"));
}
});
assertEquals("UnexpectedLambdaException", ex.getErrorCode());
assertEquals(400, ex.getHttpStatus());
assertEquals("PreAuthentication trigger failed: Function not found: arn:aws:lambda:::pre", ex.getMessage());
}
@Test
void preAuthenticationRuntimeFailureIsAnUnexpectedLambdaException() {
UserPool pool = createPoolWithLambdaConfig(Map.of("PreAuthentication", "arn:aws:lambda:::pre"));
seedUser(pool, "alice", "Perm1234!");
UserPoolClient client = createClient(pool);
when(lambdaService.invoke(anyString(), eq("arn:aws:lambda:::pre"), any(byte[].class), any()))
.thenThrow(new IllegalStateException("runtime container crashed"));
AwsException ex = assertThrows(AwsException.class, () ->
service.initiateAuth(client.getClientId(), "USER_PASSWORD_AUTH",
Map.of("USERNAME", "alice", "PASSWORD", "Perm1234!")));
assertEquals("UnexpectedLambdaException", ex.getErrorCode());
assertEquals("PreAuthentication trigger failed: runtime container crashed", ex.getMessage());
}
@ParameterizedTest
@ValueSource(strings = {"not-json", "null", "{\"response\":\"not-an-object\"}", ""})
void preAuthenticationMalformedResponseIsAnInvalidLambdaResponseException(String payload) {
UserPool pool = createPoolWithLambdaConfig(Map.of("PreAuthentication", "arn:aws:lambda:::pre"));
seedUser(pool, "alice", "Perm1234!");
UserPoolClient client = createClient(pool);
when(lambdaService.invoke(anyString(), eq("arn:aws:lambda:::pre"), any(byte[].class), any()))
.thenReturn(rawPayload(payload));
AwsException ex = assertThrows(AwsException.class, () ->
service.initiateAuth(client.getClientId(), "USER_PASSWORD_AUTH",
Map.of("USERNAME", "alice", "PASSWORD", "Perm1234!")));
assertEquals("InvalidLambdaResponseException", ex.getErrorCode());
assertEquals(400, ex.getHttpStatus());
assertEquals("PreAuthentication trigger failed: " + malformedResponseReason("PreAuthentication", payload),
ex.getMessage());
}
/** The reason {@code invokeTrigger} attaches to each shape of malformed function output. */
private static String malformedResponseReason(String trigger, String payload) {
if (payload.isEmpty()) {
return trigger + " trigger returned an empty response";
}
if ("not-json".equals(payload)) {
return trigger + " trigger returned malformed JSON";
}
return trigger + " trigger returned a non-object response";
}
// =========================================================================
// PostAuthentication
// =========================================================================
@@ -421,12 +495,57 @@ class CognitoLambdaTriggersTest {
when(lambdaService.invoke(anyString(), eq("arn:aws:lambda:::pre-signup"),
any(byte[].class), any()))
.thenReturn(lambdaError("Unhandled"));
.thenReturn(lambdaError("Unhandled", "Invitations are closed"));
AwsException ex = assertThrows(AwsException.class, () ->
service.signUp(client.getClientId(), "alice", "Perm1234!",
Map.of("email", "alice@example.com")));
assertEquals("NotAuthorizedException", ex.getErrorCode());
assertEquals("UserLambdaValidationException", ex.getErrorCode());
assertEquals("PreSignUp failed with error Invitations are closed.", ex.getMessage());
}
@Test
void preSignUpUninvokableFunctionIsAnUnexpectedLambdaException() {
UserPool pool = createPoolWithLambdaConfig(Map.of("PreSignUp", "arn:aws:lambda:::pre-signup"));
UserPoolClient client = createClient(pool);
when(lambdaService.invoke(anyString(), eq("arn:aws:lambda:::pre-signup"),
any(byte[].class), any()))
.thenThrow(new AwsException("ResourceNotFoundException",
"Function not found: arn:aws:lambda:::pre-signup", 404));
AwsException ex = assertThrows(AwsException.class, () ->
service.signUp(client.getClientId(), "alice", "Perm1234!",
Map.of("email", "alice@example.com")));
assertEquals("UnexpectedLambdaException", ex.getErrorCode());
assertEquals(400, ex.getHttpStatus());
assertEquals("PreSignUp trigger failed: Function not found: arn:aws:lambda:::pre-signup", ex.getMessage());
AwsException lookup = assertThrows(AwsException.class, () ->
service.adminGetUser(pool.getId(), "alice"));
assertEquals("UserNotFoundException", lookup.getErrorCode());
}
@ParameterizedTest
@ValueSource(strings = {"not-json", "null", "{\"response\":\"not-an-object\"}", ""})
void preSignUpMalformedResponseIsAnInvalidLambdaResponseException(String payload) {
UserPool pool = createPoolWithLambdaConfig(Map.of("PreSignUp", "arn:aws:lambda:::pre-signup"));
UserPoolClient client = createClient(pool);
when(lambdaService.invoke(anyString(), eq("arn:aws:lambda:::pre-signup"),
any(byte[].class), any()))
.thenReturn(rawPayload(payload));
AwsException ex = assertThrows(AwsException.class, () ->
service.signUp(client.getClientId(), "alice", "Perm1234!",
Map.of("email", "alice@example.com")));
assertEquals("InvalidLambdaResponseException", ex.getErrorCode());
assertEquals(400, ex.getHttpStatus());
assertEquals("PreSignUp trigger failed: " + malformedResponseReason("PreSignUp", payload), ex.getMessage());
AwsException lookup = assertThrows(AwsException.class, () ->
service.adminGetUser(pool.getId(), "alice"));
assertEquals("UserNotFoundException", lookup.getErrorCode());
}
@Test
@@ -956,7 +956,7 @@ class CognitoManagedLoginIntegrationTest {
Response refused = post(null, wrong, Map.of("code", code));
String html = refused.then().statusCode(400).extract().asString();
assertTrue(html.contains("<p role=\"alert\">User is disabled</p>"), html);
assertTrue(html.contains("<p role=\"alert\">User is disabled.</p>"), html);
assertNull(input(html, "code"), "the code is used up, so the page does not ask for it again");
assertTrue(input(html, "username").contains("value=\"" + pool.email() + "\""), html);
assertNull(refused.getHeader("Location"));
@@ -4664,7 +4664,8 @@ class CognitoServiceTest {
AwsException ex = assertThrows(AwsException.class, () ->
service.initiateAuth(client.getClientId(), "USER_PASSWORD_AUTH",
Map.of("USERNAME", "alice", "PASSWORD", "Perm1234!")));
assertEquals("UserNotConfirmedException", ex.getErrorCode());
assertEquals("NotAuthorizedException", ex.getErrorCode());
assertEquals("User is disabled.", ex.getMessage());
}
@Test
@@ -0,0 +1,109 @@
package io.github.hectorvent.floci.services.cognito;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.github.hectorvent.floci.services.lambda.LambdaService;
import io.github.hectorvent.floci.services.lambda.model.InvokeResult;
import io.github.hectorvent.floci.testing.RestAssuredJsonUtils;
import io.quarkus.test.InjectMock;
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.ValueSource;
import java.util.Map;
import static io.github.hectorvent.floci.services.cognito.CognitoRestAssuredUtils.cognitoAction;
import static io.github.hectorvent.floci.services.cognito.CognitoRestAssuredUtils.cognitoJson;
import static org.hamcrest.Matchers.equalTo;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.when;
/**
* The error a sign-in denial puts on the wire, which the AWS SDKs map to the exception class
* named by {@code __type}: a disabled user is {@code NotAuthorizedException}, and a
* PreAuthentication function that raised is {@code UserLambdaValidationException}, as on AWS.
*/
@QuarkusTest
class CognitoSignInDenialIntegrationTest {
private static final String PASSWORD = "Perm1234!";
private static final String PRE_AUTHENTICATION_ARN = "arn:aws:lambda:::pre-authentication";
private static final ObjectMapper MAPPER = new ObjectMapper();
@InjectMock
LambdaService lambdaService;
@BeforeAll
static void configureRestAssured() {
RestAssuredJsonUtils.configureAwsContentTypes();
}
@ParameterizedTest
@ValueSource(booleans = {false, true})
void disabledUserIsNotAuthorized(boolean adminAuth) throws Exception {
Pool pool = newPool(Map.of());
cognitoAction("AdminDisableUser", """
{"UserPoolId":"%s","Username":"%s"}
""".formatted(pool.poolId(), pool.username())).then().statusCode(200);
signIn(pool, adminAuth)
.then()
.statusCode(400)
.body("__type", equalTo("NotAuthorizedException"))
.body("message", equalTo("User is disabled."));
}
@ParameterizedTest
@ValueSource(booleans = {false, true})
void preAuthenticationFunctionErrorIsAUserLambdaValidationException(boolean adminAuth) throws Exception {
Pool pool = newPool(Map.of("PreAuthentication", PRE_AUTHENTICATION_ARN));
when(lambdaService.invoke(anyString(), eq(PRE_AUTHENTICATION_ARN), any(), any()))
.thenReturn(new InvokeResult(200, "Unhandled", MAPPER.writeValueAsBytes(Map.of(
"errorMessage", "Org requires SSO login through IdP",
"errorType", "ForbiddenError")), null, "req-id"));
signIn(pool, adminAuth)
.then()
.statusCode(400)
.body("__type", equalTo("UserLambdaValidationException"))
.body("message", equalTo(
"PreAuthentication failed with error Org requires SSO login through IdP."));
}
private record Pool(String poolId, String clientId, String username) {
}
private static Pool newPool(Map<String, String> lambdaConfig) throws Exception {
String poolId = cognitoJson("CreateUserPool", """
{"PoolName":"SignInDenialPool","LambdaConfig":%s}
""".formatted(MAPPER.writeValueAsString(lambdaConfig))).path("UserPool").path("Id").asText();
String clientId = cognitoJson("CreateUserPoolClient", """
{"UserPoolId":"%s","ClientName":"app",
"ExplicitAuthFlows":["ALLOW_USER_PASSWORD_AUTH","ALLOW_ADMIN_USER_PASSWORD_AUTH","ALLOW_REFRESH_TOKEN_AUTH"]}
""".formatted(poolId)).path("UserPoolClient").path("ClientId").asText();
String username = "user-" + System.nanoTime();
cognitoAction("AdminCreateUser", """
{"UserPoolId":"%s","Username":"%s","UserAttributes":[{"Name":"email","Value":"%s@example.com"}]}
""".formatted(poolId, username, username)).then().statusCode(200);
cognitoAction("AdminSetUserPassword", """
{"UserPoolId":"%s","Username":"%s","Password":"%s","Permanent":true}
""".formatted(poolId, username, PASSWORD)).then().statusCode(200);
return new Pool(poolId, clientId, username);
}
private static Response signIn(Pool pool, boolean adminAuth) {
if (adminAuth) {
return cognitoAction("AdminInitiateAuth", """
{"UserPoolId":"%s","ClientId":"%s","AuthFlow":"ADMIN_USER_PASSWORD_AUTH",
"AuthParameters":{"USERNAME":"%s","PASSWORD":"%s"}}
""".formatted(pool.poolId(), pool.clientId(), pool.username(), PASSWORD));
}
return cognitoAction("InitiateAuth", """
{"ClientId":"%s","AuthFlow":"USER_PASSWORD_AUTH",
"AuthParameters":{"USERNAME":"%s","PASSWORD":"%s"}}
""".formatted(pool.clientId(), pool.username(), PASSWORD));
}
}
@@ -119,7 +119,8 @@ class CognitoTotpMfaTest {
AwsException disabled = assertThrows(AwsException.class,
() -> service.respondToAuthChallenge(client.getClientId(), "MFA_SETUP", verifiedSession,
Map.of("USERNAME", USERNAME)));
assertEquals("UserNotConfirmedException", disabled.getErrorCode());
assertEquals("NotAuthorizedException", disabled.getErrorCode());
assertEquals("User is disabled.", disabled.getMessage());
}
@Test
@@ -138,7 +139,8 @@ class CognitoTotpMfaTest {
AwsException disabled = assertThrows(AwsException.class,
() -> service.respondToAuthChallenge(client.getClientId(), "SOFTWARE_TOKEN_MFA", challengeSession,
Map.of("USERNAME", USERNAME, "SOFTWARE_TOKEN_MFA_CODE", code)));
assertEquals("UserNotConfirmedException", disabled.getErrorCode());
assertEquals("NotAuthorizedException", disabled.getErrorCode());
assertEquals("User is disabled.", disabled.getMessage());
}
@Test