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 1d38527952..08ed7aeaea 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 @@ -42,6 +42,7 @@ import java.util.LinkedHashMap; import java.util.List; import java.util.Locale; import java.util.Map; +import java.util.Optional; import java.util.Set; import java.util.UUID; import java.util.regex.Matcher; @@ -1169,17 +1170,26 @@ public class SesService { String normalized = normalizeSuppressionEmail(emailAddress); validateSuppressionReason(reason, "reason", false); String key = suppressionKey(region, normalized); - SuppressedDestination existing = suppressionStore.get(key).orElse(null); - SuppressedDestination entry = existing != null ? existing : new SuppressedDestination(normalized, reason); + SuppressionMatch match = existingSuppressionMatch(region, emailAddress, normalized).orElse(null); + SuppressedDestination entry = match != null ? match.entry() : new SuppressedDestination(normalized, reason); + entry.setEmailAddress(normalized); entry.setReason(reason); entry.setLastUpdateTime(Instant.now()); + // Write the canonical key first, then drop a legacy key it migrated from, + // so a failed write can't lose the entry. The legacy form was persisted by + // a pre-canonicalization Floci (trim-only key); migrating it avoids leaving + // a stuck duplicate after a re-PUT. suppressionStore.put(key, entry); + if (match != null && !match.key().equals(key)) { + suppressionStore.delete(match.key()); + } LOG.infov("Suppressed destination {0} in region {1} (reason={2})", normalized, region, reason); } public SuppressedDestination getSuppressedDestination(String region, String emailAddress) { String normalized = normalizeSuppressionEmail(emailAddress); - return suppressionStore.get(suppressionKey(region, normalized)) + return existingSuppressionMatch(region, emailAddress, normalized) + .map(SuppressionMatch::entry) .orElseThrow(() -> new AwsException("NotFoundException", "Email address " + normalized + " does not exist on your suppression list.", 404)); @@ -1187,16 +1197,40 @@ public class SesService { public void deleteSuppressedDestination(String region, String emailAddress) { String normalized = normalizeSuppressionEmail(emailAddress); - String key = suppressionKey(region, normalized); - if (suppressionStore.get(key).isEmpty()) { - throw new AwsException("NotFoundException", - "Email address " + normalized + " does not exist on your suppression list.", - 404); - } - suppressionStore.delete(key); + SuppressionMatch match = existingSuppressionMatch(region, emailAddress, normalized) + .orElseThrow(() -> new AwsException("NotFoundException", + "Email address " + normalized + " does not exist on your suppression list.", + 404)); + suppressionStore.delete(match.key()); LOG.infov("Removed suppression entry for {0} in region {1}", normalized, region); } + /** A suppression entry together with the storage key it currently lives under. */ + private record SuppressionMatch(String key, SuppressedDestination entry) { + } + + /** + * Resolve a suppression entry by its canonical (domain-lower-cased) key, falling + * back to the legacy raw-trimmed key used by a pre-canonicalization Floci. Returns + * the entry and the key it was found under in a single read per candidate, so + * callers don't re-fetch the store. + */ + private Optional existingSuppressionMatch(String region, String rawEmail, String normalized) { + String canonical = suppressionKey(region, normalized); + Optional hit = suppressionStore.get(canonical); + if (hit.isPresent()) { + return Optional.of(new SuppressionMatch(canonical, hit.get())); + } + String legacy = suppressionKey(region, rawEmail.trim()); + if (!legacy.equals(canonical)) { + Optional legacyHit = suppressionStore.get(legacy); + if (legacyHit.isPresent()) { + return Optional.of(new SuppressionMatch(legacy, legacyHit.get())); + } + } + return Optional.empty(); + } + public List listSuppressedDestinations(String region, List reasonFilters) { Set filters = new HashSet<>(); if (reasonFilters != null) { @@ -1251,7 +1285,8 @@ public class SesService { continue; } String normalized = normalizeSuppressionEmail(address); - SuppressedDestination entry = suppressionStore.get(suppressionKey(region, normalized)) + SuppressedDestination entry = existingSuppressionMatch(region, address, normalized) + .map(SuppressionMatch::entry) .orElse(null); if (entry != null && entry.getReason() != null && reasonFilter.contains(entry.getReason())) { @@ -1306,9 +1341,11 @@ public class SesService { return null; } // Share the same normalization used when entries are stored - // (`normalizeSuppressionEmail`) so lookups can't drift apart from inserts. + // (`normalizeSuppressionEmail`) so lookups can't drift apart from inserts, + // with the same legacy-key fallback as GET/DELETE. String normalized = normalizeSuppressionEmail(emailAddress); - SuppressedDestination entry = suppressionStore.get(suppressionKey(region, normalized)) + SuppressedDestination entry = existingSuppressionMatch(region, emailAddress, normalized) + .map(SuppressionMatch::entry) .orElse(null); if (entry == null || entry.getReason() == null) { return null; @@ -1324,8 +1361,19 @@ public class SesService { if (emailAddress == null || emailAddress.isBlank()) { throw new AwsException("BadRequestException", "EmailAddress is required.", 400); } - // AWS trims leading/trailing whitespace from EmailAddress before storing. - return emailAddress.trim(); + // AWS trims the EmailAddress and canonicalizes only the domain to lower + // case; the local-part keeps its case. Verified against real AWS SES V2 + // (2026-06-15): `Foo@Example.COM` and `Foo@example.com` collapse to one + // suppression entry (`Foo@example.com`), but `Foo@x` and `foo@x` are two + // distinct entries. Lower-casing the whole address would wrongly merge + // local-part variants and alter the stored value on read-back. + // Locale.ROOT avoids the JVM-locale Turkish-i pitfall. + String trimmed = emailAddress.trim(); + int at = trimmed.lastIndexOf('@'); + if (at < 0) { + return trimmed; + } + return trimmed.substring(0, at) + "@" + trimmed.substring(at + 1).toLowerCase(Locale.ROOT); } /** 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 new file mode 100644 index 0000000000..74217dfa93 --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/ses/SesServiceSuppressionLegacyKeyTest.java @@ -0,0 +1,90 @@ +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.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 static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.Mockito.mock; + +/** + * Backward-compat for suppression entries persisted by a pre-canonicalization Floci, + * which stored the address trim-only — so an entry with an upper-case domain lives under + * a key the new domain-lower-casing lookup would otherwise miss. GET/DELETE fall back to + * the legacy key, and PUT migrates it onto the canonical key. Only reachable by seeding + * the store directly (the HTTP API always normalizes), so it lives at the unit layer. + */ +class SesServiceSuppressionLegacyKeyTest { + + private static final String REGION = "us-east-1"; + // A pre-canonicalization entry: trim-only key with an upper-case domain. + private static final String LEGACY_ADDR = "Foo.Bar@Example.COM"; + private static final String LEGACY_KEY = "suppression::" + REGION + "::" + LEGACY_ADDR; + private static final String CANONICAL_KEY = "suppression::" + REGION + "::Foo.Bar@example.com"; + + private SesService service; + private InMemoryStorage suppressionStore; + + @BeforeEach + void setUp() { + suppressionStore = new InMemoryStorage<>(); + service = new SesService( + new InMemoryStorage(), + new InMemoryStorage(), + new InMemoryStorage(), + new InMemoryStorage(), + new InMemoryStorage(), + suppressionStore, + new InMemoryStorage(), + mock(SmtpRelay.class), + new ObjectMapper()); + } + + private void seedLegacyEntry() { + suppressionStore.put(LEGACY_KEY, new SuppressedDestination(LEGACY_ADDR, "BOUNCE")); + } + + @Test + void getReachesLegacyEntryByExactAddress() { + seedLegacyEntry(); + SuppressedDestination got = service.getSuppressedDestination(REGION, LEGACY_ADDR); + assertEquals(LEGACY_ADDR, got.getEmailAddress()); + assertEquals("BOUNCE", got.getReason()); + } + + @Test + void deleteRemovesLegacyEntry() { + seedLegacyEntry(); + service.deleteSuppressedDestination(REGION, LEGACY_ADDR); + assertFalse(suppressionStore.get(LEGACY_KEY).isPresent()); + } + + @Test + void sendTimeSuppressionReasonReachesLegacyEntry() { + // The event / send-time path (resolveSuppressionReason, collectSuppressedReasons) + // must also honor the legacy key, or a legacy entry stays deletable but no longer + // suppresses sends. Default fresh account suppresses [BOUNCE, COMPLAINT]. + seedLegacyEntry(); + assertEquals("BOUNCE", service.resolveSuppressionReason(LEGACY_ADDR, null, REGION)); + } + + @Test + void putMigratesLegacyEntryOntoCanonicalKeyWithoutDuplicate() { + seedLegacyEntry(); + service.putSuppressedDestination(REGION, LEGACY_ADDR, "COMPLAINT"); + assertFalse(suppressionStore.get(LEGACY_KEY).isPresent(), "legacy key should be migrated away"); + assertTrue(suppressionStore.get(CANONICAL_KEY).isPresent(), "entry should live under canonical key"); + SuppressedDestination migrated = suppressionStore.get(CANONICAL_KEY).orElseThrow(); + assertEquals("Foo.Bar@example.com", migrated.getEmailAddress()); + assertEquals("COMPLAINT", migrated.getReason()); + } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/ses/SesSuppressionV2IntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/ses/SesSuppressionV2IntegrationTest.java index 3ecb1bdfd2..a1452017c4 100644 --- a/src/test/java/io/github/hectorvent/floci/services/ses/SesSuppressionV2IntegrationTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/ses/SesSuppressionV2IntegrationTest.java @@ -336,4 +336,174 @@ class SesSuppressionV2IntegrationTest { .body("SuppressedDestinationSummaries.EmailAddress", hasItems("multi-bounce@example.com", "complaint-1@example.com")); } + + @Test + @Order(20) + void putSuppressedDestination_lowercasesDomainPreservesLocalPart() { + // Verified against real AWS SES V2 (2026-06-15): AWS canonicalizes only the + // domain to lower case; the local-part keeps its case. PUT MixedCase@Example.COM + // is stored and read back as MixedCase@example.com. + given() + .contentType("application/json") + .header("Authorization", AUTH_HEADER) + .body(""" + {"EmailAddress": "MixedCase@Example.COM", "Reason": "BOUNCE"} + """) + .when() + .put("/v2/email/suppression/addresses") + .then() + .statusCode(200); + + given() + .header("Authorization", AUTH_HEADER) + .when() + .get("/v2/email/suppression/addresses/MixedCase@Example.COM") + .then() + .statusCode(200) + .body("SuppressedDestination.EmailAddress", equalTo("MixedCase@example.com")) + .body("SuppressedDestination.Reason", equalTo("BOUNCE")); + } + + @Test + @Order(21) + void getSuppressedDestination_domainCaseInsensitive_localCaseSensitive() { + // Self-contained: seed its own entry so the test is order-independent. + // A differing domain case still hits the entry; a differing local-part case + // does not (it is a different key). + given() + .contentType("application/json") + .header("Authorization", AUTH_HEADER) + .body(""" + {"EmailAddress": "CaseProbe@Example.COM", "Reason": "BOUNCE"} + """) + .when() + .put("/v2/email/suppression/addresses") + .then() + .statusCode(200); + + given() + .header("Authorization", AUTH_HEADER) + .when() + .get("/v2/email/suppression/addresses/CaseProbe@EXAMPLE.com") + .then() + .statusCode(200) + .body("SuppressedDestination.EmailAddress", equalTo("CaseProbe@example.com")); + + given() + .header("Authorization", AUTH_HEADER) + .when() + .get("/v2/email/suppression/addresses/caseprobe@example.com") + .then() + .statusCode(404); + } + + @Test + @Order(22) + void deleteSuppressedDestination_domainCaseInsensitive() { + // PUT one domain case, DELETE a different domain case (same local-part), GET 404. + given() + .contentType("application/json") + .header("Authorization", AUTH_HEADER) + .body(""" + {"EmailAddress": "DeleteMe@Example.com", "Reason": "COMPLAINT"} + """) + .when() + .put("/v2/email/suppression/addresses") + .then() + .statusCode(200); + + given() + .header("Authorization", AUTH_HEADER) + .when() + .delete("/v2/email/suppression/addresses/DeleteMe@EXAMPLE.com") + .then() + .statusCode(200); + + given() + .header("Authorization", AUTH_HEADER) + .when() + .get("/v2/email/suppression/addresses/DeleteMe@example.com") + .then() + .statusCode(404); + } + + @Test + @Order(23) + void putSuppressedDestination_domainCaseCollision_lastPutWins() { + // Same local-part, domain differing only in case: one entry, latest Reason wins. + given() + .contentType("application/json") + .header("Authorization", AUTH_HEADER) + .body(""" + {"EmailAddress": "UpdateTarget@example.com", "Reason": "BOUNCE"} + """) + .when() + .put("/v2/email/suppression/addresses") + .then() + .statusCode(200); + + given() + .contentType("application/json") + .header("Authorization", AUTH_HEADER) + .body(""" + {"EmailAddress": "UpdateTarget@EXAMPLE.com", "Reason": "COMPLAINT"} + """) + .when() + .put("/v2/email/suppression/addresses") + .then() + .statusCode(200); + + given() + .header("Authorization", AUTH_HEADER) + .when() + .get("/v2/email/suppression/addresses/UpdateTarget@example.com") + .then() + .statusCode(200) + .body("SuppressedDestination.EmailAddress", equalTo("UpdateTarget@example.com")) + .body("SuppressedDestination.Reason", equalTo("COMPLAINT")); + } + + @Test + @Order(24) + void putSuppressedDestination_localPartCaseDifference_distinctEntries() { + // Local-part case differences are distinct entries (not merged), each keeping + // its own Reason. Verified against real AWS SES V2 (2026-06-15). + given() + .contentType("application/json") + .header("Authorization", AUTH_HEADER) + .body(""" + {"EmailAddress": "LocalCase@distinct.example.com", "Reason": "BOUNCE"} + """) + .when() + .put("/v2/email/suppression/addresses") + .then() + .statusCode(200); + + given() + .contentType("application/json") + .header("Authorization", AUTH_HEADER) + .body(""" + {"EmailAddress": "localcase@distinct.example.com", "Reason": "COMPLAINT"} + """) + .when() + .put("/v2/email/suppression/addresses") + .then() + .statusCode(200); + + given() + .header("Authorization", AUTH_HEADER) + .when() + .get("/v2/email/suppression/addresses/LocalCase@distinct.example.com") + .then() + .statusCode(200) + .body("SuppressedDestination.Reason", equalTo("BOUNCE")); + + given() + .header("Authorization", AUTH_HEADER) + .when() + .get("/v2/email/suppression/addresses/localcase@distinct.example.com") + .then() + .statusCode(200) + .body("SuppressedDestination.Reason", equalTo("COMPLAINT")); + } }