mirror of
https://github.com/floci-io/floci.git
synced 2026-11-27 07:39:24 -05:00
fix(cognito): send email from the pool's EmailConfiguration sender (#5150)
* fix(cognito): send email from the pool's EmailConfiguration sender Cognito email always came from no-reply@verificationemail.com. It now follows EmailConfigurationType: with DEVELOPER, From when set, otherwise the SourceArn identity's address; with COGNITO_DEFAULT, the SourceArn address. A domain identity takes its address from From. Without a SourceArn, the default address is kept. * test(cognito): read captured mail without the ?email= filter * fix(cognito): send from the configured sender only when SES has verified it A pool's EmailConfiguration sender is now used only when its SourceArn names an SES identity in the pool's account that SES has verified in the SourceArn Region (the pool's Region for a wildcard Region), and a From that supplies the sender is one mailbox at that address or in that domain. Anything else sends from no-reply@verificationemail.com and logs a warning, so a pool can no longer send as an address its account has not verified. When From has a sender name, the bare address now goes in ReturnPath. SES takes Source as the default return path, so the captured message's ReturnPath, and the envelope sender handed to the SMTP relay, was "Name <address>". The relay's mail client happened to strip the name from MAIL FROM; the envelope no longer depends on that. * style(cognito): use one parameterised message in the sender fallback log * fix(cognito): accept subdomains of a domain identity and match email identities exactly A verified SES domain covers its subdomains, so a From in one of them now sends instead of falling back. Email address identities are case sensitive, domain part included, so the From must equal the identity. The SourceArn must also be in the user pool's partition, not only its account. * refactor(ses): keep one definition of a verified identity SesService.isVerifiedIdentity now delegates to SesIdentityService.isIdentityVerified, made package-private, instead of repeating its check.
This commit is contained in:
1 parent
a33eea05cd
commit
45f45e590e
5 files changed
+511
-1
No files matched your search
+125
-1
@@ -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):
|
||||
* <ul>
|
||||
* <li>{@code DEVELOPER}: {@code From}, a sender's address or name and address, when set.
|
||||
* Only this sending account takes a sender name.</li>
|
||||
* <li>Otherwise the address of the {@code SourceArn} identity, which with
|
||||
* {@code COGNITO_DEFAULT} is the custom FROM address. A domain identity names no address,
|
||||
* so {@code From} supplies it.</li>
|
||||
* <li>Without either, {@code no-reply@verificationemail.com}.</li>
|
||||
* </ul>
|
||||
* 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<String, Object> 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 <addr>}, 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/<name>} 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},
|
||||
|
||||
@@ -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())
|
||||
|
||||
Reference in new issue
Block a user