Skip to content

armgit / floci

Public Imported from GitHub
0

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

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

shrimptails-f0ac1a0188495
diff --git a/compatibility-tests/sdk-test-java/pom.xml b/compatibility-tests/sdk-test-java/pom.xml
index 09ae65294b..4b1c137aa9 100644
--- a/compatibility-tests/sdk-test-java/pom.xml
+++ b/compatibility-tests/sdk-test-java/pom.xml
@@ -251,6 +251,10 @@
<groupId>software.amazon.awssdk</groupId>
<artifactId>sesv2</artifactId>
</dependency>
+ <dependency>
+ <groupId>software.amazon.awssdk</groupId>
+ <artifactId>route53</artifactId>
+ </dependency>
<!-- OpenSearch Service management client -->
<dependency>
<groupId>software.amazon.awssdk</groupId>
diff --git a/compatibility-tests/sdk-test-java/src/main/java/com/floci/test/TestFixtures.java b/compatibility-tests/sdk-test-java/src/main/java/com/floci/test/TestFixtures.java
index cf3b9c1ec2..0f2246aae6 100644
--- a/compatibility-tests/sdk-test-java/src/main/java/com/floci/test/TestFixtures.java
+++ b/compatibility-tests/sdk-test-java/src/main/java/com/floci/test/TestFixtures.java
@@ -64,6 +64,16 @@ import software.amazon.awssdk.services.autoscaling.AutoScalingClient;
import software.amazon.awssdk.services.backup.BackupClient;
import software.amazon.awssdk.services.elasticloadbalancingv2.ElasticLoadBalancingV2Client;
import software.amazon.awssdk.services.appsync.AppSyncClient;
+import software.amazon.awssdk.services.route53.Route53Client;
+import software.amazon.awssdk.services.route53.model.Change;
+import software.amazon.awssdk.services.route53.model.ChangeAction;
+import software.amazon.awssdk.services.route53.model.ChangeBatch;
+import software.amazon.awssdk.services.route53.model.ChangeResourceRecordSetsRequest;
+import software.amazon.awssdk.services.route53.model.CreateHostedZoneRequest;
+import software.amazon.awssdk.services.route53.model.CreateHostedZoneResponse;
+import software.amazon.awssdk.services.route53.model.RRType;
+import software.amazon.awssdk.services.route53.model.ResourceRecord;
+import software.amazon.awssdk.services.route53.model.ResourceRecordSet;
import software.amazon.awssdk.services.s3vectors.S3VectorsClient;
import software.amazon.awssdk.core.SdkBytes;
@@ -74,11 +84,15 @@ import software.amazon.awssdk.services.lambda.model.InvokeRequest;
import software.amazon.awssdk.services.lambda.model.InvokeResponse;
import software.amazon.awssdk.services.lambda.model.InvocationType;
import software.amazon.awssdk.services.lambda.model.Runtime;
+import software.amazon.awssdk.services.sesv2.model.CreateEmailIdentityRequest;
+import software.amazon.awssdk.services.sesv2.model.CreateEmailIdentityResponse;
+import software.amazon.awssdk.services.sesv2.model.GetEmailIdentityRequest;
import java.io.ByteArrayOutputStream;
import java.net.URI;
import java.nio.charset.StandardCharsets;
import java.time.Duration;
+import java.util.List;
import java.util.UUID;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
@@ -535,6 +549,75 @@ public final class TestFixtures {
.build();
}
+ public static Route53Client route53Client() {
+ return Route53Client.builder()
+ .endpointOverride(ENDPOINT)
+ .region(REGION)
+ .credentialsProvider(CREDENTIALS)
+ .build();
+ }
+
+ public static void verifySesDomainIdentityViaRoute53(SesV2Client sesV2, String domain) {
+ CreateEmailIdentityResponse identity = sesV2.createEmailIdentity(CreateEmailIdentityRequest.builder()
+ .emailIdentity(domain)
+ .build());
+ List<String> tokens = identity.dkimAttributes() != null ? identity.dkimAttributes().tokens() : null;
+ if (tokens == null || tokens.isEmpty()) {
+ throw new IllegalStateException("CreateEmailIdentity did not return DKIM tokens for " + domain);
+ }
+
+ try (Route53Client route53 = route53Client()) {
+ CreateHostedZoneResponse zone = route53.createHostedZone(CreateHostedZoneRequest.builder()
+ .name(domain)
+ .callerReference(uniqueName("ses-dkim-zone"))
+ .build());
+
+ List<Change> changes = tokens.stream()
+ .map(token -> Change.builder()
+ .action(ChangeAction.CREATE)
+ .resourceRecordSet(ResourceRecordSet.builder()
+ .name(token + "._domainkey." + domain)
+ .type(RRType.CNAME)
+ .ttl(300L)
+ .resourceRecords(ResourceRecord.builder()
+ .value(token + ".dkim.amazonses.com")
+ .build())
+ .build())
+ .build())
+ .toList();
+
+ route53.changeResourceRecordSets(ChangeResourceRecordSetsRequest.builder()
+ .hostedZoneId(stripHostedZonePrefix(zone.hostedZone().id()))
+ .changeBatch(ChangeBatch.builder().changes(changes).build())
+ .build());
+ }
+
+ for (int i = 0; i < 10; i++) {
+ boolean verified = sesV2.getEmailIdentity(GetEmailIdentityRequest.builder()
+ .emailIdentity(domain)
+ .build())
+ .verifiedForSendingStatus();
+ if (verified) {
+ return;
+ }
+ try {
+ Thread.sleep(100L);
+ } catch (InterruptedException e) {
+ Thread.currentThread().interrupt();
+ throw new RuntimeException("Interrupted while waiting for SES identity verification", e);
+ }
+ }
+
+ throw new IllegalStateException("SES identity was not verified after publishing DKIM records for " + domain);
+ }
+
+ private static String stripHostedZonePrefix(String hostedZoneId) {
+ String prefix = "/hostedzone/";
+ return hostedZoneId != null && hostedZoneId.startsWith(prefix)
+ ? hostedZoneId.substring(prefix.length())
+ : hostedZoneId;
+ }
+
public static RdsClient rdsClient() {
return RdsClient.builder()
.endpointOverride(ENDPOINT)
diff --git a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/SesConfigurationSetOptionsTest.java b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/SesConfigurationSetOptionsTest.java
index 2b89655b03..dba8e70e4b 100644
--- a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/SesConfigurationSetOptionsTest.java
+++ b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/SesConfigurationSetOptionsTest.java
@@ -15,7 +15,6 @@ import software.amazon.awssdk.services.sesv2.model.DashboardOptions;
import software.amazon.awssdk.services.sesv2.model.GuardianOptions;
import software.amazon.awssdk.services.sesv2.model.CreateConfigurationSetRequest;
import software.amazon.awssdk.services.sesv2.model.CreateDedicatedIpPoolRequest;
-import software.amazon.awssdk.services.sesv2.model.CreateEmailIdentityRequest;
import software.amazon.awssdk.services.sesv2.model.DeleteConfigurationSetRequest;
import software.amazon.awssdk.services.sesv2.model.DeleteDedicatedIpPoolRequest;
import software.amazon.awssdk.services.sesv2.model.DeleteEmailIdentityRequest;
@@ -67,11 +66,7 @@ class SesConfigurationSetOptionsTest {
deleteConfigSetQuietly(CREATE_CS_BAD);
sesV2.createConfigurationSet(CreateConfigurationSetRequest.builder()
.configurationSetName(CS_NAME).build());
- // CustomRedirectDomain must be a verified domain identity.
- try {
- sesV2.createEmailIdentity(CreateEmailIdentityRequest.builder()
- .emailIdentity(TRACK_DOMAIN).build());
- } catch (Exception ignored) {}
+ TestFixtures.verifySesDomainIdentityViaRoute53(sesV2, TRACK_DOMAIN);
}
@AfterAll
diff --git a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/SesConfigurationSetTrackingOptionsTest.java b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/SesConfigurationSetTrackingOptionsTest.java
index 9a47305f9a..5f1218ef40 100644
--- a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/SesConfigurationSetTrackingOptionsTest.java
+++ b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/SesConfigurationSetTrackingOptionsTest.java
@@ -24,12 +24,15 @@ import software.amazon.awssdk.services.ses.model.TrackingOptionsAlreadyExistsExc
import software.amazon.awssdk.services.ses.model.TrackingOptionsDoesNotExistException;
import software.amazon.awssdk.services.ses.model.UpdateConfigurationSetReputationMetricsEnabledRequest;
import software.amazon.awssdk.services.ses.model.UpdateConfigurationSetTrackingOptionsRequest;
-import software.amazon.awssdk.services.ses.model.VerifyDomainIdentityRequest;
import software.amazon.awssdk.services.sesv2.SesV2Client;
+import software.amazon.awssdk.services.sesv2.model.DeleteEmailIdentityRequest;
import software.amazon.awssdk.services.sesv2.model.GetConfigurationSetRequest;
import software.amazon.awssdk.services.sesv2.model.GetConfigurationSetResponse;
+import java.util.logging.Level;
+import java.util.logging.Logger;
+
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
@@ -46,6 +49,8 @@ import static org.assertj.core.api.Assertions.assertThatThrownBy;
@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
class SesConfigurationSetTrackingOptionsTest {
+ private static final Logger LOG = Logger.getLogger(SesConfigurationSetTrackingOptionsTest.class.getName());
+
private static final String CS = "compat-cs-v1-tracking";
private static final String DOMAIN = "track.compat.floci.test";
private static final String DOMAIN_2 = "track2.compat.floci.test";
@@ -58,8 +63,8 @@ class SesConfigurationSetTrackingOptionsTest {
sesV1 = TestFixtures.sesClient();
sesV2 = TestFixtures.sesV2Client();
deleteCsQuietly();
- sesV1.verifyDomainIdentity(VerifyDomainIdentityRequest.builder().domain(DOMAIN).build());
- sesV1.verifyDomainIdentity(VerifyDomainIdentityRequest.builder().domain(DOMAIN_2).build());
+ TestFixtures.verifySesDomainIdentityViaRoute53(sesV2, DOMAIN);
+ TestFixtures.verifySesDomainIdentityViaRoute53(sesV2, DOMAIN_2);
sesV1.createConfigurationSet(CreateConfigurationSetRequest.builder()
.configurationSet(ConfigurationSet.builder().name(CS).build()).build());
}
@@ -71,6 +76,22 @@ class SesConfigurationSetTrackingOptionsTest {
sesV1.close();
}
if (sesV2 != null) {
+ try {
+ sesV2.deleteEmailIdentity(DeleteEmailIdentityRequest.builder()
+ .emailIdentity(DOMAIN).build());
+ } catch (Exception e) {
+ LOG.log(Level.WARNING,
+ String.format("Could not delete SES identity %s during cleanup: %s", DOMAIN, e.getMessage()),
+ e);
+ }
+ try {
+ sesV2.deleteEmailIdentity(DeleteEmailIdentityRequest.builder()
+ .emailIdentity(DOMAIN_2).build());
+ } catch (Exception e) {
+ LOG.log(Level.WARNING,
+ String.format("Could not delete SES identity %s during cleanup: %s", DOMAIN_2, e.getMessage()),
+ e);
+ }
sesV2.close();
}
}
diff --git a/src/main/java/io/github/hectorvent/floci/services/ses/SesController.java b/src/main/java/io/github/hectorvent/floci/services/ses/SesController.java
index ec07dc1fd4..7acafdee62 100644
--- a/src/main/java/io/github/hectorvent/floci/services/ses/SesController.java
+++ b/src/main/java/io/github/hectorvent/floci/services/ses/SesController.java
@@ -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;
}
diff --git a/src/main/java/io/github/hectorvent/floci/services/ses/SesQueryHandler.java b/src/main/java/io/github/hectorvent/floci/services/ses/SesQueryHandler.java
index 791f3d2d7d..0ded3a8a23 100644
--- a/src/main/java/io/github/hectorvent/floci/services/ses/SesQueryHandler.java
+++ b/src/main/java/io/github/hectorvent/floci/services/ses/SesQueryHandler.java
@@ -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");
}
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 6c5093eb6b..3092885476 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
@@ -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)
diff --git a/src/main/java/io/github/hectorvent/floci/services/ses/model/Identity.java b/src/main/java/io/github/hectorvent/floci/services/ses/model/Identity.java
index 107adfc444..7e1e85e1cc 100644
--- a/src/main/java/io/github/hectorvent/floci/services/ses/model/Identity.java
+++ b/src/main/java/io/github/hectorvent/floci/services/ses/model/Identity.java
@@ -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; }
diff --git a/src/test/java/io/github/hectorvent/floci/services/ses/SesConfigurationSetTrackingOptionsV1IntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/ses/SesConfigurationSetTrackingOptionsV1IntegrationTest.java
index 26a1d2d5cb..7249c3267b 100644
--- a/src/test/java/io/github/hectorvent/floci/services/ses/SesConfigurationSetTrackingOptionsV1IntegrationTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/ses/SesConfigurationSetTrackingOptionsV1IntegrationTest.java
@@ -7,6 +7,8 @@ import org.junit.jupiter.api.Order;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestMethodOrder;
+import java.util.List;
+
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.not;
@@ -26,9 +28,80 @@ class SesConfigurationSetTrackingOptionsV1IntegrationTest {
private static final String AUTH =
"AWS4-HMAC-SHA256 Credential=AKID/20260101/us-east-1/email/aws4_request";
+ private static final String AUTH_V2 =
+ "AWS4-HMAC-SHA256 Credential=AKID/20260101/us-east-1/ses/aws4_request";
private static final String DOMAIN = "track-v1.floci.test";
private static final String CS = "v1-cs-tracking";
+ private static void verifyDomainIdentityViaRoute53(String domain, String callerReference) {
+ List<String> tokens = given()
+ .contentType("application/json")
+ .header("Authorization", AUTH_V2)
+ .body("{\"EmailIdentity\": \"" + domain + "\"}")
+ .when()
+ .post("/v2/email/identities")
+ .then()
+ .statusCode(200)
+ .extract()
+ .jsonPath()
+ .getList("DkimAttributes.Tokens", String.class);
+
+ String locationHeader = given()
+ .contentType("application/xml")
+ .body("""
+ <?xml version="1.0" encoding="UTF-8"?>
+ <CreateHostedZoneRequest xmlns="https://route53.amazonaws.com/doc/2013-04-01/">
+ <Name>floci.test</Name>
+ <CallerReference>""" + callerReference + """
+ </CallerReference>
+ </CreateHostedZoneRequest>
+ """)
+ .when()
+ .post("/2013-04-01/hostedzone")
+ .then()
+ .statusCode(201)
+ .extract()
+ .header("Location");
+
+ String zoneId = locationHeader.substring(locationHeader.lastIndexOf('/') + 1);
+ StringBuilder body = new StringBuilder("""
+ <?xml version="1.0" encoding="UTF-8"?>
+ <ChangeResourceRecordSetsRequest xmlns="https://route53.amazonaws.com/doc/2013-04-01/">
+ <ChangeBatch>
+ <Changes>
+ """);
+ for (String token : tokens) {
+ body.append("""
+ <Change>
+ <Action>CREATE</Action>
+ <ResourceRecordSet>
+ <Name>""").append(token).append("._domainkey.").append(domain).append(".</Name>\n")
+ .append("""
+ <Type>CNAME</Type>
+ <TTL>300</TTL>
+ <ResourceRecords>
+ <ResourceRecord><Value>""").append(token).append(".dkim.amazonses.com.</Value></ResourceRecord>\n")
+ .append("""
+ </ResourceRecords>
+ </ResourceRecordSet>
+ </Change>
+ """);
+ }
+ body.append("""
+ </Changes>
+ </ChangeBatch>
+ </ChangeResourceRecordSetsRequest>
+ """);
+
+ given()
+ .contentType("application/xml")
+ .body(body.toString())
+ .when()
+ .post("/2013-04-01/hostedzone/" + zoneId + "/rrset")
+ .then()
+ .statusCode(200);
+ }
+
private static RequestSpecification query(String action) {
return given()
.contentType("application/x-www-form-urlencoded")
@@ -39,8 +112,7 @@ class SesConfigurationSetTrackingOptionsV1IntegrationTest {
@Test
@Order(1)
void setup_verifyDomain_andCreateConfigSet() {
- query("VerifyDomainIdentity").formParam("Domain", DOMAIN)
- .when().post("/").then().statusCode(200);
+ verifyDomainIdentityViaRoute53(DOMAIN, "v1-cs-tracking");
query("CreateConfigurationSet").formParam("ConfigurationSet.Name", CS)
.when().post("/").then().statusCode(200);
}
@@ -100,8 +172,7 @@ class SesConfigurationSetTrackingOptionsV1IntegrationTest {
@Test
@Order(6)
void updateTrackingOptions_changesDomain() {
- query("VerifyDomainIdentity").formParam("Domain", "other." + DOMAIN)
- .when().post("/").then().statusCode(200);
+ verifyDomainIdentityViaRoute53("other." + DOMAIN, "v1-cs-tracking-other");
query("UpdateConfigurationSetTrackingOptions")
.formParam("ConfigurationSetName", CS)
.formParam("TrackingOptions.CustomRedirectDomain", "other." + DOMAIN)
diff --git a/src/test/java/io/github/hectorvent/floci/services/ses/SesConfigurationSetV2IntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/ses/SesConfigurationSetV2IntegrationTest.java
index ed97bf37a2..d1902ab741 100644
--- a/src/test/java/io/github/hectorvent/floci/services/ses/SesConfigurationSetV2IntegrationTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/ses/SesConfigurationSetV2IntegrationTest.java
@@ -6,6 +6,8 @@ import org.junit.jupiter.api.Order;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestMethodOrder;
+import java.util.List;
+
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.hasItem;
@@ -22,6 +24,75 @@ class SesConfigurationSetV2IntegrationTest {
private static final String AUTH_HEADER =
"AWS4-HMAC-SHA256 Credential=AKID/20260101/us-east-1/ses/aws4_request";
+ private static void verifyDomainIdentityViaRoute53(String domain, String callerReference) {
+ List<String> tokens = given()
+ .contentType("application/json")
+ .header("Authorization", AUTH_HEADER)
+ .body("{\"EmailIdentity\": \"" + domain + "\"}")
+ .when()
+ .post("/v2/email/identities")
+ .then()
+ .statusCode(200)
+ .extract()
+ .jsonPath()
+ .getList("DkimAttributes.Tokens", String.class);
+
+ String locationHeader = given()
+ .contentType("application/xml")
+ .body("""
+ <?xml version="1.0" encoding="UTF-8"?>
+ <CreateHostedZoneRequest xmlns="https://route53.amazonaws.com/doc/2013-04-01/">
+ <Name>floci.test</Name>
+ <CallerReference>""" + callerReference + """
+ </CallerReference>
+ </CreateHostedZoneRequest>
+ """)
+ .when()
+ .post("/2013-04-01/hostedzone")
+ .then()
+ .statusCode(201)
+ .extract()
+ .header("Location");
+
+ String zoneId = locationHeader.substring(locationHeader.lastIndexOf('/') + 1);
+ StringBuilder body = new StringBuilder("""
+ <?xml version="1.0" encoding="UTF-8"?>
+ <ChangeResourceRecordSetsRequest xmlns="https://route53.amazonaws.com/doc/2013-04-01/">
+ <ChangeBatch>
+ <Changes>
+ """);
+ for (String token : tokens) {
+ body.append("""
+ <Change>
+ <Action>CREATE</Action>
+ <ResourceRecordSet>
+ <Name>""").append(token).append("._domainkey.").append(domain).append(".</Name>\n")
+ .append("""
+ <Type>CNAME</Type>
+ <TTL>300</TTL>
+ <ResourceRecords>
+ <ResourceRecord><Value>""").append(token).append(".dkim.amazonses.com.</Value></ResourceRecord>\n")
+ .append("""
+ </ResourceRecords>
+ </ResourceRecordSet>
+ </Change>
+ """);
+ }
+ body.append("""
+ </Changes>
+ </ChangeBatch>
+ </ChangeResourceRecordSetsRequest>
+ """);
+
+ given()
+ .contentType("application/xml")
+ .body(body.toString())
+ .when()
+ .post("/2013-04-01/hostedzone/" + zoneId + "/rrset")
+ .then()
+ .statusCode(200);
+ }
+
@Test
@Order(1)
void createConfigurationSet() {
@@ -771,9 +842,7 @@ class SesConfigurationSetV2IntegrationTest {
@Test
@Order(37)
void putTrackingOptions_verifiedDomain_echoed() {
- given().contentType("application/json").header("Authorization", AUTH_HEADER)
- .body("{\"EmailIdentity\": \"track.floci.test\"}")
- .when().post("/v2/email/identities").then().statusCode(200);
+ verifyDomainIdentityViaRoute53("track.floci.test", "v2-cs-tracking");
putConfigSet("v2-cs-tracking");
given().contentType("application/json").header("Authorization", AUTH_HEADER)
.body("{\"CustomRedirectDomain\": \"track.floci.test\", \"HttpsPolicy\": \"REQUIRE\"}")
@@ -803,9 +872,7 @@ class SesConfigurationSetV2IntegrationTest {
void putTrackingOptions_invalidHttpsPolicy_returns400() {
// AWS validates the HttpsPolicy enum only after CustomRedirectDomain
// presence and verification, so the domain must be verified to reach it.
- given().contentType("application/json").header("Authorization", AUTH_HEADER)
- .body("{\"EmailIdentity\": \"track-enum.floci.test\"}")
- .when().post("/v2/email/identities").then().statusCode(200);
+ verifyDomainIdentityViaRoute53("track-enum.floci.test", "v2-cs-tracking-enum");
putConfigSet("v2-cs-tracking-enum");
given().contentType("application/json").header("Authorization", AUTH_HEADER)
.body("{\"CustomRedirectDomain\": \"track-enum.floci.test\", \"HttpsPolicy\": \"BOGUS\"}")
@@ -817,6 +884,21 @@ class SesConfigurationSetV2IntegrationTest {
+ "Member must satisfy enum value set: [OPTIONAL, REQUIRE, REQUIRE_OPEN_ONLY]"));
}
+ @Test
+ @Order(100)
+ void putTrackingOptions_pendingDomain_returns400() {
+ given().contentType("application/json").header("Authorization", AUTH_HEADER)
+ .body("{\"EmailIdentity\": \"track-pending.floci.test\"}")
+ .when().post("/v2/email/identities").then().statusCode(200);
+ putConfigSet("v2-cs-tracking-pending");
+ given().contentType("application/json").header("Authorization", AUTH_HEADER)
+ .body("{\"CustomRedirectDomain\": \"track-pending.floci.test\", \"HttpsPolicy\": \"REQUIRE\"}")
+ .when().put("/v2/email/configuration-sets/v2-cs-tracking-pending/tracking-options")
+ .then().statusCode(400)
+ .body("__type", equalTo("BadRequestException"))
+ .body("message", equalTo("Domain <track-pending.floci.test> is not verified under this account."));
+ }
+
@Test
@Order(40)
void putReputationOptions_emptyBody_disables() {
@@ -976,9 +1058,7 @@ class SesConfigurationSetV2IntegrationTest {
void putTrackingOptions_emptyBody_clears() {
// An empty PUT body clears tracking options rather than persisting an
// empty block that GetConfigurationSet would echo as {}.
- given().contentType("application/json").header("Authorization", AUTH_HEADER)
- .body("{\"EmailIdentity\": \"clear.floci.test\"}")
- .when().post("/v2/email/identities").then().statusCode(200);
+ verifyDomainIdentityViaRoute53("clear.floci.test", "v2-cs-tracking-clear");
putConfigSet("v2-cs-tracking-clear");
given().contentType("application/json").header("Authorization", AUTH_HEADER)
.body("{\"CustomRedirectDomain\": \"clear.floci.test\", \"HttpsPolicy\": \"REQUIRE\"}")
diff --git a/src/test/java/io/github/hectorvent/floci/services/ses/SesIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/ses/SesIntegrationTest.java
index 3cd4130ce4..0adf2497c9 100644
--- a/src/test/java/io/github/hectorvent/floci/services/ses/SesIntegrationTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/ses/SesIntegrationTest.java
@@ -132,6 +132,22 @@ class SesIntegrationTest {
.body(containsString("<VerificationStatus>NotStarted</VerificationStatus>"));
}
+ @Test
+ @Order(15)
+ void getIdentityVerificationAttributes_domainStartsPending() {
+ given()
+ .contentType("application/x-www-form-urlencoded")
+ .header("Authorization", authorization("email"))
+ .formParam("Action", "GetIdentityVerificationAttributes")
+ .formParam("Identities.member.1", "example.com")
+ .when()
+ .post("/")
+ .then()
+ .statusCode(200)
+ .body(containsString("example.com"))
+ .body(containsString("<VerificationStatus>Pending</VerificationStatus>"));
+ }
+
@Test
@Order(8)
void listVerifiedEmailAddresses() {
@@ -313,7 +329,9 @@ class SesIntegrationTest {
.then()
.statusCode(200)
.body(containsString("example.com"))
- .body(containsString("<DkimEnabled>"));
+ .body(containsString("<DkimEnabled>true</DkimEnabled>"))
+ .body(containsString("<DkimVerificationStatus>Pending</DkimVerificationStatus>"))
+ .body(containsString("<DkimTokens><member>"));
}
@Test
diff --git a/src/test/java/io/github/hectorvent/floci/services/ses/SesServiceDkimLookupCacheTest.java b/src/test/java/io/github/hectorvent/floci/services/ses/SesServiceDkimLookupCacheTest.java
new file mode 100644
index 0000000000..0922f53ba8
--- /dev/null
+++ b/src/test/java/io/github/hectorvent/floci/services/ses/SesServiceDkimLookupCacheTest.java
@@ -0,0 +1,142 @@
+package io.github.hectorvent.floci.services.ses;
+
+import com.fasterxml.jackson.databind.ObjectMapper;
+import io.github.hectorvent.floci.core.storage.InMemoryStorage;
+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.ConfigurationSet;
+import io.github.hectorvent.floci.services.ses.model.DedicatedIpPool;
+import io.github.hectorvent.floci.services.ses.model.EmailTemplate;
+import io.github.hectorvent.floci.services.ses.model.Identity;
+import io.github.hectorvent.floci.services.ses.model.SentEmail;
+import io.github.hectorvent.floci.services.ses.model.SuppressedDestination;
+import io.github.hectorvent.floci.testing.MutableClock;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+
+import java.time.Duration;
+import java.util.ArrayList;
+import java.util.List;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.mockito.ArgumentMatchers.eq;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.times;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+
+class SesServiceDkimLookupCacheTest {
+
+ private static final String REGION = "us-east-1";
+ private static final String DOMAIN = "example.com";
+
+ private SesService service;
+ private InMemoryStorage<String, Identity> identityStore;
+ private Route53Service route53Service;
+ private MutableClock clock;
+
+ @BeforeEach
+ void setUp() {
+ identityStore = new InMemoryStorage<>();
+ route53Service = mock(Route53Service.class);
+ clock = new MutableClock();
+ clock.reset();
+ service = new SesService(
+ identityStore,
+ new InMemoryStorage<String, SentEmail>(),
+ new InMemoryStorage<String, Boolean>(),
+ new InMemoryStorage<String, EmailTemplate>(),
+ new InMemoryStorage<String, ConfigurationSet>(),
+ new InMemoryStorage<String, SuppressedDestination>(),
+ new InMemoryStorage<String, AccountSuppressionAttributes>(),
+ new InMemoryStorage<String, DedicatedIpPool>(),
+ mock(SmtpRelay.class),
+ new ObjectMapper(),
+ route53Service,
+ clock);
+ }
+
+ @Test
+ void pendingIdentity_reusesCachedNegativeResultWithinTtl() {
+ Identity identity = storePendingDomainIdentity();
+ stubRoute53(identity, List.of());
+
+ assertEquals("Pending", service.getIdentityVerificationAttributes(DOMAIN, REGION).getVerificationStatus());
+ assertEquals("Pending", service.getIdentityVerificationAttributes(DOMAIN, REGION).getVerificationStatus());
+
+ verify(route53Service, times(1)).listHostedZones(null, Integer.MAX_VALUE);
+ verify(route53Service, times(1)).listResourceRecordSets(eq("zone-1"), eq(null), eq(null), eq(Integer.MAX_VALUE));
+ }
+
+ @Test
+ void pendingIdentity_rechecksAfterTtlExpires() {
+ Identity identity = storePendingDomainIdentity();
+ stubRoute53(identity, List.of());
+
+ assertEquals("Pending", service.getIdentityVerificationAttributes(DOMAIN, REGION).getVerificationStatus());
+ clock.advance(Duration.ofSeconds(5));
+ assertEquals("Pending", service.getIdentityVerificationAttributes(DOMAIN, REGION).getVerificationStatus());
+
+ verify(route53Service, times(2)).listHostedZones(null, Integer.MAX_VALUE);
+ verify(route53Service, times(2)).listResourceRecordSets(eq("zone-1"), eq(null), eq(null), eq(Integer.MAX_VALUE));
+ }
+
+ @Test
+ void successTransition_invalidatesCacheAfterRecordsAppear() {
+ Identity identity = storePendingDomainIdentity();
+ List<ResourceRecordSet> matchingRecords = buildMatchingRecords(identity);
+ stubRoute53(identity, List.of());
+
+ assertEquals("Pending", service.getIdentityVerificationAttributes(DOMAIN, REGION).getVerificationStatus());
+
+ when(route53Service.listResourceRecordSets("zone-1", null, null, Integer.MAX_VALUE))
+ .thenReturn(matchingRecords);
+
+ clock.advance(Duration.ofSeconds(5));
+ assertEquals("Success", service.getIdentityVerificationAttributes(DOMAIN, REGION).getVerificationStatus());
+ assertEquals("Success", service.getIdentityVerificationAttributes(DOMAIN, REGION).getVerificationStatus());
+
+ verify(route53Service, times(4)).listHostedZones(null, Integer.MAX_VALUE);
+ verify(route53Service, times(4)).listResourceRecordSets(eq("zone-1"), eq(null), eq(null), eq(Integer.MAX_VALUE));
+ }
+
+ private Identity storePendingDomainIdentity() {
+ Identity identity = new Identity(DOMAIN, "Domain");
+ identity.setVerificationStatus("Pending");
+ identity.setDkimEnabled(true);
+ identity.setDkimVerificationStatus("Pending");
+ identity.setDkimTokens(List.of("token-a", "token-b", "token-c"));
+ identityStore.put("identity::" + REGION + "::" + DOMAIN, identity);
+ return identity;
+ }
+
+ private void stubRoute53(Identity identity, List<ResourceRecordSet> records) {
+ when(route53Service.listHostedZones(null, Integer.MAX_VALUE))
+ .thenReturn(List.of(new HostedZone("zone-1", DOMAIN + ".", "ref", null, false)));
+ when(route53Service.listResourceRecordSets("zone-1", null, null, Integer.MAX_VALUE))
+ .thenReturn(records.isEmpty() ? List.of(nonMatchingRecordSet(identity)) : records);
+ }
+
+ private List<ResourceRecordSet> buildMatchingRecords(Identity identity) {
+ List<ResourceRecordSet> records = new ArrayList<>();
+ for (String token : identity.getDkimTokens()) {
+ ResourceRecordSet recordSet = new ResourceRecordSet();
+ recordSet.setName(token + "._domainkey." + DOMAIN + ".");
+ recordSet.setType("CNAME");
+ recordSet.setRecords(List.of(new ResourceRecord(token + ".dkim.amazonses.com.")));
+ records.add(recordSet);
+ }
+ return records;
+ }
+
+ private ResourceRecordSet nonMatchingRecordSet(Identity identity) {
+ ResourceRecordSet recordSet = new ResourceRecordSet();
+ recordSet.setName("other._domainkey." + DOMAIN + ".");
+ recordSet.setType("CNAME");
+ recordSet.setRecords(List.of(new ResourceRecord(identity.getDkimTokens().get(0) + ".dkim.amazonses.com.")));
+ return recordSet;
+ }
+}
diff --git a/src/test/java/io/github/hectorvent/floci/services/ses/SesServiceLegacyDkimTokensTest.java b/src/test/java/io/github/hectorvent/floci/services/ses/SesServiceLegacyDkimTokensTest.java
new file mode 100644
index 0000000000..225b664599
--- /dev/null
+++ b/src/test/java/io/github/hectorvent/floci/services/ses/SesServiceLegacyDkimTokensTest.java
@@ -0,0 +1,76 @@
+package io.github.hectorvent.floci.services.ses;
+
+import com.fasterxml.jackson.databind.ObjectMapper;
+import io.github.hectorvent.floci.core.storage.InMemoryStorage;
+import io.github.hectorvent.floci.services.ses.model.AccountSuppressionAttributes;
+import io.github.hectorvent.floci.services.ses.model.ConfigurationSet;
+import io.github.hectorvent.floci.services.ses.model.DedicatedIpPool;
+import io.github.hectorvent.floci.services.ses.model.EmailTemplate;
+import io.github.hectorvent.floci.services.ses.model.Identity;
+import io.github.hectorvent.floci.services.ses.model.SentEmail;
+import io.github.hectorvent.floci.services.ses.model.SuppressedDestination;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+
+import java.time.Clock;
+import java.util.List;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertNull;
+import static org.junit.jupiter.api.Assertions.assertSame;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.mockito.Mockito.mock;
+
+class SesServiceLegacyDkimTokensTest {
+
+ private static final String REGION = "us-east-1";
+
+ private SesService service;
+ private InMemoryStorage<String, Identity> identityStore;
+
+ @BeforeEach
+ void setUp() {
+ identityStore = new InMemoryStorage<>();
+ service = new SesService(
+ identityStore,
+ new InMemoryStorage<String, SentEmail>(),
+ new InMemoryStorage<String, Boolean>(),
+ new InMemoryStorage<String, EmailTemplate>(),
+ new InMemoryStorage<String, ConfigurationSet>(),
+ new InMemoryStorage<String, SuppressedDestination>(),
+ new InMemoryStorage<String, AccountSuppressionAttributes>(),
+ new InMemoryStorage<String, DedicatedIpPool>(),
+ mock(SmtpRelay.class),
+ new ObjectMapper(),
+ Clock.systemUTC());
+ }
+
+ @Test
+ void getIdentityVerificationAttributes_backfillsLegacyDomainDkimTokens() {
+ Identity legacy = new Identity("legacy.floci.test", "Domain");
+ legacy.setVerificationStatus("Pending");
+ legacy.setDkimEnabled(false);
+ legacy.setDkimVerificationStatus("NotStarted");
+ legacy.setDkimTokens(null);
+ assertNull(legacy.getDkimTokens());
+
+ String key = "identity::" + REGION + "::" + legacy.getIdentity();
+ identityStore.put(key, legacy);
+
+ Identity refreshed = service.getIdentityVerificationAttributes(legacy.getIdentity(), REGION);
+
+ assertSame(legacy, refreshed);
+ assertNotNull(refreshed.getDkimTokens());
+ assertEquals(3, refreshed.getDkimTokens().size());
+ assertTrue(refreshed.getDkimTokens().stream().allMatch(token -> token != null && !token.isBlank()));
+ assertEquals("Pending", refreshed.getVerificationStatus());
+ assertFalse(refreshed.isDkimEnabled());
+ assertEquals("NotStarted", refreshed.getDkimVerificationStatus());
+
+ List<String> persistedTokens = identityStore.get(key).orElseThrow().getDkimTokens();
+ assertNotNull(persistedTokens);
+ assertEquals(refreshed.getDkimTokens(), persistedTokens);
+ }
+}
diff --git a/src/test/java/io/github/hectorvent/floci/services/ses/SesServiceSmtpTest.java b/src/test/java/io/github/hectorvent/floci/services/ses/SesServiceSmtpTest.java
index 5ea3ce4151..67902b7aa1 100644
--- a/src/test/java/io/github/hectorvent/floci/services/ses/SesServiceSmtpTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/ses/SesServiceSmtpTest.java
@@ -15,6 +15,7 @@ import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
+import java.time.Clock;
import java.util.List;
import static org.junit.jupiter.api.Assertions.*;
@@ -41,7 +42,8 @@ class SesServiceSmtpTest {
new InMemoryStorage<String, AccountSuppressionAttributes>(),
new InMemoryStorage<String, DedicatedIpPool>(),
smtpRelay,
- new ObjectMapper());
+ new ObjectMapper(),
+ Clock.systemUTC());
}
@Test
diff --git a/src/test/java/io/github/hectorvent/floci/services/ses/SesServiceSuppressionLegacyKeyTest.java b/src/test/java/io/github/hectorvent/floci/services/ses/SesServiceSuppressionLegacyKeyTest.java
index c769d1de35..8eb5afc8b6 100644
--- a/src/test/java/io/github/hectorvent/floci/services/ses/SesServiceSuppressionLegacyKeyTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/ses/SesServiceSuppressionLegacyKeyTest.java
@@ -12,6 +12,8 @@ import io.github.hectorvent.floci.services.ses.model.SuppressedDestination;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
+import java.time.Clock;
+
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
@@ -48,7 +50,8 @@ class SesServiceSuppressionLegacyKeyTest {
new InMemoryStorage<String, AccountSuppressionAttributes>(),
new InMemoryStorage<String, DedicatedIpPool>(),
mock(SmtpRelay.class),
- new ObjectMapper());
+ new ObjectMapper(),
+ Clock.systemUTC());
}
private void seedLegacyEntry() {
diff --git a/src/test/java/io/github/hectorvent/floci/services/ses/SesServiceSuppressionReasonTest.java b/src/test/java/io/github/hectorvent/floci/services/ses/SesServiceSuppressionReasonTest.java
index 7d25414b30..b3a80d8380 100644
--- a/src/test/java/io/github/hectorvent/floci/services/ses/SesServiceSuppressionReasonTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/ses/SesServiceSuppressionReasonTest.java
@@ -12,6 +12,7 @@ import io.github.hectorvent.floci.services.ses.model.SuppressedDestination;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
+import java.time.Clock;
import java.util.ArrayList;
import java.util.List;
@@ -49,7 +50,8 @@ class SesServiceSuppressionReasonTest {
accountSuppressionStore,
new InMemoryStorage<String, DedicatedIpPool>(),
mock(SmtpRelay.class),
- new ObjectMapper());
+ new ObjectMapper(),
+ Clock.systemUTC());
}
@Test
diff --git a/src/test/java/io/github/hectorvent/floci/services/ses/SesV2IntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/ses/SesV2IntegrationTest.java
index 9c08351797..29aaec4afc 100644
--- a/src/test/java/io/github/hectorvent/floci/services/ses/SesV2IntegrationTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/ses/SesV2IntegrationTest.java
@@ -6,6 +6,8 @@ import org.junit.jupiter.api.Order;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestMethodOrder;
+import java.util.List;
+
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.*;
@@ -49,7 +51,11 @@ class SesV2IntegrationTest {
.post("/v2/email/identities")
.then()
.statusCode(200)
- .body("IdentityType", equalTo("DOMAIN"));
+ .body("IdentityType", equalTo("DOMAIN"))
+ .body("VerifiedForSendingStatus", equalTo(false))
+ .body("DkimAttributes.SigningEnabled", equalTo(true))
+ .body("DkimAttributes.Status", equalTo("PENDING"))
+ .body("DkimAttributes.Tokens", not(empty()));
}
@Test
@@ -97,6 +103,93 @@ class SesV2IntegrationTest {
.body("DkimAttributes", notNullValue());
}
+ @Test
+ @Order(61)
+ void getEmailIdentity_domainTransitionsToSuccessWhenDkimRecordsExist() {
+ List<String> tokens = given()
+ .contentType("application/json")
+ .header("Authorization", AUTH_HEADER)
+ .body("""
+ {"EmailIdentity": "v2dkim-success.floci.test"}
+ """)
+ .when()
+ .post("/v2/email/identities")
+ .then()
+ .statusCode(200)
+ .body("VerifiedForSendingStatus", equalTo(false))
+ .extract()
+ .jsonPath()
+ .getList("DkimAttributes.Tokens", String.class);
+
+ String locationHeader = given()
+ .contentType("application/xml")
+ .body("""
+ <?xml version="1.0" encoding="UTF-8"?>
+ <CreateHostedZoneRequest xmlns="https://route53.amazonaws.com/doc/2013-04-01/">
+ <Name>floci.test</Name>
+ <CallerReference>ses-v2-dkim-success</CallerReference>
+ </CreateHostedZoneRequest>
+ """)
+ .when()
+ .post("/2013-04-01/hostedzone")
+ .then()
+ .statusCode(201)
+ .extract()
+ .header("Location");
+
+ String zoneId = locationHeader.substring(locationHeader.lastIndexOf('/') + 1);
+ StringBuilder body = new StringBuilder("""
+ <?xml version="1.0" encoding="UTF-8"?>
+ <ChangeResourceRecordSetsRequest xmlns="https://route53.amazonaws.com/doc/2013-04-01/">
+ <ChangeBatch>
+ <Changes>
+ """);
+ for (String token : tokens) {
+ body.append("""
+ <Change>
+ <Action>CREATE</Action>
+ <ResourceRecordSet>
+ <Name>""").append(token).append("._domainkey.v2dkim-success.floci.test.</Name>\n")
+ .append("""
+ <Type>CNAME</Type>
+ <TTL>300</TTL>
+ <ResourceRecords>
+ <ResourceRecord><Value>""").append(token).append(".dkim.amazonses.com.</Value></ResourceRecord>\n")
+ .append("""
+ </ResourceRecords>
+ </ResourceRecordSet>
+ </Change>
+ """);
+ }
+ body.append("""
+ </Changes>
+ </ChangeBatch>
+ </ChangeResourceRecordSetsRequest>
+ """);
+
+ given()
+ .contentType("application/xml")
+ .body(body.toString())
+ .when()
+ .post("/2013-04-01/hostedzone/" + zoneId + "/rrset")
+ .then()
+ .statusCode(200);
+
+ given()
+ .contentType("application/json")
+ .header("Authorization", AUTH_HEADER)
+ .when()
+ .get("/v2/email/identities/v2dkim-success.floci.test")
+ .then()
+ .statusCode(200)
+ .body("IdentityType", equalTo("DOMAIN"))
+ .body("VerifiedForSendingStatus", equalTo(true))
+ .body("VerificationStatus", equalTo("SUCCESS"))
+ .body("DkimAttributes.SigningEnabled", equalTo(true))
+ .body("DkimAttributes.Status", equalTo("SUCCESS"))
+ .body("DkimAttributes.Tokens", not(empty()));
+ }
+
@Test
@Order(6)
void getEmailIdentity_notFound() {