Skip to content

armgit / floci

Public Imported from GitHub
0

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

fix(ses): create email identities atomically so failures leave nothing behind (#3146)

Kenshin Okinaka618ca5842475
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 412a8c43f7..12fb5a0aa7 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
@@ -115,41 +115,18 @@ public class SesController {
configurationSetName = configSetNode.textValue();
}
- if (sesService.getIdentityVerificationAttributes(emailIdentity, region) != null) {
- throw new AwsException("AlreadyExistsException",
- "Email identity " + emailIdentity + " already exist.", 400);
- }
-
- // Parse Tags up front. parseTagsArray is pure (it only reads the node), so validating the
- // shape before creating the identity keeps the call atomic — a malformed Tags value fails
- // without leaving a half-created identity behind, matching AWS and the ConfigurationSetName
- // pre-check below.
List<Tag> parsedTags = parseTagsArray(request.path("Tags"));
- // Validate tags before creating the identity so an invalid set fails atomically
- // instead of leaving the identity behind.
- SesTags.validate(parsedTags);
- // Verified against AWS: a non-existent ConfigurationSetName fails the whole call
- // (NotFoundException) without creating the identity, so validate it before creating.
// Only the empty string means "no default configuration set" (consistent with the
// PutEmailIdentityConfigurationSetAttributes path); a whitespace-only name flows through
// name validation and is rejected as invalid input, rather than being silently ignored.
boolean hasConfigSet = configurationSetName != null && !configurationSetName.isEmpty();
- if (hasConfigSet) {
- sesService.getConfigurationSet(configurationSetName, region);
- }
-
- Identity identity = emailIdentity.contains("@")
- ? sesService.verifyEmailIdentity(emailIdentity, region)
- : sesService.verifyDomainIdentity(emailIdentity, region);
- if (hasConfigSet) {
- sesService.setEmailIdentityConfigurationSet(emailIdentity, configurationSetName, region);
- }
-
- if (parsedTags != null) {
- sesService.setIdentityTags(emailIdentity, region, parsedTags);
- }
+ // The service builds the complete identity (default configuration set and tags included)
+ // and persists it with a single write, so any failure (AlreadyExists, invalid tags, a
+ // missing configuration set) fails the whole call and creates nothing, matching AWS.
+ Identity identity = sesService.createEmailIdentity(emailIdentity,
+ hasConfigSet ? configurationSetName : null, parsedTags, region);
ObjectNode result = objectMapper.createObjectNode();
result.put("IdentityType", toV2IdentityType(identity.getIdentityType()));
diff --git a/src/main/java/io/github/hectorvent/floci/services/ses/SesIdentityService.java b/src/main/java/io/github/hectorvent/floci/services/ses/SesIdentityService.java
index db3d659bff..8a4b8595fa 100644
--- a/src/main/java/io/github/hectorvent/floci/services/ses/SesIdentityService.java
+++ b/src/main/java/io/github/hectorvent/floci/services/ses/SesIdentityService.java
@@ -51,6 +51,10 @@ public class SesIdentityService {
private final Route53Service route53Service;
private final Clock clock;
private final ConcurrentHashMap<String, DkimLookupCacheEntry> dkimLookupCache = new ConcurrentHashMap<>();
+ // Serializes every identity check-then-put (v2 CreateEmailIdentity, the v1 verify family, the
+ // CVET pending registration) so concurrent creators can't lose each other's writes
+ // (InMemoryStorage only makes each individual operation thread-safe).
+ private final Object identityCreationLock = new Object();
@Inject
public SesIdentityService(StorageFactory storageFactory, Route53Service route53Service, Clock clock) {
@@ -71,13 +75,15 @@ public class SesIdentityService {
throw new AwsException("InvalidParameterValue", "Email address is required.", 400);
}
String key = identityKey(region, emailAddress);
- Identity existing = identityStore.get(key).orElse(null);
- if (existing != null) {
- return existing;
+ Identity identity;
+ synchronized (identityCreationLock) {
+ Identity existing = identityStore.get(key).orElse(null);
+ if (existing != null) {
+ return existing;
+ }
+ identity = new Identity(emailAddress, "EmailAddress");
+ identityStore.put(key, identity);
}
-
- Identity identity = new Identity(emailAddress, "EmailAddress");
- identityStore.put(key, identity);
LOG.infov("Verified email identity: {0} in region {1}", emailAddress, region);
return identity;
}
@@ -88,11 +94,20 @@ public class SesIdentityService {
throw new AwsException("InvalidParameterValue", "Domain is required.", 400);
}
String key = identityKey(region, domain);
- Identity existing = identityStore.get(key).orElse(null);
- if (existing != null) {
- return existing;
+ Identity identity;
+ synchronized (identityCreationLock) {
+ Identity existing = identityStore.get(key).orElse(null);
+ if (existing != null) {
+ return existing;
+ }
+ identity = newDomainIdentity(domain);
+ identityStore.put(key, identity);
}
+ LOG.infov("Verified domain identity: {0} in region {1}", domain, region);
+ return identity;
+ }
+ private Identity newDomainIdentity(String domain) {
Identity identity = new Identity(domain, "Domain");
regenerateDkimTokens(identity);
identity.setVerificationStatus("Pending");
@@ -101,8 +116,49 @@ public class SesIdentityService {
// CNAMEs yet); the first Get/List refresh transitions it to Pending. Matches AWS, where
// CreateEmailIdentity returns NOT_STARTED but a subsequent GetEmailIdentity returns PENDING.
identity.setDkimVerificationStatus("NotStarted");
- identityStore.put(key, identity);
- LOG.infov("Verified domain identity: {0} in region {1}", domain, region);
+ return identity;
+ }
+
+ /**
+ * v2 CreateEmailIdentity: builds the complete identity (default configuration set and tags
+ * included) and persists it with a single write, so a failing validation leaves nothing behind,
+ * matching real SESv2 where the whole call fails and no resource is created (probe-confirmed
+ * 2026-09-06: a failed create leaves a 404 behind, not a half-created identity). The validation
+ * order is probe-confirmed too: AlreadyExists, then tag validation, then the caller-supplied
+ * configuration-set existence check (cross-domain, so the facade passes it in), then the write.
+ * The lock closes the check-then-put race where two concurrent creates for the same identity
+ * would both return 200; the loser now gets the AlreadyExists error, as on AWS.
+ */
+ public Identity createEmailIdentity(String emailIdentity, String configurationSetName,
+ List<Tag> tags, String region,
+ Runnable configurationSetExistsCheck) {
+ // Validate with the wording the pre-atomic path produced (the verify methods' field names),
+ // so the key derivation's generic "Identity" message never surfaces on this API.
+ validateIdentityWhitespace(emailIdentity,
+ emailIdentity != null && emailIdentity.contains("@") ? "Email address" : "Domain");
+ String key = identityKey(region, emailIdentity);
+ Identity identity;
+ synchronized (identityCreationLock) {
+ if (identityStore.get(key).isPresent()) {
+ throw new AwsException("AlreadyExistsException",
+ "Email identity " + emailIdentity + " already exist.", 400);
+ }
+ SesTags.validate(tags);
+ if (configurationSetExistsCheck != null) {
+ configurationSetExistsCheck.run();
+ }
+ identity = emailIdentity.contains("@")
+ ? new Identity(emailIdentity, "EmailAddress")
+ : newDomainIdentity(emailIdentity);
+ if (configurationSetName != null) {
+ identity.setConfigurationSetName(configurationSetName);
+ }
+ if (tags != null) {
+ identity.setTags(tags);
+ }
+ identityStore.put(key, identity);
+ }
+ LOG.infov("Created email identity: {0} in region {1}", emailIdentity, region);
return identity;
}
@@ -211,13 +267,16 @@ public class SesIdentityService {
/** Registers the CVET recipient as a pending email identity when it is not already known. */
public void markPendingEmailIdentity(String emailAddress, String region) {
String key = identityKey(region, emailAddress);
- if (identityStore.get(key).isEmpty()) {
+ synchronized (identityCreationLock) {
+ if (identityStore.get(key).isPresent()) {
+ return;
+ }
Identity identity = new Identity(emailAddress, "EmailAddress");
identity.setVerificationStatus("Pending");
identityStore.put(key, identity);
- LOG.infov("SES custom verification email registered pending identity {0} in region {1}",
- emailAddress, region);
}
+ LOG.infov("SES custom verification email registered pending identity {0} in region {1}",
+ emailAddress, region);
}
static final List<String> NOTIFICATION_TYPES = List.of("Bounce", "Complaint", "Delivery");
@@ -293,13 +352,6 @@ public class SesIdentityService {
LOG.infov("Untagged SES identity: {0} (region {1}, -{2} keys)", identityValue, region, tagKeys.size());
}
- public void setTags(String identityValue, String region, List<Tag> tags) {
- SesTags.validate(tags);
- Identity identity = requireForTags(identityValue, region);
- identity.setTags(tags);
- identityStore.put(identityKey(region, identityValue), identity);
- }
-
private Identity requireForTags(String identityValue, String region) {
return identityStore.get(identityKey(region, identityValue))
.orElseThrow(() -> new AwsException("NotFoundException",
@@ -382,17 +434,20 @@ public class SesIdentityService {
// Domain-only action: an email-shaped value must not create an email-valued "Domain".
throw new AwsException("InvalidParameterValue", "Domain " + domain + " is invalid.", 400);
}
- Identity identity = identityStore.get(identityKey(region, domain)).orElse(null);
- if (identity == null) {
- identity = new Identity(domain, "Domain");
- identity.setVerificationStatus("Pending");
- identity.setDkimEnabled(true);
- identity.setDkimVerificationStatus("Pending");
- }
- if (!hasDkimTokens(identity)) {
- regenerateDkimTokens(identity);
+ Identity identity;
+ synchronized (identityCreationLock) {
+ identity = identityStore.get(identityKey(region, domain)).orElse(null);
+ if (identity == null) {
+ identity = new Identity(domain, "Domain");
+ identity.setVerificationStatus("Pending");
+ identity.setDkimEnabled(true);
+ identity.setDkimVerificationStatus("Pending");
+ }
+ if (!hasDkimTokens(identity)) {
+ regenerateDkimTokens(identity);
+ }
+ identityStore.put(identityKey(region, domain), identity);
}
- identityStore.put(identityKey(region, domain), identity);
LOG.infov("VerifyDomainDkim: {0} (region {1})", domain, region);
return identity.getDkimTokens();
}
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 0e871b75be..30802b7880 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
@@ -172,6 +172,19 @@ public class SesService {
return identityService.verifyEmailIdentity(emailAddress, region);
}
+ /**
+ * v2 CreateEmailIdentity. The identity domain builds and persists the complete record in one
+ * write; only the configuration-set existence check is cross-domain, so it is passed in as the
+ * in-lock callback (a missing set fails the whole call and nothing is created, matching AWS).
+ */
+ public Identity createEmailIdentity(String emailIdentity, String configurationSetName,
+ List<Tag> tags, String region) {
+ Runnable configurationSetExistsCheck = configurationSetName == null ? null
+ : () -> getConfigurationSet(configurationSetName, region);
+ return identityService.createEmailIdentity(emailIdentity, configurationSetName, tags, region,
+ configurationSetExistsCheck);
+ }
+
public Identity verifyDomainIdentity(String domain, String region) {
return identityService.verifyDomainIdentity(domain, region);
}
@@ -1527,10 +1540,6 @@ public class SesService {
}
}
- public void setIdentityTags(String identityValue, String region, List<Tag> tags) {
- identityService.setTags(identityValue, region, tags);
- }
-
// name is everything after the type's first slash and may itself contain one: a tenant ARN's
// <name>/<tenantId> remainder passes through whole, decomposed by the tenant domain.
private record ResourceRef(String account, String region, String type, String name) {}
diff --git a/src/test/java/io/github/hectorvent/floci/services/ses/SesIdentityServiceTest.java b/src/test/java/io/github/hectorvent/floci/services/ses/SesIdentityServiceTest.java
index 2d9d75717a..2504dc0dbc 100644
--- a/src/test/java/io/github/hectorvent/floci/services/ses/SesIdentityServiceTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/ses/SesIdentityServiceTest.java
@@ -9,6 +9,10 @@ import org.junit.jupiter.api.Test;
import java.time.Clock;
import java.util.List;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicInteger;
+import java.util.concurrent.atomic.AtomicReference;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
@@ -130,14 +134,217 @@ class SesIdentityServiceTest {
service.find("[email protected]", REGION).orElseThrow().getVerificationStatus());
}
+ @Test
+ void createEmailIdentity_buildsTheCompleteRecordInOneWrite() {
+ Identity created = service.createEmailIdentity("[email protected]", "my-cs",
+ List.of(new Tag("team", "floci")), REGION, () -> { });
+ assertEquals("EmailAddress", created.getIdentityType());
+
+ Identity stored = service.find("[email protected]", REGION).orElseThrow();
+ assertEquals("my-cs", stored.getConfigurationSetName());
+ assertEquals(List.of("team"), stored.getTags().stream().map(Tag::key).toList());
+ }
+
+ @Test
+ void createEmailIdentity_domain_getsDkimTokensAndNotStarted() {
+ Identity created = service.createEmailIdentity("example.com", null, null, REGION, null);
+ assertEquals("Domain", created.getIdentityType());
+ assertEquals(3, created.getDkimTokens().size());
+ assertEquals("NotStarted", created.getDkimVerificationStatus());
+ }
+
+ @Test
+ void createEmailIdentity_duplicateThrows_withAwsGrammar() {
+ service.createEmailIdentity("[email protected]", null, null, REGION, null);
+ AwsException e = assertThrows(AwsException.class,
+ () -> service.createEmailIdentity("[email protected]", null, null, REGION, null));
+ // "already exist." is AWS's own grammar (probe-confirmed).
+ assertEquals("Email identity [email protected] already exist.", e.getMessage());
+ }
+
+ @Test
+ void createEmailIdentity_failures_leaveNothingBehind() {
+ assertThrows(AwsException.class, () -> service.createEmailIdentity(
+ "[email protected]", null, List.of(new Tag("", "v")), REGION, null));
+ assertTrue(service.find("[email protected]", REGION).isEmpty());
+
+ AwsException configSetGone = new AwsException("ConfigurationSetDoesNotExist",
+ "Configuration set <ghost> does not exist.", 400);
+ AwsException e = assertThrows(AwsException.class, () -> service.createEmailIdentity(
+ "[email protected]", "ghost", null, REGION, () -> { throw configSetGone; }));
+ assertEquals("ConfigurationSetDoesNotExist", e.getErrorCode());
+ assertTrue(service.find("[email protected]", REGION).isEmpty());
+ }
+
+ @Test
+ void createEmailIdentity_alreadyExists_winsOverLaterChecks() {
+ service.createEmailIdentity("[email protected]", null, null, REGION, null);
+ // Existing identity beats both invalid tags and a failing configuration-set check,
+ // preserving the wire-visible validation order.
+ AwsException e = assertThrows(AwsException.class, () -> service.createEmailIdentity(
+ "[email protected]", "ghost", List.of(new Tag("", "v")), REGION,
+ () -> { throw new AwsException("ConfigurationSetDoesNotExist", "boom", 400); }));
+ assertEquals("AlreadyExistsException", e.getErrorCode());
+ }
+
+ /** Any parked state counts as contending, so a switch to e.g. ReentrantLock stays green. */
+ private static boolean isParked(Thread.State state) {
+ return state == Thread.State.BLOCKED || state == Thread.State.WAITING
+ || state == Thread.State.TIMED_WAITING;
+ }
+
+ /** Counts put calls so the single-write guarantee is asserted, not inferred. */
+ private static final class CountingStorage extends InMemoryStorage<String, Identity> {
+ final AtomicInteger puts = new AtomicInteger();
+
+ @Override
+ public void put(String key, Identity value) {
+ puts.incrementAndGet();
+ super.put(key, value);
+ }
+ }
+
+ @Test
+ void createEmailIdentity_persistsWithExactlyOneWrite() {
+ CountingStorage store = new CountingStorage();
+ SesIdentityService counted = new SesIdentityService(store, null, Clock.systemUTC());
+ counted.createEmailIdentity("[email protected]", "my-cs",
+ List.of(new Tag("team", "floci")), REGION, () -> { });
+ assertEquals(1, store.puts.get());
+ }
+
+ @Test
+ void createEmailIdentity_concurrentDuplicate_loserGetsAlreadyExists() throws Exception {
+ CountingStorage store = new CountingStorage();
+ SesIdentityService counted = new SesIdentityService(store, null, Clock.systemUTC());
+ CountDownLatch insideLock = new CountDownLatch(1);
+ CountDownLatch proceed = new CountDownLatch(1);
+ AtomicReference<Throwable> firstFailure = new AtomicReference<>();
+ AtomicReference<Throwable> secondFailure = new AtomicReference<>();
+
+ // The configuration-set callback runs inside the creation lock, so it gives the test a
+ // deterministic point where the first create holds the lock after its AlreadyExists check.
+ Thread first = new Thread(() -> {
+ try {
+ counted.createEmailIdentity("[email protected]", "my-cs", null, REGION, () -> {
+ insideLock.countDown();
+ try {
+ proceed.await();
+ } catch (InterruptedException e) {
+ Thread.currentThread().interrupt();
+ }
+ });
+ } catch (Throwable t) {
+ firstFailure.set(t);
+ }
+ });
+ first.start();
+
+ Thread second = new Thread(() -> {
+ try {
+ counted.createEmailIdentity("[email protected]", null, null, REGION, null);
+ } catch (Throwable t) {
+ secondFailure.set(t);
+ }
+ });
+ // Every wait is bounded and proceed is always released, so a locking regression fails the
+ // test instead of wedging the suite.
+ try {
+ assertTrue(insideLock.await(5, TimeUnit.SECONDS), "first create never entered the lock");
+ second.start();
+ // The second create must park on the creation lock before the first is released; a
+ // TERMINATED second thread means it completed without contending, i.e. the lock is gone.
+ long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(5);
+ while (!isParked(second.getState())) {
+ assertTrue(second.getState() != Thread.State.TERMINATED,
+ "second create finished without blocking on the creation lock");
+ assertTrue(System.nanoTime() < deadline,
+ "second create never blocked on the creation lock");
+ Thread.onSpinWait();
+ }
+ } finally {
+ proceed.countDown();
+ }
+ first.join(TimeUnit.SECONDS.toMillis(5));
+ second.join(TimeUnit.SECONDS.toMillis(5));
+ assertTrue(!first.isAlive() && !second.isAlive(), "creates did not finish in time");
+
+ assertEquals(null, firstFailure.get());
+ AwsException e = (AwsException) secondFailure.get();
+ assertEquals("AlreadyExistsException", e.getErrorCode());
+ assertEquals(1, store.puts.get());
+ assertEquals("my-cs",
+ counted.find("[email protected]", REGION).orElseThrow().getConfigurationSetName());
+ }
+
+ @Test
+ void verifyEmailIdentity_contendsWithCreate_neverClobbersTheFullRecord() throws Exception {
+ CountingStorage store = new CountingStorage();
+ SesIdentityService counted = new SesIdentityService(store, null, Clock.systemUTC());
+ CountDownLatch insideLock = new CountDownLatch(1);
+ CountDownLatch proceed = new CountDownLatch(1);
+ AtomicReference<Identity> verifyResult = new AtomicReference<>();
+
+ Thread creator = new Thread(() -> counted.createEmailIdentity(
+ "[email protected]", "my-cs", List.of(new Tag("team", "floci")), REGION, () -> {
+ insideLock.countDown();
+ try {
+ proceed.await();
+ } catch (InterruptedException e) {
+ Thread.currentThread().interrupt();
+ }
+ }));
+ creator.start();
+
+ Thread verifier = new Thread(() ->
+ verifyResult.set(counted.verifyEmailIdentity("[email protected]", REGION)));
+ try {
+ assertTrue(insideLock.await(5, TimeUnit.SECONDS), "create never entered the lock");
+ verifier.start();
+ long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(5);
+ // The v1 verify path takes the same creation lock, so it must park here rather than
+ // overwrite the in-flight create with a bare identity (the lost-update it used to allow).
+ while (!isParked(verifier.getState())) {
+ assertTrue(verifier.getState() != Thread.State.TERMINATED,
+ "verify finished without contending on the creation lock");
+ assertTrue(System.nanoTime() < deadline,
+ "verify never blocked on the creation lock");
+ Thread.onSpinWait();
+ }
+ } finally {
+ proceed.countDown();
+ }
+ creator.join(TimeUnit.SECONDS.toMillis(5));
+ verifier.join(TimeUnit.SECONDS.toMillis(5));
+ assertTrue(!creator.isAlive() && !verifier.isAlive(), "threads did not finish in time");
+
+ // Verify returned the creator's record instead of replacing it; nothing was lost.
+ assertEquals("my-cs", verifyResult.get().getConfigurationSetName());
+ assertEquals(1, store.puts.get());
+ assertEquals("my-cs",
+ counted.find("[email protected]", REGION).orElseThrow().getConfigurationSetName());
+ }
+
+ @Test
+ void createEmailIdentity_whitespace_keepsFieldSpecificWording() {
+ assertEquals("Email address must not contain leading or trailing whitespace.",
+ assertThrows(AwsException.class, () -> create(" [email protected]")).getMessage());
+ assertEquals("Domain must not contain leading or trailing whitespace.",
+ assertThrows(AwsException.class, () -> create(" example.com")).getMessage());
+ assertTrue(service.listIdentities(null, REGION).isEmpty());
+ }
+
+ private void create(String identity) {
+ service.createEmailIdentity(identity, null, null, REGION, null);
+ }
+
@Test
void tags_lifecycle_andNotFoundMessage() {
service.verifyEmailIdentity("[email protected]", REGION);
service.tag("[email protected]", REGION, List.of(new Tag("team", "floci")));
assertEquals(1, service.listTags("[email protected]", REGION).size());
- service.setTags("[email protected]", REGION,
- List.of(new Tag("team", "floci"), new Tag("env", "dev")));
+ service.tag("[email protected]", REGION, List.of(new Tag("env", "dev")));
service.untag("[email protected]", REGION, List.of("team"));
assertEquals(List.of("env"),
service.listTags("[email protected]", REGION).stream().map(Tag::key).toList());