fix(ses): align CreateEmailIdentity DKIM behavior with AWS (#1620)

* fix(ses): align CreateEmailIdentity DKIM behavior with AWS

* test(ses): verify tracking domains via route53 in sdk compatibility tests

* fix(ses): cache pending DKIM Route53 lookups

* test(ses): log cleanup failures in tracking options test
This commit is contained in:
shrimptails-f authored and GitHub committed 2026-07-02 18:09:36 -05:00
1 parent 04fd34fd22
commit 0ac1a01884
17 files changed
+821 -33

No files matched your search

@@ -103,7 +103,8 @@ public class SesController {
ObjectNode result = objectMapper.createObjectNode();
result.put("IdentityType", toV2IdentityType(identity.getIdentityType()));
result.put("VerifiedForSendingStatus", true);
result.put("VerifiedForSendingStatus",
"Success".equals(identity.getVerificationStatus()));
result.set("DkimAttributes", buildDkimAttributes(identity));
LOG.infov("SES V2 CreateEmailIdentity: {0}", emailIdentity);
@@ -1448,7 +1449,12 @@ public class SesController {
ObjectNode dkim = objectMapper.createObjectNode();
dkim.put("SigningEnabled", identity.isDkimEnabled());
dkim.put("Status", toV2Status(identity.getDkimVerificationStatus()));
dkim.putArray("Tokens");
ArrayNode tokens = dkim.putArray("Tokens");
if (identity.getDkimTokens() != null) {
for (String token : identity.getDkimTokens()) {
tokens.add(token);
}
}
return dkim;
}
@@ -313,7 +313,13 @@ public class SesQueryHandler {
xml.start("value");
xml.elem("DkimEnabled", identity != null ? String.valueOf(identity.isDkimEnabled()) : "false");
xml.elem("DkimVerificationStatus", identity != null ? identity.getDkimVerificationStatus() : "NotStarted");
xml.start("DkimTokens").end("DkimTokens");
xml.start("DkimTokens");
if (identity != null && identity.getDkimTokens() != null) {
for (String token : identity.getDkimTokens()) {
xml.elem("member", token);
}
}
xml.end("DkimTokens");
xml.end("value");
xml.end("entry");
}
@@ -5,6 +5,10 @@ import io.github.hectorvent.floci.core.common.AwsArnUtils;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.storage.StorageBackend;
import io.github.hectorvent.floci.core.storage.StorageFactory;
import io.github.hectorvent.floci.services.route53.Route53Service;
import io.github.hectorvent.floci.services.route53.model.HostedZone;
import io.github.hectorvent.floci.services.route53.model.ResourceRecord;
import io.github.hectorvent.floci.services.route53.model.ResourceRecordSet;
import io.github.hectorvent.floci.services.ses.model.AccountSuppressionAttributes;
import io.github.hectorvent.floci.services.ses.model.ArchivingOptions;
import io.github.hectorvent.floci.services.ses.model.BulkEmailEntry;
@@ -33,6 +37,8 @@ import jakarta.inject.Inject;
import org.jboss.logging.Logger;
import java.security.SecureRandom;
import java.time.Clock;
import java.time.Duration;
import java.time.Instant;
import java.time.ZoneOffset;
import java.time.ZonedDateTime;
@@ -50,6 +56,7 @@ import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
@@ -62,6 +69,7 @@ public class SesService {
private static final int MAX_BULK_DESTINATIONS = 50;
private static final int MAX_RECIPIENTS_PER_DESTINATION = 50;
private static final Duration DKIM_LOOKUP_CACHE_TTL = Duration.ofSeconds(5);
private static final SecureRandom BOUNDARY_RANDOM = new SecureRandom();
@@ -77,10 +85,14 @@ public class SesService {
private final ObjectMapper objectMapper;
private final SesEventPublisher eventPublisher;
private final String defaultAccountId;
private final Route53Service route53Service;
private final Clock clock;
private final ConcurrentHashMap<String, DkimLookupCacheEntry> dkimLookupCache = new ConcurrentHashMap<>();
@Inject
public SesService(StorageFactory storageFactory, SmtpRelay smtpRelay, ObjectMapper objectMapper,
SesEventPublisher eventPublisher, EmulatorConfig config) {
SesEventPublisher eventPublisher, EmulatorConfig config, Route53Service route53Service,
Clock clock) {
this.identityStore = storageFactory.create("ses", "ses-identities.json",
new TypeReference<Map<String, Identity>>() {});
this.emailStore = storageFactory.create("ses", "ses-emails.json",
@@ -101,6 +113,8 @@ public class SesService {
this.objectMapper = objectMapper;
this.eventPublisher = eventPublisher;
this.defaultAccountId = config.defaultAccountId();
this.route53Service = route53Service;
this.clock = clock;
}
SesService(StorageBackend<String, Identity> identityStore,
@@ -112,7 +126,24 @@ public class SesService {
StorageBackend<String, AccountSuppressionAttributes> accountSuppressionStore,
StorageBackend<String, DedicatedIpPool> dedicatedIpPoolStore,
SmtpRelay smtpRelay,
ObjectMapper objectMapper) {
ObjectMapper objectMapper,
Clock clock) {
this(identityStore, emailStore, accountSettingsStore, templateStore, configSetStore, suppressionStore,
accountSuppressionStore, dedicatedIpPoolStore, smtpRelay, objectMapper, null, clock);
}
SesService(StorageBackend<String, Identity> identityStore,
StorageBackend<String, SentEmail> emailStore,
StorageBackend<String, Boolean> accountSettingsStore,
StorageBackend<String, EmailTemplate> templateStore,
StorageBackend<String, ConfigurationSet> configSetStore,
StorageBackend<String, SuppressedDestination> suppressionStore,
StorageBackend<String, AccountSuppressionAttributes> accountSuppressionStore,
StorageBackend<String, DedicatedIpPool> dedicatedIpPoolStore,
SmtpRelay smtpRelay,
ObjectMapper objectMapper,
Route53Service route53Service,
Clock clock) {
this.identityStore = identityStore;
this.emailStore = emailStore;
this.accountSettingsStore = accountSettingsStore;
@@ -125,6 +156,8 @@ public class SesService {
this.objectMapper = objectMapper;
this.eventPublisher = null;
this.defaultAccountId = "000000000000";
this.route53Service = route53Service;
this.clock = clock;
}
public Identity verifyEmailIdentity(String emailAddress, String region) {
@@ -152,6 +185,10 @@ public class SesService {
if (existing != null) return existing;
Identity identity = new Identity(domain, "Domain");
identity.setDkimTokens(generateDkimTokens());
identity.setVerificationStatus("Pending");
identity.setDkimEnabled(true);
identity.setDkimVerificationStatus("Pending");
identityStore.put(key, identity);
LOG.infov("Verified domain identity: {0} in region {1}", domain, region);
return identity;
@@ -163,6 +200,7 @@ public class SesService {
}
String key = identityKey(region, identityValue);
identityStore.delete(key);
invalidateDkimLookupCache(region, identityValue);
String prefix = "identity::" + region + "::";
List<String> keys = new ArrayList<>(identityStore.keys().stream()
@@ -191,7 +229,8 @@ public class SesService {
public Identity getIdentityVerificationAttributes(String identityValue, String region) {
String key = identityKey(region, identityValue);
return identityStore.get(key).orElse(null);
Identity identity = identityStore.get(key).orElse(null);
return refreshIdentityState(identity, region);
}
public String sendEmail(String source, List<String> toAddresses, List<String> ccAddresses,
@@ -537,6 +576,147 @@ public class SesService {
LOG.infov("Updated DKIM attributes for {0}: signingEnabled={1}", identityValue, signingEnabled);
}
private List<String> generateDkimTokens() {
List<String> tokens = new ArrayList<>(3);
for (int i = 0; i < 3; i++) {
tokens.add(UUID.randomUUID().toString().replace("-", ""));
}
return tokens;
}
private Identity refreshIdentityState(Identity identity, String region) {
if (identity == null) {
return null;
}
boolean changed = false;
if ("Domain".equals(identity.getIdentityType()) && identity.getDkimTokens() == null) {
identity.setDkimTokens(generateDkimTokens());
changed = true;
}
if ("Domain".equals(identity.getIdentityType()) && hasDkimTokens(identity)) {
changed |= normalizePendingDomainState(identity);
if (!"Success".equals(identity.getVerificationStatus())
&& hasAllExpectedDkimRecords(identity, region)) {
identity.setVerificationStatus("Success");
if (identity.isDkimEnabled()) {
identity.setDkimVerificationStatus("Success");
}
changed = true;
}
}
if ("Success".equals(identity.getVerificationStatus())) {
invalidateDkimLookupCache(region, identity.getIdentity());
}
if (changed) {
identityStore.put(identityKey(region, identity.getIdentity()), identity);
}
return identity;
}
private boolean hasDkimTokens(Identity identity) {
return identity.getDkimTokens() != null && !identity.getDkimTokens().isEmpty();
}
private boolean normalizePendingDomainState(Identity identity) {
boolean changed = false;
if (!"Success".equals(identity.getVerificationStatus())
&& !"Pending".equals(identity.getVerificationStatus())) {
identity.setVerificationStatus("Pending");
changed = true;
}
if (identity.isDkimEnabled()
&& !"Success".equals(identity.getDkimVerificationStatus())
&& !"Pending".equals(identity.getDkimVerificationStatus())) {
identity.setDkimVerificationStatus("Pending");
changed = true;
}
return changed;
}
private boolean hasAllExpectedDkimRecords(Identity identity, String region) {
if (route53Service == null) {
return false;
}
Instant now = Instant.now(clock);
String cacheKey = dkimLookupCacheKey(region, identity);
DkimLookupCacheEntry cached = dkimLookupCache.get(cacheKey);
if (cached != null) {
if (now.isBefore(cached.expiresAt())) {
return cached.present();
}
dkimLookupCache.remove(cacheKey, cached);
}
boolean present = true;
for (String token : identity.getDkimTokens()) {
if (!hasExpectedDkimRecord(identity.getIdentity(), token)) {
present = false;
break;
}
}
dkimLookupCache.put(cacheKey, new DkimLookupCacheEntry(present, now.plus(DKIM_LOOKUP_CACHE_TTL)));
return present;
}
private boolean hasExpectedDkimRecord(String domain, String token) {
String expectedName = normalizeDnsName(token + "._domainkey." + domain);
String expectedValue = normalizeDnsName(token + ".dkim.amazonses.com");
for (HostedZone zone : route53Service.listHostedZones(null, Integer.MAX_VALUE)) {
for (ResourceRecordSet recordSet : route53Service.listResourceRecordSets(zone.getId(), null, null,
Integer.MAX_VALUE)) {
if (!"CNAME".equalsIgnoreCase(recordSet.getType())) {
continue;
}
if (!expectedName.equals(normalizeDnsName(recordSet.getName()))) {
continue;
}
List<ResourceRecord> records = recordSet.getRecords();
if (records == null) {
continue;
}
for (ResourceRecord record : records) {
if (record != null && expectedValue.equals(normalizeDnsName(record.getValue()))) {
return true;
}
}
}
}
return false;
}
private String normalizeDnsName(String value) {
if (value == null) {
return "";
}
String normalized = value.trim().toLowerCase(Locale.ROOT);
while (normalized.endsWith(".")) {
normalized = normalized.substring(0, normalized.length() - 1);
}
return normalized;
}
private void invalidateDkimLookupCache(String region, String identityValue) {
if (identityValue == null || identityValue.isBlank()) {
return;
}
String cachePrefix = region + "::" + normalizeDnsName(identityValue) + "::";
dkimLookupCache.keySet().removeIf(key -> key.startsWith(cachePrefix));
}
private String dkimLookupCacheKey(String region, Identity identity) {
List<String> normalizedTokens = identity.getDkimTokens().stream()
.map(this::normalizeDnsName)
.sorted()
.toList();
return region + "::" + normalizeDnsName(identity.getIdentity()) + "::" + String.join(",", normalizedTokens);
}
private record DkimLookupCacheEntry(boolean present, Instant expiresAt) {}
public void setFeedbackForwardingEnabled(String identityValue, boolean enabled, String region) {
String key = identityKey(region, identityValue);
Identity identity = identityStore.get(key)
@@ -32,6 +32,9 @@ public class Identity {
@JsonProperty("DkimVerificationStatus")
private String dkimVerificationStatus;
@JsonProperty("DkimTokens")
private List<String> dkimTokens;
@JsonProperty("NotificationAttributes")
private Map<String, String> notificationAttributes = new HashMap<>();
@@ -86,6 +89,9 @@ public class Identity {
public String getDkimVerificationStatus() { return dkimVerificationStatus; }
public void setDkimVerificationStatus(String dkimVerificationStatus) { this.dkimVerificationStatus = dkimVerificationStatus; }
public List<String> getDkimTokens() { return dkimTokens; }
public void setDkimTokens(List<String> dkimTokens) { this.dkimTokens = dkimTokens; }
public Map<String, String> getNotificationAttributes() { return notificationAttributes; }
public void setNotificationAttributes(Map<String, String> notificationAttributes) { this.notificationAttributes = notificationAttributes; }