diff --git a/src/main/java/io/github/hectorvent/floci/services/ses/SesConfigurationSetService.java b/src/main/java/io/github/hectorvent/floci/services/ses/SesConfigurationSetService.java index de75049233..ed14d384af 100644 --- a/src/main/java/io/github/hectorvent/floci/services/ses/SesConfigurationSetService.java +++ b/src/main/java/io/github/hectorvent/floci/services/ses/SesConfigurationSetService.java @@ -7,7 +7,9 @@ import io.github.hectorvent.floci.core.storage.StorageFactory; import io.github.hectorvent.floci.services.ses.model.ArchivingOptions; import io.github.hectorvent.floci.services.ses.model.CloudWatchDimensionConfiguration; import io.github.hectorvent.floci.services.ses.model.ConfigurationSet; +import io.github.hectorvent.floci.services.ses.model.DeliveryOptions; import io.github.hectorvent.floci.services.ses.model.EventDestination; +import io.github.hectorvent.floci.services.ses.model.TrackingOptions; import io.github.hectorvent.floci.services.ses.model.SuppressionOptions; import io.github.hectorvent.floci.services.ses.model.Tag; import io.github.hectorvent.floci.services.ses.model.VdmOptions; @@ -21,8 +23,10 @@ import java.util.Comparator; import java.util.HashSet; import java.util.List; import java.util.Map; +import java.util.Objects; import java.util.Optional; import java.util.Set; +import java.util.function.Predicate; import java.util.regex.Pattern; /** @@ -30,13 +34,13 @@ import java.util.regex.Pattern; * split: the store, key derivation, name validation, CRUD, the domain-pure option setters, and the * event destinations live here. * - *

The boundary follows the cross-domain seams: option validation that reads OTHER domains stays - * in the facade (tracking options check a verified domain identity, delivery options check a - * dedicated IP pool), which validates first (or resolves existence through {@link #get}) and then - * mutates through {@link #save}. The ARN-dispatched configuration-set tagging and the send-time - * validation ({@link #validateForSending}: existence plus the sending-paused gate) live here; the - * facade keeps the remaining send-path reads (event publishing, effective suppression reasons) - * and the tenant delete-guard around {@link #remove}. + *

The option validation that reads OTHER domains lives here too, with the cross-domain probes + * (a verified domain identity for tracking, an existing dedicated IP pool for delivery) injected + * as predicates by the facade, so the service owns every validated create and option operation + * without gaining a peer-service dependency. The ARN-dispatched configuration-set tagging and the + * send-time validation ({@link #validateForSending}: existence plus the sending-paused gate) live + * here as well; the facade keeps the send-path reads (event publishing, effective suppression + * reasons) and the tenant delete-guard around {@link #remove}. */ @ApplicationScoped public class SesConfigurationSetService { @@ -65,10 +69,43 @@ public class SesConfigurationSetService { } /** - * Stores a validated configuration set. The option validation runs in the facade first, since - * the cross-domain pieces (tracking's verified-domain check, delivery's dedicated-pool check) - * can't live here, so this owns only the duplicate check, the timestamp, and the write. + * v1 CreateConfigurationSet / v2 CreateConfigurationSet: the full probe-confirmed validation + * sequence (name, tags, suppression reasons, tracking, delivery, VDM) followed by the write. + * The two cross-domain probes arrive as predicates from the facade. */ + public ConfigurationSet createConfigurationSet(ConfigurationSet configSet, String region, + Predicate verifiedDomainIdentity, + Predicate dedicatedIpPoolExists) { + if (configSet == null) { + throw new AwsException("InvalidParameterValue", + "ConfigurationSetName is required.", 400); + } + validateConfigurationSetName(configSet.getName()); + SesTags.validate(configSet.getTags()); + if (configSet.getSuppressionOptions() != null + && configSet.getSuppressionOptions().getSuppressedReasons() != null) { + for (String reason : configSet.getSuppressionOptions().getSuppressedReasons()) { + if (reason == null) { + throw new AwsException("BadRequestException", + invalidSuppressionReasonMessage(null), 400); + } + if (!isValidSuppressionReason(reason)) { + throw new AwsException("BadRequestException", + "1 validation error detected: Value at " + + "'suppressionOptions.suppressedReasons' failed to satisfy " + + "constraint: Member must satisfy constraint: " + + "[Member must satisfy enum value set: [BOUNCE, COMPLAINT]]", + 400); + } + } + } + validateTrackingOptions(configSet.getTrackingOptions(), verifiedDomainIdentity); + validateDeliveryOptions(configSet.getDeliveryOptions(), dedicatedIpPoolExists); + validateVdmOptions(configSet.getVdmOptions()); + return create(configSet, region); + } + + /** The raw duplicate check, timestamp, and write behind the validated create above. */ public ConfigurationSet create(ConfigurationSet configSet, String region) { String key = configSetKey(region, configSet.getName()); if (configSetStore.get(key).isPresent()) { @@ -131,6 +168,147 @@ public class SesConfigurationSetService { } } + // The cross-domain probes (a verified domain identity for tracking, an existing dedicated IP + // pool for delivery) are injected as predicates by the facade, so this service stays free of + // peer-service dependencies while owning the full probe-confirmed validation sequences. + private static final Set HTTPS_POLICIES = + Set.of("REQUIRE", "REQUIRE_OPEN_ONLY", "OPTIONAL"); + private static final Set TLS_POLICIES = Set.of("REQUIRE", "OPTIONAL"); + + + void validateTrackingOptions(TrackingOptions options, Predicate verifiedDomainIdentity) { + Objects.requireNonNull(verifiedDomainIdentity, "verifiedDomainIdentity probe is required"); + if (options == null) { + return; + } + String domain = options.getCustomRedirectDomain(); + String httpsPolicy = options.getHttpsPolicy(); + // AWS validation order (verified against real AWS 2026-06-17): a present + // CustomRedirectDomain must be non-blank, and it is required whenever + // HttpsPolicy is set; then the domain must be a verified domain identity + // (checked even without HttpsPolicy); then HttpsPolicy must be a valid enum. + if ((domain != null && domain.isBlank()) || (httpsPolicy != null && domain == null)) { + throw new AwsException("BadRequestException", + "CustomRedirectDomain must be specified.", 400); + } + if (domain != null && !verifiedDomainIdentity.test(domain)) { + throw new AwsException("BadRequestException", + "Domain <" + domain + "> is not verified under this account.", 400); + } + if (httpsPolicy != null && !HTTPS_POLICIES.contains(httpsPolicy)) { + throw new AwsException("BadRequestException", + "1 validation error detected: Value at 'httpsPolicy' failed to satisfy constraint: " + + "Member must satisfy enum value set: [OPTIONAL, REQUIRE, REQUIRE_OPEN_ONLY]", 400); + } + } + + void validateDeliveryOptions(DeliveryOptions options, Predicate dedicatedIpPoolExists) { + Objects.requireNonNull(dedicatedIpPoolExists, "dedicatedIpPoolExists probe is required"); + if (options == null) { + return; + } + if (options.getTlsPolicy() != null && !TLS_POLICIES.contains(options.getTlsPolicy())) { + throw new AwsException("BadRequestException", + "1 validation error detected: Value at 'tlsPolicy' failed to satisfy constraint: " + + "Member must satisfy enum value set: [OPTIONAL, REQUIRE]", 400); + } + // AWS rejects a blank SendingPoolName outright, and a non-existent + // dedicated IP pool (both verified against real AWS 2026-06-17). The + // pool must have been created via CreateDedicatedIpPool. + if (options.getSendingPoolName() != null) { + if (options.getSendingPoolName().isBlank()) { + throw new AwsException("BadRequestException", + "sendingPoolName can't be blank.", 400); + } + if (!dedicatedIpPoolExists.test(options.getSendingPoolName())) { + throw new AwsException("BadRequestException", + "SendingPool <" + options.getSendingPoolName() + "> doesn't exist", 400); + } + } + // AWS constrains MaxDeliverySeconds to [300, 50400] (max verified against + // real AWS 2026-06-17; min follows the same smithy range-constraint shape). + if (options.getMaxDeliverySeconds() != null) { + long maxDeliverySeconds = options.getMaxDeliverySeconds(); + if (maxDeliverySeconds < 300) { + throw new AwsException("BadRequestException", + "1 validation error detected: Value at 'maxDeliverySeconds' failed to satisfy constraint: " + + "Member must have value greater than or equal to 300", 400); + } + if (maxDeliverySeconds > 50400) { + throw new AwsException("BadRequestException", + "1 validation error detected: Value at 'maxDeliverySeconds' failed to satisfy constraint: " + + "Member must have value less than or equal to 50400", 400); + } + } + } + + void requireVerifiedRedirectDomain(String domain, Predicate verifiedDomainIdentity) { + Objects.requireNonNull(verifiedDomainIdentity, "verifiedDomainIdentity probe is required"); + if (domain == null) { + throw new AwsException("ValidationError", + "1 validation error detected: Value at 'trackingOptions' failed to satisfy constraint: " + + "Member must not be null", 400); + } + if (domain.isBlank()) { + throw new AwsException("InvalidTrackingOptions", + "At least one field of TrackingOptions must contain a value.", 400); + } + if (!verifiedDomainIdentity.test(domain)) { + throw new AwsException("InvalidTrackingOptions", + "Domain <" + domain + "> is not verified under this account.", 400); + } + } + + /** v2 PutConfigurationSetTrackingOptions: validated replace of the tracking options. */ + public void setTrackingOptions(String configSetName, TrackingOptions options, String region, + Predicate verifiedDomainIdentity) { + ConfigurationSet cs = get(configSetName, region); + validateTrackingOptions(options, verifiedDomainIdentity); + cs.setTrackingOptions(options); + save(cs, region); + LOG.infov("Updated TrackingOptions on configuration set {0} in region {1}", configSetName, region); + } + + /** v2 PutConfigurationSetDeliveryOptions: validated replace of the delivery options. */ + public void setDeliveryOptions(String configSetName, DeliveryOptions options, String region, + Predicate dedicatedIpPoolExists) { + ConfigurationSet cs = get(configSetName, region); + validateDeliveryOptions(options, dedicatedIpPoolExists); + cs.setDeliveryOptions(options); + save(cs, region); + LOG.infov("Updated DeliveryOptions on configuration set {0} in region {1}", configSetName, region); + } + + /** v1 CreateConfigurationSetTrackingOptions: rejects a set that already has a redirect domain. */ + public void createTrackingOptions(String configSetName, String customRedirectDomain, String region, + Predicate verifiedDomainIdentity) { + requireVerifiedRedirectDomain(customRedirectDomain, verifiedDomainIdentity); + ConfigurationSet cs = get(configSetName, region); + if (cs.getTrackingOptions() != null && cs.getTrackingOptions().getCustomRedirectDomain() != null) { + throw new AwsException("TrackingOptionsAlreadyExistsException", + "Configuration set <" + configSetName + "> already has tracking options.", 400); + } + TrackingOptions options = new TrackingOptions(); + options.setCustomRedirectDomain(customRedirectDomain); + cs.setTrackingOptions(options); + save(cs, region); + LOG.infov("Created TrackingOptions on configuration set {0} in region {1}", configSetName, region); + } + + /** v1 UpdateConfigurationSetTrackingOptions: requires existing tracking options. */ + public void updateTrackingOptions(String configSetName, String customRedirectDomain, String region, + Predicate verifiedDomainIdentity) { + requireVerifiedRedirectDomain(customRedirectDomain, verifiedDomainIdentity); + ConfigurationSet cs = get(configSetName, region); + if (cs.getTrackingOptions() == null || cs.getTrackingOptions().getCustomRedirectDomain() == null) { + throw new AwsException("TrackingOptionsDoesNotExistException", + "There are no tracking options for configuration set <" + configSetName + ">", 400); + } + cs.getTrackingOptions().setCustomRedirectDomain(customRedirectDomain); + save(cs, region); + LOG.infov("Updated TrackingOptions on configuration set {0} in region {1}", configSetName, region); + } + /** The ARN-dispatched tag operations, sharing the store behind {@code CreateConfigurationSet.Tags}. */ public List listTags(String name, String region) { return new ArrayList<>(requireForTags(name, region).getTags()); @@ -166,7 +344,7 @@ public class SesConfigurationSetService { return configSetStore.get(configSetKey(region, name)); } - /** Persists a configuration set the facade mutated (the cross-domain option setters). */ + /** Persists a configuration set mutated by an orchestration that holds the loaded record. */ public void save(ConfigurationSet configSet, String region) { configSetStore.put(configSetKey(region, configSet.getName()), configSet); } @@ -220,7 +398,7 @@ public class SesConfigurationSetService { LOG.infov("Updated VdmOptions on configuration set {0} in region {1}", configSetName, region); } - static void validateVdmOptions(VdmOptions options) { + private static void validateVdmOptions(VdmOptions options) { if (options == null) { return; } @@ -284,11 +462,11 @@ public class SesConfigurationSetService { } } - static boolean isValidSuppressionReason(String reason) { + private static boolean isValidSuppressionReason(String reason) { return "BOUNCE".equals(reason) || "COMPLAINT".equals(reason); } - static String invalidSuppressionReasonMessage(String reason) { + private static String invalidSuppressionReasonMessage(String reason) { return "Reason " + reason + " is invalid, must be one of [BOUNCE, COMPLAINT]."; } @@ -460,7 +638,7 @@ public class SesConfigurationSetService { return count; } - static void validateConfigurationSetName(String name) { + private static void validateConfigurationSetName(String name) { if (name == null || name.isBlank()) { throw new AwsException("InvalidParameterValue", "ConfigurationSetName is required.", 400); 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 index fea8d2495e..87855be41b 100644 --- a/src/main/java/io/github/hectorvent/floci/services/ses/SesContactService.java +++ b/src/main/java/io/github/hectorvent/floci/services/ses/SesContactService.java @@ -12,15 +12,19 @@ import io.github.hectorvent.floci.services.ses.model.TopicPreference; import jakarta.enterprise.context.ApplicationScoped; import jakarta.inject.Inject; import org.jboss.logging.Logger; +import io.github.hectorvent.floci.services.ses.model.ListManagementOptions; import java.time.Clock; import java.time.Instant; import java.util.ArrayList; +import java.util.Collection; import java.util.Comparator; import java.util.HashSet; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; +import java.util.Objects; +import java.util.function.UnaryOperator; import java.util.Set; import java.util.regex.Pattern; @@ -31,9 +35,9 @@ import java.util.regex.Pattern; *

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. + * ({@link #getOrAutoCreateContact}, {@link #isListManagementOptedOut}, {@link #unsubscribeContact}), + * including {@link #collectListManagementOptOuts}, which resolves a send's opted-out recipients + * with the facade's address extractor injected as a callback. */ @ApplicationScoped public class SesContactService { @@ -623,4 +627,52 @@ public class SesContactService { } contact.setTopicPreferences(prefs); } + + /** + * Resolves the recipients suppressed by SES V2 {@code SendEmail} {@code ListManagementOptions}: + * for each envelope recipient that is opted out of the named contact list (or the given topic), + * returns a {@code BOUNCE} suppression reason so the shared send path drops the recipient from + * the relay and publishes a Bounce event, matching AWS ("SES will issue a bounce event for a + * message that is sent to an unsubscribed contact"). Returns an empty map when no + * {@code ListManagementOptions} was supplied. The display-name stripping is the facade's shared + * send helper, injected as {@code addressExtractor} so this service stays free of facade + * dependencies. Throws when the contact list does not exist, so a + * bad reference fails the whole send. A recipient that is not yet a contact is created + * automatically (matching AWS), then evaluated like any other contact. + */ + public Map collectListManagementOptOuts(Collection addresses, + ListManagementOptions listManagement, String region, + UnaryOperator addressExtractor) { + Objects.requireNonNull(addressExtractor, "addressExtractor is required"); + if (listManagement == null || listManagement.contactListName() == null + || listManagement.contactListName().isBlank() || addresses == null || addresses.isEmpty()) { + return Map.of(); + } + ContactList list = 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) { + throw new AwsException("BadRequestException", + "Topic " + effectiveTopic + " does not exist in contact list " + + list.getContactListName() + ".", 400); + } + Map optOuts = new LinkedHashMap<>(); + for (String address : addresses) { + if (address == null || address.isBlank() || optOuts.containsKey(address)) { + continue; + } + String email = addressExtractor.apply(address); + if (email == null || email.isBlank()) { + continue; + } + Contact contact = getOrAutoCreateContact(list, email, region); + if (isListManagementOptedOut(contact, list, effectiveTopic)) { + optOuts.put(address, "BOUNCE"); + } + } + return optOuts; + } } 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 8d5acf1b73..3ad3ab715b 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 @@ -242,7 +242,8 @@ public class SesService { collectSuppressedReasons(envelope, effectiveConfigSet, region)); // putIfAbsent so a suppression-list reason already set for an address (e.g. COMPLAINT) wins // over the list-management BOUNCE and keeps its synthetic event type. - collectListManagementOptOuts(envelope, listManagement, region).forEach(suppressedReasons::putIfAbsent); + contactService.collectListManagementOptOuts(envelope, listManagement, region, + SesService::extractEmailAddress).forEach(suppressedReasons::putIfAbsent); // A single-recipient list-managed send gets a functional unsubscribe link: the // {{amazonSESUnsubscribeUrl}} body placeholder is replaced and the List-Unsubscribe headers @@ -335,7 +336,8 @@ public class SesService { collectSuppressedReasons(effectiveDestinations, effectiveConfigSet, region)); // putIfAbsent so a suppression-list reason already set for an address (e.g. COMPLAINT) wins // over the list-management BOUNCE and keeps its synthetic event type. - collectListManagementOptOuts(effectiveDestinations, listManagement, region) + contactService.collectListManagementOptOuts(effectiveDestinations, listManagement, region, + SesService::extractEmailAddress) .forEach(suppressedReasons::putIfAbsent); String messageId = UUID.randomUUID().toString(); @@ -876,53 +878,22 @@ public class SesService { } public ConfigurationSet createConfigurationSet(ConfigurationSet configSet, String region) { - if (configSet == null) { - throw new AwsException("InvalidParameterValue", - "ConfigurationSetName is required.", 400); - } - SesConfigurationSetService.validateConfigurationSetName(configSet.getName()); - SesTags.validate(configSet.getTags()); - if (configSet.getSuppressionOptions() != null - && configSet.getSuppressionOptions().getSuppressedReasons() != null) { - for (String reason : configSet.getSuppressionOptions().getSuppressedReasons()) { - if (reason == null) { - throw new AwsException("BadRequestException", - SesConfigurationSetService.invalidSuppressionReasonMessage(null), 400); - } - if (!SesConfigurationSetService.isValidSuppressionReason(reason)) { - throw new AwsException("BadRequestException", - "1 validation error detected: Value at " - + "'suppressionOptions.suppressedReasons' failed to satisfy " - + "constraint: Member must satisfy constraint: " - + "[Member must satisfy enum value set: [BOUNCE, COMPLAINT]]", - 400); - } - } - } - validateTrackingOptions(configSet.getTrackingOptions(), region); - validateDeliveryOptions(configSet.getDeliveryOptions(), region); - SesConfigurationSetService.validateVdmOptions(configSet.getVdmOptions()); - return configSetService.create(configSet, region); + return configSetService.createConfigurationSet(configSet, region, + domain -> isVerifiedDomainIdentity(domain, region), + pool -> dedicatedIpPoolExists(pool, region)); } - // The tracking and delivery setters stay here: their validation reads other domains (a verified - // domain identity, a dedicated IP pool), so the facade resolves existence through the service, - // validates, and writes back through save. + // The option operations live in the service; the facade only supplies the cross-domain probes + // (a verified domain identity, a dedicated IP pool) as predicates. public void setConfigurationSetTrackingOptions(String configSetName, TrackingOptions options, String region) { - ConfigurationSet cs = configSetService.get(configSetName, region); - validateTrackingOptions(options, region); - cs.setTrackingOptions(options); - configSetService.save(cs, region); - LOG.infov("Updated TrackingOptions on configuration set {0} in region {1}", configSetName, region); + configSetService.setTrackingOptions(configSetName, options, region, + domain -> isVerifiedDomainIdentity(domain, region)); } public void setConfigurationSetDeliveryOptions(String configSetName, DeliveryOptions options, String region) { - ConfigurationSet cs = configSetService.get(configSetName, region); - validateDeliveryOptions(options, region); - cs.setDeliveryOptions(options); - configSetService.save(cs, region); - LOG.infov("Updated DeliveryOptions on configuration set {0} in region {1}", configSetName, region); + configSetService.setDeliveryOptions(configSetName, options, region, + pool -> dedicatedIpPoolExists(pool, region)); } public void setConfigurationSetReputationOptions(String configSetName, boolean metricsEnabled, String region) { @@ -935,48 +906,16 @@ public class SesService { && "Domain".equals(identity.getIdentityType()); } - private void requireVerifiedRedirectDomain(String domain, String region) { - if (domain == null) { - throw new AwsException("ValidationError", - "1 validation error detected: Value at 'trackingOptions' failed to satisfy constraint: " - + "Member must not be null", 400); - } - if (domain.isBlank()) { - throw new AwsException("InvalidTrackingOptions", - "At least one field of TrackingOptions must contain a value.", 400); - } - if (!isVerifiedDomainIdentity(domain, region)) { - throw new AwsException("InvalidTrackingOptions", - "Domain <" + domain + "> is not verified under this account.", 400); - } - } - public void createConfigurationSetTrackingOptions(String configSetName, String customRedirectDomain, String region) { - requireVerifiedRedirectDomain(customRedirectDomain, region); - ConfigurationSet cs = configSetService.get(configSetName, region); - if (cs.getTrackingOptions() != null && cs.getTrackingOptions().getCustomRedirectDomain() != null) { - throw new AwsException("TrackingOptionsAlreadyExistsException", - "Configuration set <" + configSetName + "> already has tracking options.", 400); - } - TrackingOptions options = new TrackingOptions(); - options.setCustomRedirectDomain(customRedirectDomain); - cs.setTrackingOptions(options); - configSetService.save(cs, region); - LOG.infov("Created TrackingOptions on configuration set {0} in region {1}", configSetName, region); + configSetService.createTrackingOptions(configSetName, customRedirectDomain, region, + domain -> isVerifiedDomainIdentity(domain, region)); } public void updateConfigurationSetTrackingOptions(String configSetName, String customRedirectDomain, String region) { - requireVerifiedRedirectDomain(customRedirectDomain, region); - ConfigurationSet cs = configSetService.get(configSetName, region); - if (cs.getTrackingOptions() == null || cs.getTrackingOptions().getCustomRedirectDomain() == null) { - throw new AwsException("TrackingOptionsDoesNotExistException", - "There are no tracking options for configuration set <" + configSetName + ">", 400); - } - cs.getTrackingOptions().setCustomRedirectDomain(customRedirectDomain); - configSetService.save(cs, region); - LOG.infov("Updated TrackingOptions on configuration set {0} in region {1}", configSetName, region); + configSetService.updateTrackingOptions(configSetName, customRedirectDomain, region, + domain -> isVerifiedDomainIdentity(domain, region)); } public void deleteConfigurationSetTrackingOptions(String configSetName, String region) { @@ -991,74 +930,6 @@ public class SesService { configSetService.setVdmOptions(configSetName, options, region); } - private static final java.util.Set HTTPS_POLICIES = - java.util.Set.of("REQUIRE", "REQUIRE_OPEN_ONLY", "OPTIONAL"); - private static final java.util.Set TLS_POLICIES = java.util.Set.of("REQUIRE", "OPTIONAL"); - - private void validateTrackingOptions(TrackingOptions options, String region) { - if (options == null) { - return; - } - String domain = options.getCustomRedirectDomain(); - String httpsPolicy = options.getHttpsPolicy(); - // AWS validation order (verified against real AWS 2026-06-17): a present - // CustomRedirectDomain must be non-blank, and it is required whenever - // HttpsPolicy is set; then the domain must be a verified domain identity - // (checked even without HttpsPolicy); then HttpsPolicy must be a valid enum. - if ((domain != null && domain.isBlank()) || (httpsPolicy != null && domain == null)) { - throw new AwsException("BadRequestException", - "CustomRedirectDomain must be specified.", 400); - } - if (domain != null && !isVerifiedDomainIdentity(domain, region)) { - throw new AwsException("BadRequestException", - "Domain <" + domain + "> is not verified under this account.", 400); - } - if (httpsPolicy != null && !HTTPS_POLICIES.contains(httpsPolicy)) { - throw new AwsException("BadRequestException", - "1 validation error detected: Value at 'httpsPolicy' failed to satisfy constraint: " - + "Member must satisfy enum value set: [OPTIONAL, REQUIRE, REQUIRE_OPEN_ONLY]", 400); - } - } - - private void validateDeliveryOptions(DeliveryOptions options, String region) { - if (options == null) { - return; - } - if (options.getTlsPolicy() != null && !TLS_POLICIES.contains(options.getTlsPolicy())) { - throw new AwsException("BadRequestException", - "1 validation error detected: Value at 'tlsPolicy' failed to satisfy constraint: " - + "Member must satisfy enum value set: [OPTIONAL, REQUIRE]", 400); - } - // AWS rejects a blank SendingPoolName outright, and a non-existent - // dedicated IP pool (both verified against real AWS 2026-06-17). The - // pool must have been created via CreateDedicatedIpPool. - if (options.getSendingPoolName() != null) { - if (options.getSendingPoolName().isBlank()) { - throw new AwsException("BadRequestException", - "sendingPoolName can't be blank.", 400); - } - if (!dedicatedIpPoolExists(options.getSendingPoolName(), region)) { - throw new AwsException("BadRequestException", - "SendingPool <" + options.getSendingPoolName() + "> doesn't exist", 400); - } - } - // AWS constrains MaxDeliverySeconds to [300, 50400] (max verified against - // real AWS 2026-06-17; min follows the same smithy range-constraint shape). - if (options.getMaxDeliverySeconds() != null) { - long maxDeliverySeconds = options.getMaxDeliverySeconds(); - if (maxDeliverySeconds < 300) { - throw new AwsException("BadRequestException", - "1 validation error detected: Value at 'maxDeliverySeconds' failed to satisfy constraint: " - + "Member must have value greater than or equal to 300", 400); - } - if (maxDeliverySeconds > 50400) { - throw new AwsException("BadRequestException", - "1 validation error detected: Value at 'maxDeliverySeconds' failed to satisfy constraint: " - + "Member must have value less than or equal to 50400", 400); - } - } - } - public ConfigurationSet getConfigurationSet(String name, String region) { return configSetService.get(name, region); } @@ -1744,50 +1615,6 @@ public class SesService { return result; } - /** - * Resolves the recipients suppressed by SES V2 {@code SendEmail} {@code ListManagementOptions}: - * for each envelope recipient that is opted out of the named contact list (or the given topic), - * returns a {@code BOUNCE} suppression reason so the shared send path drops the recipient from - * the relay and publishes a Bounce event — matching AWS ("SES will issue a bounce event for a - * message that is sent to an unsubscribed contact"). Returns an empty map when no - * {@code ListManagementOptions} was supplied. Throws when the contact list does not exist, so a - * bad reference fails the whole send. A recipient that is not yet a contact is created - * automatically (matching AWS), then evaluated like any other contact. - */ - private Map collectListManagementOptOuts(Collection addresses, - ListManagementOptions listManagement, String region) { - if (listManagement == null || listManagement.contactListName() == null - || listManagement.contactListName().isBlank() || addresses == null || addresses.isEmpty()) { - return Map.of(); - } - 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 && contactService.defaultTopicStatus(list, effectiveTopic) == null) { - throw new AwsException("BadRequestException", - "Topic " + effectiveTopic + " does not exist in contact list " - + list.getContactListName() + ".", 400); - } - Map optOuts = new LinkedHashMap<>(); - for (String address : addresses) { - if (address == null || address.isBlank() || optOuts.containsKey(address)) { - continue; - } - String email = extractEmailAddress(address); - if (email == null || email.isBlank()) { - continue; - } - Contact contact = contactService.getOrAutoCreateContact(list, email, region); - if (contactService.isListManagementOptedOut(contact, list, effectiveTopic)) { - optOuts.put(address, "BOUNCE"); - } - } - return optOuts; - } - private static final String UNSUBSCRIBE_PLACEHOLDER = "{{amazonSESUnsubscribeUrl}}"; private static boolean hasListManagement(ListManagementOptions listManagement) { diff --git a/src/test/java/io/github/hectorvent/floci/services/ses/SesConfigurationSetServiceTest.java b/src/test/java/io/github/hectorvent/floci/services/ses/SesConfigurationSetServiceTest.java index 9f5d6f063f..c9e6c84d5e 100644 --- a/src/test/java/io/github/hectorvent/floci/services/ses/SesConfigurationSetServiceTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/ses/SesConfigurationSetServiceTest.java @@ -3,6 +3,8 @@ 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.ConfigurationSet; +import io.github.hectorvent.floci.services.ses.model.DeliveryOptions; +import io.github.hectorvent.floci.services.ses.model.TrackingOptions; import io.github.hectorvent.floci.services.ses.model.Tag; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -119,4 +121,63 @@ class SesConfigurationSetServiceTest { AwsException e = assertThrows(AwsException.class, () -> service.listTags("ghost", REGION)); assertEquals("No ConfigurationSet present with name: ghost", e.getMessage()); } + + @Test + void validateTrackingOptions_orderAndPredicate() { + TrackingOptions blankDomain = new TrackingOptions(); + blankDomain.setCustomRedirectDomain(" "); + assertEquals("CustomRedirectDomain must be specified.", + assertThrows(AwsException.class, () -> service.validateTrackingOptions( + blankDomain, domain -> true)).getMessage()); + + TrackingOptions unverified = new TrackingOptions(); + unverified.setCustomRedirectDomain("example.com"); + assertEquals("Domain is not verified under this account.", + assertThrows(AwsException.class, () -> service.validateTrackingOptions( + unverified, domain -> false)).getMessage()); + + // The verified-domain probe is injected; a passing predicate reaches the enum check. + TrackingOptions badPolicy = new TrackingOptions(); + badPolicy.setCustomRedirectDomain("example.com"); + badPolicy.setHttpsPolicy("BOGUS"); + assertTrue(assertThrows(AwsException.class, () -> service.validateTrackingOptions( + badPolicy, domain -> true)).getMessage().contains("httpsPolicy")); + + badPolicy.setHttpsPolicy("REQUIRE"); + service.validateTrackingOptions(badPolicy, domain -> true); + service.validateTrackingOptions(null, domain -> { throw new AssertionError("not called"); }); + } + + @Test + void validateDeliveryOptions_orderAndPredicate() { + DeliveryOptions badTls = new DeliveryOptions(); + badTls.setTlsPolicy("BOGUS"); + assertTrue(assertThrows(AwsException.class, () -> service.validateDeliveryOptions( + badTls, pool -> true)).getMessage().contains("tlsPolicy")); + + DeliveryOptions missingPool = new DeliveryOptions(); + missingPool.setSendingPoolName("ghost-pool"); + assertEquals("SendingPool doesn't exist", + assertThrows(AwsException.class, () -> service.validateDeliveryOptions( + missingPool, pool -> false)).getMessage()); + service.validateDeliveryOptions(missingPool, pool -> true); + + DeliveryOptions tooFast = new DeliveryOptions(); + tooFast.setMaxDeliverySeconds(299L); + assertTrue(assertThrows(AwsException.class, () -> service.validateDeliveryOptions( + tooFast, pool -> true)).getMessage().contains("greater than or equal to 300")); + } + + @Test + void requireVerifiedRedirectDomain_nullBlankUnverified() { + assertTrue(assertThrows(AwsException.class, () -> service.requireVerifiedRedirectDomain( + null, domain -> true)).getMessage().contains("must not be null")); + assertEquals("At least one field of TrackingOptions must contain a value.", + assertThrows(AwsException.class, () -> service.requireVerifiedRedirectDomain( + " ", domain -> true)).getMessage()); + assertEquals("Domain is not verified under this account.", + assertThrows(AwsException.class, () -> service.requireVerifiedRedirectDomain( + "example.com", domain -> false)).getMessage()); + service.requireVerifiedRedirectDomain("example.com", domain -> true); + } } 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 index b1ea5b0854..f0e44cd200 100644 --- a/src/test/java/io/github/hectorvent/floci/services/ses/SesContactServiceTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/ses/SesContactServiceTest.java @@ -4,12 +4,14 @@ 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.ListManagementOptions; 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 java.util.Map; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertThrows; @@ -70,4 +72,24 @@ class SesContactServiceTest { Contact c = service.getContact(LIST, "bye@example.com", REGION).contact(); assertTrue(service.isListManagementOptedOut(c, list, null)); } + + @Test + void collectListManagementOptOuts_usesInjectedExtractor_flagsOptedOut() { + // Sports defaults to OPT_OUT (see setUp), so an auto-created contact is opted out of it. + Map optOuts = service.collectListManagementOptOuts( + List.of("Alice ", "", "Bob "), + new ListManagementOptions(LIST, "Sports"), REGION, + address -> address.substring(address.indexOf('<') + 1, address.indexOf('>'))); + // The ORIGINAL envelope strings key the result; the extractor only feeds the contact lookup. + assertEquals(Map.of("Alice ", "BOUNCE", "Bob ", "BOUNCE"), + optOuts); + + AwsException e = assertThrows(AwsException.class, () -> service.collectListManagementOptOuts( + List.of("alice@example.com"), new ListManagementOptions(LIST, "ghost-topic"), + REGION, address -> address)); + assertEquals("Topic ghost-topic does not exist in contact list news.", e.getMessage()); + + assertTrue(service.collectListManagementOptOuts( + List.of("alice@example.com"), null, REGION, address -> address).isEmpty()); + } }