Light, fluffy, and always free - The AWS Local Emulator alternative
fix(cognito): fail authentication when token triggers fail (#4727)
Aniket Shukla45b00779b7a3
diff --git a/docs/services/cognito.md b/docs/services/cognito.mdindex 9bb07891d9..7df36bba6b 100644--- a/docs/services/cognito.md+++ b/docs/services/cognito.md@@ -5,6 +5,10 @@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.+`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.* `floci:override-cognito-client-id`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.javaindex eb0538fd04..b64bf480a3 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@@ -1,5 +1,6 @@package io.github.hectorvent.floci.services.cognito;+import com.fasterxml.jackson.core.JsonProcessingException;import com.fasterxml.jackson.core.type.TypeReference;import com.fasterxml.jackson.databind.JsonNode;import com.fasterxml.jackson.databind.ObjectMapper;@@ -1363,9 +1364,21 @@ final class CognitoAuthFlowHandler {return TriggerResult.error(TriggerErrorKind.USER_VALIDATION, errorMessage);}if (result.getPayload() == null || result.getPayload().length == 0) {- return TriggerResult.success(Map.of());+ return TriggerResult.error(TriggerErrorKind.INVALID_RESPONSE,+ triggerKey + " trigger returned an empty response");+ }+ Map<String, Object> parsed;+ try {+ parsed = MAPPER.readValue(result.getPayload(), new TypeReference<>() {});+ } catch (JsonProcessingException e) {+ LOG.debugv(e, "Cognito trigger {0} returned malformed JSON", triggerKey);+ return TriggerResult.error(TriggerErrorKind.INVALID_RESPONSE,+ triggerKey + " trigger returned malformed JSON");+ }+ if (parsed == null) {+ return TriggerResult.error(TriggerErrorKind.INVALID_RESPONSE,+ triggerKey + " trigger returned a non-object response");}- Map<String, Object> parsed = MAPPER.readValue(result.getPayload(), new TypeReference<>() {});Object response = parsed.get("response");if (response != null && !(response instanceof Map<?, ?>)) {return TriggerResult.error(TriggerErrorKind.INVALID_RESPONSE,@@ -1404,14 +1417,7 @@ final class CognitoAuthFlowHandler {triggerName + " trigger is not configured");}if (result.errored()) {- if (result.errorKind() == TriggerErrorKind.USER_VALIDATION) {- throw customAuthTriggerFailure("UserLambdaValidationException",- triggerName + " failed with error " + result.errorMessage());- }- String errorCode = result.errorKind() == TriggerErrorKind.INVALID_RESPONSE- ? "InvalidLambdaResponseException"- : "UnexpectedLambdaException";- throw customAuthTriggerFailure(errorCode, triggerName + " trigger failed: " + result.errorMessage());+ throw triggerFailure(result, triggerName);}if (result.response() == null) {throw customAuthTriggerFailure("InvalidLambdaResponseException",@@ -1420,6 +1426,16 @@ final class CognitoAuthFlowHandler {return result.response();}+ private AwsException triggerFailure(TriggerResult result, String triggerName) {+ if (result.errorKind() == TriggerErrorKind.USER_VALIDATION) {+ return customAuthTriggerFailure("UserLambdaValidationException",+ triggerName + " failed with error " + result.errorMessage());+ }+ String errorCode = result.errorKind() == TriggerErrorKind.INVALID_RESPONSE+ ? "InvalidLambdaResponseException" : "UnexpectedLambdaException";+ return customAuthTriggerFailure(errorCode, triggerName + " trigger failed: " + result.errorMessage());+ }+private AwsException customAuthTriggerFailure(String errorCode, String message) {return new AwsException(errorCode, message, 400);}@@ -1446,7 +1462,11 @@ final class CognitoAuthFlowHandler {Map<String, Object> req = new HashMap<>();req.put("newDeviceUsed", newDeviceUsed);req.put("clientMetadata", clientMetadata == null ? Map.of() : clientMetadata);- invokeTrigger(pool, client, user, "PostAuthentication", "PostAuthentication_Authentication", req);+ TriggerResult result = invokeTrigger(pool, client, user,+ "PostAuthentication", "PostAuthentication_Authentication", req);+ if (result.errored()) {+ throw triggerFailure(result, "PostAuthentication");+ }}void firePostConfirmation(UserPool pool, UserPoolClient client, CognitoUser user,@@ -1486,7 +1506,7 @@ final class CognitoAuthFlowHandler {* Fires the CustomMessage trigger, if configured, so the function can override the* subject/body Cognito would otherwise deliver. Non-blocking: an unconfigured or* failing trigger falls back to the pool's default templated message, mirroring how- * {@link #firePostAuthentication} and {@link #firePostConfirmation} tolerate errors.+ * {@link #firePostConfirmation} tolerates errors.*/Map<String, Object> fireCustomMessage(UserPool pool, UserPoolClient client, CognitoUser user,String triggerSource) {@@ -1515,7 +1535,10 @@ final class CognitoAuthFlowHandler {// the others pass an empty list, which is what the request carries there.req.put("scopes", scopes == null ? List.of() : List.copyOf(scopes));TriggerResult result = invokeTrigger(pool, client, user, "PreTokenGeneration", triggerSource, req);- if (!result.configured() || result.errored()) return null;+ if (!result.configured()) return null;+ if (result.errored()) {+ throw triggerFailure(result, "PreTokenGeneration");+ }Map<String, Object> response = result.response();if (response == null) return null;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.javaindex f7476ffcaa..534929c2f9 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@@ -307,8 +307,7 @@ class CognitoLambdaTriggersTest {}@Test- @SuppressWarnings("unchecked")- void postAuthenticationLambdaErrorDoesNotBlockAuth() {+ void postAuthenticationLambdaErrorBlocksAuth() {UserPool pool = createPoolWithLambdaConfig(Map.of("PostAuthentication", "arn:aws:lambda:::post"));seedUser(pool, "alice", "Perm1234!");UserPoolClient client = createClient(pool);@@ -316,12 +315,10 @@ class CognitoLambdaTriggersTest {when(lambdaService.invoke(anyString(), eq("arn:aws:lambda:::post"), any(byte[].class), any())).thenReturn(lambdaError("Unhandled"));- Map<String, Object> result = service.initiateAuth(client.getClientId(), "USER_PASSWORD_AUTH",- Map.of("USERNAME", "alice", "PASSWORD", "Perm1234!"));-- Map<String, Object> auth = (Map<String, Object>) result.get("AuthenticationResult");- assertNotNull(auth, "Auth should still succeed when PostAuthentication errors");- assertNotNull(auth.get("AccessToken"));+ AwsException error = assertThrows(AwsException.class,+ () -> service.initiateAuth(client.getClientId(), "USER_PASSWORD_AUTH",+ Map.of("USERNAME", "alice", "PASSWORD", "Perm1234!")));+ assertEquals("UserLambdaValidationException", error.getErrorCode());}// =========================================================================@@ -491,6 +488,53 @@ class CognitoLambdaTriggersTest {// PreTokenGeneration// =========================================================================+ @Test+ void preTokenGenerationLambdaErrorBlocksTokenIssuance() {+ UserPool pool = createPoolWithLambdaConfig(Map.of("PreTokenGeneration", "arn:aws:lambda:::pre-token"));+ seedUser(pool, "alice", "Perm1234!");+ UserPoolClient client = createClient(pool);++ when(lambdaService.invoke(anyString(), eq("arn:aws:lambda:::pre-token"), any(byte[].class), any()))+ .thenReturn(lambdaError("Unhandled"));++ AwsException error = assertThrows(AwsException.class,+ () -> service.initiateAuth(client.getClientId(), "USER_PASSWORD_AUTH",+ Map.of("USERNAME", "alice", "PASSWORD", "Perm1234!")));+ assertEquals("UserLambdaValidationException", error.getErrorCode());+ }++ @Test+ void preTokenGenerationMalformedResponseBlocksTokenIssuance() {+ UserPool pool = createPoolWithLambdaConfig(Map.of("PreTokenGeneration", "arn:aws:lambda:::pre-token"));+ seedUser(pool, "alice", "Perm1234!");+ UserPoolClient client = createClient(pool);++ when(lambdaService.invoke(anyString(), eq("arn:aws:lambda:::pre-token"), any(byte[].class), any()))+ .thenReturn(rawPayload("not-json"));++ AwsException error = assertThrows(AwsException.class,+ () -> service.initiateAuth(client.getClientId(), "USER_PASSWORD_AUTH",+ Map.of("USERNAME", "alice", "PASSWORD", "Perm1234!")));+ assertEquals("InvalidLambdaResponseException", error.getErrorCode());+ }++ @ParameterizedTest+ @ValueSource(booleans = {true, false})+ void preTokenGenerationEmptyResponseBlocksTokenIssuance(boolean nullPayload) {+ UserPool pool = createPoolWithLambdaConfig(Map.of("PreTokenGeneration", "arn:aws:lambda:::pre-token"));+ seedUser(pool, "alice", "Perm1234!");+ UserPoolClient client = createClient(pool);++ byte[] payload = nullPayload ? null : new byte[0];+ when(lambdaService.invoke(anyString(), eq("arn:aws:lambda:::pre-token"), any(byte[].class), any()))+ .thenReturn(new InvokeResult(200, null, payload, null, "req-id"));++ AwsException error = assertThrows(AwsException.class,+ () -> service.initiateAuth(client.getClientId(), "USER_PASSWORD_AUTH",+ Map.of("USERNAME", "alice", "PASSWORD", "Perm1234!")));+ assertEquals("InvalidLambdaResponseException", error.getErrorCode());+ }+@Testvoid newPasswordMfaSetupPreservesPreTokenGenerationSource() throws Exception {MutableClock clock = new MutableClock();