mirror of
https://github.com/floci-io/floci.git
synced 2026-11-22 21:50:46 -05:00
fix(cognito): invoke the CustomMessage Lambda trigger before delivering verification emails (#3140)
SignUp, ResendConfirmationCode and ForgotPassword now call the pool's CustomMessage trigger and use its emailSubject/emailMessage/smsMessage response instead of the default template. Non-blocking on trigger failure. Signed-off-by: Matheus Oliveira <matheus.6148@gmail.com>
This commit is contained in:
1 parent
121a9292b7
commit
148ec839bd
5 files changed
+287
-35
No files matched your search
@@ -41,6 +41,7 @@ final class CognitoAuthFlowHandler {
|
||||
|
||||
private static final Logger LOG = Logger.getLogger(CognitoAuthFlowHandler.class);
|
||||
private static final ObjectMapper MAPPER = new ObjectMapper();
|
||||
private static final String CUSTOM_MESSAGE_CODE_PARAMETER = "{####}";
|
||||
|
||||
private final CognitoService service;
|
||||
private final LambdaService lambdaService;
|
||||
@@ -854,6 +855,28 @@ final class CognitoAuthFlowHandler {
|
||||
Boolean.TRUE.equals(resp.get("autoVerifyPhone")));
|
||||
}
|
||||
|
||||
/**
|
||||
* Fires the CustomMessage trigger, if configured, so the function can override the
|
||||
* subject/body Cognito would otherwise deliver. Non-blocking: an unconfigured or
|
||||
* failing trigger falls back to the pool's default templated message, mirroring how
|
||||
* {@link #firePostAuthentication} and {@link #firePostConfirmation} tolerate errors.
|
||||
*/
|
||||
Map<String, Object> fireCustomMessage(UserPool pool, UserPoolClient client, CognitoUser user,
|
||||
String triggerSource) {
|
||||
Map<String, Object> req = new HashMap<>();
|
||||
req.put("codeParameter", CUSTOM_MESSAGE_CODE_PARAMETER);
|
||||
req.put("usernameParameter", user.getUsername());
|
||||
req.put("clientMetadata", Map.of());
|
||||
TriggerResult result = invokeTrigger(pool, client, user, "CustomMessage", triggerSource, req);
|
||||
if (!result.configured()) return null;
|
||||
if (result.errored()) {
|
||||
LOG.warnv("CustomMessage trigger failed for pool {0} (source {1}): {2}",
|
||||
pool.getId(), triggerSource, result.errorMessage());
|
||||
return null;
|
||||
}
|
||||
return result.response();
|
||||
}
|
||||
|
||||
private CognitoService.ClaimsOverride firePreTokenGeneration(UserPool pool, UserPoolClient client, CognitoUser user,
|
||||
Map<String, String> clientMetadata, String triggerSource) {
|
||||
Map<String, Object> req = new HashMap<>();
|
||||
|
||||
@@ -2258,8 +2258,10 @@ public class CognitoService implements ResourceProvider {
|
||||
try {
|
||||
String code = verificationCodeService.issue(pool.getId(), user.getUsername(),
|
||||
VerificationCode.Purpose.SIGNUP_CONFIRMATION, Duration.ofHours(24));
|
||||
Map<String, Object> customMessage = authFlowHandler.fireCustomMessage(
|
||||
pool, client, user, "CustomMessage_SignUp");
|
||||
messageDispatcher.dispatch(pool, user, VerificationCode.Purpose.SIGNUP_CONFIRMATION,
|
||||
code, List.of(deliveryTarget.deliveryMedium()));
|
||||
code, List.of(deliveryTarget.deliveryMedium()), customMessage);
|
||||
} catch (VerificationCodeException e) {
|
||||
rollbackSignUpConfirmationArtifacts(pool.getId(), user.getUsername(), key);
|
||||
throw mapVerificationCodeException(e);
|
||||
@@ -2355,8 +2357,10 @@ public class CognitoService implements ResourceProvider {
|
||||
try {
|
||||
String code = verificationCodeService.issue(pool.getId(), user.getUsername(),
|
||||
VerificationCode.Purpose.SIGNUP_CONFIRMATION, Duration.ofHours(24));
|
||||
Map<String, Object> customMessage = authFlowHandler.fireCustomMessage(
|
||||
pool, client, user, "CustomMessage_ResendCode");
|
||||
messageDispatcher.dispatch(pool, user, VerificationCode.Purpose.SIGNUP_CONFIRMATION,
|
||||
code, List.of(deliveryTarget.deliveryMedium()));
|
||||
code, List.of(deliveryTarget.deliveryMedium()), customMessage);
|
||||
} catch (VerificationCodeException e) {
|
||||
throw mapVerificationCodeException(e);
|
||||
} catch (RuntimeException e) {
|
||||
@@ -2464,8 +2468,10 @@ public class CognitoService implements ResourceProvider {
|
||||
try {
|
||||
String code = verificationCodeService.issue(pool.getId(), user.getUsername(),
|
||||
VerificationCode.Purpose.PASSWORD_RESET, Duration.ofHours(1));
|
||||
Map<String, Object> customMessage = authFlowHandler.fireCustomMessage(
|
||||
pool, client, user, "CustomMessage_ForgotPassword");
|
||||
messageDispatcher.dispatch(pool, user, VerificationCode.Purpose.PASSWORD_RESET, code,
|
||||
List.of(deliveryTarget.deliveryMedium()));
|
||||
List.of(deliveryTarget.deliveryMedium()), customMessage);
|
||||
} catch (VerificationCodeException e) {
|
||||
throw mapVerificationCodeException(e);
|
||||
}
|
||||
@@ -2504,7 +2510,7 @@ public class CognitoService implements ResourceProvider {
|
||||
validateOriginJtiNotRevoked(accessToken, poolId);
|
||||
Long iat = extractIatFromToken(accessToken);
|
||||
validateUserNotGloballySignedOut(username, poolId, "access", iat != null ? iat : 0L);
|
||||
|
||||
|
||||
CognitoUser user = adminGetUser(poolId, username);
|
||||
Map<String, Object> result = new HashMap<>();
|
||||
result.put("Username", user.getUsername());
|
||||
@@ -2605,7 +2611,7 @@ public class CognitoService implements ResourceProvider {
|
||||
validateOriginJtiNotRevoked(accessToken, poolId);
|
||||
Long iat = extractIatFromToken(accessToken);
|
||||
validateUserNotGloballySignedOut(username, poolId, "access", iat != null ? iat : 0L);
|
||||
|
||||
|
||||
adminDeleteUserAttributes(poolId, username, attributeNames);
|
||||
}
|
||||
|
||||
@@ -2690,14 +2696,14 @@ public class CognitoService implements ResourceProvider {
|
||||
String poolId = parts[0];
|
||||
String username = parts[1];
|
||||
String refreshTokenUuid = parts[4]; // UUID from refresh token
|
||||
|
||||
|
||||
if (!client.getUserPoolId().equals(poolId)) {
|
||||
throw new AwsException("NotAuthorizedException", "Invalid refresh token", 400);
|
||||
}
|
||||
if (isRefreshTokenExpired(client, parts)) {
|
||||
throw new AwsException("NotAuthorizedException", "Refresh Token has expired", 400);
|
||||
}
|
||||
|
||||
|
||||
// Check if refresh token has been revoked
|
||||
validateTokenNotRevoked(refreshTokenUuid, poolId, "refresh");
|
||||
long issuedAt = 0L;
|
||||
@@ -2705,11 +2711,11 @@ public class CognitoService implements ResourceProvider {
|
||||
issuedAt = Long.parseLong(parts[3]);
|
||||
} catch (NumberFormatException ignored) {}
|
||||
validateUserNotGloballySignedOut(username, poolId, "refresh", issuedAt);
|
||||
|
||||
|
||||
UserPool pool = describeUserPool(poolId);
|
||||
CognitoUser user = adminGetUser(poolId, username);
|
||||
ClaimsOverride override = authFlowHandler.preTokenGenerationForRefresh(pool, client, user);
|
||||
|
||||
|
||||
// Use refresh token UUID as origin_jti for derived tokens
|
||||
Map<String, Object> auth = new HashMap<>();
|
||||
auth.put("AccessToken", generateSignedJwt(user, pool, "access", client, override, refreshTokenUuid));
|
||||
@@ -2779,7 +2785,7 @@ public class CognitoService implements ResourceProvider {
|
||||
String originJti = UUID.randomUUID().toString();
|
||||
return generateAuthResult(user, pool, client, override, originJti);
|
||||
}
|
||||
|
||||
|
||||
Map<String, Object> generateAuthResult(CognitoUser user, UserPool pool, UserPoolClient client, ClaimsOverride override, String originJti) {
|
||||
Map<String, Object> auth = new HashMap<>();
|
||||
auth.put("AccessToken", generateSignedJwt(user, pool, "access", client, override, originJti));
|
||||
@@ -2793,7 +2799,7 @@ public class CognitoService implements ResourceProvider {
|
||||
String generateSignedJwt(CognitoUser user, UserPool pool, String type, UserPoolClient client, ClaimsOverride override) {
|
||||
return generateSignedJwt(user, pool, type, client, override, null);
|
||||
}
|
||||
|
||||
|
||||
String generateSignedJwt(CognitoUser user, UserPool pool, String type, UserPoolClient client, ClaimsOverride override, String originJti) {
|
||||
String header = encodeJwtHeader(pool);
|
||||
long now = System.currentTimeMillis() / 1000L;
|
||||
@@ -2818,11 +2824,11 @@ public class CognitoService implements ResourceProvider {
|
||||
// Add JWT ID (jti) claim for token revocation support
|
||||
String jti = UUID.randomUUID().toString();
|
||||
claims.put("jti", jti);
|
||||
|
||||
|
||||
if (("access".equals(type) || "id".equals(type)) && originJti != null && isTokenRevocationEnabled(client)) {
|
||||
claims.put("origin_jti", originJti);
|
||||
}
|
||||
|
||||
|
||||
String clientId = client != null ? client.getClientId() : null;
|
||||
if (clientId != null && !clientId.isBlank()) {
|
||||
if ("access".equals(type)) claims.put("client_id", clientId);
|
||||
@@ -3699,7 +3705,7 @@ public class CognitoService implements ResourceProvider {
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Validate that a refresh token has not been revoked, including global user sign-out.
|
||||
* Called from CognitoAuthFlowHandler for the REFRESH_TOKEN_AUTH flow.
|
||||
@@ -3708,7 +3714,7 @@ public class CognitoService implements ResourceProvider {
|
||||
validateTokenNotRevoked(jti, poolId, "refresh");
|
||||
validateUserNotGloballySignedOut(username, poolId, "refresh", iat);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Validate that a token has not been revoked.
|
||||
* @param jti The JWT ID to check
|
||||
@@ -3720,20 +3726,20 @@ public class CognitoService implements ResourceProvider {
|
||||
if (jti == null) {
|
||||
return; // Skip validation for tokens without jti (legacy tokens)
|
||||
}
|
||||
|
||||
|
||||
// Check for specific token revocation
|
||||
String revokedKey = revokedTokenKey(poolId, jti);
|
||||
Optional<RevokedTokenInfo> revoked = revokedTokenStore.get(revokedKey);
|
||||
|
||||
|
||||
if (revoked.isPresent()) {
|
||||
RevokedTokenInfo revokedInfo = revoked.get();
|
||||
|
||||
|
||||
// Clean up expired revocation records
|
||||
if (revokedInfo.isExpired()) {
|
||||
revokedTokenStore.delete(revokedKey);
|
||||
return;
|
||||
}
|
||||
|
||||
|
||||
// Token has been revoked
|
||||
String errorMessage = switch (tokenType) {
|
||||
case "access" -> "Access Token has been revoked";
|
||||
@@ -3744,7 +3750,7 @@ public class CognitoService implements ResourceProvider {
|
||||
throw new AwsException("NotAuthorizedException", errorMessage, 400);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
private void validateOriginJtiNotRevoked(String accessToken, String poolId) {
|
||||
String originJti = extractOriginJtiFromToken(accessToken);
|
||||
if (originJti != null) {
|
||||
@@ -3759,13 +3765,13 @@ public class CognitoService implements ResourceProvider {
|
||||
private void validateUserNotGloballySignedOut(String username, String poolId, String tokenType, long iat) {
|
||||
String globalRevokeKey = revokedTokenKey(poolId, "global:" + username);
|
||||
Optional<RevokedTokenInfo> globalRevoked = revokedTokenStore.get(globalRevokeKey);
|
||||
|
||||
|
||||
if (globalRevoked.isPresent()) {
|
||||
RevokedTokenInfo globalInfo = globalRevoked.get();
|
||||
if (!globalInfo.isExpired()) {
|
||||
long revokedAtMs = globalInfo.getRevokedAt();
|
||||
boolean revoked = false;
|
||||
|
||||
|
||||
if (iat > 1000000000000L) {
|
||||
// iat is in milliseconds (refresh token)
|
||||
revoked = iat <= revokedAtMs;
|
||||
@@ -3778,7 +3784,7 @@ public class CognitoService implements ResourceProvider {
|
||||
if (revoked) {
|
||||
String errorMessage = switch (tokenType) {
|
||||
case "access" -> "Access Token has been revoked";
|
||||
case "id" -> "ID Token has been revoked";
|
||||
case "id" -> "ID Token has been revoked";
|
||||
case "refresh" -> "Refresh Token has been revoked";
|
||||
default -> "Token has been revoked";
|
||||
};
|
||||
@@ -3789,24 +3795,24 @@ public class CognitoService implements ResourceProvider {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Revoke all tokens (refresh, access, ID) for a specific user.
|
||||
* This implements the core logic for AdminUserGlobalSignOut.
|
||||
*/
|
||||
private void revokeAllUserTokens(String userPoolId, String username) {
|
||||
long nowMs = System.currentTimeMillis();
|
||||
|
||||
|
||||
// Note: In a real implementation, we would need to track all active tokens for a user.
|
||||
// Since Floci doesn't currently maintain a token registry, we implement a simpler
|
||||
// approach that marks the user as globally signed out with a future expiration.
|
||||
// This covers the most common use case where tokens are checked at validation time.
|
||||
|
||||
|
||||
// Create a revocation record for the user with a future expiration
|
||||
// This will catch any existing tokens when they're next validated
|
||||
String globalRevokeKey = revokedTokenKey(userPoolId, "global:" + username);
|
||||
long globalExpiration = nowMs + (365L * 24L * 60L * 60L * 1000L); // 1 year from now in ms
|
||||
|
||||
|
||||
RevokedTokenInfo globalRevocation = new RevokedTokenInfo(
|
||||
"global:" + username,
|
||||
"global",
|
||||
@@ -3815,12 +3821,12 @@ public class CognitoService implements ResourceProvider {
|
||||
nowMs,
|
||||
globalExpiration
|
||||
);
|
||||
|
||||
|
||||
revokedTokenStore.put(globalRevokeKey, globalRevocation);
|
||||
|
||||
|
||||
LOG.debugv("Created global revocation record for user {0} in pool {1}", username, userPoolId);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Generate a storage key for revoked token information.
|
||||
*/
|
||||
|
||||
+33
-3
@@ -13,6 +13,10 @@ import java.util.Map;
|
||||
* {@link UserPool#getVerificationMessageTemplate()} and the requested delivery
|
||||
* mediums. Renders the {@code {####}} placeholder; appends a failsafe line if
|
||||
* the template lacks the placeholder.
|
||||
*
|
||||
* The caller may supply the response of a CustomMessage Lambda trigger invocation,
|
||||
* whose {@code emailSubject}/{@code emailMessage}/{@code smsMessage} take precedence
|
||||
* over the pool's own template.
|
||||
*/
|
||||
public final class CognitoMessageDispatcher {
|
||||
|
||||
@@ -35,6 +39,19 @@ public final class CognitoMessageDispatcher {
|
||||
|
||||
public void dispatch(UserPool pool, CognitoUser user, VerificationCode.Purpose purpose,
|
||||
String code, List<String> deliveryMediums) {
|
||||
dispatch(pool, user, purpose, code, deliveryMediums, null);
|
||||
}
|
||||
|
||||
/**
|
||||
* Same as {@link #dispatch(UserPool, CognitoUser, VerificationCode.Purpose, String, List)},
|
||||
* but takes the response of a CustomMessage Lambda trigger invocation (or {@code null} if
|
||||
* none was configured or invoked). When present, its {@code emailSubject}/{@code emailMessage}
|
||||
* (or {@code smsMessage}) take precedence over the pool's VerificationMessageTemplate, matching
|
||||
* how real Cognito lets the trigger override the delivered message.
|
||||
*/
|
||||
public void dispatch(UserPool pool, CognitoUser user, VerificationCode.Purpose purpose,
|
||||
String code, List<String> deliveryMediums,
|
||||
Map<String, Object> customMessageResponse) {
|
||||
|
||||
Map<String, Object> template = pool.getVerificationMessageTemplate();
|
||||
if (template == null) template = Map.of();
|
||||
@@ -45,8 +62,11 @@ public final class CognitoMessageDispatcher {
|
||||
|
||||
for (String medium : mediums) {
|
||||
if ("EMAIL".equalsIgnoreCase(medium) && email != null) {
|
||||
String subject = stringOr(template.get("EmailSubject"), DEFAULT_EMAIL_SUBJECT);
|
||||
String body = renderTemplate(stringOr(template.get(emailTemplateKey()), DEFAULT_EMAIL_BODY), code);
|
||||
String subject = stringOrNull(customMessageResponse, "emailSubject");
|
||||
if (subject == null) subject = stringOr(template.get("EmailSubject"), DEFAULT_EMAIL_SUBJECT);
|
||||
String rawBody = stringOrNull(customMessageResponse, "emailMessage");
|
||||
if (rawBody == null) rawBody = stringOr(template.get(emailTemplateKey()), DEFAULT_EMAIL_BODY);
|
||||
String body = renderTemplate(rawBody, code);
|
||||
ses.sendEmail(
|
||||
DEFAULT_FROM,
|
||||
List.of(email),
|
||||
@@ -61,7 +81,9 @@ public final class CognitoMessageDispatcher {
|
||||
DEFAULT_REGION
|
||||
);
|
||||
} else if ("SMS".equalsIgnoreCase(medium) && phone != null) {
|
||||
String body = renderTemplate(stringOr(resolveSmsTemplate(pool, template, purpose), DEFAULT_SMS_BODY), code);
|
||||
String rawBody = stringOrNull(customMessageResponse, "smsMessage");
|
||||
if (rawBody == null) rawBody = stringOr(resolveSmsTemplate(pool, template, purpose), DEFAULT_SMS_BODY);
|
||||
String body = renderTemplate(rawBody, code);
|
||||
sns.publish(
|
||||
null, null,
|
||||
phone,
|
||||
@@ -118,6 +140,14 @@ public final class CognitoMessageDispatcher {
|
||||
return s.isEmpty() ? fallback : s;
|
||||
}
|
||||
|
||||
private String stringOrNull(Map<String, Object> response, String key) {
|
||||
if (response == null) return null;
|
||||
Object value = response.get(key);
|
||||
if (value == null) return null;
|
||||
String s = value.toString();
|
||||
return s.isEmpty() ? null : s;
|
||||
}
|
||||
|
||||
private String renderTemplate(String template, String code) {
|
||||
if (template.contains(CODE_PLACEHOLDER)) {
|
||||
return template.replace(CODE_PLACEHOLDER, code);
|
||||
|
||||
+194
-1
@@ -2,6 +2,7 @@ package io.github.hectorvent.floci.services.cognito;
|
||||
|
||||
import com.fasterxml.jackson.core.type.TypeReference;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import io.github.hectorvent.floci.config.TlsCertificateManager;
|
||||
import io.github.hectorvent.floci.core.common.AwsException;
|
||||
import io.github.hectorvent.floci.core.common.RegionResolver;
|
||||
import io.github.hectorvent.floci.core.storage.InMemoryStorage;
|
||||
@@ -9,9 +10,14 @@ import io.github.hectorvent.floci.services.acm.AcmService;
|
||||
import io.github.hectorvent.floci.services.cognito.model.CognitoUser;
|
||||
import io.github.hectorvent.floci.services.cognito.model.UserPool;
|
||||
import io.github.hectorvent.floci.services.cognito.model.UserPoolClient;
|
||||
import io.github.hectorvent.floci.services.cognito.verification.CognitoMessageDispatcher;
|
||||
import io.github.hectorvent.floci.services.cognito.verification.VerificationCode;
|
||||
import io.github.hectorvent.floci.services.cognito.verification.VerificationCodeService;
|
||||
import io.github.hectorvent.floci.services.lambda.LambdaService;
|
||||
import io.github.hectorvent.floci.services.lambda.model.InvocationType;
|
||||
import io.github.hectorvent.floci.services.lambda.model.InvokeResult;
|
||||
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.mockito.ArgumentCaptor;
|
||||
@@ -48,12 +54,13 @@ class CognitoLambdaTriggersTest {
|
||||
private static final ObjectMapper MAPPER = new ObjectMapper();
|
||||
|
||||
private LambdaService lambdaService;
|
||||
private RegionResolver regionResolver;
|
||||
private CognitoService service;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
lambdaService = mock(LambdaService.class);
|
||||
RegionResolver regionResolver = new RegionResolver("us-east-1", "000000000000");
|
||||
regionResolver = new RegionResolver("us-east-1", "000000000000");
|
||||
service = new CognitoService(
|
||||
new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(),
|
||||
new InMemoryStorage<>(), new InMemoryStorage<>(),
|
||||
@@ -61,6 +68,22 @@ class CognitoLambdaTriggersTest {
|
||||
"http://localhost:4566", regionResolver, lambdaService, mock(AcmService.class));
|
||||
}
|
||||
|
||||
/**
|
||||
* Builds a CognitoService with a real {@link CognitoMessageDispatcher} (backed by the given
|
||||
* mocked {@link SesService}/{@link SnsService}) so tests can assert on the message actually
|
||||
* delivered, not just that dispatch() was called.
|
||||
*/
|
||||
private CognitoService createServiceWithMessaging(SesService ses, SnsService sns,
|
||||
VerificationCodeService verificationCodeService) {
|
||||
return new CognitoService(
|
||||
new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(),
|
||||
new InMemoryStorage<>(), new InMemoryStorage<>(),
|
||||
new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(),
|
||||
"http://localhost:4566", regionResolver, lambdaService, mock(AcmService.class),
|
||||
verificationCodeService, new CognitoMessageDispatcher(ses, sns),
|
||||
mock(TlsCertificateManager.class));
|
||||
}
|
||||
|
||||
private UserPool createPoolWithLambdaConfig(Map<String, Object> lambdaConfig) {
|
||||
Map<String, Object> req = new HashMap<>();
|
||||
req.put("PoolName", "trigger-pool");
|
||||
@@ -889,4 +912,174 @@ class CognitoLambdaTriggersTest {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
}
|
||||
|
||||
// =========================================================================
|
||||
// CustomMessage
|
||||
// =========================================================================
|
||||
|
||||
@Test
|
||||
void customMessageOverridesSignUpVerificationEmail() {
|
||||
SesService ses = mock(SesService.class);
|
||||
VerificationCodeService verificationCodeService = mock(VerificationCodeService.class);
|
||||
when(verificationCodeService.issue(any(), any(), eq(VerificationCode.Purpose.SIGNUP_CONFIRMATION), any()))
|
||||
.thenReturn("246962");
|
||||
CognitoService svc = createServiceWithMessaging(ses, mock(SnsService.class), verificationCodeService);
|
||||
|
||||
UserPool pool = svc.createUserPool(Map.of(
|
||||
"PoolName", "trigger-pool",
|
||||
"AutoVerifiedAttributes", List.of("email"),
|
||||
"LambdaConfig", Map.of("CustomMessage", "arn:aws:lambda:::custom-message")), "us-east-1");
|
||||
UserPoolClient client = svc.createUserPoolClient(pool.getId(), "c", false, false, List.of(), List.of());
|
||||
|
||||
when(lambdaService.invoke(anyString(), eq("arn:aws:lambda:::custom-message"),
|
||||
any(byte[].class), eq(InvocationType.RequestResponse)))
|
||||
.thenReturn(ok(Map.of(
|
||||
"emailSubject", "TRIGGER-FIRED",
|
||||
"emailMessage", "TRIGGER-FIRED code={####}")));
|
||||
|
||||
svc.signUp(client.getClientId(), "spike", "Spike@Test1", Map.of("email", "spike@example.com"));
|
||||
|
||||
verify(ses).sendEmail(
|
||||
anyString(), eq(List.of("spike@example.com")),
|
||||
eq(List.of()), eq(List.of()), eq(List.of()),
|
||||
eq("TRIGGER-FIRED"),
|
||||
eq("TRIGGER-FIRED code=246962"),
|
||||
any(), any(), eq(List.of()), eq(List.of()), any(), anyString());
|
||||
}
|
||||
|
||||
@Test
|
||||
@SuppressWarnings("unchecked")
|
||||
void customMessageSignUpTriggerReceivesCodeParameterAndUsername() throws Exception {
|
||||
VerificationCodeService verificationCodeService = mock(VerificationCodeService.class);
|
||||
when(verificationCodeService.issue(any(), any(), eq(VerificationCode.Purpose.SIGNUP_CONFIRMATION), any()))
|
||||
.thenReturn("246962");
|
||||
CognitoService svc = createServiceWithMessaging(mock(SesService.class), mock(SnsService.class),
|
||||
verificationCodeService);
|
||||
|
||||
UserPool pool = svc.createUserPool(Map.of(
|
||||
"PoolName", "trigger-pool",
|
||||
"AutoVerifiedAttributes", List.of("email"),
|
||||
"LambdaConfig", Map.of("CustomMessage", "arn:aws:lambda:::custom-message")), "us-east-1");
|
||||
UserPoolClient client = svc.createUserPoolClient(pool.getId(), "c", false, false, List.of(), List.of());
|
||||
|
||||
ArgumentCaptor<byte[]> payloadCaptor = ArgumentCaptor.forClass(byte[].class);
|
||||
when(lambdaService.invoke(anyString(), eq("arn:aws:lambda:::custom-message"),
|
||||
payloadCaptor.capture(), eq(InvocationType.RequestResponse)))
|
||||
.thenReturn(ok(Map.of()));
|
||||
|
||||
svc.signUp(client.getClientId(), "spike", "Spike@Test1", Map.of("email", "spike@example.com"));
|
||||
|
||||
Map<String, Object> event = MAPPER.readValue(payloadCaptor.getValue(), new TypeReference<>() {});
|
||||
assertEquals("CustomMessage_SignUp", event.get("triggerSource"));
|
||||
Map<String, Object> request = (Map<String, Object>) event.get("request");
|
||||
assertEquals("{####}", request.get("codeParameter"));
|
||||
assertEquals("spike", request.get("usernameParameter"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void customMessageLambdaErrorFallsBackToDefaultSignUpMessage() {
|
||||
SesService ses = mock(SesService.class);
|
||||
VerificationCodeService verificationCodeService = mock(VerificationCodeService.class);
|
||||
when(verificationCodeService.issue(any(), any(), eq(VerificationCode.Purpose.SIGNUP_CONFIRMATION), any()))
|
||||
.thenReturn("246962");
|
||||
CognitoService svc = createServiceWithMessaging(ses, mock(SnsService.class), verificationCodeService);
|
||||
|
||||
UserPool pool = svc.createUserPool(Map.of(
|
||||
"PoolName", "trigger-pool",
|
||||
"AutoVerifiedAttributes", List.of("email"),
|
||||
"LambdaConfig", Map.of("CustomMessage", "arn:aws:lambda:::custom-message")), "us-east-1");
|
||||
UserPoolClient client = svc.createUserPoolClient(pool.getId(), "c", false, false, List.of(), List.of());
|
||||
|
||||
when(lambdaService.invoke(anyString(), eq("arn:aws:lambda:::custom-message"), any(byte[].class), any()))
|
||||
.thenReturn(lambdaError("Unhandled"));
|
||||
|
||||
// SignUp must still succeed and deliver the default message when CustomMessage errors.
|
||||
svc.signUp(client.getClientId(), "spike", "Spike@Test1", Map.of("email", "spike@example.com"));
|
||||
|
||||
verify(ses).sendEmail(
|
||||
anyString(), eq(List.of("spike@example.com")),
|
||||
any(), any(), any(),
|
||||
eq("Your verification code"),
|
||||
eq("Your verification code is 246962."),
|
||||
any(), any(), any(), any(), any(), anyString());
|
||||
}
|
||||
|
||||
@Test
|
||||
void customMessageDoesNotFireWhenNotConfigured() {
|
||||
SesService ses = mock(SesService.class);
|
||||
VerificationCodeService verificationCodeService = mock(VerificationCodeService.class);
|
||||
when(verificationCodeService.issue(any(), any(), eq(VerificationCode.Purpose.SIGNUP_CONFIRMATION), any()))
|
||||
.thenReturn("246962");
|
||||
CognitoService svc = createServiceWithMessaging(ses, mock(SnsService.class), verificationCodeService);
|
||||
|
||||
UserPool pool = svc.createUserPool(Map.of(
|
||||
"PoolName", "trigger-pool",
|
||||
"AutoVerifiedAttributes", List.of("email")), "us-east-1");
|
||||
UserPoolClient client = svc.createUserPoolClient(pool.getId(), "c", false, false, List.of(), List.of());
|
||||
|
||||
svc.signUp(client.getClientId(), "spike", "Spike@Test1", Map.of("email", "spike@example.com"));
|
||||
|
||||
verify(lambdaService, never()).invoke(anyString(), anyString(), any(byte[].class), any());
|
||||
verify(ses).sendEmail(
|
||||
anyString(), eq(List.of("spike@example.com")),
|
||||
any(), any(), any(),
|
||||
eq("Your verification code"),
|
||||
eq("Your verification code is 246962."),
|
||||
any(), any(), any(), any(), any(), anyString());
|
||||
}
|
||||
|
||||
@Test
|
||||
@SuppressWarnings("unchecked")
|
||||
void customMessageFiresWithResendCodeTriggerSourceOnResendConfirmationCode() throws Exception {
|
||||
VerificationCodeService verificationCodeService = mock(VerificationCodeService.class);
|
||||
when(verificationCodeService.issue(any(), any(), eq(VerificationCode.Purpose.SIGNUP_CONFIRMATION), any()))
|
||||
.thenReturn("111222");
|
||||
CognitoService svc = createServiceWithMessaging(mock(SesService.class), mock(SnsService.class),
|
||||
verificationCodeService);
|
||||
|
||||
UserPool pool = svc.createUserPool(Map.of(
|
||||
"PoolName", "trigger-pool",
|
||||
"AutoVerifiedAttributes", List.of("email"),
|
||||
"LambdaConfig", Map.of("CustomMessage", "arn:aws:lambda:::custom-message")), "us-east-1");
|
||||
UserPoolClient client = svc.createUserPoolClient(pool.getId(), "c", false, false, List.of(), List.of());
|
||||
svc.signUp(client.getClientId(), "spike", "Spike@Test1", Map.of("email", "spike@example.com"));
|
||||
|
||||
ArgumentCaptor<byte[]> payloadCaptor = ArgumentCaptor.forClass(byte[].class);
|
||||
when(lambdaService.invoke(anyString(), eq("arn:aws:lambda:::custom-message"),
|
||||
payloadCaptor.capture(), eq(InvocationType.RequestResponse)))
|
||||
.thenReturn(ok(Map.of()));
|
||||
|
||||
svc.resendConfirmationCode(client.getClientId(), "spike");
|
||||
|
||||
Map<String, Object> event = MAPPER.readValue(payloadCaptor.getValue(), new TypeReference<>() {});
|
||||
assertEquals("CustomMessage_ResendCode", event.get("triggerSource"));
|
||||
}
|
||||
|
||||
@Test
|
||||
@SuppressWarnings("unchecked")
|
||||
void customMessageFiresWithForgotPasswordTriggerSourceOnForgotPassword() throws Exception {
|
||||
VerificationCodeService verificationCodeService = mock(VerificationCodeService.class);
|
||||
when(verificationCodeService.issue(any(), any(), eq(VerificationCode.Purpose.PASSWORD_RESET), any()))
|
||||
.thenReturn("333444");
|
||||
CognitoService svc = createServiceWithMessaging(mock(SesService.class), mock(SnsService.class),
|
||||
verificationCodeService);
|
||||
|
||||
UserPool pool = svc.createUserPool(Map.of(
|
||||
"PoolName", "trigger-pool",
|
||||
"LambdaConfig", Map.of("CustomMessage", "arn:aws:lambda:::custom-message")), "us-east-1");
|
||||
UserPoolClient client = svc.createUserPoolClient(pool.getId(), "c", false, false, List.of(), List.of());
|
||||
svc.adminCreateUser(pool.getId(), "spike",
|
||||
Map.of("email", "spike@example.com", "email_verified", "true"), null);
|
||||
svc.adminSetUserPassword(pool.getId(), "spike", "Spike@Test1", true);
|
||||
|
||||
ArgumentCaptor<byte[]> payloadCaptor = ArgumentCaptor.forClass(byte[].class);
|
||||
when(lambdaService.invoke(anyString(), eq("arn:aws:lambda:::custom-message"),
|
||||
payloadCaptor.capture(), eq(InvocationType.RequestResponse)))
|
||||
.thenReturn(ok(Map.of()));
|
||||
|
||||
svc.forgotPassword(client.getClientId(), "spike");
|
||||
|
||||
Map<String, Object> event = MAPPER.readValue(payloadCaptor.getValue(), new TypeReference<>() {});
|
||||
assertEquals("CustomMessage_ForgotPassword", event.get("triggerSource"));
|
||||
}
|
||||
}
|
||||
@@ -1436,7 +1436,7 @@ class CognitoServiceTest {
|
||||
when(verificationCodeService.issue(any(), any(), eq(VerificationCode.Purpose.SIGNUP_CONFIRMATION), any()))
|
||||
.thenReturn("123456");
|
||||
doThrow(new RuntimeException("SES unavailable")).when(messageDispatcher)
|
||||
.dispatch(any(), any(), eq(VerificationCode.Purpose.SIGNUP_CONFIRMATION), eq("123456"), any());
|
||||
.dispatch(any(), any(), eq(VerificationCode.Purpose.SIGNUP_CONFIRMATION), eq("123456"), any(), any());
|
||||
|
||||
CognitoService serviceWithVerification = new CognitoService(
|
||||
new InMemoryStorage<>(),
|
||||
|
||||
Reference in new issue
Block a user