fix(cognito): align CUSTOM_AUTH trigger failures with AWS behavior (#1484)

* fix(cognito): align CUSTOM_AUTH trigger failures with AWS behavior

* fix(cognito): align custom auth trigger error mapping with AWS
This commit is contained in:
shrimptails-f authored and GitHub committed 2026-06-25 20:05:11 -05:00
1 parent 86c4aae2e2
commit 8435357640
3 files changed
+162 -114

No files matched your search

@@ -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());
}
}
@@ -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() {
void customAuthInitiateFailsWhenDefineTriggerIsMissing() {
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() {
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"));
}
@Test
void customAuthRequiresNonEmptyAnswer() {
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", "CHALLENGE_NAME", "SRP_A")));
assertEquals("InvalidUserPoolConfigurationException", ex.getErrorCode());
}
@Test
void customAuthRejectsWhenNoLambdaTriggersAreConfigured() {
UserPool pool = createPoolAndUser();
UserPoolClient client = service.createUserPoolClient(
pool.getId(), "c", false, false, List.of(), List.of());
AwsException ex = assertThrows(AwsException.class, () ->
service.initiateAuth(client.getClientId(), "CUSTOM_AUTH",
Map.of("USERNAME", "alice")));
assertEquals("InvalidUserPoolConfigurationException", ex.getErrorCode());
}
@Test