Skip to content

armgit / floci

Public Imported from GitHub
0

Light, fluffy, and always free - The AWS Local Emulator alternative

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

danielxoibcfb9c786c4e
diff --git a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/CognitoSignInDenialTest.java b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/CognitoSignInDenialTest.java
new file mode 100644
index 0000000000..deff17565b
--- /dev/null
+++ b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/CognitoSignInDenialTest.java
@@ -0,0 +1,209 @@
+package com.floci.test;
+
+import org.junit.jupiter.api.AfterAll;
+import org.junit.jupiter.api.Assumptions;
+import org.junit.jupiter.api.BeforeAll;
+import org.junit.jupiter.api.DisplayName;
+import org.junit.jupiter.api.Test;
+import software.amazon.awssdk.core.SdkBytes;
+import software.amazon.awssdk.services.cognitoidentityprovider.CognitoIdentityProviderClient;
+import software.amazon.awssdk.services.cognitoidentityprovider.model.AttributeType;
+import software.amazon.awssdk.services.cognitoidentityprovider.model.AuthFlowType;
+import software.amazon.awssdk.services.cognitoidentityprovider.model.ExplicitAuthFlowsType;
+import software.amazon.awssdk.services.cognitoidentityprovider.model.MessageActionType;
+import software.amazon.awssdk.services.cognitoidentityprovider.model.NotAuthorizedException;
+import software.amazon.awssdk.services.cognitoidentityprovider.model.UserLambdaValidationException;
+import software.amazon.awssdk.services.lambda.LambdaClient;
+import software.amazon.awssdk.services.lambda.model.Runtime;
+
+import java.io.ByteArrayOutputStream;
+import java.io.IOException;
+import java.nio.charset.StandardCharsets;
+import java.util.Map;
+import java.util.zip.ZipEntry;
+import java.util.zip.ZipOutputStream;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThatThrownBy;
+
+/**
+ * Sign-in denials must surface through the exception classes the AWS SDK models for Cognito:
+ * a disabled user is {@code NotAuthorizedException} ("User is disabled."), and a PreAuthentication
+ * trigger that raises is {@code UserLambdaValidationException} carrying the function's message.
+ */
+@DisplayName("Cognito IDP: sign-in denial exception classes")
+class CognitoSignInDenialTest {
+
+ private static final String ROLE = "arn:aws:iam::000000000000:role/lambda-role";
+ private static final String PASSWORD = "CompatPass1!";
+ private static final String DENIAL_MESSAGE = "Email not verified";
+ private static final String PRE_AUTH_SOURCE = """
+ def handler(event, context):
+ raise Exception("%s")
+ """.formatted(DENIAL_MESSAGE);
+
+ private static CognitoIdentityProviderClient cognito;
+ private static LambdaClient lambda;
+ private static String poolId;
+ private static String clientId;
+ private static String triggerPoolId;
+ private static String triggerClientId;
+ private static String triggerFunctionName;
+
+ @BeforeAll
+ static void setup() {
+ cognito = TestFixtures.cognitoClient();
+ lambda = TestFixtures.lambdaClient();
+
+ poolId = cognito.createUserPool(b -> b.poolName(TestFixtures.uniqueName("compat-denial-pool")))
+ .userPool().id();
+ clientId = createPasswordClient(poolId);
+ }
+
+ @AfterAll
+ static void cleanup() {
+ if (cognito != null) {
+ deletePoolQuietly(poolId);
+ deletePoolQuietly(triggerPoolId);
+ cognito.close();
+ }
+ if (lambda != null) {
+ if (triggerFunctionName != null) {
+ try {
+ lambda.deleteFunction(b -> b.functionName(triggerFunctionName));
+ } catch (Exception ignored) {
+ // Cleanup only. A failed delete must not hide the test result.
+ }
+ }
+ lambda.close();
+ }
+ }
+
+ @Test
+ @DisplayName("InitiateAuth for a disabled user is NotAuthorizedException: User is disabled.")
+ void initiateAuthDisabledUserIsNotAuthorized() {
+ String username = createConfirmedUser(poolId, "disabled-initiate");
+ cognito.adminDisableUser(b -> b.userPoolId(poolId).username(username));
+
+ assertThatThrownBy(() -> cognito.initiateAuth(b -> b
+ .clientId(clientId)
+ .authFlow(AuthFlowType.USER_PASSWORD_AUTH)
+ .authParameters(Map.of("USERNAME", username, "PASSWORD", PASSWORD))))
+ .isInstanceOfSatisfying(NotAuthorizedException.class, e -> {
+ assertThat(e.awsErrorDetails().errorMessage()).isEqualTo("User is disabled.");
+ assertThat(e.statusCode()).isEqualTo(400);
+ });
+ }
+
+ @Test
+ @DisplayName("AdminInitiateAuth for a disabled user is NotAuthorizedException: User is disabled.")
+ void adminInitiateAuthDisabledUserIsNotAuthorized() {
+ String username = createConfirmedUser(poolId, "disabled-admin");
+ cognito.adminDisableUser(b -> b.userPoolId(poolId).username(username));
+
+ assertThatThrownBy(() -> cognito.adminInitiateAuth(b -> b
+ .userPoolId(poolId)
+ .clientId(clientId)
+ .authFlow(AuthFlowType.ADMIN_USER_PASSWORD_AUTH)
+ .authParameters(Map.of("USERNAME", username, "PASSWORD", PASSWORD))))
+ .isInstanceOfSatisfying(NotAuthorizedException.class, e -> {
+ assertThat(e.awsErrorDetails().errorMessage()).isEqualTo("User is disabled.");
+ assertThat(e.statusCode()).isEqualTo(400);
+ });
+ }
+
+ @Test
+ @DisplayName("a raising PreAuthentication trigger is UserLambdaValidationException with the function's message")
+ void preAuthenticationTriggerErrorIsUserLambdaValidationException() {
+ Assumptions.assumeTrue(TestFixtures.isLambdaDispatchAvailable(),
+ "skipping: Lambda dispatch (Docker) not available in this environment");
+
+ triggerFunctionName = TestFixtures.uniqueName("compat-pre-auth-deny");
+ String functionArn = lambda.createFunction(b -> b
+ .functionName(triggerFunctionName)
+ .runtime(Runtime.PYTHON3_12)
+ .role(ROLE)
+ .handler("lambda_function.handler")
+ .timeout(10)
+ .code(c -> c.zipFile(SdkBytes.fromByteArray(zip("lambda_function.py", PRE_AUTH_SOURCE)))))
+ .functionArn();
+
+ triggerPoolId = cognito.createUserPool(b -> b
+ .poolName(TestFixtures.uniqueName("compat-denial-trigger-pool"))
+ .lambdaConfig(l -> l.preAuthentication(functionArn)))
+ .userPool().id();
+ triggerClientId = createPasswordClient(triggerPoolId);
+ String username = createConfirmedUser(triggerPoolId, "pre-auth-denied");
+
+ assertThatThrownBy(() -> cognito.initiateAuth(b -> b
+ .clientId(triggerClientId)
+ .authFlow(AuthFlowType.USER_PASSWORD_AUTH)
+ .authParameters(Map.of("USERNAME", username, "PASSWORD", PASSWORD))))
+ .isInstanceOfSatisfying(UserLambdaValidationException.class, e -> {
+ assertThat(e.awsErrorDetails().errorMessage())
+ .isEqualTo("PreAuthentication failed with error " + DENIAL_MESSAGE + ".");
+ assertThat(e.statusCode()).isEqualTo(400);
+ });
+
+ assertThatThrownBy(() -> cognito.adminInitiateAuth(b -> b
+ .userPoolId(triggerPoolId)
+ .clientId(triggerClientId)
+ .authFlow(AuthFlowType.ADMIN_USER_PASSWORD_AUTH)
+ .authParameters(Map.of("USERNAME", username, "PASSWORD", PASSWORD))))
+ .isInstanceOfSatisfying(UserLambdaValidationException.class, e ->
+ assertThat(e.awsErrorDetails().errorMessage())
+ .isEqualTo("PreAuthentication failed with error " + DENIAL_MESSAGE + "."));
+ }
+
+ private static String createPasswordClient(String userPoolId) {
+ return cognito.createUserPoolClient(b -> b
+ .userPoolId(userPoolId)
+ .clientName("compat-denial-client")
+ .explicitAuthFlows(
+ ExplicitAuthFlowsType.ALLOW_USER_PASSWORD_AUTH,
+ ExplicitAuthFlowsType.ALLOW_ADMIN_USER_PASSWORD_AUTH))
+ .userPoolClient().clientId();
+ }
+
+ private static String createConfirmedUser(String userPoolId, String prefix) {
+ String username = TestFixtures.uniqueName(prefix);
+ cognito.adminCreateUser(b -> b
+ .userPoolId(userPoolId)
+ .username(username)
+ .userAttributes(
+ AttributeType.builder().name("email").value(username + "@example.com").build(),
+ AttributeType.builder().name("email_verified").value("true").build())
+ .messageAction(MessageActionType.SUPPRESS));
+ cognito.adminSetUserPassword(b -> b
+ .userPoolId(userPoolId)
+ .username(username)
+ .password(PASSWORD)
+ .permanent(true));
+ return username;
+ }
+
+ private static void deletePoolQuietly(String userPoolId) {
+ if (userPoolId == null) {
+ return;
+ }
+ try {
+ cognito.deleteUserPool(b -> b.userPoolId(userPoolId));
+ } catch (Exception ignored) {
+ // Cleanup only. A failed delete must not hide the test result.
+ }
+ }
+
+ private static byte[] zip(String entryName, String content) {
+ try {
+ ByteArrayOutputStream bytes = new ByteArrayOutputStream();
+ try (ZipOutputStream zip = new ZipOutputStream(bytes)) {
+ zip.putNextEntry(new ZipEntry(entryName));
+ zip.write(content.getBytes(StandardCharsets.UTF_8));
+ zip.closeEntry();
+ }
+ return bytes.toByteArray();
+ } catch (IOException e) {
+ throw new IllegalStateException("cannot build the Lambda deployment package", e);
+ }
+ }
+}
diff --git a/docs/services/cognito.md b/docs/services/cognito.md
index cd6711b283..bd0cf98057 100644
--- a/docs/services/cognito.md
+++ b/docs/services/cognito.md
@@ -5,9 +5,14 @@
Floci serves pool-specific discovery and JWKS endpoints, plus a relaxed OAuth token endpoint, so local clients can mint and validate Cognito-like access tokens against RS256 signing keys.
-When configured, `PostAuthentication` and `PreTokenGeneration` Lambda triggers must succeed
-before authentication or token issuance completes. Function errors and malformed responses
-return Cognito Lambda errors instead of issuing tokens without the trigger's claims.
+When configured, `PreAuthentication`, `PostAuthentication` and `PreTokenGeneration` Lambda triggers
+must succeed before authentication or token issuance completes. Function errors and malformed
+responses return Cognito Lambda errors instead of issuing tokens without the trigger's claims. A
+`PreSignUp` or `PreAuthentication` function that raises refuses the request with
+`UserLambdaValidationException` and the message `<Trigger> failed with error <errorMessage>.`,
+where `errorMessage` is taken verbatim from the function's error payload, as on AWS.
+
+Sign-in by a disabled user fails with `NotAuthorizedException` (`User is disabled.`), as on AWS.
`CreateUserPool` supports overriding several values using user-pool tags **only** at creation time:
* `floci:override-id`, to pin the resulting `UserPool.Id`. Because a pinned id is caller-chosen it can be reused, which AWS never does. `DeleteUserPool` therefore deletes everything the pool owns (users, groups, app clients, resource servers, revoked token records and outstanding verification codes) so a pool recreated on the same id starts empty rather than inheriting the deleted pool's password hashes and client secrets.
@@ -214,7 +219,7 @@ further divergences, both deliberate:
| AdminUpdateUserAttributes | Updates attributes for a user in a user pool. |
| AdminDeleteUserAttributes | Deletes the named attributes from a user, along with any pending verification of them. |
| AdminConfirmSignUp | Confirms a user's sign-up without a confirmation code. |
-| AdminDisableUser | Disables a user, who can no longer sign in. Tokens already issued keep working, where AWS revokes the user's access tokens. |
+| AdminDisableUser | Disables a user, whose sign-in then fails with `NotAuthorizedException` (`User is disabled.`). Tokens already issued keep working, where AWS revokes the user's access tokens. |
| AdminEnableUser | Re-enables a disabled user. |
| AdminResetUserPassword | Clears a user's password and sets the status to `RESET_REQUIRED`, so sign-in fails with `PasswordResetRequiredException`. Floci sends no reset code: finish with `ForgotPassword` and `ConfirmForgotPassword`, or `AdminSetUserPassword`. Refused when the pool's account recovery is `admin_only`. |
| AdminSetUserMFAPreference | Sets a user's email and software-token MFA preferences from `EmailMfaSettings` and `SoftwareTokenMfaSettings`. SMS settings are accepted but not stored. See [MFA preferences](#mfa-preferences). |
diff --git a/src/main/java/io/github/hectorvent/floci/services/cognito/CognitoAuthFlowHandler.java b/src/main/java/io/github/hectorvent/floci/services/cognito/CognitoAuthFlowHandler.java
index 2b5e6676b1..0d0f1a8ccc 100644
--- a/src/main/java/io/github/hectorvent/floci/services/cognito/CognitoAuthFlowHandler.java
+++ b/src/main/java/io/github/hectorvent/floci/services/cognito/CognitoAuthFlowHandler.java
@@ -632,13 +632,7 @@ final class CognitoAuthFlowHandler {
firePreAuthentication(pool, client, user, null, clientMetadata, false);
- if (!user.isEnabled()) throw new AwsException("UserNotConfirmedException", "User is disabled", 400);
- if ("RESET_REQUIRED".equals(user.getUserStatus())) {
- throw new AwsException("PasswordResetRequiredException", "Password reset required", 400);
- }
- if ("UNCONFIRMED".equals(user.getUserStatus())) {
- throw new AwsException("UserNotConfirmedException", "User is not confirmed", 400);
- }
+ requireSignInEligible(user);
if (user.getPasswordHash() == null || !user.getPasswordHash().equals(service.hashPassword(password))) {
throw new AwsException("NotAuthorizedException", INCORRECT_CREDENTIALS, 400);
}
@@ -779,13 +773,7 @@ final class CognitoAuthFlowHandler {
CognitoUser user = service.adminGetUser(pool.getId(), username);
firePreAuthentication(pool, client, user, null, clientMetadata, false);
- if (!user.isEnabled()) throw new AwsException("UserNotConfirmedException", "User is disabled", 400);
- if ("RESET_REQUIRED".equals(user.getUserStatus())) {
- throw new AwsException("PasswordResetRequiredException", "Password reset required", 400);
- }
- if ("UNCONFIRMED".equals(user.getUserStatus())) {
- throw new AwsException("UserNotConfirmedException", "User is not confirmed", 400);
- }
+ requireSignInEligible(user);
if (user.getSrpVerifier() == null) {
throw new AwsException("NotAuthorizedException", "User does not support SRP auth", 400);
}
@@ -856,13 +844,7 @@ final class CognitoAuthFlowHandler {
validateSecretHash(client, responses, username);
CognitoUser user = service.adminGetUser(pool.getId(), username);
- if (!user.isEnabled()) throw new AwsException("UserNotConfirmedException", "User is disabled", 400);
- if ("RESET_REQUIRED".equals(user.getUserStatus())) {
- throw new AwsException("PasswordResetRequiredException", "Password reset required", 400);
- }
- if ("UNCONFIRMED".equals(user.getUserStatus())) {
- throw new AwsException("UserNotConfirmedException", "User is not confirmed", 400);
- }
+ requireSignInEligible(user);
if (user.getSrpVerifier() == null) {
throw new AwsException("NotAuthorizedException", "User does not support SRP auth", 400);
}
@@ -1246,9 +1228,7 @@ final class CognitoAuthFlowHandler {
}
private void requireSignInEligible(CognitoUser user) {
- if (!user.isEnabled()) {
- throw new AwsException("UserNotConfirmedException", "User is disabled", 400);
- }
+ requireEnabled(user);
if ("RESET_REQUIRED".equals(user.getUserStatus())) {
throw new AwsException("PasswordResetRequiredException", "Password reset required", 400);
}
@@ -1257,6 +1237,13 @@ final class CognitoAuthFlowHandler {
}
}
+ /** AWS rejects a disabled user with NotAuthorizedException, not UserNotConfirmedException. */
+ private static void requireEnabled(CognitoUser user) {
+ if (!user.isEnabled()) {
+ throw new AwsException("NotAuthorizedException", "User is disabled.", 400);
+ }
+ }
+
// ──────────────────────────── CUSTOM_AUTH ────────────────────────────
private Map<String, Object> handleCustomAuth(UserPool pool, UserPoolClient client,
@@ -1267,7 +1254,7 @@ final class CognitoAuthFlowHandler {
CognitoUser user = service.adminGetUser(pool.getId(), username);
firePreAuthentication(pool, client, user, null, clientMetadata, false);
- if (!user.isEnabled()) throw new AwsException("UserNotConfirmedException", "User is disabled", 400);
+ requireEnabled(user);
if ("RESET_REQUIRED".equals(user.getUserStatus())) {
throw new AwsException("PasswordResetRequiredException", "Password reset required", 400);
}
@@ -1664,8 +1651,7 @@ final class CognitoAuthFlowHandler {
TriggerResult result = invokeTrigger(pool, client, user,
"PreAuthentication", "PreAuthentication_Authentication", req);
if (result.errored()) {
- throw new AwsException("NotAuthorizedException",
- "PreAuthentication failed with error " + result.errorMessage() + ".", 400);
+ throw blockingTriggerFailure(result, "PreAuthentication");
}
}
@@ -1703,8 +1689,7 @@ final class CognitoAuthFlowHandler {
req.put("clientMetadata", clientMetadata == null ? Map.of() : clientMetadata);
TriggerResult result = invokeTrigger(pool, client, user, "PreSignUp", triggerSource, req);
if (result.errored()) {
- throw new AwsException("NotAuthorizedException",
- "PreSignUp trigger denied signup: " + result.errorMessage(), 400);
+ throw blockingTriggerFailure(result, "PreSignUp");
}
if (!result.configured() || result.response() == null) return PreSignUpResponse.empty();
Map<String, Object> resp = result.response();
@@ -1726,14 +1711,23 @@ final class CognitoAuthFlowHandler {
req.put("validationData", validationData == null ? Map.of() : validationData);
req.put("clientMetadata", clientMetadata == null ? Map.of() : clientMetadata);
TriggerResult result = invokeTrigger(pool, null, user, "PreSignUp", "PreSignUp_AdminCreateUser", req);
- if (!result.errored()) {
- return;
+ if (result.errored()) {
+ throw blockingTriggerFailure(result, "PreSignUp");
}
+ }
+
+ /**
+ * Maps a failed PreSignUp/PreAuthentication invocation the way Cognito does: a function
+ * that returned an error payload surfaces as {@code UserLambdaValidationException}
+ * ("&lt;Trigger&gt; failed with error &lt;errorMessage&gt;."), while an uninvokable
+ * function or a malformed response keeps the generic Lambda error mapping.
+ */
+ private AwsException blockingTriggerFailure(TriggerResult result, String triggerName) {
if (result.errorKind() == TriggerErrorKind.USER_VALIDATION) {
- throw new AwsException("UserLambdaValidationException",
- "PreSignUp failed with error " + result.errorMessage() + ".", 400);
+ return new AwsException("UserLambdaValidationException",
+ triggerName + " failed with error " + result.errorMessage() + ".", 400);
}
- throw triggerFailure(result, "PreSignUp");
+ return triggerFailure(result, triggerName);
}
/**
diff --git a/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoLambdaTriggersTest.java b/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoLambdaTriggersTest.java
index 782758b10f..2edc9d757c 100644
--- a/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoLambdaTriggersTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoLambdaTriggersTest.java
@@ -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", "[email protected]")));
- 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", "[email protected]")));
+
+ 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", "[email protected]")));
+
+ 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
diff --git a/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoManagedLoginIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoManagedLoginIntegrationTest.java
index e76d922753..e425b9e891 100644
--- a/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoManagedLoginIntegrationTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoManagedLoginIntegrationTest.java
@@ -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"));
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 399da092b1..7639c4a751 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
@@ -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
diff --git a/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoSignInDenialIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoSignInDenialIntegrationTest.java
new file mode 100644
index 0000000000..e1357dd6e6
--- /dev/null
+++ b/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoSignInDenialIntegrationTest.java
@@ -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":"%[email protected]"}]}
+ """.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));
+ }
+}
diff --git a/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoTotpMfaTest.java b/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoTotpMfaTest.java
index 1d19adb07d..2c79ea5ce5 100644
--- a/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoTotpMfaTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoTotpMfaTest.java
@@ -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