Light, fluffy, and always free - The AWS Local Emulator alternative
fix: allow Cognito custom authentication without CreateAuthChallenge (#6410)
Matt Van Horn6256805c3380
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 5fc5d54db7..5ab5275c04 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@@ -42,6 +42,7 @@ import java.util.function.Function;** For CUSTOM_AUTH, dispatches Cognito Lambda triggers* (DefineAuthChallenge, CreateAuthChallenge, VerifyAuthChallengeResponse).+ * CreateAuthChallenge is optional; decision and custom-challenge verification triggers are required.* CUSTOM_AUTH is trigger-driven: if any required trigger is not configured,* invocation fails, or the response is incomplete, authentication fails.*@@ -1579,6 +1580,9 @@ final class CognitoAuthFlowHandler {private Map<String, Object> createAuthChallenge(UserPool pool, UserPoolClient client, CognitoUser user,CustomAuthSession state, String challengeName) {+ if (resolveTriggerArn(pool, "CreateAuthChallenge") == null) {+ return Map.of();+ }Map<String, Object> req = new HashMap<>();req.put("challengeName", challengeName);req.put("session", new ArrayList<>(state.history));diff --git a/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoCustomAuthIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoCustomAuthIntegrationTest.javanew file mode 100644index 0000000000..c21212b884--- /dev/null+++ b/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoCustomAuthIntegrationTest.java@@ -0,0 +1,126 @@+package io.github.hectorvent.floci.services.cognito;++import com.fasterxml.jackson.databind.JsonNode;+import com.fasterxml.jackson.databind.ObjectMapper;+import io.github.hectorvent.floci.services.lambda.LambdaService;+import io.github.hectorvent.floci.services.lambda.model.InvocationType;+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 org.junit.jupiter.api.BeforeAll;+import org.junit.jupiter.params.ParameterizedTest;+import org.junit.jupiter.params.provider.ValueSource;+import org.mockito.ArgumentCaptor;++import java.util.HashMap;+import java.util.List;+import java.util.Map;+import java.util.UUID;++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.endsWith;+import static org.junit.jupiter.api.Assertions.*;+import static org.mockito.ArgumentMatchers.*;+import static org.mockito.Mockito.*;++@QuarkusTest+class CognitoCustomAuthIntegrationTest {+ private static final ObjectMapper MAPPER = new ObjectMapper();++ @InjectMock+ LambdaService lambdaService;++ @BeforeAll+ static void configureRestAssured() {+ RestAssuredJsonUtils.configureAwsContentTypes();+ }++ @ParameterizedTest+ @ValueSource(booleans = {false, true})+ void customAuthWithoutCreateSupportsMultipleRounds(boolean admin) throws Exception {+ String id = UUID.randomUUID().toString();+ String define = "arn:aws:lambda:us-east-1:000000000000:function:define-" + id;+ String verify = "arn:aws:lambda:us-east-1:000000000000:function:verify-" + id;+ String poolId = cognitoJson("CreateUserPool", MAPPER.writeValueAsString(Map.of(+ "PoolName", "custom-auth-" + id,+ "LambdaConfig", Map.of("DefineAuthChallenge", define, "VerifyAuthChallengeResponse", verify))))+ .path("UserPool").path("Id").asText();+ try {+ String clientId = cognitoJson("CreateUserPoolClient", MAPPER.writeValueAsString(Map.of(+ "UserPoolId", poolId, "ClientName", "app", "ExplicitAuthFlows", List.of("ALLOW_CUSTOM_AUTH"))))+ .path("UserPoolClient").path("ClientId").asText();+ cognitoAction("AdminCreateUser", MAPPER.writeValueAsString(Map.of(+ "UserPoolId", poolId, "Username", "alice", "MessageAction", "SUPPRESS")))+ .then().statusCode(200);+ cognitoAction("AdminSetUserPassword", MAPPER.writeValueAsString(Map.of(+ "UserPoolId", poolId, "Username", "alice", "Password", "Perm1234!", "Permanent", true)))+ .then().statusCode(200);+ when(lambdaService.invoke(anyString(), eq(define), any(byte[].class), eq(InvocationType.RequestResponse)))+ .thenReturn(new InvokeResult(200, null, MAPPER.writeValueAsBytes(Map.of(+ "response", Map.of("challengeName", "CUSTOM_CHALLENGE"))), null, "request"))+ .thenReturn(new InvokeResult(200, null, MAPPER.writeValueAsBytes(Map.of(+ "response", Map.of("challengeName", "CUSTOM_CHALLENGE"))), null, "request"))+ .thenReturn(new InvokeResult(200, null, MAPPER.writeValueAsBytes(Map.of(+ "response", Map.of("issueTokens", true))), null, "request"));+ when(lambdaService.invoke(anyString(), eq(verify), any(byte[].class), eq(InvocationType.RequestResponse)))+ .thenReturn(new InvokeResult(200, null, MAPPER.writeValueAsBytes(Map.of(+ "response", Map.of("answerCorrect", true))), null, "request"));++ Map<String, Object> request = new HashMap<>(Map.of(+ "ClientId", clientId, "AuthFlow", "CUSTOM_AUTH", "AuthParameters", Map.of("USERNAME", "alice")));+ if (admin) {+ request.put("UserPoolId", poolId);+ }+ JsonNode started = cognitoJson(admin ? "AdminInitiateAuth" : "InitiateAuth",+ MAPPER.writeValueAsString(request));+ assertEquals("CUSTOM_CHALLENGE", started.path("ChallengeName").asText());+ assertEquals(MAPPER.valueToTree(Map.of("USERNAME", "alice")), started.path("ChallengeParameters"));+ String session = started.path("Session").asText();+ assertFalse(session.isBlank());+ assertFalse(started.has("AuthenticationResult"));+ request.remove("AuthFlow");+ request.remove("AuthParameters");+ request.put("ChallengeName", "CUSTOM_CHALLENGE");+ request.put("ChallengeResponses", Map.of("USERNAME", "alice", "ANSWER", "blue"));+ request.put("Session", session);+ String action = admin ? "AdminRespondToAuthChallenge" : "RespondToAuthChallenge";+ JsonNode next = cognitoJson(action, MAPPER.writeValueAsString(request));+ assertEquals("CUSTOM_CHALLENGE", next.path("ChallengeName").asText());+ assertFalse(next.has("AuthenticationResult"));+ assertEquals(started.path("ChallengeParameters"), next.path("ChallengeParameters"));+ assertFalse(next.path("Session").asText().isBlank());+ assertNotEquals(session, next.path("Session").asText());+ cognitoAction(action, MAPPER.writeValueAsString(request)).then().statusCode(400)+ .body("__type", endsWith("NotAuthorizedException"));+ request.put("Session", next.path("Session").asText());+ JsonNode completed = cognitoJson(action, MAPPER.writeValueAsString(request));+ assertFalse(completed.path("AuthenticationResult").path("AccessToken").asText().isBlank());++ ArgumentCaptor<byte[]> payloads = ArgumentCaptor.forClass(byte[].class);+ verify(lambdaService, times(3)).invoke(anyString(), eq(define), payloads.capture(),+ eq(InvocationType.RequestResponse));+ for (int round = 0; round < 3; round++) {+ JsonNode history = MAPPER.readTree(payloads.getAllValues().get(round)).path("request").path("session");+ assertEquals(round, history.size());+ for (JsonNode entry : history) {+ assertEquals("CUSTOM_CHALLENGE", entry.path("challengeName").asText());+ assertTrue(entry.path("challengeResult").asBoolean());+ }+ }+ ArgumentCaptor<byte[]> answers = ArgumentCaptor.forClass(byte[].class);+ verify(lambdaService, times(2)).invoke(anyString(), eq(verify), answers.capture(),+ eq(InvocationType.RequestResponse));+ for (byte[] payload : answers.getAllValues()) {+ JsonNode triggerRequest = MAPPER.readTree(payload).path("request");+ assertEquals("blue", triggerRequest.path("challengeAnswer").asText());+ assertEquals(MAPPER.createObjectNode(), triggerRequest.path("privateChallengeParameters"));+ }+ verifyNoMoreInteractions(lambdaService);+ } finally {+ cognitoAction("DeleteUserPool", MAPPER.writeValueAsString(Map.of("UserPoolId", poolId)))+ .then().statusCode(200);+ }+ }+}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 24ba68d71b..f059ff7e3a 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@@ -1847,7 +1847,7 @@ class CognitoLambdaTriggersTest {@Test@SuppressWarnings("unchecked")- void verifyAuthChallengeLambdaDecidesCorrectness() {+ void verifyAuthChallengeLambdaDecidesCorrectness() throws Exception {UserPool pool = createPoolWithLambdaConfig(Map.of("DefineAuthChallenge", "arn:aws:lambda:::define","CreateAuthChallenge", "arn:aws:lambda:::create",@@ -1865,7 +1865,7 @@ class CognitoLambdaTriggersTest {ok(Map.of("publicChallengeParameters",Map.of("question", "favourite-colour"),"privateChallengeParameters",- Map.of("answer", "blue"))));+ Map.of("answer", "blue"), "challengeMetadata", "QA-V1")));when(lambdaService.invoke(anyString(), eq("arn:aws:lambda:::verify"), any(byte[].class), any())).thenReturn(ok(Map.of("answerCorrect", true)));@@ -1878,7 +1878,109 @@ class CognitoLambdaTriggersTest {Map.of("USERNAME", "alice", "ANSWER", "anything"));assertNotNull(((Map<String, Object>) tokens.get("AuthenticationResult")).get("AccessToken"));- verify(lambdaService).invoke(anyString(), eq("arn:aws:lambda:::verify"), any(byte[].class), any());+ ArgumentCaptor<byte[]> payload = ArgumentCaptor.forClass(byte[].class);+ verify(lambdaService).invoke(anyString(), eq("arn:aws:lambda:::verify"), payload.capture(), any());+ assertEquals("blue", MAPPER.readTree(payload.getValue()).path("request")+ .path("privateChallengeParameters").path("answer").asText());+ verify(lambdaService, times(2)).invoke(anyString(), eq("arn:aws:lambda:::define"), payload.capture(), any());+ assertEquals("QA-V1", MAPPER.readTree(payload.getValue()).path("request")+ .path("session").get(0).path("challengeMetadata").asText());+ }++ @ParameterizedTest+ @ValueSource(booleans = {false, true})+ void customAuthWithoutCreateMatchesNoOpCreate(boolean configureCreate) throws Exception {+ Map<String, Object> config = new HashMap<>(Map.of(+ "DefineAuthChallenge", "arn:aws:lambda:::define",+ "VerifyAuthChallengeResponse", "arn:aws:lambda:::verify"));+ if (configureCreate) {+ config.put("CreateAuthChallenge", "arn:aws:lambda:::create");+ when(lambdaService.invoke(anyString(), eq("arn:aws:lambda:::create"), any(byte[].class), any()))+ .thenReturn(ok(Map.of()));+ }+ UserPool pool = createPoolWithLambdaConfig(config);+ seedUser(pool, "alice", "Perm1234!");+ UserPoolClient client = createClient(pool);+ 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:::verify"), any(byte[].class), any()))+ .thenReturn(ok(Map.of("answerCorrect", true)));++ Map<String, Object> started = service.initiateAuth(client.getClientId(), "CUSTOM_AUTH",+ Map.of("USERNAME", "alice"));+ assertEquals("CUSTOM_CHALLENGE", started.get("ChallengeName"));+ assertEquals(Map.of("USERNAME", "alice"), started.get("ChallengeParameters"));+ assertFalse(((String) started.get("Session")).isBlank());+ Map<String, Object> completed = service.respondToAuthChallenge(client.getClientId(),+ "CUSTOM_CHALLENGE", (String) started.get("Session"), Map.of("USERNAME", "alice", "ANSWER", "blue"));+ assertTrue(completed.containsKey("AuthenticationResult"));+ ArgumentCaptor<byte[]> payload = ArgumentCaptor.forClass(byte[].class);+ verify(lambdaService).invoke(anyString(), eq("arn:aws:lambda:::verify"), payload.capture(), any());+ JsonNode request = MAPPER.readTree(payload.getValue()).path("request");+ assertEquals("blue", request.path("challengeAnswer").asText());+ assertEquals(MAPPER.createObjectNode(), request.path("privateChallengeParameters"));+ verify(lambdaService, times(configureCreate ? 1 : 0))+ .invoke(anyString(), eq("arn:aws:lambda:::create"), any(byte[].class), any());+ }++ @ParameterizedTest+ @ValueSource(strings = {"lambdaError", "malformed", "invocation"})+ void configuredCreateAuthChallengeFailuresRemainErrors(String failure) {+ UserPool pool = createPoolWithLambdaConfig(Map.of(+ "DefineAuthChallenge", "arn:aws:lambda:::define",+ "CreateAuthChallenge", "arn:aws:lambda:::create"));+ seedUser(pool, "alice", "Perm1234!");+ UserPoolClient client = createClient(pool);+ when(lambdaService.invoke(anyString(), eq("arn:aws:lambda:::define"), any(byte[].class), any()))+ .thenReturn(ok(Map.of("challengeName", "CUSTOM_CHALLENGE")));+ when(lambdaService.invoke(anyString(), eq("arn:aws:lambda:::create"), any(byte[].class), any()))+ .thenAnswer(invocation -> switch (failure) {+ case "lambdaError" -> lambdaError("Unhandled");+ case "malformed" -> rawPayload("{\"response\":\"invalid\"}");+ default -> throw new IllegalStateException("invocation failed");+ });+ AwsException error = assertThrows(AwsException.class, () -> service.initiateAuth(+ client.getClientId(), "CUSTOM_AUTH", Map.of("USERNAME", "alice")));+ assertEquals(switch (failure) {+ case "lambdaError" -> "UserLambdaValidationException";+ case "malformed" -> "InvalidLambdaResponseException";+ default -> "UnexpectedLambdaException";+ }, error.getErrorCode());+ assertEquals(400, error.getHttpStatus());+ }++ @ParameterizedTest+ @ValueSource(strings = {"issueTokens", "failAuthentication", "missingDefine", "missingVerify"})+ void customAuthWithoutCreateRetainsRequiredDecisions(String decision) {+ UserPool pool = createPoolWithLambdaConfig("missingDefine".equals(decision)+ ? Map.of() : Map.of("DefineAuthChallenge", "arn:aws:lambda:::define"));+ seedUser(pool, "alice", "Perm1234!");+ UserPoolClient client = createClient(pool);+ if (!"missingDefine".equals(decision)) {+ when(lambdaService.invoke(anyString(), eq("arn:aws:lambda:::define"), any(byte[].class), any()))+ .thenReturn(ok("missingVerify".equals(decision)+ ? Map.of("challengeName", "CUSTOM_CHALLENGE") : Map.of(decision, true)))+ .thenReturn(ok(Map.of("issueTokens", true)));+ }+ if ("issueTokens".equals(decision)) {+ assertTrue(service.initiateAuth(client.getClientId(), "CUSTOM_AUTH", Map.of("USERNAME", "alice"))+ .containsKey("AuthenticationResult"));+ } else if ("missingVerify".equals(decision)) {+ Map<String, Object> started = service.initiateAuth(client.getClientId(), "CUSTOM_AUTH",+ Map.of("USERNAME", "alice"));+ AwsException error = assertThrows(AwsException.class, () -> service.respondToAuthChallenge(+ client.getClientId(), "CUSTOM_CHALLENGE", (String) started.get("Session"),+ Map.of("USERNAME", "alice", "ANSWER", "blue")));+ assertEquals("InvalidUserPoolConfigurationException", error.getErrorCode());+ verify(lambdaService, times(1)).invoke(anyString(), eq("arn:aws:lambda:::define"),+ any(byte[].class), any());+ } else {+ AwsException error = assertThrows(AwsException.class, () -> service.initiateAuth(+ client.getClientId(), "CUSTOM_AUTH", Map.of("USERNAME", "alice")));+ assertEquals("missingDefine".equals(decision)+ ? "InvalidUserPoolConfigurationException" : "NotAuthorizedException", error.getErrorCode());+ }}private CognitoService serviceWithClock(MutableClock clock) {