diff --git a/src/main/java/io/github/hectorvent/floci/services/ses/SesAccountService.java b/src/main/java/io/github/hectorvent/floci/services/ses/SesAccountService.java new file mode 100644 index 0000000000..0e526d568e --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/ses/SesAccountService.java @@ -0,0 +1,70 @@ +package io.github.hectorvent.floci.services.ses; + +import com.fasterxml.jackson.core.type.TypeReference; +import io.github.hectorvent.floci.core.storage.StorageBackend; +import io.github.hectorvent.floci.core.storage.StorageFactory; +import io.github.hectorvent.floci.services.ses.model.AccountVdmAttributes; +import jakarta.enterprise.context.ApplicationScoped; +import jakarta.inject.Inject; +import org.jboss.logging.Logger; + +import java.util.Map; +import java.util.Optional; + +/** + * Account-level SES settings, extracted from {@link SesService} as part of the store-based domain + * split. Reached through the {@code SesService} facade, which delegates here. + * + *

Owns the account sending-enabled flag ({@code accountSettingsStore}) and the VDM (Virtual + * Deliverability Manager) attributes ({@code accountVdmStore}). Account suppression is account-level + * too, but it shares {@code validateSuppressionReason} with the suppression list, so it lives in + * {@link SesSuppressionService} instead. + */ +@ApplicationScoped +public class SesAccountService { + + private static final Logger LOG = Logger.getLogger(SesAccountService.class); + + private final StorageBackend accountSettingsStore; + private final StorageBackend accountVdmStore; + + @Inject + public SesAccountService(StorageFactory storageFactory) { + this.accountSettingsStore = storageFactory.create("ses", "ses-account-settings.json", + new TypeReference>() {}); + this.accountVdmStore = storageFactory.create("ses", "ses-account-vdm.json", + new TypeReference>() {}); + } + + SesAccountService(StorageBackend accountSettingsStore, + StorageBackend accountVdmStore) { + this.accountSettingsStore = accountSettingsStore; + this.accountVdmStore = accountVdmStore; + } + + public boolean isAccountSendingEnabled(String region) { + return accountSettingsStore.get("sending::" + region).orElse(true); + } + + public void setAccountSendingEnabled(String region, boolean enabled) { + accountSettingsStore.put("sending::" + region, enabled); + LOG.infov("Updated account sending enabled for region {0}: {1}", region, enabled); + } + + // VDM (Virtual Deliverability Manager) is opt-in and per region: GetAccount omits VdmAttributes + // entirely until PutAccountVdmAttributes is called for the region, so this returns empty when the + // region was never configured. The whole tuple is stored under one region key so GetAccount never + // observes a partially updated state. + public Optional findAccountVdmAttributes(String region) { + return accountVdmStore.get(accountVdmKey(region)); + } + + public void putAccountVdmAttributes(String region, AccountVdmAttributes vdm) { + accountVdmStore.put(accountVdmKey(region), vdm); + LOG.infov("Updated account VDM attributes for region {0}: enabled={1}", region, vdm.vdmEnabled()); + } + + private static String accountVdmKey(String region) { + return "account-vdm::" + region; + } +} diff --git a/src/main/java/io/github/hectorvent/floci/services/ses/SesContactService.java b/src/main/java/io/github/hectorvent/floci/services/ses/SesContactService.java new file mode 100644 index 0000000000..e3d1de2c0d --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/ses/SesContactService.java @@ -0,0 +1,583 @@ +package io.github.hectorvent.floci.services.ses; + +import com.fasterxml.jackson.core.type.TypeReference; +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.ses.model.Contact; +import io.github.hectorvent.floci.services.ses.model.ContactList; +import io.github.hectorvent.floci.services.ses.model.Tag; +import io.github.hectorvent.floci.services.ses.model.Topic; +import io.github.hectorvent.floci.services.ses.model.TopicPreference; +import jakarta.enterprise.context.ApplicationScoped; +import jakarta.inject.Inject; +import org.jboss.logging.Logger; + +import java.time.Clock; +import java.time.Instant; +import java.util.ArrayList; +import java.util.Comparator; +import java.util.HashSet; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.regex.Pattern; + +/** + * Contact lists and contacts (the {@code contactListStore} + {@code contactStore}), extracted from + * {@link SesService} as the fifth step of the store-based domain split. + * + *

New facet: a multi-store domain — one service owns both stores and the locks that serialize + * them (contact create/update against contact-list deletion), collapsing two SesService constructor + * arguments into one. It also owns the list-management contact behaviour used during a send + * ({@link #getOrAutoCreateContact}, {@link #isListManagementOptedOut}, {@link #unsubscribeContact}); + * the facade's send orchestration ({@code collectListManagementOptOuts}) stays in {@link SesService} + * and calls into this service, keeping the shared {@code extractEmailAddress} send helper there. + */ +@ApplicationScoped +public class SesContactService { + + private static final Logger LOG = Logger.getLogger(SesContactService.class); + + private static final Set SUBSCRIPTION_STATUSES = Set.of("OPT_IN", "OPT_OUT"); + private static final Pattern CONTACT_LIST_NAME_CHARS = Pattern.compile("^[A-Za-z0-9_-]{1,64}$"); + private static final Pattern EMAIL_PATTERN = Pattern.compile("^[^@\\s]+@[^@\\s]+\\.[^@\\s]+$"); + private static final int MAX_TOPICS_PER_LIST = 20; + private static final int MAX_DISPLAY_NAME_LENGTH = 128; + private static final int MAX_LIST_DESCRIPTION_LENGTH = 500; + + private final StorageBackend contactListStore; + private final StorageBackend contactStore; + // Guards the one-list-per-account check-then-create so concurrent creates can't both pass. + private final Object contactListCreateLock = new Object(); + // Serializes contact create/update against contact-list deletion so a concurrent delete + // can't purge the list between validation and the write, leaving an orphaned contact. + private final Object contactMutationLock = new Object(); + private final Clock clock; + + @Inject + public SesContactService(StorageFactory storageFactory, Clock clock) { + this.contactListStore = storageFactory.create("ses", "ses-contact-lists.json", + new TypeReference>() {}); + this.contactStore = storageFactory.create("ses", "ses-contacts.json", + new TypeReference>() {}); + this.clock = clock; + } + + SesContactService(StorageBackend contactListStore, + StorageBackend contactStore, Clock clock) { + this.contactListStore = contactListStore; + this.contactStore = contactStore; + this.clock = clock; + } + + // ─────────────────────────── Contact lists ─────────────────────────── + + public ContactList createContactList(String name, String description, List topics, + List tags, String region) { + validateContactListInput(name, description, topics); + ContactList list = new ContactList(name); + list.setDescription(description); + list.setTopics(topics); + list.setTags(tags); + Instant now = Instant.now(); + list.setCreatedTimestamp(now); + list.setLastUpdatedTimestamp(now); + // AWS allows at most one contact list per account per region (verified against real AWS). + // A duplicate name hits this same limit before any "already exists" check, so + // AlreadyExistsException is never reachable for contact lists. Lock only the check-then-put + // so concurrent calls can't both observe an empty region; building and logging stay outside. + synchronized (contactListCreateLock) { + if (!listContactLists(region).isEmpty()) { + throw new AwsException("BadRequestException", + "A maximum of 1 Lists allowed per account.", 400); + } + contactListStore.put(contactListKey(region, name), list); + } + LOG.infov("Created SES contact list: {0} in region {1}", name, region); + return list; + } + + public ContactList getContactList(String name, String region) { + return contactListStore.get(contactListKey(region, name)) + .orElseThrow(() -> contactListNotFound(name)); + } + + public List listContactLists(String region) { + String prefix = "contactList::" + region + "::"; + return contactListStore.scan(k -> k.startsWith(prefix)).stream() + .sorted(Comparator.comparing(ContactList::getContactListName)) + .toList(); + } + + public ContactList updateContactList(String name, String description, boolean descriptionPresent, + List topics, String region) { + validateContactListInput(name, description, topics); + String key = contactListKey(region, name); + ContactList existing = contactListStore.get(key).orElseThrow(() -> contactListNotFound(name)); + if (topics != null) { + existing.setTopics(topics); + } + if (descriptionPresent) { + existing.setDescription(description); + } + existing.setLastUpdatedTimestamp(Instant.now()); + contactListStore.put(key, existing); + LOG.infov("Updated SES contact list: {0} in region {1}", name, region); + return existing; + } + + public void deleteContactList(String name, String region) { + String key = contactListKey(region, name); + // Existence check, list delete, and contact purge all under the lock: concurrent deletes + // can't both pass the check (one must 404), and a concurrent create/update can't slip a + // contact in after the purge. Contacts are stored independently, so purging them here keeps + // them from leaking into a same-named list recreated later (AWS deletes them with the list). + String prefix = "contact::" + region + "::" + name + "::"; + synchronized (contactMutationLock) { + if (contactListStore.get(key).isEmpty()) { + throw contactListNotFound(name); + } + contactListStore.delete(key); + // Delete by the actual stored keys (not keys rebuilt from each value's EmailAddress), + // so a persisted entry whose key and EmailAddress diverge is still purged. + List contactKeys = contactStore.keys().stream() + .filter(k -> k.startsWith(prefix)) + .toList(); + for (String contactKey : contactKeys) { + contactStore.delete(contactKey); + } + } + LOG.infov("Deleted SES contact list: {0} in region {1}", name, region); + } + + private static AwsException contactListNotFound(String name) { + return new AwsException("NotFoundException", + "List with name: " + name + " doesn't exist.", 404); + } + + // SES V2 surfaces missing/invalid input as Smithy validation errors. Field paths and the + // enum value order are taken verbatim from real AWS. + private static AwsException validationError(String fieldPath, String constraint) { + return new AwsException("BadRequestException", + "1 validation error detected: Value at '" + fieldPath + + "' failed to satisfy constraint: " + constraint, 400); + } + + private static void validateContactListName(String name) { + if (name == null) { + throw validationError("contactListName", "Member must not be null"); + } + if (name.isBlank()) { + throw new AwsException("BadRequestException", "ContactListName can't be blank.", 400); + } + if (!CONTACT_LIST_NAME_CHARS.matcher(name).matches()) { + throw new AwsException("BadRequestException", + "ContactListName can contain up to 64 characters. Only alphanumeric characters, " + + "underscores(_) and hyphens(-) are allowed.", 400); + } + } + + private static void validateDescription(String description) { + if (description != null && description.length() > MAX_LIST_DESCRIPTION_LENGTH) { + throw new AwsException("BadRequestException", + "List description can contain up to 500 characters.", 400); + } + } + + // Validates Create/Update input in the same two-phase order as real AWS (verified by probe): + // protocol-layer (Smithy) checks across all fields first, then service-level constraints with + // ContactListName ahead of topic/description constraints. + private static void validateContactListInput(String name, String description, List topics) { + // Phase 1 — protocol-layer (Smithy) validation: null members and the subscription-status + // enum. AWS reports these before any service-level constraint. + if (name == null) { + throw validationError("contactListName", "Member must not be null"); + } + if (topics != null) { + for (int i = 0; i < topics.size(); i++) { + Topic t = topics.get(i); + String member = "topics." + (i + 1) + ".member."; + if (t.getTopicName() == null) { + throw validationError(member + "topicName", "Member must not be null"); + } + if (t.getDisplayName() == null) { + throw validationError(member + "displayName", "Member must not be null"); + } + if (t.getDefaultSubscriptionStatus() == null) { + throw validationError(member + "defaultSubscriptionStatus", "Member must not be null"); + } + if (!SUBSCRIPTION_STATUSES.contains(t.getDefaultSubscriptionStatus())) { + throw validationError(member + "defaultSubscriptionStatus", + "Member must satisfy enum value set: [OPT_OUT, OPT_IN]"); + } + } + } + // Phase 2 — service-level constraints: ContactListName first, then topics, then description. + if (name.isBlank()) { + throw new AwsException("BadRequestException", "ContactListName can't be blank.", 400); + } + if (!CONTACT_LIST_NAME_CHARS.matcher(name).matches()) { + throw new AwsException("BadRequestException", + "ContactListName can contain up to 64 characters. Only alphanumeric characters, " + + "underscores(_) and hyphens(-) are allowed.", 400); + } + if (topics != null) { + if (topics.size() > MAX_TOPICS_PER_LIST) { + throw new AwsException("BadRequestException", + "Maximum of <" + MAX_TOPICS_PER_LIST + "> topics allowed per ContactList", 400); + } + Set seenNames = new HashSet<>(); + for (Topic t : topics) { + if (t.getTopicName().isBlank()) { + throw new AwsException("BadRequestException", "TopicName can't be blank.", 400); + } + if (!CONTACT_LIST_NAME_CHARS.matcher(t.getTopicName()).matches()) { + throw new AwsException("BadRequestException", + "TopicName can contain up to 64 characters. Only alphanumeric characters, " + + "underscores(_) and hyphens(-) are allowed.", 400); + } + if (t.getDisplayName().length() > MAX_DISPLAY_NAME_LENGTH) { + throw new AwsException("BadRequestException", + "Topic DisplayName can contain up to <" + MAX_DISPLAY_NAME_LENGTH + + "> characters.", 400); + } + if (!seenNames.add(t.getTopicName())) { + throw new AwsException("BadRequestException", + "Duplicate topic names are not allowed within a List.", 400); + } + } + } + validateDescription(description); + } + + private static String contactListKey(String region, String name) { + // Validate in the key builder so Get/Update/Delete reject an invalid ContactListName with + // the AWS validation error (400) rather than a 404, matching configSetKey. Verified + // against real AWS: read/delete with an invalid name returns the same constraint message. + validateContactListName(name); + return "contactList::" + region + "::" + name; + } + + // ─────────────────────────── Contacts ─────────────────────────── + + public Contact createContact(String listName, String emailAddress, List topicPreferences, + Boolean unsubscribeAll, String attributesData, String region) { + validateContactInput(listName, emailAddress, topicPreferences, region); + Contact contact = new Contact(emailAddress); + contact.setTopicPreferences(topicPreferences); + contact.setUnsubscribeAll(unsubscribeAll != null && unsubscribeAll); + contact.setAttributesData(attributesData); + Instant now = Instant.now(clock); + contact.setCreatedTimestamp(now); + contact.setLastUpdatedTimestamp(now); + String key = contactKey(region, listName, emailAddress); + // Re-check the list, duplicate, and put under the lock so a concurrent deleteContactList + // can't purge the list between validation and the write (which would orphan this contact). + synchronized (contactMutationLock) { + getContactList(listName, region); + if (contactStore.get(key).isPresent()) { + throw new AwsException("AlreadyExistsException", + emailAddress + " already exists in List.", 400); + } + contactStore.put(key, contact); + } + LOG.infov("Created SES contact {0} in list {1} (region {2})", emailAddress, listName, region); + return contact; + } + + // Read operations return the resolved ContactList alongside the contact(s) so the controller + // can render TopicDefaultPreferences without a second getContactList round-trip (which would + // open a TOCTOU window where a concurrent delete turns a successful read into "List not found"). + public record ContactWithList(Contact contact, ContactList list) { + } + + public record ContactsWithList(List contacts, ContactList list) { + } + + public ContactWithList getContact(String listName, String emailAddress, String region) { + validateEmailAddress(emailAddress); + ContactList list = getContactList(listName, region); + Contact contact = contactStore.get(contactKey(region, listName, emailAddress)) + .orElseThrow(() -> contactNotFound(emailAddress)); + return new ContactWithList(contact, list); + } + + public ContactsWithList listContacts(String listName, String region) { + ContactList list = getContactList(listName, region); + String prefix = "contact::" + region + "::" + listName + "::"; + List contacts = contactStore.scan(k -> k.startsWith(prefix)).stream() + .sorted(Comparator.comparing(Contact::getEmailAddress, + Comparator.nullsFirst(Comparator.naturalOrder()))) + .toList(); + return new ContactsWithList(contacts, list); + } + + public Contact updateContact(String listName, String emailAddress, List topicPreferences, + boolean topicPreferencesPresent, Boolean unsubscribeAll, String attributesData, + String region) { + validateContactInput(listName, emailAddress, topicPreferences, region); + String key = contactKey(region, listName, emailAddress); + Contact existing; + // Re-check the list and read-modify-write under the lock so a concurrent deleteContactList + // can't purge the contact/list between validation and the write (which would resurrect it). + synchronized (contactMutationLock) { + getContactList(listName, region); + existing = contactStore.get(key).orElseThrow(() -> contactNotFound(emailAddress)); + // Verified against real AWS: TopicPreferences merge by topic name (omitting keeps existing); + // AttributesData and UnsubscribeAll are replaced (omitting clears / resets them). + if (topicPreferencesPresent) { + existing.setTopicPreferences(mergeTopicPreferences(existing.getTopicPreferences(), topicPreferences)); + } + existing.setUnsubscribeAll(unsubscribeAll != null && unsubscribeAll); + existing.setAttributesData(attributesData); + existing.setLastUpdatedTimestamp(Instant.now(clock)); + contactStore.put(key, existing); + } + LOG.infov("Updated SES contact {0} in list {1}", emailAddress, listName); + return existing; + } + + public void deleteContact(String listName, String emailAddress, String region) { + validateEmailAddress(emailAddress); + String key = contactKey(region, listName, emailAddress); + // List re-check + existence check + delete under the lock (matching create/update): a + // concurrent deleteContactList then surfaces "list not found" rather than "contact not + // found", and an updateContact can't put a just-deleted contact back (resurrecting it). + synchronized (contactMutationLock) { + getContactList(listName, region); + if (contactStore.get(key).isEmpty()) { + throw contactNotFound(emailAddress); + } + contactStore.delete(key); + } + LOG.infov("Deleted SES contact {0} in list {1}", emailAddress, listName); + } + + /** + * Derives {@code TopicDefaultPreferences}: each list topic the contact has not set an explicit + * preference for, carrying that topic's default subscription status. + */ + public List deriveTopicDefaultPreferences(Contact contact, ContactList list) { + Set explicit = new HashSet<>(); + for (TopicPreference p : contact.getTopicPreferences()) { + explicit.add(p.getTopicName()); + } + List defaults = new ArrayList<>(); + for (Topic t : list.getTopics()) { + if (!explicit.contains(t.getTopicName())) { + defaults.add(new TopicPreference(t.getTopicName(), t.getDefaultSubscriptionStatus())); + } + } + return defaults; + } + + private static AwsException contactNotFound(String emailAddress) { + return new AwsException("NotFoundException", emailAddress + " doesn't exist in List.", 404); + } + + // Validation order verified against real AWS: protocol-layer (Smithy) topic-preference checks + // first, then EmailAddress format, then contact-list existence, then topic existence. + private void validateContactInput(String listName, String emailAddress, List prefs, + String region) { + if (prefs != null) { + for (int i = 0; i < prefs.size(); i++) { + TopicPreference p = prefs.get(i); + String member = "topicPreferences." + (i + 1) + ".member."; + if (p.getTopicName() == null) { + throw validationError(member + "topicName", "Member must not be null"); + } + if (p.getSubscriptionStatus() == null) { + throw validationError(member + "subscriptionStatus", "Member must not be null"); + } + if (!SUBSCRIPTION_STATUSES.contains(p.getSubscriptionStatus())) { + throw validationError(member + "subscriptionStatus", + "Member must satisfy enum value set: [OPT_OUT, OPT_IN]"); + } + } + } + validateEmailAddress(emailAddress); + ContactList list = getContactList(listName, region); + if (prefs != null && !prefs.isEmpty()) { + Set topicNames = new HashSet<>(); + for (Topic t : list.getTopics()) { + topicNames.add(t.getTopicName()); + } + for (TopicPreference p : prefs) { + if (!topicNames.contains(p.getTopicName())) { + throw new AwsException("BadRequestException", + "List: " + listName + " doesn't contain Topic: " + p.getTopicName(), 400); + } + } + } + } + + private static List mergeTopicPreferences(List existing, + List provided) { + Map byTopic = new LinkedHashMap<>(); + if (existing != null) { + for (TopicPreference p : existing) { + byTopic.put(p.getTopicName(), p); + } + } + if (provided != null) { + for (TopicPreference p : provided) { + byTopic.put(p.getTopicName(), p); + } + } + return new ArrayList<>(byTopic.values()); + } + + private static void validateEmailAddress(String emailAddress) { + // Verified against real AWS: a missing/null required member is a Smithy validation error, + // an empty/blank value is "can't be blank", and only a non-blank malformed value is "invalid". + if (emailAddress == null) { + throw validationError("emailAddress", "Member must not be null"); + } + if (emailAddress.isBlank()) { + throw new AwsException("BadRequestException", "EmailAddress can't be blank.", 400); + } + if (!EMAIL_PATTERN.matcher(emailAddress).matches()) { + throw new AwsException("BadRequestException", + "EmailAddress <" + emailAddress + "> is invalid", 400); + } + } + + private static String contactKey(String region, String listName, String emailAddress) { + return "contact::" + region + "::" + listName + "::" + emailAddress; + } + + // ──────────────── List-management contact behaviour (used by the send path) ──────────────── + + /** + * Returns the contact for {@code email} in {@code list}, creating it automatically when absent — + * AWS creates a contact on the list when {@code ListManagementOptions} names a recipient that is + * not yet a contact. The auto-created contact has no explicit topic preferences (its effective + * per-topic status derives from the list topic defaults) and is not unsubscribed. Creation runs + * under {@code contactMutationLock} so a concurrent contact-list deletion can't orphan it. + */ + public Contact getOrAutoCreateContact(ContactList list, String email, String region) { + String key = contactKey(region, list.getContactListName(), email); + Contact existing = contactStore.get(key).orElse(null); + if (existing != null) { + return existing; + } + synchronized (contactMutationLock) { + Contact raced = contactStore.get(key).orElse(null); + if (raced != null) { + return raced; + } + // Re-check the list under the lock so a concurrent deleteContactList (which purges the + // list and its contacts under the same lock) can't be followed by this creating an + // orphaned contact for a list that no longer exists. + getContactList(list.getContactListName(), region); + Contact contact = new Contact(email); + Instant now = Instant.now(clock); + contact.setCreatedTimestamp(now); + contact.setLastUpdatedTimestamp(now); + contactStore.put(key, contact); + LOG.infov("Auto-created SES contact {0} in list {1} on send (region {2})", + email, list.getContactListName(), region); + return contact; + } + } + + /** + * Whether a contact is opted out for a list-managed send. A contact with {@code UnsubscribeAll} + * is opted out of everything. When no topic is given, only {@code UnsubscribeAll} suppresses + * (AWS documents suppression of whole-list unsubscribers). When a topic is given, an explicit + * {@code OPT_OUT} preference for that topic suppresses; absent an explicit preference, the topic's + * {@code DefaultSubscriptionStatus} is used — the default-status fallback at send time is not + * documented by AWS but mirrors the effective-status model AWS uses for {@code ListContacts}. + */ + public boolean isListManagementOptedOut(Contact contact, ContactList list, String topicName) { + if (contact.isUnsubscribeAll()) { + return true; + } + if (topicName == null) { + return false; + } + String explicit = explicitTopicStatus(contact, topicName); + if (explicit != null) { + return "OPT_OUT".equals(explicit); + } + return "OPT_OUT".equals(defaultTopicStatus(list, topicName)); + } + + private static String explicitTopicStatus(Contact contact, String topicName) { + if (contact.getTopicPreferences() == null) { + return null; + } + for (TopicPreference pref : contact.getTopicPreferences()) { + if (topicName.equals(pref.getTopicName())) { + return pref.getSubscriptionStatus(); + } + } + return null; + } + + public String defaultTopicStatus(ContactList list, String topicName) { + if (list.getTopics() == null) { + return null; + } + for (Topic topic : list.getTopics()) { + if (topicName.equals(topic.getTopicName())) { + return topic.getDefaultSubscriptionStatus(); + } + } + return null; + } + + /** + * Applies a list-management unsubscribe (the action behind the {@code /_aws/ses/unsubscribe} + * link): with a topic, sets that topic's preference to {@code OPT_OUT}; without a topic, + * unsubscribes the contact from the whole list ({@code UnsubscribeAll}). The contact is created + * if it does not exist yet, consistent with send-time auto-creation. Runs under + * {@code contactMutationLock} so a concurrent contact-list deletion can't orphan it. + */ + public void unsubscribeContact(String listName, String emailAddress, String topicName, String region) { + validateEmailAddress(emailAddress); + String effectiveTopic = (topicName == null || topicName.isBlank()) ? null : topicName; + String key = contactKey(region, listName, emailAddress); + synchronized (contactMutationLock) { + ContactList list = getContactList(listName, region); + if (effectiveTopic != null && defaultTopicStatus(list, effectiveTopic) == null) { + throw new AwsException("BadRequestException", + "Topic " + effectiveTopic + " does not exist in contact list " + listName + ".", 400); + } + Contact contact = contactStore.get(key).orElseGet(() -> { + Contact created = new Contact(emailAddress); + created.setCreatedTimestamp(Instant.now(clock)); + return created; + }); + if (effectiveTopic == null) { + contact.setUnsubscribeAll(true); + } else { + setTopicPreference(contact, effectiveTopic, "OPT_OUT"); + } + contact.setLastUpdatedTimestamp(Instant.now(clock)); + contactStore.put(key, contact); + } + LOG.infov("List-management unsubscribe: {0} from list {1} topic {2} (region {3})", + emailAddress, listName, effectiveTopic == null ? "" : effectiveTopic, region); + } + + private static void setTopicPreference(Contact contact, String topicName, String status) { + // Copy into a fresh mutable list and set it back, so this works even if the contact's + // preferences were stored as an unmodifiable list (setTopicPreferences keeps the list as-is). + List prefs = new ArrayList<>(contact.getTopicPreferences()); + boolean found = false; + for (TopicPreference pref : prefs) { + if (topicName.equals(pref.getTopicName())) { + pref.setSubscriptionStatus(status); + found = true; + break; + } + } + if (!found) { + prefs.add(new TopicPreference(topicName, status)); + } + contact.setTopicPreferences(prefs); + } +} 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 8c5d0d457b..17c41f983c 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 @@ -1685,7 +1685,7 @@ public class SesController { if (body != null && !body.isBlank()) { requireJsonObject(objectMapper.readTree(body)); } - SesService.ContactsWithList listed = sesService.listContacts(contactListName, region); + SesContactService.ContactsWithList listed = sesService.listContacts(contactListName, region); ObjectNode result = objectMapper.createObjectNode(); ArrayNode arr = result.putArray("Contacts"); for (Contact c : listed.contacts()) { @@ -1705,7 +1705,7 @@ public class SesController { @PathParam("contactListName") String contactListName, @PathParam("emailAddress") String emailAddress) { String region = regionResolver.resolveRegion(headers); - SesService.ContactWithList result = sesService.getContact(contactListName, emailAddress, region); + SesContactService.ContactWithList result = sesService.getContact(contactListName, emailAddress, region); return Response.ok(contactJson(result.contact(), result.list(), true)).build(); } diff --git a/src/main/java/io/github/hectorvent/floci/services/ses/SesCvetService.java b/src/main/java/io/github/hectorvent/floci/services/ses/SesCvetService.java new file mode 100644 index 0000000000..76086794b4 --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/ses/SesCvetService.java @@ -0,0 +1,123 @@ +package io.github.hectorvent.floci.services.ses; + +import com.fasterxml.jackson.core.type.TypeReference; +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.ses.model.CustomVerificationEmailTemplate; +import jakarta.enterprise.context.ApplicationScoped; +import jakarta.inject.Inject; +import org.jboss.logging.Logger; + +import java.util.Comparator; +import java.util.List; +import java.util.Map; +import java.util.Optional; + +/** + * Storage for custom verification email templates (the {@code cvetStore}), extracted from + * {@link SesService} as the third step of the store-based domain split. + * + *

This owns only the persistence and the concurrency guard. The cross-domain parts stay in the + * {@link SesService} facade, which orchestrates them: {@code validateCustomVerificationTemplate} + * (its "From must be a verified identity" check reaches the Identity domain) runs in the facade + * before create/update delegate here, and {@code sendCustomVerificationEmail} stays in the facade + * and only reads a template through {@link #find}. This is the facade-as-coordinator model: + * a domain used by the send path is not turned into a cross-service dependency. + */ +@ApplicationScoped +public class SesCvetService { + + private static final Logger LOG = Logger.getLogger(SesCvetService.class); + + private final StorageBackend cvetStore; + // Serializes custom-verification-template create/update/delete check-then-write so concurrent + // creates for the same name can't both succeed and an update can't resurrect a concurrently + // deleted template. + private final Object cvetMutationLock = new Object(); + + @Inject + public SesCvetService(StorageFactory storageFactory) { + this.cvetStore = storageFactory.create("ses", "ses-custom-verification-templates.json", + new TypeReference>() {}); + } + + SesCvetService(StorageBackend cvetStore) { + this.cvetStore = cvetStore; + } + + public void createCustomVerificationEmailTemplate(CustomVerificationEmailTemplate template, String region) { + String key = cvetKey(region, template.getTemplateName()); + // Lock only the check-then-put so concurrent creates for the same name can't both observe + // the key as absent; the facade's validation and this logging stay outside the lock. + synchronized (cvetMutationLock) { + if (cvetStore.get(key).isPresent()) { + // v1-native code (verified: CustomVerificationEmailTemplateAlreadyExists / 400); + // remapV1Exception translates it to AlreadyExistsException / 400 for the v2 boundary. + throw new AwsException("CustomVerificationEmailTemplateAlreadyExists", + "Custom verification email template <" + template.getTemplateName() + "> already exists", 400); + } + cvetStore.put(key, template); + } + LOG.infov("Created custom verification email template {0} in region {1}", + template.getTemplateName(), region); + } + + public CustomVerificationEmailTemplate getCustomVerificationEmailTemplate(String templateName, String region) { + return cvetStore.get(cvetKey(region, templateName)).orElseThrow(() -> cvetNotFound(templateName)); + } + + public List listCustomVerificationEmailTemplates(String region) { + String prefix = "cvet::" + region + "::"; + return cvetStore.scan(k -> k.startsWith(prefix)).stream() + .sorted(Comparator.comparing(CustomVerificationEmailTemplate::getTemplateName, + Comparator.nullsFirst(Comparator.naturalOrder()))) + .toList(); + } + + public void updateCustomVerificationEmailTemplate(CustomVerificationEmailTemplate template, String region) { + String key = cvetKey(region, template.getTemplateName()); + // Guard the existence check and the put together so a concurrent delete can't slip between + // them and have the update resurrect the just-deleted template. + synchronized (cvetMutationLock) { + if (cvetStore.get(key).isEmpty()) { + throw cvetNotFound(template.getTemplateName()); + } + cvetStore.put(key, template); + } + LOG.infov("Updated custom verification email template {0} in region {1}", + template.getTemplateName(), region); + } + + public void deleteCustomVerificationEmailTemplate(String templateName, String region) { + String key = cvetKey(region, templateName); + // Guard the check-then-delete on the same lock as create/update so the three mutations + // serialize against each other. + synchronized (cvetMutationLock) { + if (cvetStore.get(key).isEmpty()) { + throw cvetNotFound(templateName); + } + cvetStore.delete(key); + } + LOG.infov("Deleted custom verification email template {0} in region {1}", templateName, region); + } + + /** + * Looks up a template without throwing, so the facade's {@code sendCustomVerificationEmail} can + * raise its own send-specific "does not exist" message rather than the CRUD one. + */ + public Optional find(String templateName, String region) { + return cvetStore.get(cvetKey(region, templateName)); + } + + private static AwsException cvetNotFound(String templateName) { + // v1-native code (verified: CustomVerificationEmailTemplateDoesNotExist / 400). + // SesController.remapV1Exception translates it to NotFoundException / 404 for the v2 boundary. + return new AwsException("CustomVerificationEmailTemplateDoesNotExist", + "Custom verification email template <" + templateName + "> does not exist", 400); + } + + private static String cvetKey(String region, String templateName) { + return "cvet::" + region + "::" + templateName; + } +} diff --git a/src/main/java/io/github/hectorvent/floci/services/ses/SesDedicatedIpService.java b/src/main/java/io/github/hectorvent/floci/services/ses/SesDedicatedIpService.java new file mode 100644 index 0000000000..af196dc063 --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/ses/SesDedicatedIpService.java @@ -0,0 +1,91 @@ +package io.github.hectorvent.floci.services.ses; + +import com.fasterxml.jackson.core.type.TypeReference; +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.ses.model.DedicatedIpPool; +import jakarta.enterprise.context.ApplicationScoped; +import jakarta.inject.Inject; +import org.jboss.logging.Logger; + +import java.util.List; +import java.util.Map; +import java.util.Set; + +/** + * Dedicated IP pools (the {@code dedicatedIpPoolStore}), extracted from {@link SesService} as part of + * the store-based domain split. A clean leaf reached through the {@code SesService} + * facade, which delegates here; the facade's configuration-set delivery-options validation also + * checks pool existence through {@link #dedicatedIpPoolExists}. + */ +@ApplicationScoped +public class SesDedicatedIpService { + + private static final Logger LOG = Logger.getLogger(SesDedicatedIpService.class); + + private static final Set SCALING_MODES = Set.of("STANDARD", "MANAGED"); + + private final StorageBackend dedicatedIpPoolStore; + + @Inject + public SesDedicatedIpService(StorageFactory storageFactory) { + this.dedicatedIpPoolStore = storageFactory.create("ses", "ses-dedicated-ip-pools.json", + new TypeReference>() {}); + } + + SesDedicatedIpService(StorageBackend dedicatedIpPoolStore) { + this.dedicatedIpPoolStore = dedicatedIpPoolStore; + } + + public DedicatedIpPool createDedicatedIpPool(String poolName, String scalingMode, String region) { + if (poolName == null || poolName.isBlank()) { + throw new AwsException("BadRequestException", "PoolName is required.", 400); + } + String effectiveScaling = (scalingMode == null || scalingMode.isBlank()) ? "STANDARD" : scalingMode; + if (!SCALING_MODES.contains(effectiveScaling)) { + throw new AwsException("BadRequestException", "The ScalingMode parameter is invalid.", 400); + } + String key = dedicatedIpPoolKey(region, poolName); + if (dedicatedIpPoolStore.get(key).isPresent()) { + throw new AwsException("AlreadyExistsException", + "The pool <" + poolName + "> already exists.", 400); + } + DedicatedIpPool pool = new DedicatedIpPool(poolName, effectiveScaling); + dedicatedIpPoolStore.put(key, pool); + LOG.infov("Created SES dedicated IP pool: {0} in region {1}", poolName, region); + return pool; + } + + public DedicatedIpPool getDedicatedIpPool(String poolName, String region) { + return dedicatedIpPoolStore.get(dedicatedIpPoolKey(region, poolName)) + .orElseThrow(() -> new AwsException("NotFoundException", + "The requested pool <" + poolName + "> does not exist.", 404)); + } + + public boolean dedicatedIpPoolExists(String poolName, String region) { + return dedicatedIpPoolStore.get(dedicatedIpPoolKey(region, poolName)).isPresent(); + } + + public List listDedicatedIpPools(String region) { + String prefix = "dedicatedIpPool::" + region + "::"; + return dedicatedIpPoolStore.scan(k -> k.startsWith(prefix)).stream() + .map(DedicatedIpPool::getPoolName) + .sorted() + .toList(); + } + + public void deleteDedicatedIpPool(String poolName, String region) { + String key = dedicatedIpPoolKey(region, poolName); + if (dedicatedIpPoolStore.get(key).isEmpty()) { + throw new AwsException("NotFoundException", + "The requested pool <" + poolName + "> does not exist.", 404); + } + dedicatedIpPoolStore.delete(key); + LOG.infov("Deleted SES dedicated IP pool: {0} in region {1}", poolName, region); + } + + private static String dedicatedIpPoolKey(String region, String name) { + return "dedicatedIpPool::" + region + "::" + name; + } +} diff --git a/src/main/java/io/github/hectorvent/floci/services/ses/SesPolicyService.java b/src/main/java/io/github/hectorvent/floci/services/ses/SesPolicyService.java new file mode 100644 index 0000000000..35b74f4bc8 --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/ses/SesPolicyService.java @@ -0,0 +1,211 @@ +package io.github.hectorvent.floci.services.ses; + +import com.fasterxml.jackson.core.type.TypeReference; +import com.fasterxml.jackson.databind.ObjectMapper; +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 jakarta.enterprise.context.ApplicationScoped; +import jakarta.inject.Inject; +import org.jboss.logging.Logger; + +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.regex.Pattern; + +/** + * Identity sending-authorization policies (the {@code policyStore}), extracted from + * {@link SesService} as the fourth step of the store-based domain split. + * + *

New facet vs the earlier steps: a two-way relationship with the (not-yet-extracted) Identity + * domain. The facade keeps the identity-existence check ({@code requireIdentityExists} reads the + * identity store) and runs it before delegating the v2 mutators here. In the other direction, the + * facade's {@code deleteIdentity} calls {@link #deletePoliciesForIdentity} so an identity's policies + * are purged with it — the monolith depending on the extracted service, which is how the pieces will + * fit once Identity is itself extracted. + */ +@ApplicationScoped +public class SesPolicyService { + + private static final Logger LOG = Logger.getLogger(SesPolicyService.class); + + static final int MAX_POLICIES_PER_IDENTITY = 20; + private static final Pattern POLICY_NAME_CHARS = Pattern.compile("[A-Za-z0-9_-]+"); + + private final StorageBackend policyStore; + // Serializes the per-identity policy count check-then-put so concurrent creates can't both pass. + private final Object policyMutationLock = new Object(); + private final ObjectMapper objectMapper; + + @Inject + public SesPolicyService(StorageFactory storageFactory, ObjectMapper objectMapper) { + this.policyStore = storageFactory.create("ses", "ses-identity-policies.json", + new TypeReference>() {}); + this.objectMapper = objectMapper; + } + + SesPolicyService(StorageBackend policyStore, ObjectMapper objectMapper) { + this.policyStore = policyStore; + this.objectMapper = objectMapper; + } + + // v1 PutIdentityPolicy: upsert (create or overwrite); v1 does not require the identity to exist. + public void putIdentityPolicy(String identity, String policyName, String policy, String region) { + validatePolicyName(policyName); + String normalized = normalizePolicy(policy); + String key = policyKey(region, identity, policyName); + synchronized (policyMutationLock) { + if (policyStore.get(key).isEmpty()) { + enforcePolicyLimit(region, identity, false); + } + policyStore.put(key, normalized); + } + LOG.infov("SES PutIdentityPolicy: {0} on {1} (region {2})", policyName, identity, region); + } + + // v2 CreateEmailIdentityPolicy: fails if the name already exists. The identity-existence check is + // done by the SesService facade before this is called. + public void createEmailIdentityPolicy(String identity, String policyName, String policy, String region) { + validatePolicyName(policyName); + String normalized = normalizePolicy(policy); + String key = policyKey(region, identity, policyName); + synchronized (policyMutationLock) { + if (policyStore.get(key).isPresent()) { + throw new AwsException("AlreadyExistsException", + "Policy <" + policyName + "> already exists", 400); + } + enforcePolicyLimit(region, identity, true); + policyStore.put(key, normalized); + } + LOG.infov("SES v2 CreateEmailIdentityPolicy: {0} on {1} (region {2})", policyName, identity, region); + } + + // v2 UpdateEmailIdentityPolicy: fails if the name is missing. Identity check done by the facade. + public void updateEmailIdentityPolicy(String identity, String policyName, String policy, String region) { + validatePolicyName(policyName); + String normalized = normalizePolicy(policy); + String key = policyKey(region, identity, policyName); + synchronized (policyMutationLock) { + if (policyStore.get(key).isEmpty()) { + throw policyNotFound(policyName); + } + policyStore.put(key, normalized); + } + LOG.infov("SES v2 UpdateEmailIdentityPolicy: {0} on {1} (region {2})", policyName, identity, region); + } + + // v1 GetIdentityPolicies: requested names only, missing silently omitted; no identity check. + public Map getIdentityPolicies(String identity, List policyNames, String region) { + Map out = new LinkedHashMap<>(); + for (String name : policyNames) { + policyStore.get(policyKey(region, identity, name)).ifPresent(doc -> out.put(name, doc)); + } + return out; + } + + // All policies for the identity, keyed by policy name. + public Map listAllPolicies(String identity, String region) { + String prefix = policyPrefix(region, identity); + Map out = new LinkedHashMap<>(); + for (String key : policyStore.keys()) { + if (key.startsWith(prefix)) { + policyStore.get(key).ifPresent(doc -> out.put(key.substring(prefix.length()), doc)); + } + } + return out; + } + + // v1 ListIdentityPolicies: policy names (sorted); no identity check. + public List listIdentityPolicyNames(String identity, String region) { + return listAllPolicies(identity, region).keySet().stream().sorted().toList(); + } + + // v2 DeleteEmailIdentityPolicy: NotFound if the policy is missing. Identity check done by the facade. + public void deleteEmailIdentityPolicy(String identity, String policyName, String region) { + String key = policyKey(region, identity, policyName); + synchronized (policyMutationLock) { + if (policyStore.get(key).isEmpty()) { + throw policyNotFound(policyName); + } + policyStore.delete(key); + } + LOG.infov("SES v2 DeleteEmailIdentityPolicy: {0} on {1} (region {2})", policyName, identity, region); + } + + // v1 DeleteIdentityPolicy: idempotent; no identity check, no error on a missing policy. + public void deleteIdentityPolicy(String identity, String policyName, String region) { + policyStore.delete(policyKey(region, identity, policyName)); + LOG.infov("SES DeleteIdentityPolicy: {0} on {1} (region {2})", policyName, identity, region); + } + + /** + * Purges every policy attached to an identity. Called by the facade's {@code deleteIdentity} so + * policies can't resurrect into a same-named identity recreated later (and the per-identity count + * stays correct). + */ + public void deletePoliciesForIdentity(String identity, String region) { + synchronized (policyMutationLock) { + String prefix = policyPrefix(region, identity); + for (String key : List.copyOf(policyStore.keys())) { + if (key.startsWith(prefix)) { + policyStore.delete(key); + } + } + } + } + + private void enforcePolicyLimit(String region, String identity, boolean v2) { + long count = policyStore.keys().stream() + .filter(k -> k.startsWith(policyPrefix(region, identity))).count(); + if (count >= MAX_POLICIES_PER_IDENTITY) { + String msg = "Number of policies for <" + identity + + "> exceeds max allowed number of policies per resource"; + throw new AwsException(v2 ? "LimitExceededException" : "InvalidParameterValue", msg, 400); + } + } + + // Error codes are the v1 (Query) codes verified against AWS; the v2 controller remaps them to + // BadRequestException. The messages are identical across v1 and v2. + private static void validatePolicyName(String policyName) { + if (policyName == null || policyName.isBlank()) { + throw new AwsException("InvalidParameterValue", "PolicyName is required.", 400); + } + if (policyName.length() > 64) { + throw new AwsException("ValidationError", + "1 validation error detected: Value at 'policyName' failed to satisfy constraint: " + + "Member must have length less than or equal to 64", 400); + } + if (!POLICY_NAME_CHARS.matcher(policyName).matches()) { + throw new AwsException("InvalidParameterValue", + "PolicyName is invalid. Policy names must only include alpha-numeric characters, " + + "dashes, and underscores.", 400); + } + } + + private String normalizePolicy(String policy) { + if (policy == null || policy.isBlank()) { + throw new AwsException("InvalidParameterValue", "Policy is required.", 400); + } + try { + // AWS returns the policy with insignificant whitespace stripped; compact it to match. + return objectMapper.readTree(policy).toString(); + } catch (com.fasterxml.jackson.core.JsonProcessingException e) { + // Floci does not validate policy semantics; keep an unparseable document verbatim. + LOG.debugv("Identity policy is not valid JSON, storing as-is: {0}", e.getMessage()); + return policy; + } + } + + private static AwsException policyNotFound(String policyName) { + return new AwsException("NotFoundException", "Policy <" + policyName + "> does not exist", 404); + } + + private static String policyKey(String region, String identity, String policyName) { + return policyPrefix(region, identity) + policyName; + } + + private static String policyPrefix(String region, String identity) { + return "policy::" + region + "::" + identity + "::"; + } +} diff --git a/src/main/java/io/github/hectorvent/floci/services/ses/SesReceiptRuleService.java b/src/main/java/io/github/hectorvent/floci/services/ses/SesReceiptRuleService.java new file mode 100644 index 0000000000..23cd91d3e2 --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/ses/SesReceiptRuleService.java @@ -0,0 +1,175 @@ +package io.github.hectorvent.floci.services.ses; + +import com.fasterxml.jackson.core.type.TypeReference; +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.ses.model.ReceiptRuleSet; +import jakarta.enterprise.context.ApplicationScoped; +import jakarta.inject.Inject; +import org.jboss.logging.Logger; + +import java.time.Clock; +import java.time.Instant; +import java.util.ArrayList; +import java.util.Comparator; +import java.util.List; +import java.util.Map; +import java.util.regex.Pattern; + +/** + * Owns the SES receipt-rule-set domain (the {@code receiptRuleSetStore}). Extracted from + * {@link SesService} as the first step of the store-based domain split: a leaf + * domain with no cross-service coupling, reached only through the {@code SesService} facade, which + * now delegates its {@code *ReceiptRuleSet*} methods here. + * + *

Floci has no inbound-mail endpoint, so receipt rule sets are stored inertly: a set never holds + * any rules and routes no mail. They exist only so the management API round-trips (enough to unblock + * tools such as Terraform that declare a rule set during bootstrap). + */ +@ApplicationScoped +public class SesReceiptRuleService { + + private static final Logger LOG = Logger.getLogger(SesReceiptRuleService.class); + + // These RuleSetName constraints are not in the botocore model: service-2.json (SES 2010-12-01) + // declares ReceiptRuleSetName as a bare {"type": "string"} with no pattern or length. They were + // established by probing real SES in us-west-2 via boto3 (2026-08): a character outside + // ^[a-zA-Z0-9_.-]+$ is a Smithy ValidationError, and a name that is >64 chars or does not + // start/end with an alphanumeric is a service-level "Not a valid ruleSetName" InvalidParameterValue. + // Re-verify against live SES (not the model, which can't confirm it) if these ever need to change. + private static final Pattern RULE_SET_NAME_CHARS = Pattern.compile("^[a-zA-Z0-9_.-]+$"); + + private final StorageBackend receiptRuleSetStore; + // Serializes receipt-rule-set create (check-then-put) and set-active (clear-then-set) so the + // one-active-per-region invariant and duplicate-name rejection hold under concurrency. + private final Object receiptRuleSetLock = new Object(); + private final Clock clock; + + @Inject + public SesReceiptRuleService(StorageFactory storageFactory, Clock clock) { + this.receiptRuleSetStore = storageFactory.create("ses", "ses-receipt-rule-sets.json", + new TypeReference>() {}); + this.clock = clock; + } + + SesReceiptRuleService(StorageBackend receiptRuleSetStore, Clock clock) { + this.receiptRuleSetStore = receiptRuleSetStore; + this.clock = clock; + } + + public ReceiptRuleSet createReceiptRuleSet(String name, String region) { + requireRuleSetName(name); + String key = receiptRuleSetKey(region, name); + ReceiptRuleSet ruleSet = new ReceiptRuleSet(name, Instant.now(clock)); + synchronized (receiptRuleSetLock) { + if (receiptRuleSetStore.get(key).isPresent()) { + throw new AwsException("AlreadyExists", "Rule set already exists: " + name, 400); + } + receiptRuleSetStore.put(key, ruleSet); + } + LOG.infov("Created SES receipt rule set: {0} in region {1}", name, region); + return ruleSet; + } + + public ReceiptRuleSet describeReceiptRuleSet(String name, String region) { + requireRuleSetName(name); + return receiptRuleSetStore.get(receiptRuleSetKey(region, name)) + .orElseThrow(() -> ruleSetDoesNotExist(name)); + } + + public List listReceiptRuleSets(String region) { + String prefix = "receiptRuleSet::" + region + "::"; + List all = new ArrayList<>(receiptRuleSetStore.scan(k -> k.startsWith(prefix))); + all.sort(Comparator.comparing(ReceiptRuleSet::getCreatedTimestamp, + Comparator.nullsLast(Comparator.naturalOrder())) + .thenComparing(ReceiptRuleSet::getName, Comparator.nullsLast(Comparator.naturalOrder()))); + return all; + } + + public void deleteReceiptRuleSet(String name, String region) { + requireRuleSetName(name); + // Hold the lock so the active-check-then-delete is atomic and a concurrent set-active/clear + // (which scans and re-puts active sets) can't resurrect the rule set we just deleted. + synchronized (receiptRuleSetLock) { + ReceiptRuleSet existing = receiptRuleSetStore.get(receiptRuleSetKey(region, name)).orElse(null); + if (existing != null && existing.isActive()) { + // AWS rejects deleting the active rule set (verified: CannotDelete / 400). + throw new AwsException("CannotDelete", "Cannot delete active rule set: " + name, 400); + } + // AWS is idempotent otherwise: deleting a non-existent rule set succeeds without error. + receiptRuleSetStore.delete(receiptRuleSetKey(region, name)); + } + LOG.infov("Deleted SES receipt rule set: {0} in region {1}", name, region); + } + + public void setActiveReceiptRuleSet(String name, String region) { + // No RuleSetName clears the account's active rule set (matches AWS). + boolean clearOnly = name == null || name.isBlank(); + if (!clearOnly) { + requireRuleSetName(name); + } + synchronized (receiptRuleSetLock) { + if (!clearOnly) { + ReceiptRuleSet target = receiptRuleSetStore.get(receiptRuleSetKey(region, name)) + .orElseThrow(() -> ruleSetDoesNotExist(name)); + clearActiveReceiptRuleSet(region); + target.setActive(true); + receiptRuleSetStore.put(receiptRuleSetKey(region, name), target); + } else { + clearActiveReceiptRuleSet(region); + } + } + if (clearOnly) { + LOG.infov("Cleared active SES receipt rule set in region {0}", region); + } else { + LOG.infov("Set active SES receipt rule set: {0} in region {1}", name, region); + } + } + + public ReceiptRuleSet describeActiveReceiptRuleSet(String region) { + String prefix = "receiptRuleSet::" + region + "::"; + // Read under the lock so a concurrent set-active replacement (clear-then-set) can't expose its + // intermediate no-active state — the reader sees either the old or the new active set. + synchronized (receiptRuleSetLock) { + return receiptRuleSetStore.scan(k -> k.startsWith(prefix)).stream() + .filter(ReceiptRuleSet::isActive) + .findFirst() + .orElse(null); + } + } + + private void clearActiveReceiptRuleSet(String region) { + String prefix = "receiptRuleSet::" + region + "::"; + for (ReceiptRuleSet rs : receiptRuleSetStore.scan(k -> k.startsWith(prefix))) { + if (rs.isActive()) { + rs.setActive(false); + receiptRuleSetStore.put(receiptRuleSetKey(region, rs.getName()), rs); + } + } + } + + private static void requireRuleSetName(String name) { + if (name == null || name.isBlank()) { + throw new AwsException("InvalidParameterValue", "RuleSetName is required.", 400); + } + if (!RULE_SET_NAME_CHARS.matcher(name).matches()) { + throw new AwsException("ValidationError", + "1 validation error detected: Value at 'ruleSetName' failed to satisfy constraint: " + + "Member must satisfy regular expression pattern: ^[a-zA-Z0-9_.-]+$", 400); + } + if (name.length() > 64 + || !Character.isLetterOrDigit(name.charAt(0)) + || !Character.isLetterOrDigit(name.charAt(name.length() - 1))) { + throw new AwsException("InvalidParameterValue", "Not a valid ruleSetName: " + name, 400); + } + } + + private static AwsException ruleSetDoesNotExist(String name) { + return new AwsException("RuleSetDoesNotExist", "Rule set does not exist: " + name, 400); + } + + private static String receiptRuleSetKey(String region, String name) { + return "receiptRuleSet::" + region + "::" + name; + } +} diff --git a/src/main/java/io/github/hectorvent/floci/services/ses/SesSentEmailService.java b/src/main/java/io/github/hectorvent/floci/services/ses/SesSentEmailService.java new file mode 100644 index 0000000000..767ced6018 --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/ses/SesSentEmailService.java @@ -0,0 +1,59 @@ +package io.github.hectorvent.floci.services.ses; + +import com.fasterxml.jackson.core.type.TypeReference; +import io.github.hectorvent.floci.core.storage.StorageBackend; +import io.github.hectorvent.floci.core.storage.StorageFactory; +import io.github.hectorvent.floci.services.ses.model.SentEmail; +import jakarta.enterprise.context.ApplicationScoped; +import jakarta.inject.Inject; +import org.jboss.logging.Logger; + +import java.util.List; +import java.util.Map; + +/** + * Sent-email records (the {@code emailStore}), extracted from {@link SesService} as part of the + * store-based domain split. This is the send path's output sink: the facade's send methods keep the + * whole send orchestration and only hand the finished record here through {@link #record}, while the + * send-statistics and inspection endpoints read it back through {@link #countInRegion} / + * {@link #listAll} / {@link #clear}. Nothing else reads the store, so it is a clean leaf. + */ +@ApplicationScoped +public class SesSentEmailService { + + private static final Logger LOG = Logger.getLogger(SesSentEmailService.class); + + private final StorageBackend emailStore; + + @Inject + public SesSentEmailService(StorageFactory storageFactory) { + this.emailStore = storageFactory.create("ses", "ses-emails.json", + new TypeReference>() {}); + } + + SesSentEmailService(StorageBackend emailStore) { + this.emailStore = emailStore; + } + + public void record(String region, String messageId, SentEmail email) { + emailStore.put(emailKey(region, messageId), email); + } + + public long countInRegion(String region) { + String prefix = "email::" + region + "::"; + return emailStore.scan(k -> k.startsWith(prefix)).size(); + } + + public List listAll() { + return emailStore.scan(k -> k.startsWith("email::")); + } + + public void clear() { + emailStore.clear(); + LOG.info("Cleared all SES emails"); + } + + private static String emailKey(String region, String messageId) { + return "email::" + region + "::" + messageId; + } +} 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 5229e61ec5..47cbb11516 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 @@ -84,37 +84,31 @@ public class SesService { private static final SecureRandom BOUNDARY_RANDOM = new SecureRandom(); private final StorageBackend identityStore; - private final StorageBackend emailStore; - private final StorageBackend accountSettingsStore; - private final StorageBackend templateStore; + // Sent-email records extracted to SesSentEmailService. The send path records finished emails via + // it; send-statistics and inspection read back through it. + private final SesSentEmailService sentEmailService; + // Account-level settings, extracted to its own service. The facade delegates. + private final SesAccountService accountService; + // Email templates extracted to SesTemplateService. The facade delegates; the templated-send path + // reads via it, and ARN-dispatched tagging reads/writes via its find/save. + private final SesTemplateService templateService; private final StorageBackend configSetStore; - private final StorageBackend suppressionStore; - private final StorageBackend accountSuppressionStore; - private final StorageBackend accountVdmStore; - private final StorageBackend dedicatedIpPoolStore; - private final StorageBackend contactListStore; - private final StorageBackend contactStore; - // Identity (sending authorization) policies: key policy::::::, - // value the (normalized) policy JSON. One store shared by the v1 and v2 policy APIs. - private final StorageBackend policyStore; - private final StorageBackend receiptRuleSetStore; - // Custom verification email templates (key cvet::::), shared by the v1 and v2 APIs. - private final StorageBackend cvetStore; - // Guards the one-list-per-account check-then-create so concurrent creates can't both pass. - private final Object contactListCreateLock = new Object(); - // Serializes contact create/update against contact-list deletion so a concurrent delete - // can't purge the list between validation and the write, leaving an orphaned contact. - private final Object contactMutationLock = new Object(); - // Serializes the per-identity policy count check-then-put so concurrent creates can't both pass. - private final Object policyMutationLock = new Object(); - static final int MAX_POLICIES_PER_IDENTITY = 20; - // Serializes receipt-rule-set create (check-then-put) and set-active (clear-then-set) so the - // one-active-per-region invariant and duplicate-name rejection hold under concurrency. - private final Object receiptRuleSetLock = new Object(); - // Serializes custom-verification-template create/update/delete check-then-write so concurrent - // creates for the same name can't both succeed and an update can't resurrect a concurrently - // deleted template. - private final Object cvetMutationLock = new Object(); + // Account suppression attributes + the per-address suppression list (two stores) extracted to + // SesSuppressionService. The facade delegates; its send filters read via it. + private final SesSuppressionService suppressionService; + // Dedicated IP pools extracted to SesDedicatedIpService. The facade delegates. + private final SesDedicatedIpService dedicatedIpService; + // Contact lists and contacts (two stores) extracted to SesContactService. The + // facade delegates, and its send-path list-management orchestration calls into the service. + private final SesContactService contactService; + // Identity (sending authorization) policy storage, extracted to SesPolicyService. + // The facade keeps the identity-existence check and delegates the rest. + private final SesPolicyService policyService; + // Receipt-rule-set domain, extracted to its own service. The facade delegates. + private final SesReceiptRuleService receiptRuleService; + // Custom verification email templates: storage extracted to SesCvetService. The + // facade keeps the identity-dependent validation and the send path; the service owns the store. + private final SesCvetService cvetService; private final SmtpRelay smtpRelay; private final ObjectMapper objectMapper; private final SesEventPublisher eventPublisher; @@ -127,37 +121,27 @@ public class SesService { private final ConcurrentHashMap dkimLookupCache = new ConcurrentHashMap<>(); @Inject - public SesService(StorageFactory storageFactory, SmtpRelay smtpRelay, ObjectMapper objectMapper, + public SesService(StorageFactory storageFactory, SesReceiptRuleService receiptRuleService, + SesAccountService accountService, SesCvetService cvetService, + SesPolicyService policyService, SesContactService contactService, + SesSuppressionService suppressionService, SesDedicatedIpService dedicatedIpService, + SesTemplateService templateService, SesSentEmailService sentEmailService, + SmtpRelay smtpRelay, ObjectMapper objectMapper, SesEventPublisher eventPublisher, EmulatorConfig config, Route53Service route53Service, Clock clock) { this.identityStore = storageFactory.create("ses", "ses-identities.json", new TypeReference>() {}); - this.emailStore = storageFactory.create("ses", "ses-emails.json", - new TypeReference>() {}); - this.accountSettingsStore = storageFactory.create("ses", "ses-account-settings.json", - new TypeReference>() {}); - this.templateStore = storageFactory.create("ses", "ses-templates.json", - new TypeReference>() {}); + this.sentEmailService = sentEmailService; + this.accountService = accountService; + this.templateService = templateService; this.configSetStore = storageFactory.create("ses", "ses-config-sets.json", new TypeReference>() {}); - this.suppressionStore = storageFactory.create("ses", "ses-suppression.json", - new TypeReference>() {}); - this.accountSuppressionStore = storageFactory.create("ses", "ses-account-suppression.json", - new TypeReference>() {}); - this.accountVdmStore = storageFactory.create("ses", "ses-account-vdm.json", - new TypeReference>() {}); - this.dedicatedIpPoolStore = storageFactory.create("ses", "ses-dedicated-ip-pools.json", - new TypeReference>() {}); - this.contactListStore = storageFactory.create("ses", "ses-contact-lists.json", - new TypeReference>() {}); - this.contactStore = storageFactory.create("ses", "ses-contacts.json", - new TypeReference>() {}); - this.policyStore = storageFactory.create("ses", "ses-identity-policies.json", - new TypeReference>() {}); - this.receiptRuleSetStore = storageFactory.create("ses", "ses-receipt-rule-sets.json", - new TypeReference>() {}); - this.cvetStore = storageFactory.create("ses", "ses-custom-verification-templates.json", - new TypeReference>() {}); + this.suppressionService = suppressionService; + this.dedicatedIpService = dedicatedIpService; + this.contactService = contactService; + this.policyService = policyService; + this.receiptRuleService = receiptRuleService; + this.cvetService = cvetService; this.smtpRelay = smtpRelay; this.objectMapper = objectMapper; this.eventPublisher = eventPublisher; @@ -168,59 +152,50 @@ public class SesService { } SesService(StorageBackend identityStore, - StorageBackend emailStore, - StorageBackend accountSettingsStore, - StorageBackend templateStore, + SesSentEmailService sentEmailService, + SesAccountService accountService, + SesTemplateService templateService, StorageBackend configSetStore, - StorageBackend suppressionStore, - StorageBackend accountSuppressionStore, - StorageBackend accountVdmStore, - StorageBackend dedicatedIpPoolStore, - StorageBackend contactListStore, - StorageBackend contactStore, - StorageBackend policyStore, - StorageBackend receiptRuleSetStore, - StorageBackend cvetStore, + SesSuppressionService suppressionService, + SesDedicatedIpService dedicatedIpService, + SesContactService contactService, + SesPolicyService policyService, + SesReceiptRuleService receiptRuleService, + SesCvetService cvetService, SmtpRelay smtpRelay, ObjectMapper objectMapper, Clock clock) { - this(identityStore, emailStore, accountSettingsStore, templateStore, configSetStore, suppressionStore, - accountSuppressionStore, accountVdmStore, dedicatedIpPoolStore, contactListStore, contactStore, - policyStore, receiptRuleSetStore, cvetStore, smtpRelay, objectMapper, null, clock); + this(identityStore, sentEmailService, accountService, templateService, configSetStore, suppressionService, + dedicatedIpService, contactService, policyService, + receiptRuleService, cvetService, smtpRelay, objectMapper, null, clock); } SesService(StorageBackend identityStore, - StorageBackend emailStore, - StorageBackend accountSettingsStore, - StorageBackend templateStore, + SesSentEmailService sentEmailService, + SesAccountService accountService, + SesTemplateService templateService, StorageBackend configSetStore, - StorageBackend suppressionStore, - StorageBackend accountSuppressionStore, - StorageBackend accountVdmStore, - StorageBackend dedicatedIpPoolStore, - StorageBackend contactListStore, - StorageBackend contactStore, - StorageBackend policyStore, - StorageBackend receiptRuleSetStore, - StorageBackend cvetStore, + SesSuppressionService suppressionService, + SesDedicatedIpService dedicatedIpService, + SesContactService contactService, + SesPolicyService policyService, + SesReceiptRuleService receiptRuleService, + SesCvetService cvetService, SmtpRelay smtpRelay, ObjectMapper objectMapper, Route53Service route53Service, Clock clock) { this.identityStore = identityStore; - this.emailStore = emailStore; - this.accountSettingsStore = accountSettingsStore; - this.templateStore = templateStore; + this.sentEmailService = sentEmailService; + this.accountService = accountService; + this.templateService = templateService; this.configSetStore = configSetStore; - this.suppressionStore = suppressionStore; - this.accountSuppressionStore = accountSuppressionStore; - this.accountVdmStore = accountVdmStore; - this.dedicatedIpPoolStore = dedicatedIpPoolStore; - this.contactListStore = contactListStore; - this.contactStore = contactStore; - this.policyStore = policyStore; - this.receiptRuleSetStore = receiptRuleSetStore; - this.cvetStore = cvetStore; + this.suppressionService = suppressionService; + this.dedicatedIpService = dedicatedIpService; + this.contactService = contactService; + this.policyService = policyService; + this.receiptRuleService = receiptRuleService; + this.cvetService = cvetService; this.smtpRelay = smtpRelay; this.objectMapper = objectMapper; this.eventPublisher = null; @@ -288,14 +263,7 @@ public class SesService { // Policies are sub-resources of the identity; drop them too so they can't resurrect into a // same-named identity recreated later (and so the per-identity count stays correct). - synchronized (policyMutationLock) { - String policyPrefix = policyPrefix(region, identityValue); - for (String policyKey : new ArrayList<>(policyStore.keys())) { - if (policyKey.startsWith(policyPrefix)) { - policyStore.delete(policyKey); - } - } - } + policyService.deletePoliciesForIdentity(identityValue, region); LOG.infov("Deleted identity: {0}", identityValue); } @@ -368,7 +336,7 @@ public class SesService { if (additionalHeaders != null && !additionalHeaders.isEmpty()) { email.setHeaders(additionalHeaders); } - emailStore.put("email::" + region + "::" + messageId, email); + sentEmailService.record(region, messageId, email); List relayedTo = filterUnsuppressed(toAddresses, suppressedReasons); List relayedCc = filterUnsuppressed(ccAddresses, suppressedReasons); @@ -440,7 +408,7 @@ public class SesService { String messageId = UUID.randomUUID().toString(); SentEmail email = new SentEmail(messageId, region, effectiveSource, effectiveDestinations, rawMessage); - emailStore.put("email::" + region + "::" + messageId, email); + sentEmailService.record(region, messageId, email); List relayedDestinations = filterUnsuppressed(effectiveDestinations, suppressedReasons); if (!relayedDestinations.isEmpty()) { @@ -656,8 +624,7 @@ public class SesService { } public long getSentEmailCount(String region) { - String prefix = "email::" + region + "::"; - return emailStore.scan(k -> k.startsWith(prefix)).size(); + return sentEmailService.countInRegion(region); } public void setIdentityNotificationTopic(String identityValue, String notificationType, @@ -1142,38 +1109,27 @@ public class SesService { } public List getEmails() { - return emailStore.scan(k -> k.startsWith("email::")); + return sentEmailService.listAll(); } public void clearEmails() { - emailStore.clear(); - LOG.info("Cleared all SES emails"); + sentEmailService.clear(); } public boolean isAccountSendingEnabled(String region) { - return accountSettingsStore.get("sending::" + region).orElse(true); + return accountService.isAccountSendingEnabled(region); } public void setAccountSendingEnabled(String region, boolean enabled) { - accountSettingsStore.put("sending::" + region, enabled); - LOG.infov("Updated account sending enabled for region {0}: {1}", region, enabled); + accountService.setAccountSendingEnabled(region, enabled); } - // VDM (Virtual Deliverability Manager) is opt-in and per region: GetAccount omits VdmAttributes - // entirely until PutAccountVdmAttributes is called for the region, so this returns empty when the - // region was never configured. The whole tuple is stored under one region key so GetAccount never - // observes a partially updated state. public Optional findAccountVdmAttributes(String region) { - return accountVdmStore.get(accountVdmKey(region)); + return accountService.findAccountVdmAttributes(region); } public void putAccountVdmAttributes(String region, AccountVdmAttributes vdm) { - accountVdmStore.put(accountVdmKey(region), vdm); - LOG.infov("Updated account VDM attributes for region {0}: enabled={1}", region, vdm.vdmEnabled()); - } - - private static String accountVdmKey(String region) { - return "account-vdm::" + region; + accountService.putAccountVdmAttributes(region, vdm); } public void setConfigurationSetSendingEnabled(String configSetName, boolean enabled, String region) { @@ -1186,65 +1142,27 @@ public class SesService { // ──────────────────────────── Templates ──────────────────────────── + // Email templates live in SesTemplateService; the facade forwards. The templated-send path below + // reads them back through getTemplate, and ARN-dispatched tagging through find/save. + public EmailTemplate createTemplate(EmailTemplate template, String region) { - validateTemplate(template); - if (template.getTags() != null) { - for (Tag tag : template.getTags()) { - validateTag(tag); - } - } - String key = templateKey(region, template.getTemplateName()); - if (templateStore.get(key).isPresent()) { - throw new AwsException("AlreadyExists", - "Template " + template.getTemplateName() + " already exists.", 400); - } - Instant now = Instant.now(); - template.setCreatedTimestamp(now); - template.setLastUpdatedTimestamp(now); - templateStore.put(key, template); - LOG.infov("Created SES template: {0} in region {1}", template.getTemplateName(), region); - return template; + return templateService.createTemplate(template, region); } public EmailTemplate getTemplate(String templateName, String region) { - return templateStore.get(templateKey(region, templateName)) - .orElseThrow(() -> new AwsException("TemplateDoesNotExist", - "Template " + templateName + " does not exist.", 400)); + return templateService.getTemplate(templateName, region); } public EmailTemplate updateTemplate(EmailTemplate template, String region) { - validateTemplate(template); - String key = templateKey(region, template.getTemplateName()); - EmailTemplate existing = templateStore.get(key) - .orElseThrow(() -> new AwsException("TemplateDoesNotExist", - "Template " + template.getTemplateName() + " does not exist.", 400)); - template.setCreatedTimestamp(existing.getCreatedTimestamp()); - template.setLastUpdatedTimestamp(Instant.now()); - // Tags are managed exclusively via Tag/UntagResource — preserve them on update. - template.setTags(existing.getTags()); - templateStore.put(key, template); - LOG.infov("Updated SES template: {0} in region {1}", template.getTemplateName(), region); - return template; + return templateService.updateTemplate(template, region); } public void deleteTemplate(String templateName, String region) { - String key = templateKey(region, templateName); - if (templateStore.get(key).isEmpty()) { - throw new AwsException("TemplateDoesNotExist", - "Template " + templateName + " does not exist.", 400); - } - templateStore.delete(key); - LOG.infov("Deleted SES template: {0} in region {1}", templateName, region); + templateService.deleteTemplate(templateName, region); } public List listTemplates(String region) { - String prefix = "template::" + region + "::"; - List all = new ArrayList<>(templateStore.scan(k -> k.startsWith(prefix))); - all.sort(Comparator.comparing(EmailTemplate::getCreatedTimestamp, - Comparator.nullsLast(Comparator.naturalOrder())) - .thenComparing(EmailTemplate::getTemplateName, - Comparator.nullsLast(Comparator.naturalOrder()))); - return all; + return templateService.listTemplates(region); } // ──────────── Custom verification email templates (v1 + v2 shared store) ──────────── @@ -1253,64 +1171,29 @@ public class SesService { // From-verified check against its own identity store (it does track verified identities). public void createCustomVerificationEmailTemplate(CustomVerificationEmailTemplate template, String region) { + // The From-verified check inside validation reaches the Identity domain, so the facade + // validates here before the storage service performs the create. validateCustomVerificationTemplate(template, region); - String key = cvetKey(region, template.getTemplateName()); - // Lock only the check-then-put so concurrent creates for the same name can't both observe - // the key as absent; validation and logging stay outside the lock. - synchronized (cvetMutationLock) { - if (cvetStore.get(key).isPresent()) { - // v1-native code (verified: CustomVerificationEmailTemplateAlreadyExists / 400); - // remapV1Exception translates it to AlreadyExistsException / 400 for the v2 boundary. - throw new AwsException("CustomVerificationEmailTemplateAlreadyExists", - "Custom verification email template <" + template.getTemplateName() + "> already exists", 400); - } - cvetStore.put(key, template); - } - LOG.infov("Created custom verification email template {0} in region {1}", - template.getTemplateName(), region); + cvetService.createCustomVerificationEmailTemplate(template, region); } public CustomVerificationEmailTemplate getCustomVerificationEmailTemplate(String templateName, String region) { - return cvetStore.get(cvetKey(region, templateName)).orElseThrow(() -> cvetNotFound(templateName)); + return cvetService.getCustomVerificationEmailTemplate(templateName, region); } public List listCustomVerificationEmailTemplates(String region) { - String prefix = "cvet::" + region + "::"; - return cvetStore.scan(k -> k.startsWith(prefix)).stream() - .sorted(Comparator.comparing(CustomVerificationEmailTemplate::getTemplateName, - Comparator.nullsFirst(Comparator.naturalOrder()))) - .toList(); + return cvetService.listCustomVerificationEmailTemplates(region); } public void updateCustomVerificationEmailTemplate(CustomVerificationEmailTemplate template, String region) { - // Validate required fields (including TemplateName) before the existence check so a missing or - // blank name yields the required-field InvalidParameterValue rather than NotFoundException, - // matching createCustomVerificationEmailTemplate. + // Validate (including the From-verified identity check and the required-field checks) before + // delegating the storage update, matching createCustomVerificationEmailTemplate. validateCustomVerificationTemplate(template, region); - String key = cvetKey(region, template.getTemplateName()); - // Guard the existence check and the put together so a concurrent delete can't slip between - // them and have the update resurrect the just-deleted template. - synchronized (cvetMutationLock) { - if (cvetStore.get(key).isEmpty()) { - throw cvetNotFound(template.getTemplateName()); - } - cvetStore.put(key, template); - } - LOG.infov("Updated custom verification email template {0} in region {1}", - template.getTemplateName(), region); + cvetService.updateCustomVerificationEmailTemplate(template, region); } public void deleteCustomVerificationEmailTemplate(String templateName, String region) { - String key = cvetKey(region, templateName); - // Guard the check-then-delete on the same lock as create/update so the three mutations - // serialize against each other. - synchronized (cvetMutationLock) { - if (cvetStore.get(key).isEmpty()) { - throw cvetNotFound(templateName); - } - cvetStore.delete(key); - } - LOG.infov("Deleted custom verification email template {0} in region {1}", templateName, region); + cvetService.deleteCustomVerificationEmailTemplate(templateName, region); } // AWS appends this exact disclaimer to the end of every custom verification email and it cannot @@ -1342,7 +1225,7 @@ public class SesService { if (templateName == null || templateName.isBlank()) { throw new AwsException("InvalidParameterValue", "TemplateName is required.", 400); } - CustomVerificationEmailTemplate template = cvetStore.get(cvetKey(region, templateName)) + CustomVerificationEmailTemplate template = cvetService.find(templateName, region) .orElseThrow(() -> new AwsException("CustomVerificationEmailTemplateDoesNotExist", "Template <" + templateName + "> does not exist", 400)); if (!isVerifiedSender(template.getFromEmailAddress(), region)) { @@ -1369,7 +1252,7 @@ public class SesService { SentEmail email = new SentEmail(messageId, region, template.getFromEmailAddress(), List.of(emailAddress), List.of(), List.of(), List.of(), template.getTemplateSubject(), null, renderedHtml); - emailStore.put("email::" + region + "::" + messageId, email); + sentEmailService.record(region, messageId, email); smtpRelay.relay(template.getFromEmailAddress(), List.of(emailAddress), List.of(), List.of(), List.of(), template.getTemplateSubject(), null, renderedHtml, List.of()); LOG.infov("SES custom verification email sent: to={0}, template={1}, messageId={2}", @@ -1471,17 +1354,6 @@ public class SesService { } } - private static AwsException cvetNotFound(String templateName) { - // v1-native code (verified: CustomVerificationEmailTemplateDoesNotExist / 400). - // SesController.remapV1Exception translates it to NotFoundException / 404 for the v2 boundary. - return new AwsException("CustomVerificationEmailTemplateDoesNotExist", - "Custom verification email template <" + templateName + "> does not exist", 400); - } - - private static String cvetKey(String region, String templateName) { - return "cvet::" + region + "::" + templateName; - } - public ConfigurationSet createConfigurationSet(ConfigurationSet configSet, String region) { if (configSet == null) { throw new AwsException("InvalidParameterValue", @@ -1490,7 +1362,7 @@ public class SesService { String key = configSetKey(region, configSet.getName()); if (configSet.getTags() != null) { for (Tag tag : configSet.getTags()) { - validateTag(tag); + SesTags.validate(tag); } } if (configSet.getSuppressionOptions() != null @@ -1752,304 +1624,114 @@ public class SesService { // ──────────────────────── Receipt rule sets (inbound) ──────────────────────── // - // Floci has no inbound-mail endpoint, so receipt rule sets are stored inertly: a set never holds - // any rules and routes no mail. They exist only so the management API round-trips (enough to - // unblock tools such as Terraform that declare a rule set during bootstrap). + // Receipt rule sets live in SesReceiptRuleService; this facade + // just forwards, keeping the v1 SesQueryHandler call sites unchanged. public ReceiptRuleSet createReceiptRuleSet(String name, String region) { - requireRuleSetName(name); - String key = receiptRuleSetKey(region, name); - ReceiptRuleSet ruleSet = new ReceiptRuleSet(name, Instant.now(clock)); - synchronized (receiptRuleSetLock) { - if (receiptRuleSetStore.get(key).isPresent()) { - throw new AwsException("AlreadyExists", "Rule set already exists: " + name, 400); - } - receiptRuleSetStore.put(key, ruleSet); - } - LOG.infov("Created SES receipt rule set: {0} in region {1}", name, region); - return ruleSet; + return receiptRuleService.createReceiptRuleSet(name, region); } public ReceiptRuleSet describeReceiptRuleSet(String name, String region) { - requireRuleSetName(name); - return receiptRuleSetStore.get(receiptRuleSetKey(region, name)) - .orElseThrow(() -> ruleSetDoesNotExist(name)); + return receiptRuleService.describeReceiptRuleSet(name, region); } public List listReceiptRuleSets(String region) { - String prefix = "receiptRuleSet::" + region + "::"; - List all = new ArrayList<>(receiptRuleSetStore.scan(k -> k.startsWith(prefix))); - all.sort(Comparator.comparing(ReceiptRuleSet::getCreatedTimestamp, - Comparator.nullsLast(Comparator.naturalOrder())) - .thenComparing(ReceiptRuleSet::getName, Comparator.nullsLast(Comparator.naturalOrder()))); - return all; + return receiptRuleService.listReceiptRuleSets(region); } public void deleteReceiptRuleSet(String name, String region) { - requireRuleSetName(name); - // Hold the lock so the active-check-then-delete is atomic and a concurrent set-active/clear - // (which scans and re-puts active sets) can't resurrect the rule set we just deleted. - synchronized (receiptRuleSetLock) { - ReceiptRuleSet existing = receiptRuleSetStore.get(receiptRuleSetKey(region, name)).orElse(null); - if (existing != null && existing.isActive()) { - // AWS rejects deleting the active rule set (verified: CannotDelete / 400). - throw new AwsException("CannotDelete", "Cannot delete active rule set: " + name, 400); - } - // AWS is idempotent otherwise: deleting a non-existent rule set succeeds without error. - receiptRuleSetStore.delete(receiptRuleSetKey(region, name)); - } - LOG.infov("Deleted SES receipt rule set: {0} in region {1}", name, region); + receiptRuleService.deleteReceiptRuleSet(name, region); } public void setActiveReceiptRuleSet(String name, String region) { - // No RuleSetName clears the account's active rule set (matches AWS). - boolean clearOnly = name == null || name.isBlank(); - if (!clearOnly) { - requireRuleSetName(name); - } - synchronized (receiptRuleSetLock) { - if (!clearOnly) { - ReceiptRuleSet target = receiptRuleSetStore.get(receiptRuleSetKey(region, name)) - .orElseThrow(() -> ruleSetDoesNotExist(name)); - clearActiveReceiptRuleSet(region); - target.setActive(true); - receiptRuleSetStore.put(receiptRuleSetKey(region, name), target); - } else { - clearActiveReceiptRuleSet(region); - } - } - if (clearOnly) { - LOG.infov("Cleared active SES receipt rule set in region {0}", region); - } else { - LOG.infov("Set active SES receipt rule set: {0} in region {1}", name, region); - } + receiptRuleService.setActiveReceiptRuleSet(name, region); } public ReceiptRuleSet describeActiveReceiptRuleSet(String region) { - String prefix = "receiptRuleSet::" + region + "::"; - // Read under the lock so a concurrent set-active replacement (clear-then-set) can't expose its - // intermediate no-active state — the reader sees either the old or the new active set. - synchronized (receiptRuleSetLock) { - return receiptRuleSetStore.scan(k -> k.startsWith(prefix)).stream() - .filter(ReceiptRuleSet::isActive) - .findFirst() - .orElse(null); - } - } - - private void clearActiveReceiptRuleSet(String region) { - String prefix = "receiptRuleSet::" + region + "::"; - for (ReceiptRuleSet rs : receiptRuleSetStore.scan(k -> k.startsWith(prefix))) { - if (rs.isActive()) { - rs.setActive(false); - receiptRuleSetStore.put(receiptRuleSetKey(region, rs.getName()), rs); - } - } - } - - // These RuleSetName constraints are not in the botocore model: service-2.json (SES 2010-12-01) - // declares ReceiptRuleSetName as a bare {"type": "string"} with no pattern or length. They were - // established by probing real SES in us-west-2 via boto3 (2026-08): a character outside - // ^[a-zA-Z0-9_.-]+$ is a Smithy ValidationError, and a name that is >64 chars or does not - // start/end with an alphanumeric is a service-level "Not a valid ruleSetName" InvalidParameterValue. - // Re-verify against live SES (not the model, which can't confirm it) if these ever need to change. - private static final Pattern RULE_SET_NAME_CHARS = Pattern.compile("^[a-zA-Z0-9_.-]+$"); - - private static void requireRuleSetName(String name) { - if (name == null || name.isBlank()) { - throw new AwsException("InvalidParameterValue", "RuleSetName is required.", 400); - } - if (!RULE_SET_NAME_CHARS.matcher(name).matches()) { - throw new AwsException("ValidationError", - "1 validation error detected: Value at 'ruleSetName' failed to satisfy constraint: " - + "Member must satisfy regular expression pattern: ^[a-zA-Z0-9_.-]+$", 400); - } - if (name.length() > 64 - || !Character.isLetterOrDigit(name.charAt(0)) - || !Character.isLetterOrDigit(name.charAt(name.length() - 1))) { - throw new AwsException("InvalidParameterValue", "Not a valid ruleSetName: " + name, 400); - } - } - - private static AwsException ruleSetDoesNotExist(String name) { - return new AwsException("RuleSetDoesNotExist", "Rule set does not exist: " + name, 400); - } - - private static String receiptRuleSetKey(String region, String name) { - return "receiptRuleSet::" + region + "::" + name; + return receiptRuleService.describeActiveReceiptRuleSet(region); } // ──────────────────────── Dedicated IP Pools ──────────────────────── - private static final java.util.Set SCALING_MODES = java.util.Set.of("STANDARD", "MANAGED"); + // Storage lives in SesDedicatedIpService; the facade forwards. public DedicatedIpPool createDedicatedIpPool(String poolName, String scalingMode, String region) { - if (poolName == null || poolName.isBlank()) { - throw new AwsException("BadRequestException", "PoolName is required.", 400); - } - String effectiveScaling = (scalingMode == null || scalingMode.isBlank()) ? "STANDARD" : scalingMode; - if (!SCALING_MODES.contains(effectiveScaling)) { - throw new AwsException("BadRequestException", "The ScalingMode parameter is invalid.", 400); - } - String key = dedicatedIpPoolKey(region, poolName); - if (dedicatedIpPoolStore.get(key).isPresent()) { - throw new AwsException("AlreadyExistsException", - "The pool <" + poolName + "> already exists.", 400); - } - DedicatedIpPool pool = new DedicatedIpPool(poolName, effectiveScaling); - dedicatedIpPoolStore.put(key, pool); - LOG.infov("Created SES dedicated IP pool: {0} in region {1}", poolName, region); - return pool; + return dedicatedIpService.createDedicatedIpPool(poolName, scalingMode, region); } public DedicatedIpPool getDedicatedIpPool(String poolName, String region) { - return dedicatedIpPoolStore.get(dedicatedIpPoolKey(region, poolName)) - .orElseThrow(() -> new AwsException("NotFoundException", - "The requested pool <" + poolName + "> does not exist.", 404)); + return dedicatedIpService.getDedicatedIpPool(poolName, region); } public boolean dedicatedIpPoolExists(String poolName, String region) { - return dedicatedIpPoolStore.get(dedicatedIpPoolKey(region, poolName)).isPresent(); + return dedicatedIpService.dedicatedIpPoolExists(poolName, region); } public List listDedicatedIpPools(String region) { - String prefix = "dedicatedIpPool::" + region + "::"; - return dedicatedIpPoolStore.scan(k -> k.startsWith(prefix)).stream() - .map(DedicatedIpPool::getPoolName) - .sorted() - .toList(); + return dedicatedIpService.listDedicatedIpPools(region); } public void deleteDedicatedIpPool(String poolName, String region) { - String key = dedicatedIpPoolKey(region, poolName); - if (dedicatedIpPoolStore.get(key).isEmpty()) { - throw new AwsException("NotFoundException", - "The requested pool <" + poolName + "> does not exist.", 404); - } - dedicatedIpPoolStore.delete(key); - LOG.infov("Deleted SES dedicated IP pool: {0} in region {1}", poolName, region); + dedicatedIpService.deleteDedicatedIpPool(poolName, region); } - private static String dedicatedIpPoolKey(String region, String name) { - return "dedicatedIpPool::" + region + "::" + name; - } - private static final Set SUBSCRIPTION_STATUSES = Set.of("OPT_IN", "OPT_OUT"); - private static final Pattern CONTACT_LIST_NAME_CHARS = Pattern.compile("^[A-Za-z0-9_-]{1,64}$"); - private static final int MAX_TOPICS_PER_LIST = 20; - private static final int MAX_DISPLAY_NAME_LENGTH = 128; - private static final int MAX_LIST_DESCRIPTION_LENGTH = 500; + // Contact lists and contacts live in SesContactService; the facade forwards. + // Its send-path list-management (collectListManagementOptOuts) also calls into that service. public ContactList createContactList(String name, String description, List topics, List tags, String region) { - validateContactListInput(name, description, topics); - ContactList list = new ContactList(name); - list.setDescription(description); - list.setTopics(topics); - list.setTags(tags); - Instant now = Instant.now(); - list.setCreatedTimestamp(now); - list.setLastUpdatedTimestamp(now); - // AWS allows at most one contact list per account per region (verified against real AWS). - // A duplicate name hits this same limit before any "already exists" check, so - // AlreadyExistsException is never reachable for contact lists. Lock only the check-then-put - // so concurrent calls can't both observe an empty region; building and logging stay outside. - synchronized (contactListCreateLock) { - if (!listContactLists(region).isEmpty()) { - throw new AwsException("BadRequestException", - "A maximum of 1 Lists allowed per account.", 400); - } - contactListStore.put(contactListKey(region, name), list); - } - LOG.infov("Created SES contact list: {0} in region {1}", name, region); - return list; + return contactService.createContactList(name, description, topics, tags, region); } public ContactList getContactList(String name, String region) { - return contactListStore.get(contactListKey(region, name)) - .orElseThrow(() -> contactListNotFound(name)); + return contactService.getContactList(name, region); } public List listContactLists(String region) { - String prefix = "contactList::" + region + "::"; - return contactListStore.scan(k -> k.startsWith(prefix)).stream() - .sorted(Comparator.comparing(ContactList::getContactListName)) - .toList(); + return contactService.listContactLists(region); } public ContactList updateContactList(String name, String description, boolean descriptionPresent, List topics, String region) { - validateContactListInput(name, description, topics); - String key = contactListKey(region, name); - ContactList existing = contactListStore.get(key).orElseThrow(() -> contactListNotFound(name)); - if (topics != null) { - existing.setTopics(topics); - } - if (descriptionPresent) { - existing.setDescription(description); - } - existing.setLastUpdatedTimestamp(Instant.now()); - contactListStore.put(key, existing); - LOG.infov("Updated SES contact list: {0} in region {1}", name, region); - return existing; + return contactService.updateContactList(name, description, descriptionPresent, topics, region); } public void deleteContactList(String name, String region) { - String key = contactListKey(region, name); - // Existence check, list delete, and contact purge all under the lock: concurrent deletes - // can't both pass the check (one must 404), and a concurrent create/update can't slip a - // contact in after the purge. Contacts are stored independently, so purging them here keeps - // them from leaking into a same-named list recreated later (AWS deletes them with the list). - String prefix = "contact::" + region + "::" + name + "::"; - synchronized (contactMutationLock) { - if (contactListStore.get(key).isEmpty()) { - throw contactListNotFound(name); - } - contactListStore.delete(key); - // Delete by the actual stored keys (not keys rebuilt from each value's EmailAddress), - // so a persisted entry whose key and EmailAddress diverge is still purged. - List contactKeys = contactStore.keys().stream() - .filter(k -> k.startsWith(prefix)) - .toList(); - for (String contactKey : contactKeys) { - contactStore.delete(contactKey); - } - } - LOG.infov("Deleted SES contact list: {0} in region {1}", name, region); + contactService.deleteContactList(name, region); } - private static AwsException contactListNotFound(String name) { - return new AwsException("NotFoundException", - "List with name: " + name + " doesn't exist.", 404); + public Contact createContact(String listName, String emailAddress, List topicPreferences, + Boolean unsubscribeAll, String attributesData, String region) { + return contactService.createContact(listName, emailAddress, topicPreferences, unsubscribeAll, + attributesData, region); } - // SES V2 surfaces missing/invalid input as Smithy validation errors. Field paths and the - // enum value order are taken verbatim from real AWS. - private static AwsException validationError(String fieldPath, String constraint) { - return new AwsException("BadRequestException", - "1 validation error detected: Value at '" + fieldPath - + "' failed to satisfy constraint: " + constraint, 400); + public SesContactService.ContactWithList getContact(String listName, String emailAddress, String region) { + return contactService.getContact(listName, emailAddress, region); } - private static void validateContactListName(String name) { - if (name == null) { - throw validationError("contactListName", "Member must not be null"); - } - if (name.isBlank()) { - throw new AwsException("BadRequestException", "ContactListName can't be blank.", 400); - } - if (!CONTACT_LIST_NAME_CHARS.matcher(name).matches()) { - throw new AwsException("BadRequestException", - "ContactListName can contain up to 64 characters. Only alphanumeric characters, " - + "underscores(_) and hyphens(-) are allowed.", 400); - } + public SesContactService.ContactsWithList listContacts(String listName, String region) { + return contactService.listContacts(listName, region); } - private static void validateDescription(String description) { - if (description != null && description.length() > MAX_LIST_DESCRIPTION_LENGTH) { - throw new AwsException("BadRequestException", - "List description can contain up to 500 characters.", 400); - } + public Contact updateContact(String listName, String emailAddress, List topicPreferences, + boolean topicPreferencesPresent, Boolean unsubscribeAll, String attributesData, + String region) { + return contactService.updateContact(listName, emailAddress, topicPreferences, topicPreferencesPresent, + unsubscribeAll, attributesData, region); + } + + public void deleteContact(String listName, String emailAddress, String region) { + contactService.deleteContact(listName, emailAddress, region); + } + + public List deriveTopicDefaultPreferences(Contact contact, ContactList list) { + return contactService.deriveTopicDefaultPreferences(contact, list); + } + + public void unsubscribeContact(String listName, String emailAddress, String topicName, String region) { + contactService.unsubscribeContact(listName, emailAddress, topicName, region); } // ──────────────── Identity (sending authorization) policies ──────────────── @@ -2058,112 +1740,43 @@ public class SesService { // against real AWS. Floci stores and returns policies but does not enforce the authorization // (Principal-account existence, Resource-ARN match, or send-time checks) — it has no account // registry and does not gate sending, so these are treated as metadata. - private static final Pattern POLICY_NAME_CHARS = Pattern.compile("[A-Za-z0-9_-]+"); + // Policy storage lives in SesPolicyService; this facade forwards, and for the v2 mutators it runs + // the identity-existence check (an Identity-domain read) first, before delegating. - // v1 PutIdentityPolicy: upsert (create or overwrite); v1 does not require the identity to exist. public void putIdentityPolicy(String identity, String policyName, String policy, String region) { - validatePolicyName(policyName); - String normalized = normalizePolicy(policy); - String key = policyKey(region, identity, policyName); - synchronized (policyMutationLock) { - if (policyStore.get(key).isEmpty()) { - enforcePolicyLimit(region, identity, false); - } - policyStore.put(key, normalized); - } - LOG.infov("SES PutIdentityPolicy: {0} on {1} (region {2})", policyName, identity, region); + policyService.putIdentityPolicy(identity, policyName, policy, region); } - // v2 CreateEmailIdentityPolicy: fails if the name already exists; requires the identity. public void createEmailIdentityPolicy(String identity, String policyName, String policy, String region) { requireIdentityExists(identity, region); - validatePolicyName(policyName); - String normalized = normalizePolicy(policy); - String key = policyKey(region, identity, policyName); - synchronized (policyMutationLock) { - if (policyStore.get(key).isPresent()) { - throw new AwsException("AlreadyExistsException", - "Policy <" + policyName + "> already exists", 400); - } - enforcePolicyLimit(region, identity, true); - policyStore.put(key, normalized); - } - LOG.infov("SES v2 CreateEmailIdentityPolicy: {0} on {1} (region {2})", policyName, identity, region); + policyService.createEmailIdentityPolicy(identity, policyName, policy, region); } - // v2 UpdateEmailIdentityPolicy: fails if the name is missing; requires the identity. public void updateEmailIdentityPolicy(String identity, String policyName, String policy, String region) { requireIdentityExists(identity, region); - validatePolicyName(policyName); - String normalized = normalizePolicy(policy); - String key = policyKey(region, identity, policyName); - synchronized (policyMutationLock) { - if (policyStore.get(key).isEmpty()) { - throw policyNotFound(policyName); - } - policyStore.put(key, normalized); - } - LOG.infov("SES v2 UpdateEmailIdentityPolicy: {0} on {1} (region {2})", policyName, identity, region); + policyService.updateEmailIdentityPolicy(identity, policyName, policy, region); } - // v2 GetEmailIdentityPolicies: all policies for the identity; requires the identity. public Map getEmailIdentityPolicies(String identity, String region) { requireIdentityExists(identity, region); - return listPolicies(region, identity); + return policyService.listAllPolicies(identity, region); } - // v1 GetIdentityPolicies: requested names only, missing silently omitted; no identity check. public Map getIdentityPolicies(String identity, List policyNames, String region) { - Map out = new LinkedHashMap<>(); - for (String name : policyNames) { - policyStore.get(policyKey(region, identity, name)).ifPresent(doc -> out.put(name, doc)); - } - return out; + return policyService.getIdentityPolicies(identity, policyNames, region); } - // v1 ListIdentityPolicies: policy names (sorted); no identity check. public List listIdentityPolicyNames(String identity, String region) { - return listPolicies(region, identity).keySet().stream().sorted().toList(); + return policyService.listIdentityPolicyNames(identity, region); } - // v2 DeleteEmailIdentityPolicy: requires the identity; NotFound if the policy is missing. public void deleteEmailIdentityPolicy(String identity, String policyName, String region) { requireIdentityExists(identity, region); - String key = policyKey(region, identity, policyName); - synchronized (policyMutationLock) { - if (policyStore.get(key).isEmpty()) { - throw policyNotFound(policyName); - } - policyStore.delete(key); - } - LOG.infov("SES v2 DeleteEmailIdentityPolicy: {0} on {1} (region {2})", policyName, identity, region); + policyService.deleteEmailIdentityPolicy(identity, policyName, region); } - // v1 DeleteIdentityPolicy: idempotent; no identity check, no error on a missing policy. public void deleteIdentityPolicy(String identity, String policyName, String region) { - policyStore.delete(policyKey(region, identity, policyName)); - LOG.infov("SES DeleteIdentityPolicy: {0} on {1} (region {2})", policyName, identity, region); - } - - private Map listPolicies(String region, String identity) { - String prefix = policyPrefix(region, identity); - Map out = new LinkedHashMap<>(); - for (String key : policyStore.keys()) { - if (key.startsWith(prefix)) { - policyStore.get(key).ifPresent(doc -> out.put(key.substring(prefix.length()), doc)); - } - } - return out; - } - - private void enforcePolicyLimit(String region, String identity, boolean v2) { - long count = policyStore.keys().stream() - .filter(k -> k.startsWith(policyPrefix(region, identity))).count(); - if (count >= MAX_POLICIES_PER_IDENTITY) { - String msg = "Number of policies for <" + identity - + "> exceeds max allowed number of policies per resource"; - throw new AwsException(v2 ? "LimitExceededException" : "InvalidParameterValue", msg, 400); - } + policyService.deleteIdentityPolicy(identity, policyName, region); } private void requireIdentityExists(String identity, String region) { @@ -2173,313 +1786,7 @@ public class SesService { } } - // Error codes are the v1 (Query) codes verified against AWS; the v2 controller remaps them to - // BadRequestException. The messages are identical across v1 and v2. - private static void validatePolicyName(String policyName) { - if (policyName == null || policyName.isBlank()) { - throw new AwsException("InvalidParameterValue", "PolicyName is required.", 400); - } - if (policyName.length() > 64) { - throw new AwsException("ValidationError", - "1 validation error detected: Value at 'policyName' failed to satisfy constraint: " - + "Member must have length less than or equal to 64", 400); - } - if (!POLICY_NAME_CHARS.matcher(policyName).matches()) { - throw new AwsException("InvalidParameterValue", - "PolicyName is invalid. Policy names must only include alpha-numeric characters, " - + "dashes, and underscores.", 400); - } - } - private String normalizePolicy(String policy) { - if (policy == null || policy.isBlank()) { - throw new AwsException("InvalidParameterValue", "Policy is required.", 400); - } - try { - // AWS returns the policy with insignificant whitespace stripped; compact it to match. - return objectMapper.readTree(policy).toString(); - } catch (com.fasterxml.jackson.core.JsonProcessingException e) { - // Floci does not validate policy semantics; keep an unparseable document verbatim. - LOG.debugv("Identity policy is not valid JSON, storing as-is: {0}", e.getMessage()); - return policy; - } - } - - private static AwsException policyNotFound(String policyName) { - return new AwsException("NotFoundException", "Policy <" + policyName + "> does not exist", 404); - } - - private static String policyKey(String region, String identity, String policyName) { - return policyPrefix(region, identity) + policyName; - } - - private static String policyPrefix(String region, String identity) { - return "policy::" + region + "::" + identity + "::"; - } - - // Validates Create/Update input in the same two-phase order as real AWS (verified by probe): - // protocol-layer (Smithy) checks across all fields first, then service-level constraints with - // ContactListName ahead of topic/description constraints. - private static void validateContactListInput(String name, String description, List topics) { - // Phase 1 — protocol-layer (Smithy) validation: null members and the subscription-status - // enum. AWS reports these before any service-level constraint. - if (name == null) { - throw validationError("contactListName", "Member must not be null"); - } - if (topics != null) { - for (int i = 0; i < topics.size(); i++) { - Topic t = topics.get(i); - String member = "topics." + (i + 1) + ".member."; - if (t.getTopicName() == null) { - throw validationError(member + "topicName", "Member must not be null"); - } - if (t.getDisplayName() == null) { - throw validationError(member + "displayName", "Member must not be null"); - } - if (t.getDefaultSubscriptionStatus() == null) { - throw validationError(member + "defaultSubscriptionStatus", "Member must not be null"); - } - if (!SUBSCRIPTION_STATUSES.contains(t.getDefaultSubscriptionStatus())) { - throw validationError(member + "defaultSubscriptionStatus", - "Member must satisfy enum value set: [OPT_OUT, OPT_IN]"); - } - } - } - // Phase 2 — service-level constraints: ContactListName first, then topics, then description. - if (name.isBlank()) { - throw new AwsException("BadRequestException", "ContactListName can't be blank.", 400); - } - if (!CONTACT_LIST_NAME_CHARS.matcher(name).matches()) { - throw new AwsException("BadRequestException", - "ContactListName can contain up to 64 characters. Only alphanumeric characters, " - + "underscores(_) and hyphens(-) are allowed.", 400); - } - if (topics != null) { - if (topics.size() > MAX_TOPICS_PER_LIST) { - throw new AwsException("BadRequestException", - "Maximum of <" + MAX_TOPICS_PER_LIST + "> topics allowed per ContactList", 400); - } - Set seenNames = new HashSet<>(); - for (Topic t : topics) { - if (t.getTopicName().isBlank()) { - throw new AwsException("BadRequestException", "TopicName can't be blank.", 400); - } - if (!CONTACT_LIST_NAME_CHARS.matcher(t.getTopicName()).matches()) { - throw new AwsException("BadRequestException", - "TopicName can contain up to 64 characters. Only alphanumeric characters, " - + "underscores(_) and hyphens(-) are allowed.", 400); - } - if (t.getDisplayName().length() > MAX_DISPLAY_NAME_LENGTH) { - throw new AwsException("BadRequestException", - "Topic DisplayName can contain up to <" + MAX_DISPLAY_NAME_LENGTH - + "> characters.", 400); - } - if (!seenNames.add(t.getTopicName())) { - throw new AwsException("BadRequestException", - "Duplicate topic names are not allowed within a List.", 400); - } - } - } - validateDescription(description); - } - - private static String contactListKey(String region, String name) { - // Validate in the key builder so Get/Update/Delete reject an invalid ContactListName with - // the AWS validation error (400) rather than a 404, matching configSetKey. Verified - // against real AWS: read/delete with an invalid name returns the same constraint message. - validateContactListName(name); - return "contactList::" + region + "::" + name; - } - - // ─────────────────────────── Contacts ─────────────────────────── - - private static final Pattern EMAIL_PATTERN = Pattern.compile("^[^@\\s]+@[^@\\s]+\\.[^@\\s]+$"); - - public Contact createContact(String listName, String emailAddress, List topicPreferences, - Boolean unsubscribeAll, String attributesData, String region) { - validateContactInput(listName, emailAddress, topicPreferences, region); - Contact contact = new Contact(emailAddress); - contact.setTopicPreferences(topicPreferences); - contact.setUnsubscribeAll(unsubscribeAll != null && unsubscribeAll); - contact.setAttributesData(attributesData); - Instant now = Instant.now(clock); - contact.setCreatedTimestamp(now); - contact.setLastUpdatedTimestamp(now); - String key = contactKey(region, listName, emailAddress); - // Re-check the list, duplicate, and put under the lock so a concurrent deleteContactList - // can't purge the list between validation and the write (which would orphan this contact). - synchronized (contactMutationLock) { - getContactList(listName, region); - if (contactStore.get(key).isPresent()) { - throw new AwsException("AlreadyExistsException", - emailAddress + " already exists in List.", 400); - } - contactStore.put(key, contact); - } - LOG.infov("Created SES contact {0} in list {1} (region {2})", emailAddress, listName, region); - return contact; - } - - // Read operations return the resolved ContactList alongside the contact(s) so the controller - // can render TopicDefaultPreferences without a second getContactList round-trip (which would - // open a TOCTOU window where a concurrent delete turns a successful read into "List not found"). - public record ContactWithList(Contact contact, ContactList list) { - } - - public record ContactsWithList(List contacts, ContactList list) { - } - - public ContactWithList getContact(String listName, String emailAddress, String region) { - validateEmailAddress(emailAddress); - ContactList list = getContactList(listName, region); - Contact contact = contactStore.get(contactKey(region, listName, emailAddress)) - .orElseThrow(() -> contactNotFound(emailAddress)); - return new ContactWithList(contact, list); - } - - public ContactsWithList listContacts(String listName, String region) { - ContactList list = getContactList(listName, region); - String prefix = "contact::" + region + "::" + listName + "::"; - List contacts = contactStore.scan(k -> k.startsWith(prefix)).stream() - .sorted(Comparator.comparing(Contact::getEmailAddress, - Comparator.nullsFirst(Comparator.naturalOrder()))) - .toList(); - return new ContactsWithList(contacts, list); - } - - public Contact updateContact(String listName, String emailAddress, List topicPreferences, - boolean topicPreferencesPresent, Boolean unsubscribeAll, String attributesData, - String region) { - validateContactInput(listName, emailAddress, topicPreferences, region); - String key = contactKey(region, listName, emailAddress); - Contact existing; - // Re-check the list and read-modify-write under the lock so a concurrent deleteContactList - // can't purge the contact/list between validation and the write (which would resurrect it). - synchronized (contactMutationLock) { - getContactList(listName, region); - existing = contactStore.get(key).orElseThrow(() -> contactNotFound(emailAddress)); - // Verified against real AWS: TopicPreferences merge by topic name (omitting keeps existing); - // AttributesData and UnsubscribeAll are replaced (omitting clears / resets them). - if (topicPreferencesPresent) { - existing.setTopicPreferences(mergeTopicPreferences(existing.getTopicPreferences(), topicPreferences)); - } - existing.setUnsubscribeAll(unsubscribeAll != null && unsubscribeAll); - existing.setAttributesData(attributesData); - existing.setLastUpdatedTimestamp(Instant.now(clock)); - contactStore.put(key, existing); - } - LOG.infov("Updated SES contact {0} in list {1}", emailAddress, listName); - return existing; - } - - public void deleteContact(String listName, String emailAddress, String region) { - validateEmailAddress(emailAddress); - String key = contactKey(region, listName, emailAddress); - // List re-check + existence check + delete under the lock (matching create/update): a - // concurrent deleteContactList then surfaces "list not found" rather than "contact not - // found", and an updateContact can't put a just-deleted contact back (resurrecting it). - synchronized (contactMutationLock) { - getContactList(listName, region); - if (contactStore.get(key).isEmpty()) { - throw contactNotFound(emailAddress); - } - contactStore.delete(key); - } - LOG.infov("Deleted SES contact {0} in list {1}", emailAddress, listName); - } - - /** - * Derives {@code TopicDefaultPreferences}: each list topic the contact has not set an explicit - * preference for, carrying that topic's default subscription status. - */ - public List deriveTopicDefaultPreferences(Contact contact, ContactList list) { - Set explicit = new HashSet<>(); - for (TopicPreference p : contact.getTopicPreferences()) { - explicit.add(p.getTopicName()); - } - List defaults = new ArrayList<>(); - for (Topic t : list.getTopics()) { - if (!explicit.contains(t.getTopicName())) { - defaults.add(new TopicPreference(t.getTopicName(), t.getDefaultSubscriptionStatus())); - } - } - return defaults; - } - - private static AwsException contactNotFound(String emailAddress) { - return new AwsException("NotFoundException", emailAddress + " doesn't exist in List.", 404); - } - - // Validation order verified against real AWS: protocol-layer (Smithy) topic-preference checks - // first, then EmailAddress format, then contact-list existence, then topic existence. - private void validateContactInput(String listName, String emailAddress, List prefs, - String region) { - if (prefs != null) { - for (int i = 0; i < prefs.size(); i++) { - TopicPreference p = prefs.get(i); - String member = "topicPreferences." + (i + 1) + ".member."; - if (p.getTopicName() == null) { - throw validationError(member + "topicName", "Member must not be null"); - } - if (p.getSubscriptionStatus() == null) { - throw validationError(member + "subscriptionStatus", "Member must not be null"); - } - if (!SUBSCRIPTION_STATUSES.contains(p.getSubscriptionStatus())) { - throw validationError(member + "subscriptionStatus", - "Member must satisfy enum value set: [OPT_OUT, OPT_IN]"); - } - } - } - validateEmailAddress(emailAddress); - ContactList list = getContactList(listName, region); - if (prefs != null && !prefs.isEmpty()) { - Set topicNames = new HashSet<>(); - for (Topic t : list.getTopics()) { - topicNames.add(t.getTopicName()); - } - for (TopicPreference p : prefs) { - if (!topicNames.contains(p.getTopicName())) { - throw new AwsException("BadRequestException", - "List: " + listName + " doesn't contain Topic: " + p.getTopicName(), 400); - } - } - } - } - - private static List mergeTopicPreferences(List existing, - List provided) { - Map byTopic = new LinkedHashMap<>(); - if (existing != null) { - for (TopicPreference p : existing) { - byTopic.put(p.getTopicName(), p); - } - } - if (provided != null) { - for (TopicPreference p : provided) { - byTopic.put(p.getTopicName(), p); - } - } - return new ArrayList<>(byTopic.values()); - } - - private static void validateEmailAddress(String emailAddress) { - // Verified against real AWS: a missing/null required member is a Smithy validation error, - // an empty/blank value is "can't be blank", and only a non-blank malformed value is "invalid". - if (emailAddress == null) { - throw validationError("emailAddress", "Member must not be null"); - } - if (emailAddress.isBlank()) { - throw new AwsException("BadRequestException", "EmailAddress can't be blank.", 400); - } - if (!EMAIL_PATTERN.matcher(emailAddress).matches()) { - throw new AwsException("BadRequestException", - "EmailAddress <" + emailAddress + "> is invalid", 400); - } - } - - private static String contactKey(String region, String listName, String emailAddress) { - return "contact::" + region + "::" + listName + "::" + emailAddress; - } static void validateConfigurationSetName(String name) { if (name == null || name.isBlank()) { @@ -2740,7 +2047,7 @@ public class SesService { + "Member must have length greater than or equal to 1", 400); } for (Tag t : newTags) { - validateTag(t); + SesTags.validate(t); } switch (ref.type()) { case "configuration-set" -> tagConfigurationSet(ref.name(), ref.region(), newTags); @@ -2810,19 +2117,18 @@ public class SesService { } private List listEmailTemplateTags(String name, String region) { - EmailTemplate template = templateStore.get(templateKey(region, name)) + EmailTemplate template = templateService.find(name, region) .orElseThrow(() -> new AwsException("NotFoundException", "No Template present with name: " + name, 404)); return new ArrayList<>(template.getTags()); } private void tagEmailTemplate(String name, String region, List newTags) { - String key = templateKey(region, name); - EmailTemplate template = templateStore.get(key) + EmailTemplate template = templateService.find(name, region) .orElseThrow(() -> new AwsException("NotFoundException", "No Template present with name: " + name, 404)); template.setTags(mergeTags(template.getTags(), newTags)); - templateStore.put(key, template); + templateService.save(template, region); LOG.infov("Tagged SES template: {0} (region {1}, +{2} tags)", name, region, newTags.size()); } @@ -2871,7 +2177,7 @@ public class SesService { public void setIdentityTags(String identityValue, String region, List tags) { if (tags != null) { for (Tag tag : tags) { - validateTag(tag); + SesTags.validate(tag); } } String key = identityKey(region, identityValue); @@ -2883,13 +2189,12 @@ public class SesService { } private void untagEmailTemplate(String name, String region, List tagKeys) { - String key = templateKey(region, name); - EmailTemplate template = templateStore.get(key) + EmailTemplate template = templateService.find(name, region) .orElseThrow(() -> new AwsException("NotFoundException", "No Template present with name: " + name, 404)); Set toRemove = new HashSet<>(tagKeys); template.getTags().removeIf(t -> toRemove.contains(t.key())); - templateStore.put(key, template); + templateService.save(template, region); LOG.infov("Untagged SES template: {0} (region {1}, -{2} keys)", name, region, tagKeys.size()); } @@ -2921,132 +2226,32 @@ public class SesService { return new ResourceRef(parsed.region(), resource.substring(0, slash), resource.substring(slash + 1)); } - // ──────────────────── Account-level suppression attributes ──────────────────── + // ──────────────────── Suppression (account attributes + list) ──────────────────── + // Storage lives in SesSuppressionService; the facade forwards, and its send + // filters (collectSuppressedReasons / resolveSuppressionReason) read entries back through it. public AccountSuppressionAttributes getAccountSuppressionAttributes(String region) { - return accountSuppressionStore.get(accountSuppressionKey(region)) - .orElseGet(SesService::defaultAccountSuppressionAttributes); - } - - private static AccountSuppressionAttributes defaultAccountSuppressionAttributes() { - // Fresh SES accounts default to auto-suppression on both BOUNCE and COMPLAINT; - // an explicit PUT (including an empty list) overrides this. - AccountSuppressionAttributes attrs = new AccountSuppressionAttributes(); - attrs.setSuppressedReasons(new ArrayList<>(List.of("BOUNCE", "COMPLAINT"))); - return attrs; + return suppressionService.getAccountSuppressionAttributes(region); } public void putAccountSuppressionAttributes(String region, List suppressedReasons) { - List sanitized = new ArrayList<>(); - if (suppressedReasons != null) { - for (String r : suppressedReasons) { - validateSuppressionReason(r, "suppressedReasons", true); - sanitized.add(r); - } - } - AccountSuppressionAttributes attrs = new AccountSuppressionAttributes(); - attrs.setSuppressedReasons(sanitized); - accountSuppressionStore.put(accountSuppressionKey(region), attrs); - LOG.infov("Updated account suppression attributes for region {0}: {1}", region, sanitized); + suppressionService.putAccountSuppressionAttributes(region, suppressedReasons); } - private static String accountSuppressionKey(String region) { - return "account-suppression::" + region; - } - - // ──────────────────────────── Suppression list ──────────────────────────── - public void putSuppressedDestination(String region, String emailAddress, String reason) { - String normalized = normalizeSuppressionEmail(emailAddress); - validateSuppressionReason(reason, "reason", false); - String key = suppressionKey(region, normalized); - 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); + suppressionService.putSuppressedDestination(region, emailAddress, reason); } public SuppressedDestination getSuppressedDestination(String region, String emailAddress) { - String normalized = normalizeSuppressionEmail(emailAddress); - return existingSuppressionMatch(region, emailAddress, normalized) - .map(SuppressionMatch::entry) - .orElseThrow(() -> new AwsException("NotFoundException", - "Email address " + normalized + " does not exist on your suppression list.", - 404)); + return suppressionService.getSuppressedDestination(region, emailAddress); } public void deleteSuppressedDestination(String region, String emailAddress) { - String normalized = normalizeSuppressionEmail(emailAddress); - 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(); + suppressionService.deleteSuppressedDestination(region, emailAddress); } public List listSuppressedDestinations(String region, List reasonFilters) { - Set filters = new HashSet<>(); - if (reasonFilters != null) { - for (String r : reasonFilters) { - if (r != null && !r.isBlank()) { - validateSuppressionReason(r, "reasons", true); - filters.add(r); - } - } - } - String prefix = "suppression::" + region + "::"; - List all = new ArrayList<>(suppressionStore.scan(k -> k.startsWith(prefix))); - all.sort(Comparator.comparing(SuppressedDestination::getLastUpdateTime, - Comparator.nullsLast(Comparator.naturalOrder())) - .thenComparing(SuppressedDestination::getEmailAddress, - Comparator.nullsLast(Comparator.naturalOrder()))); - if (filters.isEmpty()) { - return all; - } - return all.stream() - .filter(s -> filters.contains(s.getReason())) - .toList(); - } - - private static String suppressionKey(String region, String emailAddress) { - return "suppression::" + region + "::" + emailAddress; + return suppressionService.listSuppressedDestinations(region, reasonFilters); } /** @@ -3074,9 +2279,7 @@ public class SesService { if (address == null || address.isBlank() || result.containsKey(address)) { continue; } - String normalized = normalizeSuppressionEmail(address); - SuppressedDestination entry = existingSuppressionMatch(region, address, normalized) - .map(SuppressionMatch::entry) + SuppressedDestination entry = suppressionService.findSuppressedDestination(region, address) .orElse(null); if (entry != null && entry.getReason() != null && reasonFilter.contains(entry.getReason())) { @@ -3102,13 +2305,13 @@ public class SesService { || listManagement.contactListName().isBlank() || addresses == null || addresses.isEmpty()) { return Map.of(); } - ContactList list = getContactList(listManagement.contactListName(), region); + ContactList list = contactService.getContactList(listManagement.contactListName(), region); String topicName = listManagement.topicName(); String effectiveTopic = (topicName == null || topicName.isBlank()) ? null : topicName; // Fail fast on a topic that isn't defined on the list rather than silently skipping // suppression (a typo would otherwise send to everyone). AWS does not document this, so the // exact error is best-effort. - if (effectiveTopic != null && defaultTopicStatus(list, effectiveTopic) == null) { + if (effectiveTopic != null && contactService.defaultTopicStatus(list, effectiveTopic) == null) { throw new AwsException("BadRequestException", "Topic " + effectiveTopic + " does not exist in contact list " + list.getContactListName() + ".", 400); @@ -3122,93 +2325,14 @@ public class SesService { if (email == null || email.isBlank()) { continue; } - Contact contact = getOrAutoCreateContact(list, email, region); - if (isListManagementOptedOut(contact, list, effectiveTopic)) { + Contact contact = contactService.getOrAutoCreateContact(list, email, region); + if (contactService.isListManagementOptedOut(contact, list, effectiveTopic)) { optOuts.put(address, "BOUNCE"); } } return optOuts; } - /** - * Returns the contact for {@code email} in {@code list}, creating it automatically when absent — - * AWS creates a contact on the list when {@code ListManagementOptions} names a recipient that is - * not yet a contact. The auto-created contact has no explicit topic preferences (its effective - * per-topic status derives from the list topic defaults) and is not unsubscribed. Creation runs - * under {@code contactMutationLock} so a concurrent contact-list deletion can't orphan it. - */ - private Contact getOrAutoCreateContact(ContactList list, String email, String region) { - String key = contactKey(region, list.getContactListName(), email); - Contact existing = contactStore.get(key).orElse(null); - if (existing != null) { - return existing; - } - synchronized (contactMutationLock) { - Contact raced = contactStore.get(key).orElse(null); - if (raced != null) { - return raced; - } - // Re-check the list under the lock so a concurrent deleteContactList (which purges the - // list and its contacts under the same lock) can't be followed by this creating an - // orphaned contact for a list that no longer exists. - getContactList(list.getContactListName(), region); - Contact contact = new Contact(email); - Instant now = Instant.now(clock); - contact.setCreatedTimestamp(now); - contact.setLastUpdatedTimestamp(now); - contactStore.put(key, contact); - LOG.infov("Auto-created SES contact {0} in list {1} on send (region {2})", - email, list.getContactListName(), region); - return contact; - } - } - - /** - * Whether a contact is opted out for a list-managed send. A contact with {@code UnsubscribeAll} - * is opted out of everything. When no topic is given, only {@code UnsubscribeAll} suppresses - * (AWS documents suppression of whole-list unsubscribers). When a topic is given, an explicit - * {@code OPT_OUT} preference for that topic suppresses; absent an explicit preference, the topic's - * {@code DefaultSubscriptionStatus} is used — the default-status fallback at send time is not - * documented by AWS but mirrors the effective-status model AWS uses for {@code ListContacts}. - */ - private static boolean isListManagementOptedOut(Contact contact, ContactList list, String topicName) { - if (contact.isUnsubscribeAll()) { - return true; - } - if (topicName == null) { - return false; - } - String explicit = explicitTopicStatus(contact, topicName); - if (explicit != null) { - return "OPT_OUT".equals(explicit); - } - return "OPT_OUT".equals(defaultTopicStatus(list, topicName)); - } - - private static String explicitTopicStatus(Contact contact, String topicName) { - if (contact.getTopicPreferences() == null) { - return null; - } - for (TopicPreference pref : contact.getTopicPreferences()) { - if (topicName.equals(pref.getTopicName())) { - return pref.getSubscriptionStatus(); - } - } - return null; - } - - private static String defaultTopicStatus(ContactList list, String topicName) { - if (list.getTopics() == null) { - return null; - } - for (Topic topic : list.getTopics()) { - if (topicName.equals(topic.getTopicName())) { - return topic.getDefaultSubscriptionStatus(); - } - } - return null; - } - private static final String UNSUBSCRIBE_PLACEHOLDER = "{{amazonSESUnsubscribeUrl}}"; private static boolean hasListManagement(ListManagementOptions listManagement) { @@ -3275,57 +2399,6 @@ public class SesService { return out; } - /** - * Applies a list-management unsubscribe (the action behind the {@code /_aws/ses/unsubscribe} - * link): with a topic, sets that topic's preference to {@code OPT_OUT}; without a topic, - * unsubscribes the contact from the whole list ({@code UnsubscribeAll}). The contact is created - * if it does not exist yet, consistent with send-time auto-creation. Runs under - * {@code contactMutationLock} so a concurrent contact-list deletion can't orphan it. - */ - public void unsubscribeContact(String listName, String emailAddress, String topicName, String region) { - validateEmailAddress(emailAddress); - String effectiveTopic = (topicName == null || topicName.isBlank()) ? null : topicName; - String key = contactKey(region, listName, emailAddress); - synchronized (contactMutationLock) { - ContactList list = getContactList(listName, region); - if (effectiveTopic != null && defaultTopicStatus(list, effectiveTopic) == null) { - throw new AwsException("BadRequestException", - "Topic " + effectiveTopic + " does not exist in contact list " + listName + ".", 400); - } - Contact contact = contactStore.get(key).orElseGet(() -> { - Contact created = new Contact(emailAddress); - created.setCreatedTimestamp(Instant.now(clock)); - return created; - }); - if (effectiveTopic == null) { - contact.setUnsubscribeAll(true); - } else { - setTopicPreference(contact, effectiveTopic, "OPT_OUT"); - } - contact.setLastUpdatedTimestamp(Instant.now(clock)); - contactStore.put(key, contact); - } - LOG.infov("List-management unsubscribe: {0} from list {1} topic {2} (region {3})", - emailAddress, listName, effectiveTopic == null ? "" : effectiveTopic, region); - } - - private static void setTopicPreference(Contact contact, String topicName, String status) { - // Copy into a fresh mutable list and set it back, so this works even if the contact's - // preferences were stored as an unmodifiable list (setTopicPreferences keeps the list as-is). - List prefs = new ArrayList<>(contact.getTopicPreferences()); - boolean found = false; - for (TopicPreference pref : prefs) { - if (topicName.equals(pref.getTopicName())) { - pref.setSubscriptionStatus(status); - found = true; - break; - } - } - if (!found) { - prefs.add(new TopicPreference(topicName, status)); - } - contact.setTopicPreferences(prefs); - } /** * Filter out recipients whose effective suppression reason is non-null. Returns a new @@ -3362,7 +2435,7 @@ public class SesService { * callers (publishSendEvents) to map the recipient to a synthetic Bounce / Complaint * event without consulting the store again. Both the per-address suppression entries * and the account-level / per-CS {@code suppressedReasons} go through - * {@link #validateSuppressionReason} / {@link #validateConfigSetSuppressionReason}, + * {@link SesSuppressionService}'s reason validation / {@link #validateConfigSetSuppressionReason}, * which enforce exact case-sensitive equality with the two canonical values, so * {@code entry.getReason()} is guaranteed to be canonical and downstream * {@code .equals("BOUNCE")} / {@code .equals("COMPLAINT")} checks are safe. @@ -3371,12 +2444,9 @@ public class SesService { if (emailAddress == null || emailAddress.isBlank()) { return null; } - // Share the same normalization used when entries are stored - // (`normalizeSuppressionEmail`) so lookups can't drift apart from inserts, - // with the same legacy-key fallback as GET/DELETE. - String normalized = normalizeSuppressionEmail(emailAddress); - SuppressedDestination entry = existingSuppressionMatch(region, emailAddress, normalized) - .map(SuppressionMatch::entry) + // Read through the suppression service so this shares its normalization and legacy-key + // fallback with GET/DELETE (lookups can't drift apart from inserts). + SuppressedDestination entry = suppressionService.findSuppressedDestination(region, emailAddress) .orElse(null); if (entry == null || entry.getReason() == null) { return null; @@ -3388,46 +2458,6 @@ public class SesService { return effective.contains(entry.getReason()) ? entry.getReason() : null; } - private static String normalizeSuppressionEmail(String emailAddress) { - if (emailAddress == null || emailAddress.isBlank()) { - throw new AwsException("BadRequestException", "EmailAddress is required.", 400); - } - // 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); - } - - /** - * Validation message used by PutAccountSuppressionAttributes, - * PutSuppressedDestination, and ListSuppressedDestinations — all three - * return the AWS "1 validation error detected: Value at '' - * failed to satisfy constraint: ..." V1-style nested message verbatim. - * (Verified against real AWS V2 SES on 2026-06-03.) The {@code nested} - * flag controls whether the inner enum constraint is wrapped in - * {@code Member must satisfy constraint: [...]} — PutSuppressedDestination - * (single Reason field) returns the unwrapped form; the two list-bearing - * APIs return the wrapped form. - */ - private static void validateSuppressionReason(String reason, String fieldName, boolean nested) { - if (reason == null || (!"BOUNCE".equals(reason) && !"COMPLAINT".equals(reason))) { - String constraint = nested - ? "Member must satisfy constraint: [Member must satisfy enum value set: [BOUNCE, COMPLAINT]]" - : "Member must satisfy enum value set: [BOUNCE, COMPLAINT]"; - throw new AwsException("BadRequestException", - "1 validation error detected: Value at '" + fieldName + "' failed to satisfy constraint: " - + constraint, 400); - } - } /** * Validation message used by PutConfigurationSetSuppressionOptions. AWS @@ -3454,25 +2484,6 @@ public class SesService { return "Reason " + reason + " is invalid, must be one of [BOUNCE, COMPLAINT]."; } - static void validateTag(Tag tag) { - if (tag == null) { - throw new AwsException("InvalidParameterValue", "Tag must not be null.", 400); - } - String key = tag.key(); - if (key == null || key.isEmpty()) { - throw new AwsException("InvalidParameterValue", "Tag Key is required.", 400); - } - if (key.length() > 128) { - throw new AwsException("InvalidParameterValue", - "Tag Key must be 1-128 characters.", 400); - } - String value = tag.value(); - if (value != null && value.length() > 256) { - throw new AwsException("InvalidParameterValue", - "Tag Value must be 0-256 characters.", 400); - } - } - public String sendTemplatedEmail(String source, List toAddresses, List ccAddresses, List bccAddresses, List replyToAddresses, String templateName, JsonNode templateData, @@ -3800,36 +2811,6 @@ public class SesService { return out.toString(); } - private static void validateTemplate(EmailTemplate template) { - if (template == null) { - throw new AwsException("InvalidTemplate", "Template is required.", 400); - } - validateTemplateName(template.getTemplateName()); - boolean hasSubject = template.getSubject() != null && !template.getSubject().isBlank(); - boolean hasText = template.getTextPart() != null && !template.getTextPart().isBlank(); - boolean hasHtml = template.getHtmlPart() != null && !template.getHtmlPart().isBlank(); - if (!hasSubject && !hasText && !hasHtml) { - throw new AwsException("InvalidTemplate", - "Template must have at least a subject, text, or html part.", 400); - } - } - - private static void validateTemplateName(String templateName) { - if (templateName == null || templateName.isBlank()) { - throw new AwsException("InvalidTemplate", "TemplateName is required.", 400); - } - if (Character.isWhitespace(templateName.charAt(0)) - || Character.isWhitespace(templateName.charAt(templateName.length() - 1))) { - throw new AwsException("InvalidTemplate", - "TemplateName must not contain leading or trailing whitespace.", 400); - } - } - - private static String templateKey(String region, String templateName) { - validateTemplateName(templateName); - return "template::" + region + "::" + templateName; - } - /** * Extracts the template name from an SES template ARN of the form * {@code arn:aws:ses:::template/}. Region and diff --git a/src/main/java/io/github/hectorvent/floci/services/ses/SesSuppressionService.java b/src/main/java/io/github/hectorvent/floci/services/ses/SesSuppressionService.java new file mode 100644 index 0000000000..143a32ca4e --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/ses/SesSuppressionService.java @@ -0,0 +1,236 @@ +package io.github.hectorvent.floci.services.ses; + +import com.fasterxml.jackson.core.type.TypeReference; +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.ses.model.AccountSuppressionAttributes; +import io.github.hectorvent.floci.services.ses.model.SuppressedDestination; +import jakarta.enterprise.context.ApplicationScoped; +import jakarta.inject.Inject; +import org.jboss.logging.Logger; + +import java.time.Instant; +import java.util.ArrayList; +import java.util.Comparator; +import java.util.HashSet; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.Optional; +import java.util.Set; + +/** + * Suppression: the account-level suppression attributes and the per-address suppression list, + * extracted from {@link SesService} as the sixth step of the store-based domain split. + * + *

New facet: this resolves the shared-helper deferral called out in the account step. The + * account-suppression and suppression-list sub-domains share {@code validateSuppressionReason}, so + * rather than splitting one off, both stores move together into this service and the helper becomes + * a private detail of it. The send path keeps its cross-domain orchestration + * ({@code getEffectiveSuppressedReasons} reads a configuration set's options or falls back here; + * {@code collectSuppressedReasons}/{@code resolveSuppressionReason} filter a send) in the + * {@link SesService} facade, which reads entries back through {@link #findSuppressedDestination}. + */ +@ApplicationScoped +public class SesSuppressionService { + + private static final Logger LOG = Logger.getLogger(SesSuppressionService.class); + + private final StorageBackend suppressionStore; + private final StorageBackend accountSuppressionStore; + + @Inject + public SesSuppressionService(StorageFactory storageFactory) { + this.suppressionStore = storageFactory.create("ses", "ses-suppression.json", + new TypeReference>() {}); + this.accountSuppressionStore = storageFactory.create("ses", "ses-account-suppression.json", + new TypeReference>() {}); + } + + SesSuppressionService(StorageBackend suppressionStore, + StorageBackend accountSuppressionStore) { + this.suppressionStore = suppressionStore; + this.accountSuppressionStore = accountSuppressionStore; + } + + // ──────────────────── Account-level suppression attributes ──────────────────── + + public AccountSuppressionAttributes getAccountSuppressionAttributes(String region) { + return accountSuppressionStore.get(accountSuppressionKey(region)) + .orElseGet(SesSuppressionService::defaultAccountSuppressionAttributes); + } + + private static AccountSuppressionAttributes defaultAccountSuppressionAttributes() { + // Fresh SES accounts default to auto-suppression on both BOUNCE and COMPLAINT; + // an explicit PUT (including an empty list) overrides this. + AccountSuppressionAttributes attrs = new AccountSuppressionAttributes(); + attrs.setSuppressedReasons(new ArrayList<>(List.of("BOUNCE", "COMPLAINT"))); + return attrs; + } + + public void putAccountSuppressionAttributes(String region, List suppressedReasons) { + List sanitized = new ArrayList<>(); + if (suppressedReasons != null) { + for (String r : suppressedReasons) { + validateSuppressionReason(r, "suppressedReasons", true); + sanitized.add(r); + } + } + AccountSuppressionAttributes attrs = new AccountSuppressionAttributes(); + attrs.setSuppressedReasons(sanitized); + accountSuppressionStore.put(accountSuppressionKey(region), attrs); + LOG.infov("Updated account suppression attributes for region {0}: {1}", region, sanitized); + } + + private static String accountSuppressionKey(String region) { + return "account-suppression::" + region; + } + + // ──────────────────────────── Suppression list ──────────────────────────── + + public void putSuppressedDestination(String region, String emailAddress, String reason) { + String normalized = normalizeSuppressionEmail(emailAddress); + validateSuppressionReason(reason, "reason", false); + String key = suppressionKey(region, normalized); + 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 existingSuppressionMatch(region, emailAddress, normalized) + .map(SuppressionMatch::entry) + .orElseThrow(() -> new AwsException("NotFoundException", + "Email address " + normalized + " does not exist on your suppression list.", + 404)); + } + + public void deleteSuppressedDestination(String region, String emailAddress) { + String normalized = normalizeSuppressionEmail(emailAddress); + 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); + } + + /** + * Reads a suppression entry without throwing, so the facade's send-path filters + * ({@code collectSuppressedReasons} / {@code resolveSuppressionReason}) can look one up by raw + * address and share this service's normalization and legacy-key fallback. + */ + public Optional findSuppressedDestination(String region, String rawEmail) { + if (rawEmail == null || rawEmail.isBlank()) { + return Optional.empty(); + } + String normalized = normalizeSuppressionEmail(rawEmail); + return existingSuppressionMatch(region, rawEmail, normalized).map(SuppressionMatch::entry); + } + + /** 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) { + for (String r : reasonFilters) { + if (r != null && !r.isBlank()) { + validateSuppressionReason(r, "reasons", true); + filters.add(r); + } + } + } + String prefix = "suppression::" + region + "::"; + List all = new ArrayList<>(suppressionStore.scan(k -> k.startsWith(prefix))); + all.sort(Comparator.comparing(SuppressedDestination::getLastUpdateTime, + Comparator.nullsLast(Comparator.naturalOrder())) + .thenComparing(SuppressedDestination::getEmailAddress, + Comparator.nullsLast(Comparator.naturalOrder()))); + if (filters.isEmpty()) { + return all; + } + return all.stream() + .filter(s -> filters.contains(s.getReason())) + .toList(); + } + + private static String suppressionKey(String region, String emailAddress) { + return "suppression::" + region + "::" + emailAddress; + } + + private static String normalizeSuppressionEmail(String emailAddress) { + if (emailAddress == null || emailAddress.isBlank()) { + throw new AwsException("BadRequestException", "EmailAddress is required.", 400); + } + // 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); + } + + /** + * Validation message used by PutAccountSuppressionAttributes, PutSuppressedDestination, and + * ListSuppressedDestinations — all three return the AWS "1 validation error detected: Value at + * '' failed to satisfy constraint: ..." V1-style nested message verbatim. (Verified + * against real AWS V2 SES on 2026-06-03.) The {@code nested} flag controls whether the inner enum + * constraint is wrapped in {@code Member must satisfy constraint: [...]} — PutSuppressedDestination + * (single Reason field) returns the unwrapped form; the two list-bearing APIs return the wrapped + * form. Shared by the two sub-domains above, which is why they were extracted together. + */ + private static void validateSuppressionReason(String reason, String fieldName, boolean nested) { + if (reason == null || (!"BOUNCE".equals(reason) && !"COMPLAINT".equals(reason))) { + String constraint = nested + ? "Member must satisfy constraint: [Member must satisfy enum value set: [BOUNCE, COMPLAINT]]" + : "Member must satisfy enum value set: [BOUNCE, COMPLAINT]"; + throw new AwsException("BadRequestException", + "1 validation error detected: Value at '" + fieldName + "' failed to satisfy constraint: " + + constraint, 400); + } + } +} diff --git a/src/main/java/io/github/hectorvent/floci/services/ses/SesTags.java b/src/main/java/io/github/hectorvent/floci/services/ses/SesTags.java new file mode 100644 index 0000000000..0e1700d096 --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/ses/SesTags.java @@ -0,0 +1,32 @@ +package io.github.hectorvent.floci.services.ses; + +import io.github.hectorvent.floci.core.common.AwsException; +import io.github.hectorvent.floci.services.ses.model.Tag; + +/** + * Shared SES resource-tag validation. Lives outside the facade so the extracted domain services can + * validate tags without depending back on {@link SesService}. + */ +final class SesTags { + + private SesTags() {} + + static void validate(Tag tag) { + if (tag == null) { + throw new AwsException("InvalidParameterValue", "Tag must not be null.", 400); + } + String key = tag.key(); + if (key == null || key.isEmpty()) { + throw new AwsException("InvalidParameterValue", "Tag Key is required.", 400); + } + if (key.length() > 128) { + throw new AwsException("InvalidParameterValue", + "Tag Key must be 1-128 characters.", 400); + } + String value = tag.value(); + if (value != null && value.length() > 256) { + throw new AwsException("InvalidParameterValue", + "Tag Value must be 0-256 characters.", 400); + } + } +} diff --git a/src/main/java/io/github/hectorvent/floci/services/ses/SesTemplateService.java b/src/main/java/io/github/hectorvent/floci/services/ses/SesTemplateService.java new file mode 100644 index 0000000000..3a43e325f3 --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/ses/SesTemplateService.java @@ -0,0 +1,154 @@ +package io.github.hectorvent.floci.services.ses; + +import com.fasterxml.jackson.core.type.TypeReference; +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.ses.model.EmailTemplate; +import io.github.hectorvent.floci.services.ses.model.Tag; +import jakarta.enterprise.context.ApplicationScoped; +import jakarta.inject.Inject; +import org.jboss.logging.Logger; + +import java.time.Instant; +import java.util.ArrayList; +import java.util.Comparator; +import java.util.List; +import java.util.Map; +import java.util.Optional; + +/** + * Email templates (the {@code templateStore}), extracted from {@link SesService} as part of the + * store-based domain split. Reached through the {@code SesService} facade, which delegates the CRUD + * here; the facade's templated-send path reads templates back through {@link #getTemplate}, and its + * ARN-dispatched tagging reads/writes through {@link #find} / {@link #save}. + * + *

Tag validation is a shared cross-resource concern, so {@code createTemplate} calls + * {@link SesTags#validate} rather than depending back on the facade. The template ARN parser + * ({@code SesService.templateNameFromArn}) stays on the facade because external callers reference it + * statically. + */ +@ApplicationScoped +public class SesTemplateService { + + private static final Logger LOG = Logger.getLogger(SesTemplateService.class); + + private final StorageBackend templateStore; + + @Inject + public SesTemplateService(StorageFactory storageFactory) { + this.templateStore = storageFactory.create("ses", "ses-templates.json", + new TypeReference>() {}); + } + + SesTemplateService(StorageBackend templateStore) { + this.templateStore = templateStore; + } + + public EmailTemplate createTemplate(EmailTemplate template, String region) { + validateTemplate(template); + if (template.getTags() != null) { + for (Tag tag : template.getTags()) { + SesTags.validate(tag); + } + } + String key = templateKey(region, template.getTemplateName()); + if (templateStore.get(key).isPresent()) { + throw new AwsException("AlreadyExists", + "Template " + template.getTemplateName() + " already exists.", 400); + } + Instant now = Instant.now(); + template.setCreatedTimestamp(now); + template.setLastUpdatedTimestamp(now); + templateStore.put(key, template); + LOG.infov("Created SES template: {0} in region {1}", template.getTemplateName(), region); + return template; + } + + public EmailTemplate getTemplate(String templateName, String region) { + return templateStore.get(templateKey(region, templateName)) + .orElseThrow(() -> new AwsException("TemplateDoesNotExist", + "Template " + templateName + " does not exist.", 400)); + } + + public EmailTemplate updateTemplate(EmailTemplate template, String region) { + validateTemplate(template); + String key = templateKey(region, template.getTemplateName()); + EmailTemplate existing = templateStore.get(key) + .orElseThrow(() -> new AwsException("TemplateDoesNotExist", + "Template " + template.getTemplateName() + " does not exist.", 400)); + template.setCreatedTimestamp(existing.getCreatedTimestamp()); + template.setLastUpdatedTimestamp(Instant.now()); + // Tags are managed exclusively via Tag/UntagResource — preserve them on update. + template.setTags(existing.getTags()); + templateStore.put(key, template); + LOG.infov("Updated SES template: {0} in region {1}", template.getTemplateName(), region); + return template; + } + + public void deleteTemplate(String templateName, String region) { + String key = templateKey(region, templateName); + if (templateStore.get(key).isEmpty()) { + throw new AwsException("TemplateDoesNotExist", + "Template " + templateName + " does not exist.", 400); + } + templateStore.delete(key); + LOG.infov("Deleted SES template: {0} in region {1}", templateName, region); + } + + public List listTemplates(String region) { + String prefix = "template::" + region + "::"; + List all = new ArrayList<>(templateStore.scan(k -> k.startsWith(prefix))); + all.sort(Comparator.comparing(EmailTemplate::getCreatedTimestamp, + Comparator.nullsLast(Comparator.naturalOrder())) + .thenComparing(EmailTemplate::getTemplateName, + Comparator.nullsLast(Comparator.naturalOrder()))); + return all; + } + + /** + * Reads a template without throwing, so the facade's ARN-dispatched tagging can look one up by + * name and reuse this service's key derivation. + */ + public Optional find(String templateName, String region) { + return templateStore.get(templateKey(region, templateName)); + } + + /** + * Persists a template under its canonical key, so the facade's tagging can write the merged tags + * back without owning the key derivation. + */ + public void save(EmailTemplate template, String region) { + templateStore.put(templateKey(region, template.getTemplateName()), template); + } + + private static void validateTemplate(EmailTemplate template) { + if (template == null) { + throw new AwsException("InvalidTemplate", "Template is required.", 400); + } + validateTemplateName(template.getTemplateName()); + boolean hasSubject = template.getSubject() != null && !template.getSubject().isBlank(); + boolean hasText = template.getTextPart() != null && !template.getTextPart().isBlank(); + boolean hasHtml = template.getHtmlPart() != null && !template.getHtmlPart().isBlank(); + if (!hasSubject && !hasText && !hasHtml) { + throw new AwsException("InvalidTemplate", + "Template must have at least a subject, text, or html part.", 400); + } + } + + private static void validateTemplateName(String templateName) { + if (templateName == null || templateName.isBlank()) { + throw new AwsException("InvalidTemplate", "TemplateName is required.", 400); + } + if (Character.isWhitespace(templateName.charAt(0)) + || Character.isWhitespace(templateName.charAt(templateName.length() - 1))) { + throw new AwsException("InvalidTemplate", + "TemplateName must not contain leading or trailing whitespace.", 400); + } + } + + private static String templateKey(String region, String templateName) { + validateTemplateName(templateName); + return "template::" + region + "::" + templateName; + } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/ses/SesAccountServiceTest.java b/src/test/java/io/github/hectorvent/floci/services/ses/SesAccountServiceTest.java new file mode 100644 index 0000000000..9803d399eb --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/ses/SesAccountServiceTest.java @@ -0,0 +1,57 @@ +package io.github.hectorvent.floci.services.ses; + +import io.github.hectorvent.floci.core.storage.InMemoryStorage; +import io.github.hectorvent.floci.services.ses.model.AccountVdmAttributes; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +/** + * Unit test for the extracted account domain: the account sending-enabled flag and + * the VDM attributes. The service is constructed with just its own two stores — no 14-argument + * SesService needed. + */ +class SesAccountServiceTest { + + private static final String REGION = "us-east-1"; + private SesAccountService service; + + @BeforeEach + void setUp() { + service = new SesAccountService(new InMemoryStorage<>(), new InMemoryStorage<>()); + } + + @Test + void sendingEnabled_defaultsTrue() { + assertTrue(service.isAccountSendingEnabled(REGION)); + } + + @Test + void setSendingEnabled_roundTrips() { + service.setAccountSendingEnabled(REGION, false); + assertFalse(service.isAccountSendingEnabled(REGION)); + + service.setAccountSendingEnabled(REGION, true); + assertTrue(service.isAccountSendingEnabled(REGION)); + } + + @Test + void sendingEnabled_isPerRegion() { + service.setAccountSendingEnabled(REGION, false); + assertTrue(service.isAccountSendingEnabled("eu-west-1")); + } + + @Test + void vdmAttributes_absentUntilConfigured_thenRoundTrip() { + // Opt-in: a never-configured region has no VdmAttributes at all. + assertTrue(service.findAccountVdmAttributes(REGION).isEmpty()); + + service.putAccountVdmAttributes(REGION, new AccountVdmAttributes(true, true, false)); + AccountVdmAttributes vdm = service.findAccountVdmAttributes(REGION).orElseThrow(); + assertTrue(vdm.vdmEnabled()); + assertTrue(vdm.engagementMetrics()); + assertFalse(vdm.optimizedSharedDelivery()); + } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/ses/SesContactServiceTest.java b/src/test/java/io/github/hectorvent/floci/services/ses/SesContactServiceTest.java new file mode 100644 index 0000000000..b1ea5b0854 --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/ses/SesContactServiceTest.java @@ -0,0 +1,73 @@ +package io.github.hectorvent.floci.services.ses; + +import io.github.hectorvent.floci.core.common.AwsException; +import io.github.hectorvent.floci.core.storage.InMemoryStorage; +import io.github.hectorvent.floci.services.ses.model.Contact; +import io.github.hectorvent.floci.services.ses.model.ContactList; +import io.github.hectorvent.floci.services.ses.model.Topic; +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.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +/** + * Unit test for the extracted contact domain. New facet: a multi-store service + * (contact lists + contacts) constructed with just its two stores and a clock — the two SesService + * constructor arguments collapse into one. Also exercises the list-management behaviour the send + * path calls into. + */ +class SesContactServiceTest { + + private static final String REGION = "us-east-1"; + private static final String LIST = "news"; + private SesContactService service; + + @BeforeEach + void setUp() { + service = new SesContactService(new InMemoryStorage<>(), new InMemoryStorage<>(), Clock.systemUTC()); + service.createContactList(LIST, "desc", + List.of(new Topic("Sports", "Sports", "OPT_OUT", "d")), List.of(), REGION); + } + + @Test + void secondContactList_hitsOneListLimit() { + AwsException e = assertThrows(AwsException.class, + () -> service.createContactList("other", "d", List.of(), List.of(), REGION)); + assertEquals("BadRequestException", e.getErrorCode()); + } + + @Test + void createContact_thenGet_roundTrips() { + service.createContact(LIST, "a@example.com", List.of(), false, null, REGION); + assertEquals("a@example.com", service.getContact(LIST, "a@example.com", REGION).contact().getEmailAddress()); + } + + @Test + void deleteContactList_purgesContacts() { + service.createContact(LIST, "a@example.com", List.of(), false, null, REGION); + service.deleteContactList(LIST, REGION); + // The list — and its contacts — are gone. + assertThrows(AwsException.class, () -> service.listContacts(LIST, REGION)); + } + + @Test + void getOrAutoCreateContact_createsOnSend() { + ContactList list = service.getContactList(LIST, REGION); + Contact created = service.getOrAutoCreateContact(list, "auto@example.com", REGION); + assertEquals("auto@example.com", created.getEmailAddress()); + assertTrue(service.getContact(LIST, "auto@example.com", REGION).contact() != null); + } + + @Test + void unsubscribeAll_thenListManagementOptedOut() { + ContactList list = service.getContactList(LIST, REGION); + service.unsubscribeContact(LIST, "bye@example.com", null, REGION); + Contact c = service.getContact(LIST, "bye@example.com", REGION).contact(); + assertTrue(service.isListManagementOptedOut(c, list, null)); + } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/ses/SesCvetServiceTest.java b/src/test/java/io/github/hectorvent/floci/services/ses/SesCvetServiceTest.java new file mode 100644 index 0000000000..c3cfb956ef --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/ses/SesCvetServiceTest.java @@ -0,0 +1,75 @@ +package io.github.hectorvent.floci.services.ses; + +import io.github.hectorvent.floci.core.common.AwsException; +import io.github.hectorvent.floci.core.storage.InMemoryStorage; +import io.github.hectorvent.floci.services.ses.model.CustomVerificationEmailTemplate; +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.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +/** + * Unit test for the extracted CVET storage domain. The identity-dependent + * validation lives in the SesService facade, so this service is a pure store — constructed with just + * its own store and unit-tested without a 14-argument SesService. + */ +class SesCvetServiceTest { + + private static final String REGION = "us-east-1"; + private SesCvetService service; + + @BeforeEach + void setUp() { + service = new SesCvetService(new InMemoryStorage<>()); + } + + private static CustomVerificationEmailTemplate template(String name) { + CustomVerificationEmailTemplate t = new CustomVerificationEmailTemplate(); + t.setTemplateName(name); + t.setFromEmailAddress("verify@example.com"); + t.setTemplateSubject("Verify"); + t.setTemplateContent("Hello"); + t.setSuccessRedirectionURL("https://example.com/ok"); + t.setFailureRedirectionURL("https://example.com/no"); + return t; + } + + @Test + void create_thenGet_roundTrips() { + service.createCustomVerificationEmailTemplate(template("t1"), REGION); + assertEquals("t1", service.getCustomVerificationEmailTemplate("t1", REGION).getTemplateName()); + } + + @Test + void create_duplicate_throwsAlreadyExists() { + service.createCustomVerificationEmailTemplate(template("t1"), REGION); + AwsException e = assertThrows(AwsException.class, + () -> service.createCustomVerificationEmailTemplate(template("t1"), REGION)); + assertEquals("CustomVerificationEmailTemplateAlreadyExists", e.getErrorCode()); + } + + @Test + void get_unknown_throwsDoesNotExist() { + AwsException e = assertThrows(AwsException.class, + () -> service.getCustomVerificationEmailTemplate("ghost", REGION)); + assertEquals("CustomVerificationEmailTemplateDoesNotExist", e.getErrorCode()); + } + + @Test + void delete_removesIt_andFindReflectsIt() { + service.createCustomVerificationEmailTemplate(template("t1"), REGION); + assertTrue(service.find("t1", REGION).isPresent()); + + service.deleteCustomVerificationEmailTemplate("t1", REGION); + assertTrue(service.find("t1", REGION).isEmpty()); + } + + @Test + void update_unknown_throwsDoesNotExist() { + AwsException e = assertThrows(AwsException.class, + () -> service.updateCustomVerificationEmailTemplate(template("ghost"), REGION)); + assertEquals("CustomVerificationEmailTemplateDoesNotExist", e.getErrorCode()); + } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/ses/SesDedicatedIpServiceTest.java b/src/test/java/io/github/hectorvent/floci/services/ses/SesDedicatedIpServiceTest.java new file mode 100644 index 0000000000..b4cbccc963 --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/ses/SesDedicatedIpServiceTest.java @@ -0,0 +1,80 @@ +package io.github.hectorvent.floci.services.ses; + +import io.github.hectorvent.floci.core.common.AwsException; +import io.github.hectorvent.floci.core.storage.InMemoryStorage; +import io.github.hectorvent.floci.services.ses.model.DedicatedIpPool; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +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.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +/** + * Unit test for the extracted dedicated-IP-pool domain: create/get/list/delete plus + * the scaling-mode and duplicate validation. The service is constructed with just its own store — no + * 14-argument SesService needed. + */ +class SesDedicatedIpServiceTest { + + private static final String REGION = "us-east-1"; + private SesDedicatedIpService service; + + @BeforeEach + void setUp() { + service = new SesDedicatedIpService(new InMemoryStorage<>()); + } + + @Test + void create_defaultsScalingModeToStandard() { + DedicatedIpPool pool = service.createDedicatedIpPool("pool-a", null, REGION); + assertEquals("pool-a", pool.getPoolName()); + assertEquals("STANDARD", pool.getScalingMode()); + assertTrue(service.dedicatedIpPoolExists("pool-a", REGION)); + } + + @Test + void create_rejectsBlankName() { + assertThrows(AwsException.class, () -> service.createDedicatedIpPool(" ", "STANDARD", REGION)); + } + + @Test + void create_rejectsInvalidScalingMode() { + assertThrows(AwsException.class, () -> service.createDedicatedIpPool("pool-a", "TURBO", REGION)); + } + + @Test + void create_rejectsDuplicate() { + service.createDedicatedIpPool("pool-a", "STANDARD", REGION); + assertThrows(AwsException.class, () -> service.createDedicatedIpPool("pool-a", "STANDARD", REGION)); + } + + @Test + void get_missingThrows() { + assertThrows(AwsException.class, () -> service.getDedicatedIpPool("ghost", REGION)); + } + + @Test + void list_isSortedAndPerRegion() { + service.createDedicatedIpPool("pool-b", "STANDARD", REGION); + service.createDedicatedIpPool("pool-a", "STANDARD", REGION); + service.createDedicatedIpPool("pool-other", "STANDARD", "eu-west-1"); + + assertEquals(List.of("pool-a", "pool-b"), service.listDedicatedIpPools(REGION)); + } + + @Test + void delete_removesPool() { + service.createDedicatedIpPool("pool-a", "MANAGED", REGION); + service.deleteDedicatedIpPool("pool-a", REGION); + assertFalse(service.dedicatedIpPoolExists("pool-a", REGION)); + } + + @Test + void delete_missingThrows() { + assertThrows(AwsException.class, () -> service.deleteDedicatedIpPool("ghost", REGION)); + } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/ses/SesPolicyServiceTest.java b/src/test/java/io/github/hectorvent/floci/services/ses/SesPolicyServiceTest.java new file mode 100644 index 0000000000..1c682e1e06 --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/ses/SesPolicyServiceTest.java @@ -0,0 +1,74 @@ +package io.github.hectorvent.floci.services.ses; + +import com.fasterxml.jackson.databind.ObjectMapper; +import io.github.hectorvent.floci.core.common.AwsException; +import io.github.hectorvent.floci.core.storage.InMemoryStorage; +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.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +/** + * Unit test for the extracted identity-policy domain. The identity-existence check + * stays in the SesService facade, so this service is a pure policy store — unit-tested with just its + * store and an ObjectMapper, and it exercises the reverse-coupling helper deletePoliciesForIdentity. + */ +class SesPolicyServiceTest { + + private static final String REGION = "us-east-1"; + private static final String IDENTITY = "sender@example.com"; + private SesPolicyService service; + + @BeforeEach + void setUp() { + service = new SesPolicyService(new InMemoryStorage<>(), new ObjectMapper()); + } + + @Test + void create_thenList_roundTrips() { + service.createEmailIdentityPolicy(IDENTITY, "p1", "{\"Version\":\"2012-10-17\"}", REGION); + assertTrue(service.listAllPolicies(IDENTITY, REGION).containsKey("p1")); + } + + @Test + void create_duplicate_throwsAlreadyExists() { + service.createEmailIdentityPolicy(IDENTITY, "p1", "{}", REGION); + AwsException e = assertThrows(AwsException.class, + () -> service.createEmailIdentityPolicy(IDENTITY, "p1", "{}", REGION)); + assertEquals("AlreadyExistsException", e.getErrorCode()); + } + + @Test + void update_missing_throwsNotFound() { + AwsException e = assertThrows(AwsException.class, + () -> service.updateEmailIdentityPolicy(IDENTITY, "ghost", "{}", REGION)); + assertEquals("NotFoundException", e.getErrorCode()); + } + + @Test + void invalidPolicyName_throws() { + AwsException e = assertThrows(AwsException.class, + () -> service.createEmailIdentityPolicy(IDENTITY, "bad name!", "{}", REGION)); + assertEquals("InvalidParameterValue", e.getErrorCode()); + } + + @Test + void enforcesPerIdentityLimit() { + for (int i = 0; i < SesPolicyService.MAX_POLICIES_PER_IDENTITY; i++) { + service.createEmailIdentityPolicy(IDENTITY, "p" + i, "{}", REGION); + } + AwsException e = assertThrows(AwsException.class, + () -> service.createEmailIdentityPolicy(IDENTITY, "one-too-many", "{}", REGION)); + assertEquals("LimitExceededException", e.getErrorCode()); + } + + @Test + void deletePoliciesForIdentity_purgesAll() { + service.putIdentityPolicy(IDENTITY, "p1", "{}", REGION); + service.putIdentityPolicy(IDENTITY, "p2", "{}", REGION); + service.deletePoliciesForIdentity(IDENTITY, REGION); + assertTrue(service.listAllPolicies(IDENTITY, REGION).isEmpty()); + } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/ses/SesReceiptRuleServiceTest.java b/src/test/java/io/github/hectorvent/floci/services/ses/SesReceiptRuleServiceTest.java new file mode 100644 index 0000000000..2b196e4466 --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/ses/SesReceiptRuleServiceTest.java @@ -0,0 +1,70 @@ +package io.github.hectorvent.floci.services.ses; + +import io.github.hectorvent.floci.core.common.AwsException; +import io.github.hectorvent.floci.core.storage.InMemoryStorage; +import io.github.hectorvent.floci.services.ses.model.ReceiptRuleSet; +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.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertThrows; + +/** + * Unit test for the extracted receipt-rule domain. The payoff of the split: the + * service is constructed with just its own store and a clock — no 14-argument SesService needed. + */ +class SesReceiptRuleServiceTest { + + private static final String REGION = "us-east-1"; + private SesReceiptRuleService service; + + @BeforeEach + void setUp() { + service = new SesReceiptRuleService(new InMemoryStorage<>(), Clock.systemUTC()); + } + + @Test + void create_thenDescribe_roundTrips() { + service.createReceiptRuleSet("rules-a", REGION); + assertEquals("rules-a", service.describeReceiptRuleSet("rules-a", REGION).getName()); + } + + @Test + void create_duplicate_throwsAlreadyExists() { + service.createReceiptRuleSet("rules-a", REGION); + AwsException e = assertThrows(AwsException.class, + () -> service.createReceiptRuleSet("rules-a", REGION)); + assertEquals("AlreadyExists", e.getErrorCode()); + } + + @Test + void describe_unknown_throwsRuleSetDoesNotExist() { + AwsException e = assertThrows(AwsException.class, + () -> service.describeReceiptRuleSet("ghost", REGION)); + assertEquals("RuleSetDoesNotExist", e.getErrorCode()); + } + + @Test + void setActive_thenDescribeActive_andDeleteActiveRejected() { + service.createReceiptRuleSet("rules-a", REGION); + service.setActiveReceiptRuleSet("rules-a", REGION); + + ReceiptRuleSet active = service.describeActiveReceiptRuleSet(REGION); + assertNotNull(active); + assertEquals("rules-a", active.getName()); + + AwsException e = assertThrows(AwsException.class, + () -> service.deleteReceiptRuleSet("rules-a", REGION)); + assertEquals("CannotDelete", e.getErrorCode()); + } + + @Test + void invalidName_throwsValidationError() { + AwsException e = assertThrows(AwsException.class, + () -> service.createReceiptRuleSet("bad name!", REGION)); + assertEquals("ValidationError", e.getErrorCode()); + } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/ses/SesSentEmailServiceTest.java b/src/test/java/io/github/hectorvent/floci/services/ses/SesSentEmailServiceTest.java new file mode 100644 index 0000000000..08d46e5d6a --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/ses/SesSentEmailServiceTest.java @@ -0,0 +1,72 @@ +package io.github.hectorvent.floci.services.ses; + +import io.github.hectorvent.floci.core.storage.InMemoryStorage; +import io.github.hectorvent.floci.services.ses.model.SentEmail; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import java.util.List; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +/** + * Unit test for the extracted sent-email record domain: the send path's output sink plus the + * per-region count and the inspection list/clear. The service is constructed with just its own store + * — no 14-argument SesService needed. + */ +class SesSentEmailServiceTest { + + private static final String REGION = "us-east-1"; + private SesSentEmailService service; + + @BeforeEach + void setUp() { + service = new SesSentEmailService(new InMemoryStorage<>()); + } + + private static SentEmail email(String messageId, String region) { + SentEmail e = new SentEmail(); + e.setMessageId(messageId); + e.setRegion(region); + e.setSource("sender@example.com"); + return e; + } + + @Test + void record_thenListAll() { + service.record(REGION, "m1", email("m1", REGION)); + service.record(REGION, "m2", email("m2", REGION)); + + List all = service.listAll(); + assertEquals(2, all.size()); + } + + @Test + void countInRegion_isPerRegion() { + service.record(REGION, "m1", email("m1", REGION)); + service.record(REGION, "m2", email("m2", REGION)); + service.record("eu-west-1", "m3", email("m3", "eu-west-1")); + + assertEquals(2, service.countInRegion(REGION)); + assertEquals(1, service.countInRegion("eu-west-1")); + assertEquals(0, service.countInRegion("ap-northeast-1")); + } + + @Test + void record_sameMessageId_isOverwrittenNotDuplicated() { + service.record(REGION, "m1", email("m1", REGION)); + service.record(REGION, "m1", email("m1", REGION)); + assertEquals(1, service.countInRegion(REGION)); + } + + @Test + void clear_removesEverything() { + service.record(REGION, "m1", email("m1", REGION)); + service.record("eu-west-1", "m2", email("m2", "eu-west-1")); + + service.clear(); + assertTrue(service.listAll().isEmpty()); + assertEquals(0, service.countInRegion(REGION)); + } +} 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 index d99b4f55dd..2984e17207 100644 --- a/src/test/java/io/github/hectorvent/floci/services/ses/SesServiceDkimLookupCacheTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/ses/SesServiceDkimLookupCacheTest.java @@ -51,19 +51,16 @@ class SesServiceDkimLookupCacheTest { clock.reset(); service = new SesService( identityStore, - new InMemoryStorage(), - new InMemoryStorage(), - new InMemoryStorage(), + new SesSentEmailService(new InMemoryStorage()), + new SesAccountService(new InMemoryStorage(), new InMemoryStorage()), + new SesTemplateService(new InMemoryStorage()), new InMemoryStorage(), - new InMemoryStorage(), - new InMemoryStorage(), - new InMemoryStorage(), - new InMemoryStorage(), - new InMemoryStorage(), - new InMemoryStorage(), - new InMemoryStorage(), - new InMemoryStorage(), - new InMemoryStorage(), + new SesSuppressionService(new InMemoryStorage(), new InMemoryStorage()), + new SesDedicatedIpService(new InMemoryStorage()), + new SesContactService(new InMemoryStorage(), new InMemoryStorage(), clock), + new SesPolicyService(new InMemoryStorage(), new ObjectMapper()), + new SesReceiptRuleService(new InMemoryStorage(), clock), + new SesCvetService(new InMemoryStorage()), mock(SmtpRelay.class), new ObjectMapper(), route53Service, 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 index a79707eb53..0a169adc95 100644 --- a/src/test/java/io/github/hectorvent/floci/services/ses/SesServiceLegacyDkimTokensTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/ses/SesServiceLegacyDkimTokensTest.java @@ -40,19 +40,16 @@ class SesServiceLegacyDkimTokensTest { identityStore = new InMemoryStorage<>(); service = new SesService( identityStore, - new InMemoryStorage(), - new InMemoryStorage(), - new InMemoryStorage(), + new SesSentEmailService(new InMemoryStorage()), + new SesAccountService(new InMemoryStorage(), new InMemoryStorage()), + new SesTemplateService(new InMemoryStorage()), new InMemoryStorage(), - new InMemoryStorage(), - new InMemoryStorage(), - new InMemoryStorage(), - new InMemoryStorage(), - new InMemoryStorage(), - new InMemoryStorage(), - new InMemoryStorage(), - new InMemoryStorage(), - new InMemoryStorage(), + new SesSuppressionService(new InMemoryStorage(), new InMemoryStorage()), + new SesDedicatedIpService(new InMemoryStorage()), + new SesContactService(new InMemoryStorage(), new InMemoryStorage(), Clock.systemUTC()), + new SesPolicyService(new InMemoryStorage(), new ObjectMapper()), + new SesReceiptRuleService(new InMemoryStorage(), Clock.systemUTC()), + new SesCvetService(new InMemoryStorage()), mock(SmtpRelay.class), new ObjectMapper(), Clock.systemUTC()); diff --git a/src/test/java/io/github/hectorvent/floci/services/ses/SesServiceListManagementTest.java b/src/test/java/io/github/hectorvent/floci/services/ses/SesServiceListManagementTest.java index 97798409e8..341b9f7dac 100644 --- a/src/test/java/io/github/hectorvent/floci/services/ses/SesServiceListManagementTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/ses/SesServiceListManagementTest.java @@ -60,19 +60,16 @@ class SesServiceListManagementTest { contactStore = new InMemoryStorage<>(); service = new SesService( new InMemoryStorage(), - new InMemoryStorage(), - new InMemoryStorage(), - new InMemoryStorage(), + new SesSentEmailService(new InMemoryStorage()), + new SesAccountService(new InMemoryStorage(), new InMemoryStorage()), + new SesTemplateService(new InMemoryStorage()), new InMemoryStorage(), - new InMemoryStorage(), - new InMemoryStorage(), - new InMemoryStorage(), - new InMemoryStorage(), - new InMemoryStorage(), - contactStore, - new InMemoryStorage(), - new InMemoryStorage(), - new InMemoryStorage(), + new SesSuppressionService(new InMemoryStorage(), new InMemoryStorage()), + new SesDedicatedIpService(new InMemoryStorage()), + new SesContactService(new InMemoryStorage(), contactStore, Clock.systemUTC()), + new SesPolicyService(new InMemoryStorage(), new ObjectMapper()), + new SesReceiptRuleService(new InMemoryStorage(), Clock.systemUTC()), + new SesCvetService(new InMemoryStorage()), smtpRelay, new ObjectMapper(), Clock.systemUTC()); 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 df42df70c8..1303cbf99c 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 @@ -39,19 +39,16 @@ class SesServiceSmtpTest { emailStore = new InMemoryStorage<>(); service = new SesService( new InMemoryStorage(), - emailStore, - new InMemoryStorage(), - new InMemoryStorage(), + new SesSentEmailService(emailStore), + new SesAccountService(new InMemoryStorage(), new InMemoryStorage()), + new SesTemplateService(new InMemoryStorage()), new InMemoryStorage(), - new InMemoryStorage(), - new InMemoryStorage(), - new InMemoryStorage(), - new InMemoryStorage(), - new InMemoryStorage(), - new InMemoryStorage(), - new InMemoryStorage(), - new InMemoryStorage(), - new InMemoryStorage(), + new SesSuppressionService(new InMemoryStorage(), new InMemoryStorage()), + new SesDedicatedIpService(new InMemoryStorage()), + new SesContactService(new InMemoryStorage(), new InMemoryStorage(), Clock.systemUTC()), + new SesPolicyService(new InMemoryStorage(), new ObjectMapper()), + new SesReceiptRuleService(new InMemoryStorage(), Clock.systemUTC()), + new SesCvetService(new InMemoryStorage()), smtpRelay, new ObjectMapper(), Clock.systemUTC()); 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 b9715bab3e..da31f35285 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 @@ -47,19 +47,16 @@ class SesServiceSuppressionLegacyKeyTest { suppressionStore = new InMemoryStorage<>(); service = new SesService( new InMemoryStorage(), - new InMemoryStorage(), - new InMemoryStorage(), - new InMemoryStorage(), + new SesSentEmailService(new InMemoryStorage()), + new SesAccountService(new InMemoryStorage(), new InMemoryStorage()), + new SesTemplateService(new InMemoryStorage()), new InMemoryStorage(), - suppressionStore, - new InMemoryStorage(), - new InMemoryStorage(), - new InMemoryStorage(), - new InMemoryStorage(), - new InMemoryStorage(), - new InMemoryStorage(), - new InMemoryStorage(), - new InMemoryStorage(), + new SesSuppressionService(suppressionStore, new InMemoryStorage()), + new SesDedicatedIpService(new InMemoryStorage()), + new SesContactService(new InMemoryStorage(), new InMemoryStorage(), Clock.systemUTC()), + new SesPolicyService(new InMemoryStorage(), new ObjectMapper()), + new SesReceiptRuleService(new InMemoryStorage(), Clock.systemUTC()), + new SesCvetService(new InMemoryStorage()), mock(SmtpRelay.class), new ObjectMapper(), Clock.systemUTC()); 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 749b71309b..6e51671de8 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 @@ -47,19 +47,16 @@ class SesServiceSuppressionReasonTest { accountSuppressionStore = new InMemoryStorage<>(); service = new SesService( new InMemoryStorage(), - new InMemoryStorage(), - new InMemoryStorage(), - new InMemoryStorage(), + new SesSentEmailService(new InMemoryStorage()), + new SesAccountService(new InMemoryStorage(), new InMemoryStorage()), + new SesTemplateService(new InMemoryStorage()), new InMemoryStorage(), - suppressionStore, - accountSuppressionStore, - new InMemoryStorage(), - new InMemoryStorage(), - new InMemoryStorage(), - new InMemoryStorage(), - new InMemoryStorage(), - new InMemoryStorage(), - new InMemoryStorage(), + new SesSuppressionService(suppressionStore, accountSuppressionStore), + new SesDedicatedIpService(new InMemoryStorage()), + new SesContactService(new InMemoryStorage(), new InMemoryStorage(), Clock.systemUTC()), + new SesPolicyService(new InMemoryStorage(), new ObjectMapper()), + new SesReceiptRuleService(new InMemoryStorage(), Clock.systemUTC()), + new SesCvetService(new InMemoryStorage()), mock(SmtpRelay.class), new ObjectMapper(), Clock.systemUTC()); diff --git a/src/test/java/io/github/hectorvent/floci/services/ses/SesSuppressionServiceTest.java b/src/test/java/io/github/hectorvent/floci/services/ses/SesSuppressionServiceTest.java new file mode 100644 index 0000000000..00286b3abe --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/ses/SesSuppressionServiceTest.java @@ -0,0 +1,67 @@ +package io.github.hectorvent.floci.services.ses; + +import io.github.hectorvent.floci.core.common.AwsException; +import io.github.hectorvent.floci.core.storage.InMemoryStorage; +import io.github.hectorvent.floci.services.ses.model.SuppressedDestination; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import java.util.List; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +/** + * Unit test for the extracted suppression domain. New facet: this closes the + * shared-helper deferral from the account step — account suppression and the suppression list both + * live here and share the (now private) reason validation, exercised by both paths below. Two stores, + * one service. + */ +class SesSuppressionServiceTest { + + private static final String REGION = "us-east-1"; + private SesSuppressionService service; + + @BeforeEach + void setUp() { + service = new SesSuppressionService(new InMemoryStorage<>(), new InMemoryStorage<>()); + } + + @Test + void accountSuppression_defaultsToBounceAndComplaint() { + assertEquals(List.of("BOUNCE", "COMPLAINT"), + service.getAccountSuppressionAttributes(REGION).getSuppressedReasons()); + } + + @Test + void putAccountSuppression_rejectsInvalidReason() { + AwsException e = assertThrows(AwsException.class, + () -> service.putAccountSuppressionAttributes(REGION, List.of("NONSENSE"))); + assertEquals("BadRequestException", e.getErrorCode()); + } + + @Test + void suppressedDestination_putGetDelete_roundTrips() { + service.putSuppressedDestination(REGION, "a@example.com", "BOUNCE"); + SuppressedDestination got = service.getSuppressedDestination(REGION, "a@example.com"); + assertEquals("BOUNCE", got.getReason()); + + service.deleteSuppressedDestination(REGION, "a@example.com"); + assertTrue(service.findSuppressedDestination(REGION, "a@example.com").isEmpty()); + } + + @Test + void putSuppressedDestination_rejectsInvalidReason() { + AwsException e = assertThrows(AwsException.class, + () -> service.putSuppressedDestination(REGION, "a@example.com", "NONSENSE")); + assertEquals("BadRequestException", e.getErrorCode()); + } + + @Test + void findSuppressedDestination_normalizesDomainCase() { + service.putSuppressedDestination(REGION, "User@Example.COM", "COMPLAINT"); + // Domain is canonicalized to lower case, so a differently-cased domain resolves the entry. + assertTrue(service.findSuppressedDestination(REGION, "User@example.com").isPresent()); + } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/ses/SesTemplateServiceTest.java b/src/test/java/io/github/hectorvent/floci/services/ses/SesTemplateServiceTest.java new file mode 100644 index 0000000000..dac05f38b6 --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/ses/SesTemplateServiceTest.java @@ -0,0 +1,115 @@ +package io.github.hectorvent.floci.services.ses; + +import io.github.hectorvent.floci.core.common.AwsException; +import io.github.hectorvent.floci.core.storage.InMemoryStorage; +import io.github.hectorvent.floci.services.ses.model.EmailTemplate; +import io.github.hectorvent.floci.services.ses.model.Tag; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import java.util.List; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +/** + * Unit test for the extracted email-template domain: CRUD plus the template-shape validation and + * duplicate/not-found handling. The service is constructed with just its own store — no 14-argument + * SesService needed. + */ +class SesTemplateServiceTest { + + private static final String REGION = "us-east-1"; + private SesTemplateService service; + + @BeforeEach + void setUp() { + service = new SesTemplateService(new InMemoryStorage<>()); + } + + private static EmailTemplate template(String name) { + return new EmailTemplate(name, "Subject", "text body", "

html

"); + } + + @Test + void create_thenGet_roundTrips() { + EmailTemplate created = service.createTemplate(template("welcome"), REGION); + assertNotNull(created.getCreatedTimestamp()); + assertNotNull(created.getLastUpdatedTimestamp()); + + EmailTemplate fetched = service.getTemplate("welcome", REGION); + assertEquals("Subject", fetched.getSubject()); + } + + @Test + void create_rejectsDuplicate() { + service.createTemplate(template("welcome"), REGION); + assertThrows(AwsException.class, () -> service.createTemplate(template("welcome"), REGION)); + } + + @Test + void create_rejectsBlankName() { + assertThrows(AwsException.class, () -> service.createTemplate(template(" "), REGION)); + } + + @Test + void create_rejectsEmptyBody() { + assertThrows(AwsException.class, + () -> service.createTemplate(new EmailTemplate("empty", null, null, null), REGION)); + } + + @Test + void get_missingThrows() { + assertThrows(AwsException.class, () -> service.getTemplate("ghost", REGION)); + } + + @Test + void update_preservesCreatedTimestamp_missingThrows() { + EmailTemplate created = service.createTemplate(template("welcome"), REGION); + + EmailTemplate update = template("welcome"); + update.setSubject("Updated"); + EmailTemplate updated = service.updateTemplate(update, REGION); + assertEquals(created.getCreatedTimestamp(), updated.getCreatedTimestamp()); + assertEquals("Updated", service.getTemplate("welcome", REGION).getSubject()); + + assertThrows(AwsException.class, () -> service.updateTemplate(template("ghost"), REGION)); + } + + @Test + void delete_removesTemplate_missingThrows() { + service.createTemplate(template("welcome"), REGION); + service.deleteTemplate("welcome", REGION); + assertThrows(AwsException.class, () -> service.getTemplate("welcome", REGION)); + assertThrows(AwsException.class, () -> service.deleteTemplate("welcome", REGION)); + } + + @Test + void list_isSortedByCreationAndPerRegion() { + service.createTemplate(template("a"), REGION); + service.createTemplate(template("b"), REGION); + service.createTemplate(template("other"), "eu-west-1"); + + List list = service.listTemplates(REGION); + assertEquals(2, list.size()); + assertEquals("a", list.get(0).getTemplateName()); + assertEquals("b", list.get(1).getTemplateName()); + } + + @Test + void findAndSave_supportFacadeTagging() { + service.createTemplate(template("welcome"), REGION); + assertTrue(service.find("ghost", REGION).isEmpty()); + + EmailTemplate found = service.find("welcome", REGION).orElseThrow(); + found.setTags(List.of(new Tag("team", "ses"))); + service.save(found, REGION); + + EmailTemplate reloaded = service.find("welcome", REGION).orElseThrow(); + assertEquals(1, reloaded.getTags().size()); + assertEquals("team", reloaded.getTags().get(0).key()); + assertEquals("ses", reloaded.getTags().get(0).value()); + } +}