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
This commit is contained in:
Priamo Germosen authored and GitHub committed 2026-12-05 19:21:18 -04:00
1 parent 9975577635
commit a9d3f1ecff
3 files changed
+72 -2

No files matched your search

+3 -1
View File
@@ -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).
@@ -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<String> 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<String> 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)) {
@@ -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<String, Object> 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<String, Object> retry = respondToCustomChallenge(pool, client, admin, (String) init.get("Session"), "no");
assertEquals("MY_CHALLENGE", retry.get("ChallengeName"));
Map<String, Object> tokens = respondToCustomChallenge(pool, client, admin, (String) retry.get("Session"), "ok");
assertNotNull(((Map<String, Object>) tokens.get("AuthenticationResult")).get("AccessToken"));
ArgumentCaptor<byte[]> 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<String, Object> respondToCustomChallenge(UserPool pool, UserPoolClient client, boolean admin,
String session, String answer) {
Map<String, String> 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 {