diff --git a/docs/services/cognito.md b/docs/services/cognito.md index 5a4fe53743..93bb95c58e 100644 --- a/docs/services/cognito.md +++ b/docs/services/cognito.md @@ -46,6 +46,32 @@ format. Validation runs before pool or client lookup. | AddCustomAttributes | Adds 1 to 25 attributes to a user pool's schema, prefixing each name with `custom:`, or `dev:` for a `DeveloperOnlyAttribute`, and rejecting a name the schema already has. | | SetUserPoolMfaConfig | Sets `MfaConfiguration` (`OFF`/`ON`/`OPTIONAL`) and `SoftwareTokenMfaConfiguration`. An absent `MfaConfiguration` means `OFF`, and turning MFA off drops the factor configuration with it. Validation follows the live service: `OFF` alongside a software-token, email or SMS factor is rejected, and `ON`/`OPTIONAL` with none of those three is rejected, in both cases on the member being present, not on its `Enabled` value. `WebAuthnConfiguration` sits outside both rules, as it does in AWS. SMS, email and WebAuthn configurations are validated and not stored: Floci cannot deliver those factors, so keeping the config would imply a capability it does not have. | +Email that Cognito sends to users, such as verification codes, goes through Floci's SES (readable +at `/_aws/ses`) from the sender the pool's `EmailConfiguration` names: + +- With `EmailSendingAccount` `DEVELOPER`, `From` when it is set, as an address or a sender name + with an address, otherwise the address of the `SourceArn` identity. +- With `COGNITO_DEFAULT`, the address of the `SourceArn` identity. AWS offers a sender name in + `From` only with `DEVELOPER`. +- When the `SourceArn` identity is a domain, `From` gives the address. +- Otherwise `no-reply@verificationemail.com`. + +A configured sender is used only when SES has verified it for the pool. The `SourceArn` must name +an identity in the user pool's partition and account that SES has verified in the `SourceArn` +Region (the pool's Region when the ARN has `*` there), and a `From` that gives the sender must be a +single mailbox at that email address (matched case-sensitively, as SES matches email address +identities) or in that domain or one of its subdomains. Otherwise the email goes from +`no-reply@verificationemail.com` and Floci logs a warning. Verify the identity first with +`VerifyEmailIdentity` or `CreateEmailIdentity`, or as a domain whose DKIM records are in Route 53. +When `From` has a sender name, the captured message keeps it in `Source`, and its `ReturnPath`, +which the SMTP relay uses as the envelope sender, is the bare address. + +Differences from AWS: Floci accepts an unverified `SourceArn` when a pool is created or updated, +where AWS can fail with `InvalidEmailRoleAccessPolicyException`. It does not check the sending +authorization policy that a custom FROM address needs with `COGNITO_DEFAULT`, sends in the user +pool's Region rather than the `SourceArn` Region, and does not apply `ReplyToEmailAddress` or +`ConfigurationSet`. + ### User Pool Tags | Action | Description | diff --git a/src/main/java/io/github/hectorvent/floci/services/cognito/verification/CognitoMessageDispatcher.java b/src/main/java/io/github/hectorvent/floci/services/cognito/verification/CognitoMessageDispatcher.java index ef561df8c0..67b4ff7d9c 100644 --- a/src/main/java/io/github/hectorvent/floci/services/cognito/verification/CognitoMessageDispatcher.java +++ b/src/main/java/io/github/hectorvent/floci/services/cognito/verification/CognitoMessageDispatcher.java @@ -7,8 +7,13 @@ import io.github.hectorvent.floci.services.ses.SesService; import io.github.hectorvent.floci.services.ses.model.EmailContent; import io.github.hectorvent.floci.services.ses.model.SendEmailRequest; import io.github.hectorvent.floci.services.sns.SnsService; +import org.apache.james.mime4j.dom.address.Mailbox; +import org.apache.james.mime4j.field.address.DefaultAddressParser; +import org.apache.james.mime4j.field.address.ParseException; +import org.jboss.logging.Logger; import java.util.List; +import java.util.Locale; import java.util.Map; /** @@ -20,15 +25,23 @@ import java.util.Map; * 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. + * + * Email is sent from the address the pool's {@code EmailConfiguration} names when SES has verified + * it for the pool's account, or from {@code no-reply@verificationemail.com} otherwise. */ public final class CognitoMessageDispatcher { + private static final Logger LOG = Logger.getLogger(CognitoMessageDispatcher.class); + // Defaults match AWS Cognito's out-of-the-box verification messages (used only when the // user pool configures no VerificationMessageTemplate). private static final String DEFAULT_EMAIL_SUBJECT = "Your verification code"; private static final String DEFAULT_EMAIL_BODY = "Your verification code is {####}."; private static final String DEFAULT_SMS_BODY = "Your verification code is {####}."; private static final String DEFAULT_FROM = "no-reply@verificationemail.com"; + private static final Sender DEFAULT_SENDER = new Sender(DEFAULT_FROM, DEFAULT_FROM); + private static final String DEVELOPER_SENDING_ACCOUNT = "DEVELOPER"; + private static final String SES_IDENTITY_RESOURCE_PREFIX = "identity/"; private static final String CODE_PLACEHOLDER = "{####}"; private final SesService ses; @@ -73,8 +86,12 @@ public final class CognitoMessageDispatcher { String rawBody = stringOrNull(customMessageResponse, "emailMessage"); if (rawBody == null) rawBody = stringOr(template.get(emailTemplateKey()), DEFAULT_EMAIL_BODY); String body = renderTemplate(rawBody, code); + Sender sender = sender(pool, region); ses.sendEmail(SendEmailRequest.builder() - .source(DEFAULT_FROM) + .source(sender.from()) + // SES takes Source as the default return path, the envelope sender it records + // and hands to the SMTP relay, which takes a bare address. + .returnPath(sender.from().equals(sender.address()) ? null : sender.address()) .toAddresses(List.of(email)) .region(region) .content(new EmailContent.Simple(subject, body, null, List.of())) @@ -95,6 +112,113 @@ public final class CognitoMessageDispatcher { } } + /** + * The sender for the pool's {@code EmailConfiguration} (EmailConfigurationType): + * + * A configured sender is used only when the {@code SourceArn} names an SES identity that is + * verified in the pool's partition and account, in the {@code SourceArn} Region (the pool's + * own for a wildcard Region), and {@code From}, when it supplies the sender, is one mailbox at + * that address or in that domain or one of its subdomains. Anything else falls back to {@code no-reply@verificationemail.com}, + * so a pool cannot send as an address its account has not verified. + */ + private Sender sender(UserPool pool, String sendRegion) { + Map config = pool.getEmailConfiguration(); + if (config == null) { + return DEFAULT_SENDER; + } + String from = stringOrNull(config, "From"); + boolean developer = DEVELOPER_SENDING_ACCOUNT.equals(config.get("EmailSendingAccount")); + String sourceArn = stringOrNull(config, "SourceArn"); + String identity = sesIdentity(sourceArn); + if (identity == null) { + if (sourceArn != null) { + LOG.warnv("User pool {0} SourceArn {1} names no SES identity; sending from {2}", + pool.getId(), sourceArn, DEFAULT_FROM); + } else if (developer && from != null) { + LOG.warnv("User pool {0} sets From {1} without a SourceArn; sending from {2}", + pool.getId(), from, DEFAULT_FROM); + } + return DEFAULT_SENDER; + } + if (!isVerifiedForPool(AwsArnUtils.parse(sourceArn), identity, pool, sendRegion)) { + LOG.warnv("User pool {0} SourceArn {1} is not an SES identity verified for the pool''s account in that Region; sending from {2}", + pool.getId(), sourceArn, DEFAULT_FROM); + return DEFAULT_SENDER; + } + boolean identityIsAddress = identity.contains("@"); + if (identityIsAddress && !(developer && from != null)) { + return new Sender(identity, identity); + } + Mailbox mailbox = from == null ? null : parseMailbox(from); + if (mailbox == null || !isCoveredBy(mailbox, identity)) { + LOG.warnv("User pool {0} From {1} is not an address of the SES identity {2}; sending from {3}", + pool.getId(), from, identity, DEFAULT_FROM); + return DEFAULT_SENDER; + } + return new Sender(from, mailbox.getAddress()); + } + + /** + * True when the identity is verified in SES for the pool's account. The identity store is read + * in the caller's account, which is the pool's, so the ARN's partition and account must be the + * pool's too. + */ + private boolean isVerifiedForPool(AwsArnUtils.Arn sourceArn, String identity, UserPool pool, + String sendRegion) { + String poolPartition = AwsArnUtils.partitionOrDefault(pool.getArn(), null); + String poolAccount = AwsArnUtils.accountOrDefault(pool.getArn(), null); + if (poolPartition == null || !poolPartition.equals(sourceArn.partition()) + || poolAccount == null || !poolAccount.equals(sourceArn.accountId())) { + return false; + } + String region = sourceArn.region().isEmpty() || "*".equals(sourceArn.region()) + ? sendRegion : sourceArn.region(); + return ses.isVerifiedIdentity(identity, region); + } + + /** One RFC 5322 mailbox, {@code addr} or {@code Name }, or {@code null} for anything else. */ + private static Mailbox parseMailbox(String value) { + try { + Mailbox mailbox = DefaultAddressParser.DEFAULT.parseMailbox(value); + return mailbox.getDomain() == null ? null : mailbox; + } catch (ParseException e) { + return null; + } + } + + /** + * True when the mailbox is the email address identity, or an address in the domain identity or + * one of its subdomains. SES email address identities are case sensitive; domains are not. + */ + private static boolean isCoveredBy(Mailbox mailbox, String identity) { + if (identity.contains("@")) { + return identity.equals(mailbox.getAddress()); + } + String domain = mailbox.getDomain().toLowerCase(Locale.ROOT); + String identityDomain = identity.toLowerCase(Locale.ROOT); + return domain.equals(identityDomain) || domain.endsWith("." + identityDomain); + } + + /** The identity an SES {@code identity/} ARN names, or {@code null} for anything else. */ + private static String sesIdentity(String sourceArn) { + return AwsArnUtils.resourceIfArnFor(sourceArn, "ses") + .filter(resource -> resource.startsWith(SES_IDENTITY_RESOURCE_PREFIX)) + .map(resource -> resource.substring(SES_IDENTITY_RESOURCE_PREFIX.length())) + .filter(identity -> !identity.isEmpty() && identity.chars().noneMatch(Character::isWhitespace)) + .orElse(null); + } + + /** The From header, and the bare address SES uses as the envelope sender. */ + private record Sender(String from, String address) { + } + /** * Email template key. Returns the code-based {@code EmailMessage} ({@code {####}}). * TODO: honor the pool's {@code DefaultEmailOption}: when set to {@code CONFIRM_WITH_LINK}, diff --git a/src/main/java/io/github/hectorvent/floci/services/ses/SesService.java b/src/main/java/io/github/hectorvent/floci/services/ses/SesService.java index c1ecf1da03..8f4110ec9b 100644 --- a/src/main/java/io/github/hectorvent/floci/services/ses/SesService.java +++ b/src/main/java/io/github/hectorvent/floci/services/ses/SesService.java @@ -873,6 +873,15 @@ public class SesService { pool -> dedicatedIpService.dedicatedIpPoolExists(pool, region)); } + /** + * True when {@code identity}, an email address or a domain, is a verified identity of the + * caller's account in {@code region}. Cognito reads it to decide whether a user pool's + * {@code SourceArn} may be its sender. + */ + public boolean isVerifiedIdentity(String identity, String region) { + return identityService.isIdentityVerified(identity, region); + } + private boolean isVerifiedDomainIdentity(String domain, String region) { Identity identity = identityService.getIdentityVerificationAttributes(domain, region); return identity != null && "Success".equals(identity.getVerificationStatus()) diff --git a/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoIntegrationTest.java index 8c70f63df9..568c6f4453 100644 --- a/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoIntegrationTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoIntegrationTest.java @@ -720,6 +720,101 @@ class CognitoIntegrationTest { assertEquals("CONFIRMED", confirmedUser.path("UserStatus").asText()); } + @Test + void signUpCodeIsSentFromTheEmailConfigurationFrom() throws Exception { + verifySesEmailIdentity("noreply@repro.example"); + String fromUsername = signUpWithEmailConfiguration("EmailConfigurationFromPool", """ + { + "EmailSendingAccount": "DEVELOPER", + "SourceArn": "arn:aws:ses:us-east-1:000000000000:identity/noreply@repro.example", + "From": "Repro App " + } + """); + + // The sender name stays in Source, the From header, while the return path, which the SMTP + // relay uses as the envelope sender, is the bare address. + given() + .when() + .get("/_aws/ses") + .then() + .statusCode(200) + .body("messages.findAll { it.Destination?.ToAddresses?.contains('" + fromUsername + "') }", + hasSize(1)) + .body("messages.find { it.Destination?.ToAddresses?.contains('" + fromUsername + "') }.Source", + equalTo("Repro App ")) + .body("messages.find { it.Destination?.ToAddresses?.contains('" + fromUsername + "') }.ReturnPath", + equalTo("noreply@repro.example")); + } + + @Test + void signUpCodeIsSentFromTheDefaultAddressWhenSesHasNotVerifiedTheSourceArn() throws Exception { + String unverified = "noreply-" + UUID.randomUUID() + "@unverified.example"; + String fromUsername = signUpWithEmailConfiguration("UnverifiedSourceArnPool", """ + { + "EmailSendingAccount": "DEVELOPER", + "SourceArn": "arn:aws:ses:us-east-1:000000000000:identity/%s", + "From": "Repro App <%s>" + } + """.formatted(unverified, unverified)); + + given() + .when() + .get("/_aws/ses") + .then() + .statusCode(200) + .body("messages.findAll { it.Destination?.ToAddresses?.contains('" + fromUsername + "') }", + hasSize(1)) + .body("messages.find { it.Destination?.ToAddresses?.contains('" + fromUsername + "') }.Source", + equalTo("no-reply@verificationemail.com")); + } + + /** Creates a pool with {@code emailConfiguration}, signs a new user up to it and returns the username. */ + private static String signUpWithEmailConfiguration(String poolName, String emailConfiguration) throws Exception { + JsonNode poolResponse = cognitoJson("CreateUserPool", """ + { + "PoolName": "%s", + "AutoVerifiedAttributes": ["email"], + "EmailConfiguration": %s + } + """.formatted(poolName, emailConfiguration)); + String fromPoolId = poolResponse.path("UserPool").path("Id").asText(); + + JsonNode clientResponse = cognitoJson("CreateUserPoolClient", """ + { + "UserPoolId": "%s", + "ClientName": "email-configuration-from-client" + } + """.formatted(fromPoolId)); + String fromClientId = clientResponse.path("UserPoolClient").path("ClientId").asText(); + + String fromUsername = "from+" + UUID.randomUUID() + "@example.com"; + cognitoAction("SignUp", """ + { + "ClientId": "%s", + "Username": "%s", + "Password": "Passw0rd!", + "UserAttributes": [ + { "Name": "email", "Value": "%s" } + ] + } + """.formatted(fromClientId, fromUsername, fromUsername)) + .then() + .statusCode(200); + return fromUsername; + } + + private static void verifySesEmailIdentity(String emailAddress) { + given() + .contentType("application/x-www-form-urlencoded") + .header("Authorization", "AWS4-HMAC-SHA256 Credential=AKID/20260101/us-east-1/email/aws4_request") + .formParam("Action", "VerifyEmailIdentity") + .formParam("EmailAddress", emailAddress) + .when() + .post("/") + .then() + .statusCode(200); + } + @Test void resendConfirmationCodeReplacesTheSignUpCode() throws Exception { given().delete("/_aws/ses").then().statusCode(200); diff --git a/src/test/java/io/github/hectorvent/floci/services/cognito/verification/CognitoMessageDispatcherTest.java b/src/test/java/io/github/hectorvent/floci/services/cognito/verification/CognitoMessageDispatcherTest.java index 1dc797547d..1e89b08a0f 100644 --- a/src/test/java/io/github/hectorvent/floci/services/cognito/verification/CognitoMessageDispatcherTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/cognito/verification/CognitoMessageDispatcherTest.java @@ -23,6 +23,7 @@ import static org.mockito.ArgumentMatchers.isNull; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; class CognitoMessageDispatcherTest { @@ -206,6 +207,250 @@ class CognitoMessageDispatcherTest { assertEquals("cn-northwest-1", sentEmail().region()); } + @Test + void dispatch_withoutEmailConfiguration_sendsFromTheDefaultAddress() { + dispatcher.dispatch(pool(Map.of()), user("alice@example.com", null), + VerificationCode.Purpose.SIGNUP_CONFIRMATION, "123456", List.of("EMAIL")); + + assertEquals("no-reply@verificationemail.com", sentEmail().source()); + } + + @Test + void dispatch_developerSendingAccount_sendsFromTheConfiguredFrom() { + verified("noreply@repro.example", "us-east-1"); + UserPool pool = emailConfiguredPool(Map.of( + "EmailSendingAccount", "DEVELOPER", + "SourceArn", "arn:aws:ses:us-east-1:000000000000:identity/noreply@repro.example", + "From", "Repro App ")); + + dispatcher.dispatch(pool, user("alice@example.com", null), + VerificationCode.Purpose.SIGNUP_CONFIRMATION, "123456", List.of("EMAIL")); + + assertEquals("Repro App ", sentEmail().source()); + } + + @Test + void dispatch_senderName_staysInTheFromHeaderAndLeavesTheReturnPathBare() { + // SES takes Source as the default return path, the envelope sender, which takes a bare + // address. + verified("noreply@repro.example", "us-east-1"); + UserPool pool = emailConfiguredPool(Map.of( + "EmailSendingAccount", "DEVELOPER", + "SourceArn", "arn:aws:ses:us-east-1:000000000000:identity/noreply@repro.example", + "From", "Repro App ")); + + dispatcher.dispatch(pool, user("alice@example.com", null), + VerificationCode.Purpose.SIGNUP_CONFIRMATION, "123456", List.of("EMAIL")); + + SendEmailRequest sent = sentEmail(); + assertEquals("Repro App ", sent.source()); + assertEquals("noreply@repro.example", sent.returnPath()); + } + + @Test + void dispatch_developerSendingAccountWithoutFrom_sendsFromTheSourceArnAddress() { + verified("noreply@repro.example", "us-east-1"); + UserPool pool = emailConfiguredPool(Map.of( + "EmailSendingAccount", "DEVELOPER", + "SourceArn", "arn:aws:ses:us-east-1:000000000000:identity/noreply@repro.example")); + + dispatcher.dispatch(pool, user("alice@example.com", null), + VerificationCode.Purpose.SIGNUP_CONFIRMATION, "123456", List.of("EMAIL")); + + assertEquals("noreply@repro.example", sentEmail().source()); + } + + @Test + void dispatch_cognitoDefaultSendingAccount_sendsFromTheSourceArnAddressWithoutTheSenderName() { + // With COGNITO_DEFAULT the SourceArn address is the custom FROM address; a sender name in + // From is available only with the pool's own SES (DEVELOPER). + verified("noreply@repro.example", "us-east-1"); + UserPool pool = emailConfiguredPool(Map.of( + "EmailSendingAccount", "COGNITO_DEFAULT", + "SourceArn", "arn:aws:ses:us-east-1:000000000000:identity/noreply@repro.example", + "From", "Repro App ")); + + dispatcher.dispatch(pool, user("alice@example.com", null), + VerificationCode.Purpose.SIGNUP_CONFIRMATION, "123456", List.of("EMAIL")); + + assertEquals("noreply@repro.example", sentEmail().source()); + } + + @Test + void dispatch_cognitoDefaultSendingAccountWithoutSourceArn_ignoresFrom() { + UserPool pool = emailConfiguredPool(Map.of( + "EmailSendingAccount", "COGNITO_DEFAULT", + "From", "noreply@repro.example")); + + dispatcher.dispatch(pool, user("alice@example.com", null), + VerificationCode.Purpose.SIGNUP_CONFIRMATION, "123456", List.of("EMAIL")); + + assertEquals("no-reply@verificationemail.com", sentEmail().source()); + } + + @Test + void dispatch_domainIdentity_sendsFromTheConfiguredFrom() { + // A domain identity names no address of its own, so From supplies it. + verified("repro.example", "us-east-1"); + UserPool pool = emailConfiguredPool(Map.of( + "SourceArn", "arn:aws:ses:us-east-1:000000000000:identity/repro.example", + "From", "noreply@repro.example")); + + dispatcher.dispatch(pool, user("alice@example.com", null), + VerificationCode.Purpose.SIGNUP_CONFIRMATION, "123456", List.of("EMAIL")); + + assertEquals("noreply@repro.example", sentEmail().source()); + } + + @Test + void dispatch_unverifiedSourceArnIdentity_sendsFromTheDefaultAddress() { + UserPool pool = emailConfiguredPool(Map.of( + "EmailSendingAccount", "DEVELOPER", + "SourceArn", "arn:aws:ses:us-east-1:000000000000:identity/noreply@repro.example", + "From", "Repro App ")); + + dispatcher.dispatch(pool, user("alice@example.com", null), + VerificationCode.Purpose.SIGNUP_CONFIRMATION, "123456", List.of("EMAIL")); + + assertEquals("no-reply@verificationemail.com", sentEmail().source()); + } + + @Test + void dispatch_developerSendingAccountFromWithoutSourceArn_sendsFromTheDefaultAddress() { + UserPool pool = emailConfiguredPool(Map.of( + "EmailSendingAccount", "DEVELOPER", + "From", "Repro App ")); + + dispatcher.dispatch(pool, user("alice@example.com", null), + VerificationCode.Purpose.SIGNUP_CONFIRMATION, "123456", List.of("EMAIL")); + + assertEquals("no-reply@verificationemail.com", sentEmail().source()); + } + + @Test + void dispatch_fromOutsideTheEmailIdentity_sendsFromTheDefaultAddress() { + verified("noreply@repro.example", "us-east-1"); + UserPool pool = emailConfiguredPool(Map.of( + "EmailSendingAccount", "DEVELOPER", + "SourceArn", "arn:aws:ses:us-east-1:000000000000:identity/noreply@repro.example", + "From", "Billing ")); + + dispatcher.dispatch(pool, user("alice@example.com", null), + VerificationCode.Purpose.SIGNUP_CONFIRMATION, "123456", List.of("EMAIL")); + + assertEquals("no-reply@verificationemail.com", sentEmail().source()); + } + + @Test + void dispatch_fromOutsideTheDomainIdentity_sendsFromTheDefaultAddress() { + verified("repro.example", "us-east-1"); + UserPool pool = emailConfiguredPool(Map.of( + "EmailSendingAccount", "DEVELOPER", + "SourceArn", "arn:aws:ses:us-east-1:000000000000:identity/repro.example", + "From", "noreply@bank.example")); + + dispatcher.dispatch(pool, user("alice@example.com", null), + VerificationCode.Purpose.SIGNUP_CONFIRMATION, "123456", List.of("EMAIL")); + + assertEquals("no-reply@verificationemail.com", sentEmail().source()); + } + + @Test + void dispatch_fromInASubdomainOfTheDomainIdentity_sendsFromTheConfiguredFrom() { + // SES: a verified domain covers its subdomains without identities of their own. + verified("repro.example", "us-east-1"); + UserPool pool = emailConfiguredPool(Map.of( + "EmailSendingAccount", "DEVELOPER", + "SourceArn", "arn:aws:ses:us-east-1:000000000000:identity/repro.example", + "From", "no-reply@auth.Repro.example")); + + dispatcher.dispatch(pool, user("alice@example.com", null), + VerificationCode.Purpose.SIGNUP_CONFIRMATION, "123456", List.of("EMAIL")); + + assertEquals("no-reply@auth.Repro.example", sentEmail().source()); + } + + @Test + void dispatch_fromThatDiffersFromTheEmailIdentityOnlyInCase_sendsFromTheDefaultAddress() { + // SES: email address identities are case sensitive, domain part included. + verified("noreply@REPRO.example", "us-east-1"); + UserPool pool = emailConfiguredPool(Map.of( + "EmailSendingAccount", "DEVELOPER", + "SourceArn", "arn:aws:ses:us-east-1:000000000000:identity/noreply@REPRO.example", + "From", "noreply@repro.example")); + + dispatcher.dispatch(pool, user("alice@example.com", null), + VerificationCode.Purpose.SIGNUP_CONFIRMATION, "123456", List.of("EMAIL")); + + assertEquals("no-reply@verificationemail.com", sentEmail().source()); + } + + @Test + void dispatch_fromThatIsNotOneMailbox_sendsFromTheDefaultAddress() { + verified("repro.example", "us-east-1"); + UserPool pool = emailConfiguredPool(Map.of( + "EmailSendingAccount", "DEVELOPER", + "SourceArn", "arn:aws:ses:us-east-1:000000000000:identity/repro.example", + "From", "noreply@repro.example, billing@bank.example")); + + dispatcher.dispatch(pool, user("alice@example.com", null), + VerificationCode.Purpose.SIGNUP_CONFIRMATION, "123456", List.of("EMAIL")); + + assertEquals("no-reply@verificationemail.com", sentEmail().source()); + } + + @Test + void dispatch_sourceArnInAnotherAccount_sendsFromTheDefaultAddress() { + when(ses.isVerifiedIdentity(anyString(), anyString())).thenReturn(true); + UserPool pool = emailConfiguredPool(Map.of( + "EmailSendingAccount", "DEVELOPER", + "SourceArn", "arn:aws:ses:us-east-1:111122223333:identity/noreply@repro.example", + "From", "noreply@repro.example")); + + dispatcher.dispatch(pool, user("alice@example.com", null), + VerificationCode.Purpose.SIGNUP_CONFIRMATION, "123456", List.of("EMAIL")); + + assertEquals("no-reply@verificationemail.com", sentEmail().source()); + } + + @Test + void dispatch_sourceArnInAnotherPartition_sendsFromTheDefaultAddress() { + verified("noreply@repro.example", "cn-north-1"); + UserPool pool = emailConfiguredPool(Map.of( + "EmailSendingAccount", "DEVELOPER", + "SourceArn", "arn:aws-cn:ses:cn-north-1:000000000000:identity/noreply@repro.example")); + + dispatcher.dispatch(pool, user("alice@example.com", null), + VerificationCode.Purpose.SIGNUP_CONFIRMATION, "123456", List.of("EMAIL")); + + assertEquals("no-reply@verificationemail.com", sentEmail().source()); + } + + @Test + void dispatch_identityVerifiedOnlyOutsideTheSourceArnRegion_sendsFromTheDefaultAddress() { + verified("noreply@repro.example", "us-east-1"); + UserPool pool = emailConfiguredPool(Map.of( + "EmailSendingAccount", "DEVELOPER", + "SourceArn", "arn:aws:ses:eu-west-1:000000000000:identity/noreply@repro.example")); + + dispatcher.dispatch(pool, user("alice@example.com", null), + VerificationCode.Purpose.SIGNUP_CONFIRMATION, "123456", List.of("EMAIL")); + + assertEquals("no-reply@verificationemail.com", sentEmail().source()); + } + + @Test + void dispatch_wildcardRegionSourceArn_checksTheIdentityInThePoolsRegion() { + verified("noreply@repro.example", "us-east-1"); + UserPool pool = emailConfiguredPool(Map.of( + "SourceArn", "arn:aws:ses:*:000000000000:identity/noreply@repro.example")); + + dispatcher.dispatch(pool, user("alice@example.com", null), + VerificationCode.Purpose.SIGNUP_CONFIRMATION, "123456", List.of("EMAIL")); + + assertEquals("noreply@repro.example", sentEmail().source()); + } + private SendEmailRequest sentEmail() { ArgumentCaptor captor = ArgumentCaptor.forClass(SendEmailRequest.class); verify(ses).sendEmail(captor.capture()); @@ -220,6 +465,17 @@ class CognitoMessageDispatcherTest { return assertInstanceOf(EmailContent.Simple.class, sent.content()).bodyText(); } + private void verified(String identity, String region) { + when(ses.isVerifiedIdentity(identity, region)).thenReturn(true); + } + + private UserPool emailConfiguredPool(Map emailConfiguration) { + UserPool p = pool(Map.of()); + p.setArn("arn:aws:cognito-idp:us-east-1:000000000000:userpool/us-east-1_AbCdEfGhI"); + p.setEmailConfiguration(emailConfiguration); + return p; + } + private UserPool pool(Map template) { UserPool p = new UserPool(); p.setVerificationMessageTemplate(new HashMap<>(template));