Light, fluffy, and always free - The AWS Local Emulator alternative
fix(cognito): align CUSTOM_AUTH trigger failures with AWS behavior (#1484)
shrimptails-f8435357640e2
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 c796c65ab6..3cba441f5b 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@@ -29,9 +29,8 @@ import java.util.concurrent.ConcurrentHashMap;** For CUSTOM_AUTH, dispatches Cognito Lambda triggers* (DefineAuthChallenge, CreateAuthChallenge, VerifyAuthChallengeResponse).- * When a trigger is not configured (or invocation fails), falls back to a- * deterministic stub: single CUSTOM_CHALLENGE round, accept any non-empty- * answer (or match {@code custom:expectedAuthAnswer} attribute if set).+ * CUSTOM_AUTH is trigger-driven: if any required trigger is not configured,+ * invocation fails, or the response is incomplete, authentication fails.** Calls back into {@link CognitoService} for user/pool lookup and token* generation.@@ -485,11 +484,7 @@ final class CognitoAuthFlowHandler {CognitoUser user = service.adminGetUser(pool.getId(), state.username);- Boolean answerCorrect = verifyAuthChallenge(pool, client, user, state, answer);- if (answerCorrect == null) {- String expected = user.getAttributes() == null ? null : user.getAttributes().get("custom:expectedAuthAnswer");- answerCorrect = (expected == null) || expected.equals(answer);- }+ boolean answerCorrect = verifyAuthChallenge(pool, client, user, state, answer);if (!state.history.isEmpty()) {state.history.get(state.history.size() - 1).put("challengeResult", answerCorrect);}@@ -593,21 +588,17 @@ final class CognitoAuthFlowHandler {req.put("session", new ArrayList<>(state.history));req.put("userNotFound", false);req.put("clientMetadata", state.clientMetadata == null ? Map.of() : state.clientMetadata);- Map<String, Object> resp = invokeTrigger(pool, client, user, "DefineAuthChallenge",- "DefineAuthChallenge_Authentication", req).response();- if (resp != null) return resp;-- Map<String, Object> fallback = new HashMap<>();- boolean anyCorrect = state.history.stream().anyMatch(h -> Boolean.TRUE.equals(h.get("challengeResult")));- boolean anyWrong = state.history.stream().anyMatch(h -> Boolean.FALSE.equals(h.get("challengeResult")));- if (anyCorrect) {- fallback.put("issueTokens", true);- } else if (anyWrong && state.history.size() >= 3) {- fallback.put("failAuthentication", true);- } else {- fallback.put("challengeName", "CUSTOM_CHALLENGE");+ Map<String, Object> resp = requireCustomAuthTriggerResponse(+ invokeTrigger(pool, client, user, "DefineAuthChallenge",+ "DefineAuthChallenge_Authentication", req),+ "DefineAuthChallenge");+ if (!resp.containsKey("challengeName")+ && !Boolean.TRUE.equals(resp.get("issueTokens"))+ && !Boolean.TRUE.equals(resp.get("failAuthentication"))) {+ throw customAuthTriggerFailure("InvalidLambdaResponseException",+ "DefineAuthChallenge trigger returned no challenge decision");}- return fallback;+ return resp;}private Map<String, Object> createAuthChallenge(UserPool pool, UserPoolClient client, CognitoUser user,@@ -616,22 +607,29 @@ final class CognitoAuthFlowHandler {req.put("challengeName", challengeName);req.put("session", new ArrayList<>(state.history));req.put("clientMetadata", state.clientMetadata == null ? Map.of() : state.clientMetadata);- return invokeTrigger(pool, client, user, "CreateAuthChallenge",- "CreateAuthChallenge_Authentication", req).response();+ return requireCustomAuthTriggerResponse(+ invokeTrigger(pool, client, user, "CreateAuthChallenge",+ "CreateAuthChallenge_Authentication", req),+ "CreateAuthChallenge");}- private Boolean verifyAuthChallenge(UserPool pool, UserPoolClient client, CognitoUser user,+ private boolean verifyAuthChallenge(UserPool pool, UserPoolClient client, CognitoUser user,CustomAuthSession state, String answer) {Map<String, Object> req = new HashMap<>();req.put("challengeAnswer", answer);req.put("privateChallengeParameters",state.privateChallengeParameters == null ? Map.of() : state.privateChallengeParameters);req.put("clientMetadata", state.clientMetadata == null ? Map.of() : state.clientMetadata);- Map<String, Object> resp = invokeTrigger(pool, client, user, "VerifyAuthChallengeResponse",- "VerifyAuthChallengeResponse_Authentication", req).response();- if (resp == null) return null;+ Map<String, Object> resp = requireCustomAuthTriggerResponse(+ invokeTrigger(pool, client, user, "VerifyAuthChallengeResponse",+ "VerifyAuthChallengeResponse_Authentication", req),+ "VerifyAuthChallengeResponse");Object v = resp.get("answerCorrect");- return v instanceof Boolean b ? b : null;+ if (v instanceof Boolean b) {+ return b;+ }+ throw customAuthTriggerFailure("InvalidLambdaResponseException",+ "VerifyAuthChallengeResponse trigger returned no answerCorrect flag");}private Map<String, Object> applyCreateResponse(CustomAuthSession state, String challengeName,@@ -656,10 +654,24 @@ final class CognitoAuthFlowHandler {return entry;}- private record TriggerResult(Map<String, Object> response, String errorMessage, boolean configured) {- static TriggerResult notConfigured() { return new TriggerResult(null, null, false); }- static TriggerResult success(Map<String, Object> response) { return new TriggerResult(response, null, true); }- static TriggerResult error(String msg) { return new TriggerResult(null, msg, true); }+ private enum TriggerErrorKind {+ NOT_CONFIGURED,+ USER_VALIDATION,+ INVOCATION_FAILED,+ INVALID_RESPONSE+ }++ private record TriggerResult(Map<String, Object> response, String errorMessage, boolean configured,+ TriggerErrorKind errorKind) {+ static TriggerResult notConfigured() {+ return new TriggerResult(null, null, false, TriggerErrorKind.NOT_CONFIGURED);+ }+ static TriggerResult success(Map<String, Object> response) {+ return new TriggerResult(response, null, true, null);+ }+ static TriggerResult error(TriggerErrorKind kind, String msg) {+ return new TriggerResult(null, msg, true, kind);+ }boolean errored() { return configured && errorMessage != null; }}@@ -696,24 +708,54 @@ final class CognitoAuthFlowHandler {String msg = String.format("trigger %s (%s) returned error: %s",triggerKey, functionRef, result.getFunctionError());LOG.warnv("Cognito {0}", msg);- return TriggerResult.error(msg);+ return TriggerResult.error(TriggerErrorKind.USER_VALIDATION, result.getFunctionError());}if (result.getPayload() == null || result.getPayload().length == 0) {return TriggerResult.success(Map.of());}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,+ triggerKey + " trigger returned a non-object response");+ }Map<String, Object> respMap = response instanceof Map<?, ?> m ? (Map<String, Object>) m : Map.of();return TriggerResult.success(respMap);} catch (AwsException ae) {LOG.warnv("Cognito trigger {0} not invokable: {1}", triggerKey, ae.getMessage());- return TriggerResult.error(ae.getMessage());+ return TriggerResult.error(TriggerErrorKind.INVOCATION_FAILED, ae.getMessage());} catch (Exception e) {LOG.warnv(e, "Cognito trigger {0} invocation failed", triggerKey);- return TriggerResult.error(e.getMessage());+ return TriggerResult.error(TriggerErrorKind.INVOCATION_FAILED, e.getMessage());}}+ private Map<String, Object> requireCustomAuthTriggerResponse(TriggerResult result, String triggerName) {+ if (!result.configured()) {+ throw customAuthTriggerFailure("InvalidUserPoolConfigurationException",+ 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());+ }+ if (result.response() == null) {+ throw customAuthTriggerFailure("InvalidLambdaResponseException",+ triggerName + " trigger returned no response");+ }+ return result.response();+ }++ private AwsException customAuthTriggerFailure(String errorCode, String message) {+ return new AwsException(errorCode, message, 400);+ }+// ──────────────────────────── Pre/Post/PreToken/UserMigration ────────────────────────────private void firePreAuthentication(UserPool pool, UserPoolClient client, CognitoUser user,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 315d3526dd..cfa824035b 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@@ -90,6 +90,10 @@ class CognitoLambdaTriggersTest {return new InvokeResult(200, error, new byte[0], null, "req-id");}+ private static InvokeResult rawPayload(String payload) {+ return new InvokeResult(200, null, payload.getBytes(StandardCharsets.UTF_8), null, "req-id");+ }+private static String decodeJwtPayload(String jwt) {return new String(Base64.getUrlDecoder().decode(jwt.split("\\.")[1]), StandardCharsets.UTF_8);}@@ -630,7 +634,8 @@ class CognitoLambdaTriggersTest {void verifyAuthChallengeLambdaDecidesCorrectness() {UserPool pool = createPoolWithLambdaConfig(Map.of("DefineAuthChallenge", "arn:aws:lambda:::define",- "VerifyAuthChallengeResponse", "arn:aws:lambda:::verify"));+ "CreateAuthChallenge", "arn:aws:lambda:::create",+ "VerifyAuthChallengeResponse", "arn:aws:lambda:::verify"));seedUser(pool, "alice", "Perm1234!");UserPoolClient client = createClient(pool);@@ -639,6 +644,12 @@ class CognitoLambdaTriggersTest {when(lambdaService.invoke(anyString(), eq("arn:aws:lambda:::define"), any(byte[].class), any())).thenReturn(ok(Map.of("challengeName", "CUSTOM_CHALLENGE"))).thenReturn(ok(Map.of("issueTokens", true)));+ when(lambdaService.invoke(anyString(), eq("arn:aws:lambda:::create"), any(byte[].class),+ any())).thenReturn(+ ok(Map.of("publicChallengeParameters",+ Map.of("question", "favourite-colour"),+ "privateChallengeParameters",+ Map.of("answer", "blue"))));when(lambdaService.invoke(anyString(), eq("arn:aws:lambda:::verify"), any(byte[].class), any())).thenReturn(ok(Map.of("answerCorrect", true)));@@ -653,4 +664,59 @@ class CognitoLambdaTriggersTest {assertNotNull(((Map<String, Object>) tokens.get("AuthenticationResult")).get("AccessToken"));verify(lambdaService).invoke(anyString(), eq("arn:aws:lambda:::verify"), any(byte[].class), any());}++ @Test+ void customAuthDoesNotIssueTokensWhenVerifyAuthChallengeTriggerErrors() {+ UserPool pool = createPoolWithLambdaConfig(Map.of("DefineAuthChallenge",+ "arn:aws:lambda:::define", "CreateAuthChallenge",+ "arn:aws:lambda:::create", "VerifyAuthChallengeResponse",+ "arn:aws:lambda:::verify"));+ seedUser(pool, "alice", "Perm1234!");+ UserPoolClient client = createClient(pool);++ // First Define call presents a challenge. If the flow incorrectly falls back after+ // verify trigger failure, the second Define call will issue tokens and this test will+ // fail.+ when(lambdaService.invoke(anyString(), eq("arn:aws:lambda:::define"), any(byte[].class),+ any())).thenReturn(ok(Map.of("challengeName", "CUSTOM_CHALLENGE")))+ .thenReturn(ok(Map.of("issueTokens", true)));+ when(lambdaService.invoke(anyString(), eq("arn:aws:lambda:::create"), any(byte[].class),+ any())).thenReturn(+ ok(Map.of("publicChallengeParameters",+ Map.of("question", "favourite-colour"),+ "privateChallengeParameters",+ Map.of("answer", "blue"))));+ when(lambdaService.invoke(anyString(), eq("arn:aws:lambda:::verify"), any(byte[].class),+ any())).thenReturn(lambdaError("Unhandled"));++ Map<String, Object> initResult = service.initiateAuth(client.getClientId(),+ "CUSTOM_AUTH", Map.of("USERNAME", "alice"));+ String session = (String) initResult.get("Session");++ AwsException ex = assertThrows(AwsException.class,+ () -> service.respondToAuthChallenge(client.getClientId(),+ "CUSTOM_CHALLENGE", session,+ Map.of("USERNAME", "alice", "ANSWER", "anything")));++ assertEquals("UserLambdaValidationException", ex.getErrorCode());+ assertEquals("VerifyAuthChallengeResponse failed with error Unhandled", ex.getMessage());+ }++ @Test+ void customAuthFailsWhenTriggerReturnsNonObjectResponse() {+ UserPool pool = createPoolWithLambdaConfig(Map.of("DefineAuthChallenge", "arn:aws:lambda:::define"));+ seedUser(pool, "alice", "Perm1234!");+ UserPoolClient client = createClient(pool);++ when(lambdaService.invoke(anyString(), eq("arn:aws:lambda:::define"), any(byte[].class),+ any())).thenReturn(rawPayload("{\"response\":\"not-an-object\"}"));++ AwsException ex = assertThrows(AwsException.class,+ () -> service.initiateAuth(client.getClientId(),+ "CUSTOM_AUTH", Map.of("USERNAME", "alice")));++ assertEquals("InvalidLambdaResponseException", ex.getErrorCode());+ assertEquals("DefineAuthChallenge trigger failed: DefineAuthChallenge trigger returned a non-object response",+ ex.getMessage());+ }}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.javaindex c2d515ddc3..150f004733 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@@ -1642,91 +1642,31 @@ class CognitoServiceTest {}// =========================================================================- // CUSTOM_AUTH flow (no Lambda triggers — falls back to deterministic stub)+ // CUSTOM_AUTH flow (requires Lambda triggers)// =========================================================================@Test- @SuppressWarnings("unchecked")- void customAuthInitiateReturnsCustomChallenge() {- UserPool pool = createPoolAndUser();- UserPoolClient client = service.createUserPoolClient(- pool.getId(), "c", false, false, List.of(), List.of());-- Map<String, Object> result = service.initiateAuth(client.getClientId(), "CUSTOM_AUTH",- Map.of("USERNAME", "alice", "CHALLENGE_NAME", "SRP_A"));-- assertEquals("CUSTOM_CHALLENGE", result.get("ChallengeName"));- assertNotNull(result.get("Session"));- Map<String, String> params = (Map<String, String>) result.get("ChallengeParameters");- assertEquals("alice", params.get("USERNAME"));- assertEquals("SRP_A", params.get("CHALLENGE_NAME"),- "InitiateAuth-supplied metadata should pass through to ChallengeParameters");- }-- @Test- @SuppressWarnings("unchecked")- void customAuthAcceptsAnyAnswerWhenNoExpectedAttribute() {+ void customAuthInitiateFailsWhenDefineTriggerIsMissing() {UserPool pool = createPoolAndUser();UserPoolClient client = service.createUserPoolClient(pool.getId(), "c", false, false, List.of(), List.of());- Map<String, Object> initResult = service.initiateAuth(client.getClientId(), "CUSTOM_AUTH",- Map.of("USERNAME", "alice"));- String session = (String) initResult.get("Session");-- Map<String, Object> tokenResult = service.respondToAuthChallenge(- client.getClientId(), "CUSTOM_CHALLENGE", session,- Map.of("USERNAME", "alice", "ANSWER", "any-non-empty-answer"));-- Map<String, Object> auth = (Map<String, Object>) tokenResult.get("AuthenticationResult");- assertNotNull(auth, "AuthenticationResult should be present after correct answer");- assertNotNull(auth.get("AccessToken"));- assertNotNull(auth.get("RefreshToken"));- }-- @Test- void customAuthRejectsWhenAnswerDoesNotMatchExpectedAttribute() {- UserPool pool = createPoolAndUser();- // Stamp an expected answer attribute on the user- service.adminUpdateUserAttributes(pool.getId(), "alice",- Map.of("custom:expectedAuthAnswer", "secret-otp"));- UserPoolClient client = service.createUserPoolClient(- pool.getId(), "c", false, false, List.of(), List.of());-- Map<String, Object> initResult = service.initiateAuth(client.getClientId(), "CUSTOM_AUTH",- Map.of("USERNAME", "alice"));- String session = (String) initResult.get("Session");-- // First wrong attempt — flow should request another challenge, not fail outright- Map<String, Object> retryResult = service.respondToAuthChallenge(- client.getClientId(), "CUSTOM_CHALLENGE", session,- Map.of("USERNAME", "alice", "ANSWER", "wrong"));- assertEquals("CUSTOM_CHALLENGE", retryResult.get("ChallengeName"));- String session2 = (String) retryResult.get("Session");-- // Eventually correct answer issues tokens- Map<String, Object> tokenResult = service.respondToAuthChallenge(- client.getClientId(), "CUSTOM_CHALLENGE", session2,- Map.of("USERNAME", "alice", "ANSWER", "secret-otp"));- @SuppressWarnings("unchecked")- Map<String, Object> auth = (Map<String, Object>) tokenResult.get("AuthenticationResult");- assertNotNull(auth);- assertNotNull(auth.get("AccessToken"));+ AwsException ex = assertThrows(AwsException.class, () ->+ service.initiateAuth(client.getClientId(), "CUSTOM_AUTH",+ Map.of("USERNAME", "alice", "CHALLENGE_NAME", "SRP_A")));+ assertEquals("InvalidUserPoolConfigurationException", ex.getErrorCode());}@Test- void customAuthRequiresNonEmptyAnswer() {+ void customAuthRejectsWhenNoLambdaTriggersAreConfigured() {UserPool pool = createPoolAndUser();UserPoolClient client = service.createUserPoolClient(pool.getId(), "c", false, false, List.of(), List.of());- Map<String, Object> initResult = service.initiateAuth(client.getClientId(), "CUSTOM_AUTH",- Map.of("USERNAME", "alice"));- String session = (String) initResult.get("Session");AwsException ex = assertThrows(AwsException.class, () ->- service.respondToAuthChallenge(client.getClientId(), "CUSTOM_CHALLENGE", session,- Map.of("USERNAME", "alice", "ANSWER", "")));- assertEquals("InvalidParameterException", ex.getErrorCode());+ service.initiateAuth(client.getClientId(), "CUSTOM_AUTH",+ Map.of("USERNAME", "alice")));+ assertEquals("InvalidUserPoolConfigurationException", ex.getErrorCode());}@Test