From a9d3f1ecffd024fe0bf8a7994e95d8caa9f92465 Mon Sep 17 00:00:00 2001 From: Priamo Germosen <6233424+pgermosen@users.noreply.github.com> Date: Sat, 5 Dec 2026 19:21:18 -0400 Subject: [PATCH] fix(cognito): accept a CUSTOM_CHALLENGE answer to a challenge DefineAuthChallenge named (#10269) RespondToAuthChallenge takes only ChallengeNameType values, so a challenge DefineAuthChallenge names otherwise, such as MY_CHALLENGE, is answered with CUSTOM_CHALLENGE, as on AWS. The custom session check compared the answer with the trigger's name and refused it with Invalid session for the user. Compare it with the name the challenge is answered as; the responses and the session history keep the trigger's name. Closes #7678 --- docs/services/cognito.md | 4 +- .../cognito/CognitoAuthFlowHandler.java | 21 +++++++- .../cognito/CognitoLambdaTriggersTest.java | 49 +++++++++++++++++++ 3 files changed, 72 insertions(+), 2 deletions(-) diff --git a/docs/services/cognito.md b/docs/services/cognito.md index 0025c1d9be..df687e607c 100644 --- a/docs/services/cognito.md +++ b/docs/services/cognito.md @@ -607,7 +607,9 @@ DefineAuthChallenge history with `SRP_A=true`, issues a real `PASSWORD_VERIFIER` and verifies the SRP proof before returning to the trigger's custom challenges. Temporary-password users complete `NEW_PASSWORD_REQUIRED` within the same custom sequence. Each response must match the issued session's client, user and challenge; sessions are consumed once. Plain custom -challenges remain supported. `RESET_REQUIRED` still requires password recovery first because +challenges remain supported. A challenge name DefineAuthChallenge returns outside the +`ChallengeNameType` values, such as `MY_CHALLENGE`, is answered with `CUSTOM_CHALLENGE`, as on AWS; +the challenge responses and the trigger's session history keep the trigger's name. `RESET_REQUIRED` still requires password recovery first because Floci clears the SRP verifier when an administrator resets the password. See [AWS's custom SRP sequence](https://docs.aws.amazon.com/cognito/latest/developerguide/user-pool-lambda-challenge.html#user-pool-lambda-challenge-srp-authentication). diff --git a/src/main/java/io/floci/aws/services/cognito/CognitoAuthFlowHandler.java b/src/main/java/io/floci/aws/services/cognito/CognitoAuthFlowHandler.java index eeb1b290ce..ff6de2d8bd 100644 --- a/src/main/java/io/floci/aws/services/cognito/CognitoAuthFlowHandler.java +++ b/src/main/java/io/floci/aws/services/cognito/CognitoAuthFlowHandler.java @@ -36,6 +36,7 @@ import java.util.List; import java.util.Map; import java.util.Objects; import java.util.OptionalLong; +import java.util.Set; import java.util.UUID; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ThreadLocalRandom; @@ -72,6 +73,11 @@ final class CognitoAuthFlowHandler { private static final List PREFERRED_CHALLENGES = List.of("PASSWORD", "PASSWORD_SRP", "SMS_OTP", "EMAIL_OTP", "WEB_AUTHN"); private static final String CODE_MISMATCH = "Invalid verification code provided, please try again."; + /** The {@code ChallengeNameType} enum of the Cognito model, the names RespondToAuthChallenge accepts. */ + private static final Set CHALLENGE_NAME_TYPES = Set.of("SMS_MFA", "EMAIL_OTP", "SOFTWARE_TOKEN_MFA", + "SELECT_MFA_TYPE", "MFA_SETUP", "PASSWORD_VERIFIER", "CUSTOM_CHALLENGE", "SELECT_CHALLENGE", + "DEVICE_SRP_AUTH", "DEVICE_PASSWORD_VERIFIER", "ADMIN_NO_SRP_AUTH", "NEW_PASSWORD_REQUIRED", "SMS_OTP", + "PASSWORD", "WEB_AUTHN", "PASSWORD_SRP"); private static final String MANAGED_LOGIN_NEW_PASSWORD = "This user must set a new password, which this " + "sign-in page does not support. Set a permanent password with AdminSetUserPassword."; @@ -1760,12 +1766,25 @@ final class CognitoAuthFlowHandler { } CustomAuthSession state = token.state(); if (!state.userPoolId.equals(pool.getId()) || !state.clientId.equals(client.getClientId()) - || !challengeName.equals(state.currentChallengeName)) { + || !challengeName.equals(answeredAs(state.currentChallengeName))) { throw new AwsException("NotAuthorizedException", "Invalid session for the user.", 400); } return state; } + /** + * The {@code ChallengeName} that answers a custom auth session's current challenge. DefineAuthChallenge can + * name the challenge anything, but RespondToAuthChallenge takes only {@code ChallengeNameType} values, so a name + * outside them labels a custom challenge, answered as {@code CUSTOM_CHALLENGE}; the label is what the session's + * history and the next challenge response carry. + */ + private static String answeredAs(String challengeName) { + if (challengeName == null || CHALLENGE_NAME_TYPES.contains(challengeName)) { + return challengeName; + } + return "CUSTOM_CHALLENGE"; + } + private void consumeCustomSession(String session, CustomAuthSession state) { CustomAuthToken token = customAuthSessions.get(session); if (token == null || token.state() != state || !customAuthSessions.remove(session, token)) { diff --git a/src/test/java/io/floci/aws/services/cognito/CognitoLambdaTriggersTest.java b/src/test/java/io/floci/aws/services/cognito/CognitoLambdaTriggersTest.java index 3150f631bd..82ad0fd34f 100644 --- a/src/test/java/io/floci/aws/services/cognito/CognitoLambdaTriggersTest.java +++ b/src/test/java/io/floci/aws/services/cognito/CognitoLambdaTriggersTest.java @@ -2091,6 +2091,55 @@ class CognitoLambdaTriggersTest { .path("session").get(0).path("challengeMetadata").asString()); } + @ParameterizedTest + @ValueSource(booleans = {false, true}) + @SuppressWarnings("unchecked") + void aChallengeDefineAuthChallengeNamesIsAnsweredAsCustomChallenge(boolean admin) throws Exception { + 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); + when(lambdaService.invoke(anyString(), eq("arn:aws:lambda:::define"), any(byte[].class), any())) + .thenReturn(ok(Map.of("challengeName", "MY_CHALLENGE"))) + .thenReturn(ok(Map.of("challengeName", "MY_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", "q"), + "privateChallengeParameters", Map.of("answer", "ok")))); + when(lambdaService.invoke(anyString(), eq("arn:aws:lambda:::verify"), any(byte[].class), any())) + .thenReturn(ok(Map.of("answerCorrect", false))) + .thenReturn(ok(Map.of("answerCorrect", true))); + Map init = admin + ? service.adminInitiateAuth(pool.getId(), client.getClientId(), "CUSTOM_AUTH", + Map.of("USERNAME", "alice")) + : service.initiateAuth(client.getClientId(), "CUSTOM_AUTH", Map.of("USERNAME", "alice")); + assertEquals("MY_CHALLENGE", init.get("ChallengeName")); + + Map retry = respondToCustomChallenge(pool, client, admin, (String) init.get("Session"), "no"); + assertEquals("MY_CHALLENGE", retry.get("ChallengeName")); + Map tokens = respondToCustomChallenge(pool, client, admin, (String) retry.get("Session"), "ok"); + + assertNotNull(((Map) tokens.get("AuthenticationResult")).get("AccessToken")); + ArgumentCaptor payload = ArgumentCaptor.forClass(byte[].class); + verify(lambdaService, times(3)).invoke(anyString(), eq("arn:aws:lambda:::define"), payload.capture(), any()); + JsonNode session = MAPPER.readTree(payload.getValue()).path("request").path("session"); + assertEquals("MY_CHALLENGE", session.get(0).path("challengeName").asString()); + assertFalse(session.get(0).path("challengeResult").asBoolean()); + assertEquals("MY_CHALLENGE", session.get(1).path("challengeName").asString()); + assertTrue(session.get(1).path("challengeResult").asBoolean()); + } + + private Map respondToCustomChallenge(UserPool pool, UserPoolClient client, boolean admin, + String session, String answer) { + Map responses = Map.of("USERNAME", "alice", "ANSWER", answer); + return admin + ? service.adminRespondToAuthChallenge(pool.getId(), client.getClientId(), "CUSTOM_CHALLENGE", + session, responses) + : service.respondToAuthChallenge(client.getClientId(), "CUSTOM_CHALLENGE", session, responses); + } + @ParameterizedTest @ValueSource(booleans = {false, true}) void customAuthWithoutCreateMatchesNoOpCreate(boolean configureCreate) throws Exception {