mirror of
https://github.com/floci-io/floci.git
synced 2026-11-22 21:50:46 -05:00
fix(cognito): align pre-authentication trigger events and errors (#3861)
* fix(cognito): include user status in pre-authentication events * fix(cognito): preserve pre-authentication trigger errors * fix(cognito): constrain pre-authentication payload handling --------- Co-authored-by: xujiantop-crypto <265865031+xujiantop-crypto@users.noreply.github.com>
This commit is contained in:
1 parent
5ec3fb67a8
commit
172bfb32b0
2 files changed
+132
-8
No files matched your search
+29
-4
@@ -1,6 +1,7 @@
|
||||
package io.github.hectorvent.floci.services.cognito;
|
||||
|
||||
import com.fasterxml.jackson.core.type.TypeReference;
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import io.github.hectorvent.floci.core.common.AwsArnUtils;
|
||||
import io.github.hectorvent.floci.core.common.AwsException;
|
||||
@@ -737,7 +738,14 @@ final class CognitoAuthFlowHandler {
|
||||
event.put("triggerSource", triggerSource);
|
||||
Map<String, Object> req = new HashMap<>(request);
|
||||
if (user != null) {
|
||||
req.put("userAttributes", user.getAttributes() == null ? Map.of() : user.getAttributes());
|
||||
Map<String, String> userAttributes = new LinkedHashMap<>();
|
||||
if (user.getAttributes() != null) {
|
||||
userAttributes.putAll(user.getAttributes());
|
||||
}
|
||||
if ("PreAuthentication".equals(triggerKey)) {
|
||||
userAttributes.put("cognito:user_status", user.getUserStatus());
|
||||
}
|
||||
req.put("userAttributes", userAttributes);
|
||||
}
|
||||
event.put("request", req);
|
||||
event.put("response", new HashMap<>());
|
||||
@@ -746,10 +754,11 @@ final class CognitoAuthFlowHandler {
|
||||
byte[] payload = MAPPER.writeValueAsBytes(event);
|
||||
InvokeResult result = lambdaService.invoke(region, functionRef, payload, InvocationType.RequestResponse);
|
||||
if (result.getFunctionError() != null) {
|
||||
String errorMessage = lambdaFunctionErrorMessage(result);
|
||||
String msg = String.format("trigger %s (%s) returned error: %s",
|
||||
triggerKey, functionRef, result.getFunctionError());
|
||||
triggerKey, functionRef, errorMessage);
|
||||
LOG.warnv("Cognito {0}", msg);
|
||||
return TriggerResult.error(TriggerErrorKind.USER_VALIDATION, result.getFunctionError());
|
||||
return TriggerResult.error(TriggerErrorKind.USER_VALIDATION, errorMessage);
|
||||
}
|
||||
if (result.getPayload() == null || result.getPayload().length == 0) {
|
||||
return TriggerResult.success(Map.of());
|
||||
@@ -771,6 +780,22 @@ final class CognitoAuthFlowHandler {
|
||||
}
|
||||
}
|
||||
|
||||
private static String lambdaFunctionErrorMessage(InvokeResult result) {
|
||||
byte[] payload = result.getPayload();
|
||||
if (payload == null || payload.length == 0) {
|
||||
return result.getFunctionError();
|
||||
}
|
||||
try {
|
||||
JsonNode errorMessage = MAPPER.readTree(payload).path("errorMessage");
|
||||
if (errorMessage.isTextual() && !errorMessage.asText().isBlank()) {
|
||||
return errorMessage.asText();
|
||||
}
|
||||
} catch (Exception e) {
|
||||
LOG.debugv(e, "Unable to parse Cognito Lambda function error payload");
|
||||
}
|
||||
return result.getFunctionError();
|
||||
}
|
||||
|
||||
private Map<String, Object> requireCustomAuthTriggerResponse(TriggerResult result, String triggerName) {
|
||||
if (!result.configured()) {
|
||||
throw customAuthTriggerFailure("InvalidUserPoolConfigurationException",
|
||||
@@ -810,7 +835,7 @@ final class CognitoAuthFlowHandler {
|
||||
"PreAuthentication", "PreAuthentication_Authentication", req);
|
||||
if (result.errored()) {
|
||||
throw new AwsException("NotAuthorizedException",
|
||||
"PreAuthentication trigger denied authentication: " + result.errorMessage(), 400);
|
||||
"PreAuthentication failed with error " + result.errorMessage() + ".", 400);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+103
-4
@@ -20,6 +20,9 @@ import io.github.hectorvent.floci.services.ses.SesService;
|
||||
import io.github.hectorvent.floci.services.sns.SnsService;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.NullAndEmptySource;
|
||||
import org.junit.jupiter.params.provider.ValueSource;
|
||||
import org.mockito.ArgumentCaptor;
|
||||
|
||||
import javax.crypto.Mac;
|
||||
@@ -31,6 +34,7 @@ import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertNotEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertNotNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertNull;
|
||||
@@ -119,6 +123,17 @@ class CognitoLambdaTriggersTest {
|
||||
return new InvokeResult(200, error, new byte[0], null, "req-id");
|
||||
}
|
||||
|
||||
private static InvokeResult lambdaError(String error, String errorMessage) {
|
||||
try {
|
||||
byte[] payload = MAPPER.writeValueAsBytes(Map.of(
|
||||
"errorType", "Error",
|
||||
"errorMessage", errorMessage));
|
||||
return new InvokeResult(200, error, payload, null, "req-id");
|
||||
} catch (Exception e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
}
|
||||
|
||||
private static InvokeResult rawPayload(String payload) {
|
||||
return new InvokeResult(200, null, payload.getBytes(StandardCharsets.UTF_8), null, "req-id");
|
||||
}
|
||||
@@ -147,6 +162,40 @@ class CognitoLambdaTriggersTest {
|
||||
.invoke(anyString(), eq("arn:aws:lambda:::pre"), any(byte[].class), eq(InvocationType.RequestResponse));
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(booleans = {false, true})
|
||||
void preAuthenticationIncludesCognitoUserStatusAttribute(boolean adminAuth) throws Exception {
|
||||
UserPool pool = createPoolWithLambdaConfig(Map.of("PreAuthentication", "arn:aws:lambda:::pre"));
|
||||
seedUser(pool, "alice", "Perm1234!");
|
||||
UserPoolClient client = createClient(pool);
|
||||
|
||||
when(lambdaService.invoke(anyString(), eq("arn:aws:lambda:::pre"), any(byte[].class),
|
||||
eq(InvocationType.RequestResponse)))
|
||||
.thenReturn(ok(Map.of()));
|
||||
|
||||
if (adminAuth) {
|
||||
service.adminInitiateAuth(pool.getId(), client.getClientId(), "ADMIN_USER_PASSWORD_AUTH",
|
||||
Map.of("USERNAME", "alice", "PASSWORD", "Perm1234!"));
|
||||
} else {
|
||||
service.initiateAuth(client.getClientId(), "USER_PASSWORD_AUTH",
|
||||
Map.of("USERNAME", "alice", "PASSWORD", "Perm1234!"));
|
||||
}
|
||||
|
||||
ArgumentCaptor<byte[]> payloadCaptor = ArgumentCaptor.forClass(byte[].class);
|
||||
verify(lambdaService).invoke(anyString(), eq("arn:aws:lambda:::pre"), payloadCaptor.capture(),
|
||||
eq(InvocationType.RequestResponse));
|
||||
|
||||
Map<String, Object> event = MAPPER.readValue(payloadCaptor.getValue(), new TypeReference<>() {});
|
||||
@SuppressWarnings("unchecked")
|
||||
Map<String, Object> request = (Map<String, Object>) event.get("request");
|
||||
@SuppressWarnings("unchecked")
|
||||
Map<String, Object> userAttributes = (Map<String, Object>) request.get("userAttributes");
|
||||
assertEquals("CONFIRMED", userAttributes.get("cognito:user_status"));
|
||||
assertEquals("alice@example.com", userAttributes.get("email"));
|
||||
assertFalse(service.adminGetUser(pool.getId(), "alice").getAttributes()
|
||||
.containsKey("cognito:user_status"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void preAuthenticationLambdaErrorBlocksAuthentication() {
|
||||
UserPool pool = createPoolWithLambdaConfig(Map.of("PreAuthentication", "arn:aws:lambda:::pre"));
|
||||
@@ -160,6 +209,54 @@ class CognitoLambdaTriggersTest {
|
||||
service.initiateAuth(client.getClientId(), "USER_PASSWORD_AUTH",
|
||||
Map.of("USERNAME", "alice", "PASSWORD", "Perm1234!")));
|
||||
assertEquals("NotAuthorizedException", ex.getErrorCode());
|
||||
assertEquals("PreAuthentication failed with error Unhandled.", ex.getMessage());
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(booleans = {false, true})
|
||||
void preAuthenticationLambdaErrorPreservesThrownMessage(boolean adminAuth) {
|
||||
UserPool pool = createPoolWithLambdaConfig(Map.of("PreAuthentication", "arn:aws:lambda:::pre"));
|
||||
seedUser(pool, "alice", "Perm1234!");
|
||||
UserPoolClient client = createClient(pool);
|
||||
|
||||
when(lambdaService.invoke(anyString(), eq("arn:aws:lambda:::pre"), any(byte[].class), any()))
|
||||
.thenReturn(lambdaError("Unhandled", "Email not verified"));
|
||||
|
||||
AwsException ex = assertThrows(AwsException.class, () -> {
|
||||
if (adminAuth) {
|
||||
service.adminInitiateAuth(pool.getId(), client.getClientId(), "ADMIN_USER_PASSWORD_AUTH",
|
||||
Map.of("USERNAME", "alice", "PASSWORD", "Perm1234!"));
|
||||
} else {
|
||||
service.initiateAuth(client.getClientId(), "USER_PASSWORD_AUTH",
|
||||
Map.of("USERNAME", "alice", "PASSWORD", "Perm1234!"));
|
||||
}
|
||||
});
|
||||
|
||||
assertEquals("NotAuthorizedException", ex.getErrorCode());
|
||||
assertEquals("PreAuthentication failed with error Email not verified.", ex.getMessage());
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@NullAndEmptySource
|
||||
@ValueSource(strings = {"not-json", "{}", "{\"errorMessage\":null}",
|
||||
"{\"errorMessage\":\"\"}", "{\"errorMessage\":\" \"}",
|
||||
"{\"errorMessage\":123}", "{\"errorMessage\":true}",
|
||||
"{\"errorMessage\":[]}", "{\"errorMessage\":{}}"})
|
||||
void preAuthenticationLambdaErrorFallsBackWithoutUsableMessage(String errorPayload) {
|
||||
UserPool pool = createPoolWithLambdaConfig(Map.of("PreAuthentication", "arn:aws:lambda:::pre"));
|
||||
seedUser(pool, "alice", "Perm1234!");
|
||||
UserPoolClient client = createClient(pool);
|
||||
byte[] payload = errorPayload == null ? null : errorPayload.getBytes(StandardCharsets.UTF_8);
|
||||
|
||||
when(lambdaService.invoke(anyString(), eq("arn:aws:lambda:::pre"), any(byte[].class), any()))
|
||||
.thenReturn(new InvokeResult(200, "Unhandled", payload, null, "req-id"));
|
||||
|
||||
AwsException ex = assertThrows(AwsException.class, () ->
|
||||
service.initiateAuth(client.getClientId(), "USER_PASSWORD_AUTH",
|
||||
Map.of("USERNAME", "alice", "PASSWORD", "Perm1234!")));
|
||||
|
||||
assertEquals("NotAuthorizedException", ex.getErrorCode());
|
||||
assertEquals("PreAuthentication failed with error Unhandled.", ex.getMessage());
|
||||
}
|
||||
|
||||
// =========================================================================
|
||||
@@ -259,7 +356,7 @@ class CognitoLambdaTriggersTest {
|
||||
// =========================================================================
|
||||
|
||||
@Test
|
||||
void preSignUpFiresOnSignUp() {
|
||||
void preSignUpFiresOnSignUp() throws Exception {
|
||||
UserPool pool = createPoolWithLambdaConfig(Map.of("PreSignUp", "arn:aws:lambda:::pre-signup"));
|
||||
UserPoolClient client = createClient(pool);
|
||||
|
||||
@@ -270,9 +367,11 @@ class CognitoLambdaTriggersTest {
|
||||
service.signUp(client.getClientId(), "alice", "Perm1234!",
|
||||
Map.of("email", "alice@example.com"));
|
||||
|
||||
verify(lambdaService, atLeastOnce())
|
||||
.invoke(anyString(), eq("arn:aws:lambda:::pre-signup"),
|
||||
any(byte[].class), eq(InvocationType.RequestResponse));
|
||||
ArgumentCaptor<byte[]> payloadCaptor = ArgumentCaptor.forClass(byte[].class);
|
||||
verify(lambdaService).invoke(anyString(), eq("arn:aws:lambda:::pre-signup"),
|
||||
payloadCaptor.capture(), eq(InvocationType.RequestResponse));
|
||||
assertFalse(MAPPER.readTree(payloadCaptor.getValue()).path("request")
|
||||
.path("userAttributes").has("cognito:user_status"));
|
||||
}
|
||||
|
||||
@Test
|
||||
|
||||
Reference in new issue
Block a user