Skip to content

armgit / floci

Public Imported from GitHub
0

Light, fluffy, and always free - The AWS Local Emulator alternative

feat(cognito): fire PostConfirmation and PreSignUp triggers (#859)

Ricardo Medinae1c3f7fcf6c4
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.java
index f2fc0e6596..f16f3e9723 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
@@ -732,6 +732,39 @@ final class CognitoAuthFlowHandler {
invokeTrigger(pool, client, user, "PostAuthentication", "PostAuthentication_Authentication", req);
}
+ void firePostConfirmation(UserPool pool, UserPoolClient client, CognitoUser user,
+ Map<String, String> clientMetadata, String triggerSource) {
+ Map<String, Object> req = new HashMap<>();
+ req.put("clientMetadata", clientMetadata == null ? Map.of() : clientMetadata);
+ // PostConfirmation is fire-and-forget per AWS Cognito semantics:
+ // trigger errors are logged but never block the confirm operation.
+ invokeTrigger(pool, client, user, "PostConfirmation", triggerSource, req);
+ }
+
+ record PreSignUpResponse(boolean autoConfirmUser, boolean autoVerifyEmail, boolean autoVerifyPhone) {
+ static PreSignUpResponse empty() { return new PreSignUpResponse(false, false, false); }
+ }
+
+ PreSignUpResponse firePreSignUp(UserPool pool, UserPoolClient client, CognitoUser user,
+ Map<String, String> validationData,
+ Map<String, String> clientMetadata,
+ String triggerSource) {
+ Map<String, Object> req = new HashMap<>();
+ req.put("validationData", validationData == null ? Map.of() : validationData);
+ req.put("clientMetadata", clientMetadata == null ? Map.of() : clientMetadata);
+ TriggerResult result = invokeTrigger(pool, client, user, "PreSignUp", triggerSource, req);
+ if (result.errored()) {
+ throw new AwsException("NotAuthorizedException",
+ "PreSignUp trigger denied signup: " + result.errorMessage(), 400);
+ }
+ if (!result.configured() || result.response() == null) return PreSignUpResponse.empty();
+ Map<String, Object> resp = result.response();
+ return new PreSignUpResponse(
+ Boolean.TRUE.equals(resp.get("autoConfirmUser")),
+ Boolean.TRUE.equals(resp.get("autoVerifyEmail")),
+ Boolean.TRUE.equals(resp.get("autoVerifyPhone")));
+ }
+
@SuppressWarnings("unchecked")
private CognitoService.ClaimsOverride firePreTokenGeneration(UserPool pool, UserPoolClient client, CognitoUser user,
Map<String, String> clientMetadata, String triggerSource) {
diff --git a/src/main/java/io/github/hectorvent/floci/services/cognito/CognitoService.java b/src/main/java/io/github/hectorvent/floci/services/cognito/CognitoService.java
index 1deec6a196..be3192f5c2 100644
--- a/src/main/java/io/github/hectorvent/floci/services/cognito/CognitoService.java
+++ b/src/main/java/io/github/hectorvent/floci/services/cognito/CognitoService.java
@@ -754,7 +754,7 @@ public class CognitoService {
UserPoolClient client = clientStore.get(clientId)
.orElseThrow(() -> new AwsException("ResourceNotFoundException", "Client not found", 404));
String userPoolId = client.getUserPoolId();
- describeUserPool(userPoolId);
+ UserPool pool = describeUserPool(userPoolId);
String key = userKey(userPoolId, username);
if (userStore.get(key).isPresent()) {
@@ -770,13 +770,34 @@ public class CognitoService {
user.getAttributes().putAll(attributes);
}
- // Ensure sub attribute is present
+ // Ensure sub attribute is present (required by PreSignUp event)
if (!user.getAttributes().containsKey("sub")) {
user.getAttributes().put("sub", UUID.randomUUID().toString());
}
+ // Fire PreSignUp BEFORE persisting — allows the trigger to block signup
+ // (via lambda error) or auto-confirm/auto-verify the user (via response).
+ CognitoAuthFlowHandler.PreSignUpResponse preSignUp = authFlowHandler.firePreSignUp(
+ pool, client, user, Map.of(), Map.of(), "PreSignUp_SignUp");
+ if (preSignUp.autoConfirmUser()) {
+ user.setUserStatus("CONFIRMED");
+ }
+ if (preSignUp.autoVerifyEmail()) {
+ user.getAttributes().put("email_verified", "true");
+ }
+ if (preSignUp.autoVerifyPhone()) {
+ user.getAttributes().put("phone_number_verified", "true");
+ }
+
userStore.put(key, user);
- LOG.infov("Signed up user {0} in pool {1}", username, userPoolId);
+ LOG.infov("Signed up user {0} in pool {1} (status={2})",
+ username, userPoolId, user.getUserStatus());
+
+ // When PreSignUp auto-confirms, AWS Cognito also fires PostConfirmation.
+ // See: docs.aws.amazon.com/cognito/latest/developerguide/user-pool-lambda-pre-sign-up.html
+ if (preSignUp.autoConfirmUser()) {
+ authFlowHandler.firePostConfirmation(pool, client, user, Map.of(), "PostConfirmation_ConfirmSignUp");
+ }
return user;
}
@@ -787,6 +808,10 @@ public class CognitoService {
user.setUserStatus("CONFIRMED");
user.setLastModifiedDate(System.currentTimeMillis() / 1000L);
userStore.put(userKey(client.getUserPoolId(), user.getUsername()), user);
+
+ UserPool pool = poolStore.get(client.getUserPoolId())
+ .orElseThrow(() -> new AwsException("ResourceNotFoundException", "User pool not found", 404));
+ authFlowHandler.firePostConfirmation(pool, client, user, Map.of(), "PostConfirmation_ConfirmSignUp");
}
// ──────────────────────────── Auth ────────────────────────────
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.java
index 59df4d969d..782cbe593a 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
@@ -166,6 +166,167 @@ class CognitoLambdaTriggersTest {
assertNotNull(auth.get("AccessToken"));
}
+ // =========================================================================
+ // PostConfirmation
+ // =========================================================================
+
+ @Test
+ void postConfirmationFiresOnConfirmSignUp() {
+ UserPool pool = createPoolWithLambdaConfig(Map.of("PostConfirmation", "arn:aws:lambda:::post-confirm"));
+ UserPoolClient client = createClient(pool);
+
+ // SignUp creates an UNCONFIRMED user
+ service.signUp(client.getClientId(), "alice", "Perm1234!",
+ Map.of("email", "[email protected]"));
+
+ when(lambdaService.invoke(anyString(), eq("arn:aws:lambda:::post-confirm"),
+ any(byte[].class), eq(InvocationType.RequestResponse)))
+ .thenReturn(ok(Map.of()));
+
+ service.confirmSignUp(client.getClientId(), "alice");
+
+ verify(lambdaService, atLeastOnce())
+ .invoke(anyString(), eq("arn:aws:lambda:::post-confirm"),
+ any(byte[].class), eq(InvocationType.RequestResponse));
+ }
+
+ @Test
+ void postConfirmationLambdaErrorDoesNotBlockConfirm() {
+ UserPool pool = createPoolWithLambdaConfig(Map.of("PostConfirmation", "arn:aws:lambda:::post-confirm"));
+ UserPoolClient client = createClient(pool);
+
+ service.signUp(client.getClientId(), "alice", "Perm1234!",
+ Map.of("email", "[email protected]"));
+
+ when(lambdaService.invoke(anyString(), eq("arn:aws:lambda:::post-confirm"),
+ any(byte[].class), any()))
+ .thenReturn(lambdaError("Unhandled"));
+
+ // confirmSignUp must succeed even if the trigger errors (Cognito semantics)
+ service.confirmSignUp(client.getClientId(), "alice");
+ // Test passes if no exception was thrown.
+ }
+
+ @Test
+ void postConfirmationDoesNotFireWhenNotConfigured() {
+ UserPool pool = createPoolWithLambdaConfig(Map.of());
+ UserPoolClient client = createClient(pool);
+
+ service.signUp(client.getClientId(), "alice", "Perm1234!",
+ Map.of("email", "[email protected]"));
+ service.confirmSignUp(client.getClientId(), "alice");
+
+ verify(lambdaService, never())
+ .invoke(anyString(), anyString(), any(byte[].class), any());
+ }
+
+ // =========================================================================
+ // PreSignUp
+ // =========================================================================
+
+ @Test
+ void preSignUpFiresOnSignUp() {
+ UserPool pool = createPoolWithLambdaConfig(Map.of("PreSignUp", "arn:aws:lambda:::pre-signup"));
+ UserPoolClient client = createClient(pool);
+
+ when(lambdaService.invoke(anyString(), eq("arn:aws:lambda:::pre-signup"),
+ any(byte[].class), eq(InvocationType.RequestResponse)))
+ .thenReturn(ok(Map.of()));
+
+ service.signUp(client.getClientId(), "alice", "Perm1234!",
+ Map.of("email", "[email protected]"));
+
+ verify(lambdaService, atLeastOnce())
+ .invoke(anyString(), eq("arn:aws:lambda:::pre-signup"),
+ any(byte[].class), eq(InvocationType.RequestResponse));
+ }
+
+ @Test
+ void preSignUpLambdaErrorBlocksSignUp() {
+ UserPool pool = createPoolWithLambdaConfig(Map.of("PreSignUp", "arn:aws:lambda:::pre-signup"));
+ UserPoolClient client = createClient(pool);
+
+ when(lambdaService.invoke(anyString(), eq("arn:aws:lambda:::pre-signup"),
+ any(byte[].class), any()))
+ .thenReturn(lambdaError("Unhandled"));
+
+ AwsException ex = assertThrows(AwsException.class, () ->
+ service.signUp(client.getClientId(), "alice", "Perm1234!",
+ Map.of("email", "[email protected]")));
+ assertEquals("NotAuthorizedException", ex.getErrorCode());
+ }
+
+ @Test
+ void preSignUpAutoConfirmUserResponseSkipsConfirmStep() {
+ UserPool pool = createPoolWithLambdaConfig(Map.of("PreSignUp", "arn:aws:lambda:::pre-signup"));
+ UserPoolClient client = createClient(pool);
+
+ when(lambdaService.invoke(anyString(), eq("arn:aws:lambda:::pre-signup"),
+ any(byte[].class), any()))
+ .thenReturn(ok(Map.of(
+ "autoConfirmUser", true,
+ "autoVerifyEmail", true)));
+
+ var user = service.signUp(client.getClientId(), "alice", "Perm1234!",
+ Map.of("email", "[email protected]"));
+
+ assertEquals("CONFIRMED", user.getUserStatus(),
+ "autoConfirmUser=true should set status to CONFIRMED at signup");
+ assertEquals("true", user.getAttributes().get("email_verified"),
+ "autoVerifyEmail=true should set email_verified attribute");
+ }
+
+ @Test
+ void preSignUpAutoVerifyPhoneSetsPhoneVerifiedAttribute() {
+ UserPool pool = createPoolWithLambdaConfig(Map.of("PreSignUp", "arn:aws:lambda:::pre-signup"));
+ UserPoolClient client = createClient(pool);
+
+ when(lambdaService.invoke(anyString(), eq("arn:aws:lambda:::pre-signup"),
+ any(byte[].class), any()))
+ .thenReturn(ok(Map.of("autoVerifyPhone", true)));
+
+ var user = service.signUp(client.getClientId(), "alice", "Perm1234!",
+ Map.of("phone_number", "+15551234567"));
+
+ assertEquals("true", user.getAttributes().get("phone_number_verified"),
+ "autoVerifyPhone=true should set phone_number_verified attribute");
+ }
+
+ @Test
+ void preSignUpAutoConfirmAlsoFiresPostConfirmation() {
+ // AWS docs: when PreSignUp returns autoConfirmUser=true, PostConfirmation is also invoked.
+ UserPool pool = createPoolWithLambdaConfig(Map.of(
+ "PreSignUp", "arn:aws:lambda:::pre-signup",
+ "PostConfirmation", "arn:aws:lambda:::post-confirm"));
+ UserPoolClient client = createClient(pool);
+
+ when(lambdaService.invoke(anyString(), eq("arn:aws:lambda:::pre-signup"),
+ any(byte[].class), any()))
+ .thenReturn(ok(Map.of("autoConfirmUser", true)));
+ when(lambdaService.invoke(anyString(), eq("arn:aws:lambda:::post-confirm"),
+ any(byte[].class), any()))
+ .thenReturn(ok(Map.of()));
+
+ service.signUp(client.getClientId(), "alice", "Perm1234!",
+ Map.of("email", "[email protected]"));
+
+ verify(lambdaService, atLeastOnce())
+ .invoke(anyString(), eq("arn:aws:lambda:::post-confirm"),
+ any(byte[].class), eq(InvocationType.RequestResponse));
+ }
+
+ @Test
+ void preSignUpDoesNotFireWhenNotConfigured() {
+ UserPool pool = createPoolWithLambdaConfig(Map.of());
+ UserPoolClient client = createClient(pool);
+
+ service.signUp(client.getClientId(), "alice", "Perm1234!",
+ Map.of("email", "[email protected]"));
+
+ verify(lambdaService, never())
+ .invoke(anyString(), anyString(), any(byte[].class), any());
+ }
+
// =========================================================================
// PreTokenGeneration
// =========================================================================