diff --git a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/SesRecommendationTest.java b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/SesRecommendationTest.java new file mode 100644 index 0000000000..f5b1636195 --- /dev/null +++ b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/SesRecommendationTest.java @@ -0,0 +1,119 @@ +package com.floci.test; + +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; +import software.amazon.awssdk.services.sesv2.SesV2Client; +import software.amazon.awssdk.services.sesv2.model.BadRequestException; +import software.amazon.awssdk.services.sesv2.model.ListRecommendationsFilterKey; +import software.amazon.awssdk.services.sesv2.model.ListRecommendationsResponse; +import software.amazon.awssdk.services.sesv2.model.NotFoundException; +import software.amazon.awssdk.services.sesv2.model.PutAccountVdmAttributesRequest; +import software.amazon.awssdk.services.sesv2.model.Recommendation; +import software.amazon.awssdk.services.sesv2.model.RecommendationImpact; +import software.amazon.awssdk.services.sesv2.model.RecommendationStatus; +import software.amazon.awssdk.services.sesv2.model.RecommendationType; +import software.amazon.awssdk.services.sesv2.model.VdmAttributes; + +import java.util.List; +import java.util.Map; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +/** + * SDK compatibility test for SES v2 ListRecommendations. With Virtual Deliverability Manager enabled, a + * verified domain without DMARC or BIMI records gets a recommendation for each, described by SES's code + * rather than a sentence. + */ +@DisplayName("SES v2 Recommendations") +class SesRecommendationTest { + + private static final String DOMAIN = TestFixtures.uniqueName("compat-advisor") + ".example.com"; + + private static SesV2Client sesV2; + private static VdmAttributes originalVdm; + + @BeforeAll + static void setup() { + sesV2 = TestFixtures.sesV2Client(); + originalVdm = sesV2.getAccount(b -> { }).vdmAttributes(); + setVdmEnabled(true); + TestFixtures.verifySesDomainIdentityViaRoute53(sesV2, DOMAIN); + } + + @AfterAll + static void cleanup() { + if (sesV2 == null) { + return; + } + try { + sesV2.deleteEmailIdentity(b -> b.emailIdentity(DOMAIN)); + } catch (NotFoundException expected) { + // Setup failed before the identity existed; anything else (auth, connectivity) must surface. + } finally { + restoreVdm(); + } + } + + private static void setVdmEnabled(boolean enabled) { + sesV2.putAccountVdmAttributes(PutAccountVdmAttributesRequest.builder() + .vdmAttributes(VdmAttributes.builder() + .vdmEnabled(enabled ? "ENABLED" : "DISABLED") + .build()) + .build()); + } + + private static void restoreVdm() { + if (originalVdm == null || originalVdm.vdmEnabled() == null) { + setVdmEnabled(false); + return; + } + sesV2.putAccountVdmAttributes(PutAccountVdmAttributesRequest.builder() + .vdmAttributes(originalVdm) + .build()); + } + + private static List forDomain(ListRecommendationsResponse response) { + return response.recommendations().stream() + .filter(r -> r.resourceArn().endsWith(":identity/" + DOMAIN)) + .toList(); + } + + @Test + @DisplayName("A domain without DMARC and BIMI records gets both recommendations") + void listsDmarcAndBimi() { + List recommendations = forDomain(sesV2.listRecommendations(r -> r.pageSize(1000))); + + assertThat(recommendations).extracting(Recommendation::type) + .containsExactly(RecommendationType.BIMI, RecommendationType.DMARC); + assertThat(recommendations).extracting(Recommendation::description).containsExactly("BIMI1", "DMARC1"); + assertThat(recommendations).extracting(Recommendation::impact) + .containsExactly(RecommendationImpact.LOW, RecommendationImpact.HIGH); + assertThat(recommendations).extracting(Recommendation::status).containsOnly(RecommendationStatus.OPEN); + assertThat(recommendations).allSatisfy(r -> { + assertThat(r.createdTimestamp()).isNotNull(); + assertThat(r.lastUpdatedTimestamp()).isNotNull(); + }); + } + + @Test + @DisplayName("A TYPE filter narrows the list") + void filtersByType() { + List recommendations = forDomain(sesV2.listRecommendations(r -> r + .filter(Map.of(ListRecommendationsFilterKey.TYPE, "DMARC")) + .pageSize(1000))); + + assertThat(recommendations).extracting(Recommendation::description).containsExactly("DMARC1"); + } + + @Test + @DisplayName("An unknown TYPE value is refused") + void refusesUnknownType() { + assertThatThrownBy(() -> sesV2.listRecommendations(r -> r + .filter(Map.of(ListRecommendationsFilterKey.TYPE, "NOPE")))) + .isInstanceOf(BadRequestException.class) + .hasMessageContaining("Invalid recommendation TYPE specified"); + } +} diff --git a/docs/services/ses.md b/docs/services/ses.md index 8cd5e73cdd..7ed77760ac 100644 --- a/docs/services/ses.md +++ b/docs/services/ses.md @@ -426,6 +426,7 @@ Alongside the classic Query API, Floci implements a subset of the SES v2 REST JS | `PUT` | `/v2/email/reputation/entities/{ReputationEntityType}/{ReputationEntityReference}/policy` | `UpdateReputationEntityPolicy` | | `PUT` | `/v2/email/reputation/entities/{ReputationEntityType}/{ReputationEntityReference}/customer-managed-status` | `UpdateReputationEntityCustomerManagedStatus` | | `POST` | `/v2/email/email-address-insights/` | `GetEmailAddressInsights` | +| `POST` | `/v2/email/vdm/recommendations` | `ListRecommendations` | Floci models no leased dedicated IPs: `GetDedicatedIps` is empty and IP-targeted operations return `NotFoundException`, as real AWS does for an account with no leased IPs, with required request members validated first (`BadRequestException`). `PutDedicatedIpPoolScalingAttributes` rejects downgrading a `MANAGED` pool to `STANDARD`, and `PutAccountDedicatedIpWarmupAttributes` stores the flag behind `GetAccount.DedicatedIpAutoWarmupEnabled` (default `true`). @@ -523,9 +524,13 @@ S/MIME certificate associations are stored per region and never used: Floci does Deviations from AWS: `IsValid` is `HIGH` whenever it is not `LOW` and never `MEDIUM`, although AWS documents a `MEDIUM` overall verdict too (no probed address returned one), every domain that is not reserved is taken to have valid DNS records, Floci keeps no disposable-domain list and detects no random input, and an address with a non-ASCII character in its domain (an internationalized domain name included) or in an unquoted local part is rated `LOW` everywhere, as a send would reject it, while a quoted local part, which a send does not inspect, is rated like any other; AWS's verdicts for such addresses were not probed. +[`ListRecommendations`](https://docs.aws.amazon.com/ses/latest/dg/vdm-advisor.html) is derived on every call from the region's verified domain identities, with the TXT records in Route53 hosted zones standing in for public DNS, as for DKIM detection. As on AWS, a region without Virtual Deliverability Manager enabled answers an empty list rather than an error, and a `TYPE` filter makes an `IMPACT` filter sent with it ignored. Floci raises `DKIM1` when DKIM signing is disabled, `DKIM3` when Easy DKIM signs with a 1024-bit key, `DMARC1` without a TXT record at `_dmarc.`, and `BIMI1` without one at `default._bimi.`. + +Deviations from AWS: Floci keeps no recommendation history, so every recommendation is `OPEN`, one whose condition clears disappears instead of turning `FIXED`, `CreatedTimestamp` is the identity's creation time and `LastUpdatedTimestamp` the time of the request, and a change shows at once where AWS takes up to six hours. Floci never raises `DKIM2` (DKIM verification failed), as its DKIM status never reaches `FAILED`, nor the codes no probe could tie to a condition (`DMARC5` among them), nor `SPF`, `COMPLAINT`, `BOUNCE`, `FEEDBACK_3P`, `IP_LISTING` or AWS's `ENGAGEMENT` announcements. Which other filter combinations AWS accepts was not probed: Floci applies them all, and validates the request before checking Virtual Deliverability Manager. Also unprobed, and Floci's choice: any TXT record at `_dmarc.` or `default._bimi.` clears its finding whatever it holds, a `RESOURCE_ARN` filter matches the identity's ARN exactly, the domain's case included, an SES ARN with no account is not taken for another account's and simply matches nothing, and a `NextToken` is refused (`Failed to deserialize token.`) once the filter differs from the one it came from, as in Floci's other filtered SES v2 lists. + ### Request member types -The operations whose body nests a structure in a structure, or holds a list of structures, check the request body against the SES v2 service model before anything else is validated, as AWS's restJson1 deserializer does: the send operations (`SendEmail`, `SendBulkEmail`, `SendCustomVerificationEmail`), `CreateConfigurationSet`, `UpdateConfigurationSet`, `PutConfigurationSetSuppressionOptions`, `PutConfigurationSetVdmOptions`, `CreateConfigurationSetEventDestination`, `UpdateConfigurationSetEventDestination`, `CreateContactList`, `UpdateContactList`, `CreateContact`, `UpdateContact`, `ListContacts`, `PutAccountSuppressionAttributes`, `PutAccountVdmAttributes`, `BatchGetMetricData`, `CreateImportJob` and `CreateExportJob`. `ListReputationEntities`, `UpdateReputationEntityPolicy`, `UpdateReputationEntityCustomerManagedStatus` and `GetEmailAddressInsights` run the same check although their bodies are flat. In those operations, the first body member of the wrong JSON type, in body order, is a `SerializationException` with AWS's deserializer message: +The operations whose body nests a structure in a structure, or holds a list of structures, check the request body against the SES v2 service model before anything else is validated, as AWS's restJson1 deserializer does: the send operations (`SendEmail`, `SendBulkEmail`, `SendCustomVerificationEmail`), `CreateConfigurationSet`, `UpdateConfigurationSet`, `PutConfigurationSetSuppressionOptions`, `PutConfigurationSetVdmOptions`, `CreateConfigurationSetEventDestination`, `UpdateConfigurationSetEventDestination`, `CreateContactList`, `UpdateContactList`, `CreateContact`, `UpdateContact`, `ListContacts`, `PutAccountSuppressionAttributes`, `PutAccountVdmAttributes`, `BatchGetMetricData`, `CreateImportJob` and `CreateExportJob`. `ListReputationEntities`, `UpdateReputationEntityPolicy`, `UpdateReputationEntityCustomerManagedStatus`, `GetEmailAddressInsights` and `ListRecommendations` run the same check although their bodies are flat. In those operations, the first body member of the wrong JSON type, in body order, is a `SerializationException` with AWS's deserializer message: | Member type | Value sent | Message | |---|---|---| diff --git a/src/main/java/io/github/hectorvent/floci/core/common/ResolvedServiceCatalog.java b/src/main/java/io/github/hectorvent/floci/core/common/ResolvedServiceCatalog.java index cf48cfce21..6bde43c81f 100644 --- a/src/main/java/io/github/hectorvent/floci/core/common/ResolvedServiceCatalog.java +++ b/src/main/java/io/github/hectorvent/floci/core/common/ResolvedServiceCatalog.java @@ -88,6 +88,7 @@ import io.github.hectorvent.floci.services.ses.SesIdentityController; import io.github.hectorvent.floci.services.ses.SesImportJobController; import io.github.hectorvent.floci.services.ses.SesInsightsController; import io.github.hectorvent.floci.services.ses.SesMetricsController; +import io.github.hectorvent.floci.services.ses.SesRecommendationController; import io.github.hectorvent.floci.services.ses.SesReputationEntityController; import io.github.hectorvent.floci.services.ses.SesSendController; import io.github.hectorvent.floci.services.ses.SesSuppressionController; @@ -351,7 +352,8 @@ public class ResolvedServiceCatalog { SesDedicatedIpController.class, SesExportJobController.class, SesIdentityController.class, SesInsightsController.class, SesMetricsController.class, - SesReputationEntityController.class, SesSendController.class, + SesRecommendationController.class, SesReputationEntityController.class, + SesSendController.class, SesSuppressionController.class, SesTagController.class, SesTemplateController.class, SesImportJobController.class, SesTenantController.class)), 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 index 298818725a..4010c05072 100644 --- a/src/main/java/io/github/hectorvent/floci/services/ses/SesAccountService.java +++ b/src/main/java/io/github/hectorvent/floci/services/ses/SesAccountService.java @@ -86,6 +86,10 @@ public class SesAccountService { LOG.infov("Updated account VDM attributes for region {0}: enabled={1}", region, vdm.vdmEnabled()); } + public boolean isVdmEnabled(String region) { + return findAccountVdmAttributes(region).map(AccountVdmAttributes::vdmEnabled).orElse(false); + } + /** The probe-confirmed gate the VDM-only operations check before reading the request. */ public void requireVdmEnabled(String region) { requireVdmEnabled(region, "NotFoundException", 404); @@ -97,8 +101,7 @@ public class SesAccountService { * the identical sentence, all probe-confirmed. */ public void requireVdmEnabled(String region, String errorCode, int status) { - Optional vdm = findAccountVdmAttributes(region); - if (vdm.isEmpty() || !vdm.get().vdmEnabled()) { + if (!isVdmEnabled(region)) { throw new AwsException(errorCode, "To use this feature you must enable Virtual Deliverability Manager", status); } diff --git a/src/main/java/io/github/hectorvent/floci/services/ses/SesIdentityService.java b/src/main/java/io/github/hectorvent/floci/services/ses/SesIdentityService.java index 00fb7df524..40f0a23f84 100644 --- a/src/main/java/io/github/hectorvent/floci/services/ses/SesIdentityService.java +++ b/src/main/java/io/github/hectorvent/floci/services/ses/SesIdentityService.java @@ -30,6 +30,8 @@ import java.util.Optional; import java.util.Set; import java.util.UUID; import java.util.concurrent.ConcurrentHashMap; +import java.util.stream.Collectors; +import java.util.stream.Stream; /** * Email and domain identities, extracted from {@link SesService} as the last store of the @@ -258,7 +260,7 @@ public class SesIdentityService implements SesTaggable { } /** Only a domain that is not yet verified can still change status, through its DKIM records. */ - private Identity withCurrentStatus(Identity identity, String region) { + Identity withCurrentStatus(Identity identity, String region) { if ("Domain".equals(identity.getIdentityType()) && !"Success".equals(identity.getVerificationStatus())) { Identity refreshed = refreshIdentityState(identity, region); return refreshed == null ? identity : refreshed; @@ -774,30 +776,47 @@ public class SesIdentityService implements SesTaggable { private boolean hasExpectedDkimRecord(String domain, String token) { String expectedName = normalizeDnsName(token + "._domainkey." + domain); String expectedValue = normalizeDnsName(token + "." + DKIM_SIGNING_HOSTED_ZONE); - for (HostedZone zone : route53Service.listHostedZones(null, Integer.MAX_VALUE)) { - for (ResourceRecordSet recordSet : route53Service.listResourceRecordSets(zone.getId(), null, null, - Integer.MAX_VALUE)) { - if (!"CNAME".equalsIgnoreCase(recordSet.getType())) { - continue; - } - if (!expectedName.equals(normalizeDnsName(recordSet.getName()))) { - continue; - } - List records = recordSet.getRecords(); - if (records == null) { - continue; - } - for (ResourceRecord record : records) { - if (record != null && expectedValue.equals(normalizeDnsName(record.getValue()))) { - return true; - } - } - } - } - return false; + return recordSets("CNAME") + .filter(recordSet -> expectedName.equals(normalizeDnsName(recordSet.getName()))) + .anyMatch(recordSet -> recordSet.getRecords() != null && recordSet.getRecords().stream() + .anyMatch(record -> record != null + && expectedValue.equals(normalizeDnsName(record.getValue())))); } - private String normalizeDnsName(String value) { + /** + * The names of the TXT record sets in every Route53 hosted zone, normalized as by + * {@link #normalizeDnsName}: the stand-in for the public DNS lookups SES makes. Empty while DNS + * lookup is disabled. + */ + Set txtRecordNames() { + if (route53Service == null) { + return Set.of(); + } + return recordSets("TXT").map(recordSet -> normalizeDnsName(recordSet.getName())) + .collect(Collectors.toSet()); + } + + /** Zone by zone, so a lookup that finds its record reads no further zones. */ + private Stream recordSets(String type) { + return route53Service.listHostedZones(null, Integer.MAX_VALUE).stream() + .flatMap(zone -> zoneRecordSets(zone.getId()).stream()) + .filter(recordSet -> type.equalsIgnoreCase(recordSet.getType())); + } + + /** A zone deleted after the zones were listed holds no records rather than failing the SES call. */ + private List zoneRecordSets(String zoneId) { + try { + return route53Service.listResourceRecordSets(zoneId, null, null, Integer.MAX_VALUE); + } catch (AwsException e) { + if (!"NoSuchHostedZone".equals(e.getErrorCode())) { + throw e; + } + LOG.debugv("Hosted zone {0} was deleted during an SES DNS lookup; skipping it", zoneId); + return List.of(); + } + } + + static String normalizeDnsName(String value) { if (value == null) { return ""; } @@ -818,7 +837,7 @@ public class SesIdentityService implements SesTaggable { private String dkimLookupCacheKey(String region, Identity identity) { List normalizedTokens = identity.getDkimTokens().stream() - .map(this::normalizeDnsName) + .map(SesIdentityService::normalizeDnsName) .sorted() .toList(); return region + "::" + normalizeDnsName(identity.getIdentity()) + "::" + String.join(",", normalizedTokens); diff --git a/src/main/java/io/github/hectorvent/floci/services/ses/SesListPaging.java b/src/main/java/io/github/hectorvent/floci/services/ses/SesListPaging.java index dc14ffa624..d26011f234 100644 --- a/src/main/java/io/github/hectorvent/floci/services/ses/SesListPaging.java +++ b/src/main/java/io/github/hectorvent/floci/services/ses/SesListPaging.java @@ -147,6 +147,12 @@ public enum SesListPaging { token -> badRequest("Failed to deserialize token. "), true), + /** Probed 2026-10-27: 68 recommendations came back as 50 and a token without a PageSize. */ + V2_LIST_RECOMMENDATIONS(Namespace.RECOMMENDATION, 50, 1000, + size -> badRequest("The PageSize should be between 1 and 1000"), + token -> badRequest("Failed to deserialize token."), + true), + /** * The request has no size member; the model documents "up to 100 receipt rule sets at a time". * SES allows 40 rule sets per region, so a second page could not be observed. @@ -173,6 +179,7 @@ public enum SesListPaging { static final String SUPPRESSED_DESTINATION = "suppressed-destination"; static final String RECEIPT_RULE_SET = "receipt-rule-set"; static final String REPUTATION_ENTITY = "reputation-entity"; + static final String RECOMMENDATION = "recommendation"; } /** What the tenant lists share, and ListImportJobs borrows: the bound and Smithy's messages. */ diff --git a/src/main/java/io/github/hectorvent/floci/services/ses/SesRecommendationController.java b/src/main/java/io/github/hectorvent/floci/services/ses/SesRecommendationController.java new file mode 100644 index 0000000000..5b597f0b87 --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/ses/SesRecommendationController.java @@ -0,0 +1,85 @@ +package io.github.hectorvent.floci.services.ses; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.node.ArrayNode; +import com.fasterxml.jackson.databind.node.ObjectNode; +import io.github.hectorvent.floci.core.common.PaginatedResult; +import io.github.hectorvent.floci.core.common.RegionResolver; +import io.github.hectorvent.floci.core.common.SmithyValidationErrors; +import io.github.hectorvent.floci.services.ses.SesRecommendationService.Recommendation; +import jakarta.inject.Inject; +import jakarta.ws.rs.Consumes; +import jakarta.ws.rs.POST; +import jakarta.ws.rs.Path; +import jakarta.ws.rs.Produces; +import jakarta.ws.rs.core.Context; +import jakarta.ws.rs.core.HttpHeaders; +import jakarta.ws.rs.core.MediaType; +import jakarta.ws.rs.core.Response; + +import java.util.List; +import java.util.Map; + +import static io.github.hectorvent.floci.services.ses.SesV2Json.filterValues; +import static io.github.hectorvent.floci.services.ses.SesV2Json.intMemberOrAbsent; +import static io.github.hectorvent.floci.services.ses.SesV2Json.putTimestamp; +import static io.github.hectorvent.floci.services.ses.SesV2Json.readOptionBody; +import static io.github.hectorvent.floci.services.ses.SesV2Json.stringMapMemberOrAbsent; +import static io.github.hectorvent.floci.services.ses.SesV2Json.stringMemberOrAbsent; + +/** SES V2 Virtual Deliverability Manager advisor recommendations ({@code /v2/email/vdm/recommendations}). */ +@Path("/v2/email/vdm/recommendations") +@Produces(MediaType.APPLICATION_JSON) +@Consumes(MediaType.APPLICATION_JSON) +public class SesRecommendationController { + + /** In the model's order. */ + private static final List FILTER_KEYS = List.of("TYPE", "IMPACT", "STATUS", "RESOURCE_ARN"); + private static final int FILTER_MAX_KEYS = 2; + private static final int FILTER_VALUE_MAX = 512; + + private final SesRecommendationService recommendationService; + private final RegionResolver regionResolver; + private final ObjectMapper objectMapper; + + @Inject + public SesRecommendationController(SesRecommendationService recommendationService, + RegionResolver regionResolver, ObjectMapper objectMapper) { + this.recommendationService = recommendationService; + this.regionResolver = regionResolver; + this.objectMapper = objectMapper; + } + + @POST + public Response listRecommendations(@Context HttpHeaders headers, String body) { + String region = regionResolver.resolveRegion(headers); + JsonNode request = readOptionBody(objectMapper, body); + SesV2RequestShapes.check("ListRecommendations", request); + Map requested = stringMapMemberOrAbsent(request, "Filter"); + if (requested != null) { + String violation = SmithyValidationErrors.sizeOutOfRange("filter", requested.size(), 1, FILTER_MAX_KEYS); + if (violation != null) { + throw SmithyValidationErrors.badRequest(violation); + } + } + Map filter = filterValues(requested, FILTER_KEYS, FILTER_VALUE_MAX); + Integer pageSize = intMemberOrAbsent(request, "PageSize"); + String nextToken = stringMemberOrAbsent(request, "NextToken"); + PaginatedResult page = recommendationService.list(filter, pageSize, nextToken, region); + ObjectNode result = objectMapper.createObjectNode(); + result.put("NextToken", page.nextToken()); + ArrayNode recommendations = result.putArray("Recommendations"); + for (Recommendation recommendation : page.items()) { + ObjectNode node = recommendations.addObject(); + node.put("ResourceArn", recommendation.resourceArn()); + node.put("Type", recommendation.type()); + node.put("Description", recommendation.description()); + node.put("Status", recommendation.status()); + putTimestamp(node, "CreatedTimestamp", recommendation.createdTimestamp()); + putTimestamp(node, "LastUpdatedTimestamp", recommendation.lastUpdatedTimestamp()); + node.put("Impact", recommendation.impact()); + } + return Response.ok(result).build(); + } +} diff --git a/src/main/java/io/github/hectorvent/floci/services/ses/SesRecommendationService.java b/src/main/java/io/github/hectorvent/floci/services/ses/SesRecommendationService.java new file mode 100644 index 0000000000..6d4415095c --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/ses/SesRecommendationService.java @@ -0,0 +1,156 @@ +package io.github.hectorvent.floci.services.ses; + +import io.github.hectorvent.floci.core.common.AwsArnUtils; +import io.github.hectorvent.floci.core.common.AwsException; +import io.github.hectorvent.floci.core.common.PaginatedResult; +import io.github.hectorvent.floci.core.common.RegionResolver; +import io.github.hectorvent.floci.services.ses.SesRecommendations.Finding; +import io.github.hectorvent.floci.services.ses.model.Identity; +import jakarta.enterprise.context.ApplicationScoped; +import jakarta.inject.Inject; + +import java.time.Clock; +import java.time.Instant; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Set; +import java.util.function.Predicate; + +/** + * SES v2 ListRecommendations, derived on every call from the region's verified domains (see + * {@link SesRecommendations}). Probe-confirmed against real SES: a region without Virtual Deliverability + * Manager answers an empty list rather than an error, verified domains notwithstanding (2026-10-29); + * recommendations come newest first; and a TYPE filter makes SES ignore an IMPACT filter sent with it + * (2026-10-27). + * + *

Nothing is stored, so every recommendation is OPEN: a finding that clears disappears rather than + * turning FIXED. A recommendation is dated from its identity's creation and reports the time of the + * request as its last update, as SES re-evaluates every recommendation daily. + */ +@ApplicationScoped +public class SesRecommendationService { + + private static final List TYPES = + List.of("DKIM", "DMARC", "SPF", "BIMI", "COMPLAINT", "BOUNCE", "FEEDBACK_3P", "IP_LISTING"); + private static final List IMPACTS = List.of("LOW", "HIGH"); + private static final List STATUSES = List.of("OPEN", "FIXED"); + private static final String OPEN = "OPEN"; + + private final SesIdentityService identityService; + private final SesAccountService accountService; + private final RegionResolver regionResolver; + private final Clock clock; + + public record Recommendation(String resourceArn, String type, String description, String status, + Instant createdTimestamp, Instant lastUpdatedTimestamp, String impact) {} + + @Inject + public SesRecommendationService(SesIdentityService identityService, SesAccountService accountService, + RegionResolver regionResolver, Clock clock) { + this.identityService = identityService; + this.accountService = accountService; + this.regionResolver = regionResolver; + this.clock = clock; + } + + /** + * The controller has already checked the filter's size and keys. The page size and an empty token + * come next, then the filter values in key order, and last the token. Without VDM the request is + * still validated, the order of the gate against the validation being unprobed. + */ + public PaginatedResult list(Map filter, Integer pageSize, String nextToken, + String region) { + SesListPaging paging = SesListPaging.V2_LIST_RECOMMENDATIONS; + paging.checkRequest(pageSize, nextToken); + Predicate matches = filterPredicate(filter); + List recommendations = accountService.isVdmEnabled(region) + ? derive(region).stream().filter(matches).toList() + : List.of(); + return paging.page(region, scope(filter), recommendations, + r -> SesListPaging.newestFirst(r.createdTimestamp(), r.resourceArn() + "#" + r.description()), + pageSize, nextToken); + } + + /** The ARN goes last: the other values never hold the separator, so no ARN can pass for another filter. */ + private static String scope(Map filter) { + if (filter.isEmpty()) { + return ""; + } + return Objects.toString(filter.get("TYPE"), "") + "/" + Objects.toString(filter.get("IMPACT"), "") + + "/" + Objects.toString(filter.get("STATUS"), "") + "/" + + Objects.toString(filter.get("RESOURCE_ARN"), ""); + } + + private List derive(String region) { + Instant now = Instant.now(clock); + String accountId = regionResolver.getAccountId(); + List advised = identityService.listIdentities("Domain", region).stream() + .map(identity -> identityService.withCurrentStatus(identity, region)) + .filter(SesRecommendations::isAdvised) + .toList(); + if (advised.isEmpty()) { + return List.of(); + } + Set txtRecordNames = identityService.txtRecordNames(); + List recommendations = new ArrayList<>(); + for (Identity identity : advised) { + String domain = identity.getIdentity(); + String arn = AwsArnUtils.Arn.of("ses", region, accountId, "identity/" + domain).toString(); + List findings = SesRecommendations.findings(identity, + txtRecordNames.contains( + SesIdentityService.normalizeDnsName(SesRecommendations.dmarcRecordName(domain))), + txtRecordNames.contains( + SesIdentityService.normalizeDnsName(SesRecommendations.bimiRecordName(domain)))); + for (Finding finding : findings) { + recommendations.add(new Recommendation(arn, finding.type(), finding.description(), OPEN, + identity.getCreatedAt(), now, finding.impact())); + } + } + return recommendations; + } + + private Predicate filterPredicate(Map filter) { + Predicate matches = r -> true; + String type = filter.get("TYPE"); + if (type != null) { + requireFilterValue("TYPE", TYPES.contains(type)); + matches = matches.and(r -> type.equals(r.type())); + } + String impact = filter.get("IMPACT"); + if (impact != null) { + requireFilterValue("IMPACT", IMPACTS.contains(impact)); + if (type == null) { + matches = matches.and(r -> impact.equals(r.impact())); + } + } + String status = filter.get("STATUS"); + if (status != null) { + requireFilterValue("STATUS", STATUSES.contains(status)); + matches = matches.and(r -> status.equals(r.status())); + } + String resourceArn = filter.get("RESOURCE_ARN"); + if (resourceArn != null) { + requireOwnArn(resourceArn); + matches = matches.and(r -> resourceArn.equals(r.resourceArn())); + } + return matches; + } + + private static void requireFilterValue(String key, boolean valid) { + if (!valid) { + throw new AwsException("BadRequestException", "Invalid recommendation " + key + " specified", 400); + } + } + + private void requireOwnArn(String resourceArn) { + if (!AwsArnUtils.isArnFor(resourceArn, "ses")) { + throw new AwsException("BadRequestException", "Filter resource is invalid", 400); + } + if (AwsArnUtils.isForeignAccount(AwsArnUtils.parse(resourceArn), regionResolver.getAccountId())) { + throw new AwsException("BadRequestException", + "Provided resource ARN does not match the caller account", 400); + } + } +} diff --git a/src/main/java/io/github/hectorvent/floci/services/ses/SesRecommendations.java b/src/main/java/io/github/hectorvent/floci/services/ses/SesRecommendations.java new file mode 100644 index 0000000000..c31b675cc0 --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/ses/SesRecommendations.java @@ -0,0 +1,70 @@ +package io.github.hectorvent.floci.services.ses; + +import io.github.hectorvent.floci.services.ses.model.Identity; + +import java.util.ArrayList; +import java.util.List; + +/** + * The Virtual Deliverability Manager advisor findings SES raises for a sending domain, derived from + * the identity and from whether its DMARC and BIMI TXT records exist. SES describes each finding by a + * code rather than a sentence. The codes, their impact and the condition behind each were + * probe-confirmed against real SES (2026-10-27, us-east-1) by comparing the recommendations of + * verified domains with their identity attributes and public DNS: + * + *

    + *
  • {@code DKIM1}, HIGH: DKIM signing is disabled.
  • + *
  • {@code DKIM3}, LOW: Easy DKIM signs with a 1024-bit key; a domain that does not sign gets + * none, whatever its next key length.
  • + *
  • {@code DMARC1}, HIGH: no {@code _dmarc} TXT record.
  • + *
  • {@code BIMI1}, LOW: no {@code default._bimi} TXT record.
  • + *
+ * + *

{@code DKIM2} (DKIM verification failed) needs a FAILED DKIM status, which Floci never reaches, + * and {@code DMARC5} appeared on a domain whose DNS matched one without it, so neither is raised. + */ +final class SesRecommendations { + + record Finding(String type, String description, String impact) {} + + static final Finding DKIM_NOT_ENABLED = new Finding("DKIM", "DKIM1", "HIGH"); + static final Finding DKIM_SHORT_KEY = new Finding("DKIM", "DKIM3", "LOW"); + static final Finding DMARC_NOT_FOUND = new Finding("DMARC", "DMARC1", "HIGH"); + static final Finding BIMI_NOT_FOUND = new Finding("BIMI", "BIMI1", "LOW"); + + private SesRecommendations() { + } + + /** Every finding the probe observed was on a verified domain. */ + static boolean isAdvised(Identity identity) { + return "Domain".equals(identity.getIdentityType()) && "Success".equals(identity.getVerificationStatus()); + } + + static List findings(Identity identity, boolean hasDmarcRecord, boolean hasBimiRecord) { + if (!isAdvised(identity)) { + return List.of(); + } + List findings = new ArrayList<>(); + if (!identity.isDkimEnabled()) { + findings.add(DKIM_NOT_ENABLED); + } else if ("AWS_SES".equals(identity.getDkimSigningAttributesOrigin()) + && "RSA_1024_BIT".equals(identity.getDkimCurrentSigningKeyLength())) { + findings.add(DKIM_SHORT_KEY); + } + if (!hasDmarcRecord) { + findings.add(DMARC_NOT_FOUND); + } + if (!hasBimiRecord) { + findings.add(BIMI_NOT_FOUND); + } + return findings; + } + + static String dmarcRecordName(String domain) { + return "_dmarc." + domain; + } + + static String bimiRecordName(String domain) { + return "default._bimi." + domain; + } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/ses/SesDomainIdentityTestHelper.java b/src/test/java/io/github/hectorvent/floci/services/ses/SesDomainIdentityTestHelper.java index ee3d856cd5..7ad317cca5 100644 --- a/src/test/java/io/github/hectorvent/floci/services/ses/SesDomainIdentityTestHelper.java +++ b/src/test/java/io/github/hectorvent/floci/services/ses/SesDomainIdentityTestHelper.java @@ -9,14 +9,15 @@ import static io.restassured.RestAssured.given; * Creates a domain identity that is verified for sending. A domain identity stays Pending until * its DKIM CNAME records exist in a Route 53 hosted zone, so this publishes them in a zone of its * own. A test that checks the Pending state first creates the identity itself and then calls - * {@link #publishDkimRecords}. + * {@link #publishDkimRecords}. Both return the hosted zone id, for a test that adds records of + * its own. */ final class SesDomainIdentityTestHelper { private SesDomainIdentityTestHelper() { } - static void createVerified(String domain, String sesAuthorization) { + static String createVerified(String domain, String sesAuthorization) { List tokens = given() .contentType("application/json") .header("Authorization", sesAuthorization) @@ -28,10 +29,10 @@ final class SesDomainIdentityTestHelper { .extract() .jsonPath() .getList("DkimAttributes.Tokens", String.class); - publishDkimRecords(domain, tokens); + return publishDkimRecords(domain, tokens); } - static void publishDkimRecords(String domain, List tokens) { + static String publishDkimRecords(String domain, List tokens) { String location = given() .contentType("application/xml") .body(""" @@ -64,6 +65,7 @@ final class SesDomainIdentityTestHelper { """.formatted(token, domain, token)); } + String zoneId = location.substring(location.lastIndexOf('/') + 1); given() .contentType("application/xml") .body(""" @@ -76,8 +78,9 @@ final class SesDomainIdentityTestHelper { """.formatted(changes)) .when() - .post("/2013-04-01/hostedzone/" + location.substring(location.lastIndexOf('/') + 1) + "/rrset") + .post("/2013-04-01/hostedzone/" + zoneId + "/rrset") .then() .statusCode(200); + return zoneId; } } diff --git a/src/test/java/io/github/hectorvent/floci/services/ses/SesIdentityRoute53ScanTest.java b/src/test/java/io/github/hectorvent/floci/services/ses/SesIdentityRoute53ScanTest.java new file mode 100644 index 0000000000..7c3c8bdc91 --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/ses/SesIdentityRoute53ScanTest.java @@ -0,0 +1,101 @@ +package io.github.hectorvent.floci.services.ses; + +import io.github.hectorvent.floci.core.common.AwsException; +import io.github.hectorvent.floci.core.common.RegionResolver; +import io.github.hectorvent.floci.core.storage.InMemoryStorage; +import io.github.hectorvent.floci.services.route53.Route53Service; +import io.github.hectorvent.floci.services.route53.model.HostedZone; +import io.github.hectorvent.floci.services.route53.model.ResourceRecord; +import io.github.hectorvent.floci.services.route53.model.ResourceRecordSet; +import io.github.hectorvent.floci.services.ses.model.AccountVdmAttributes; +import io.github.hectorvent.floci.services.ses.model.Identity; +import io.github.hectorvent.floci.testing.MutableClock; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import java.util.List; +import java.util.Map; +import java.util.Set; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +/** How SES reads Route53 in place of public DNS: zone by zone, and past a zone deleted mid-scan. */ +class SesIdentityRoute53ScanTest { + + private static final String REGION = "us-east-1"; + private static final String DOMAIN = "example.com"; + + private Route53Service route53Service; + private SesIdentityService identities; + + @BeforeEach + void setUp() { + route53Service = mock(Route53Service.class); + identities = new SesIdentityService(new InMemoryStorage<>(), route53Service, new MutableClock()); + when(route53Service.listHostedZones(null, Integer.MAX_VALUE)) + .thenReturn(List.of(zone("zone-1"), zone("zone-2"))); + } + + @Test + void dkimLookupStopsAtTheZoneHoldingTheRecord() { + Identity identity = new Identity(DOMAIN, "Domain"); + identity.setVerificationStatus("Pending"); + identity.setDkimTokens(List.of("token-a")); + identities.save(identity, REGION); + when(route53Service.listResourceRecordSets("zone-1", null, null, Integer.MAX_VALUE)) + .thenReturn(List.of(recordSet("token-a._domainkey." + DOMAIN + ".", "CNAME", + "token-a.dkim.amazonses.com."))); + + assertEquals("Success", identities.getIdentityVerificationAttributes(DOMAIN, REGION).getVerificationStatus()); + verify(route53Service, never()).listResourceRecordSets("zone-2", null, null, Integer.MAX_VALUE); + } + + @Test + void txtRecordNamesSkipAZoneDeletedMidScan() { + when(route53Service.listResourceRecordSets("zone-1", null, null, Integer.MAX_VALUE)) + .thenThrow(new AwsException("NoSuchHostedZone", "No hosted zone found with ID: zone-1", 404)); + when(route53Service.listResourceRecordSets("zone-2", null, null, Integer.MAX_VALUE)) + .thenReturn(List.of(recordSet("_dmarc." + DOMAIN + ".", "TXT", "\"v=DMARC1; p=none\""))); + + assertEquals(Set.of("_dmarc." + DOMAIN), identities.txtRecordNames()); + } + + @Test + void txtRecordNamesPropagateOtherRoute53Errors() { + when(route53Service.listResourceRecordSets("zone-1", null, null, Integer.MAX_VALUE)) + .thenThrow(new AwsException("Throttling", "Rate exceeded", 400)); + + AwsException e = assertThrows(AwsException.class, () -> identities.txtRecordNames()); + assertEquals("Throttling", e.getErrorCode()); + } + + @Test + void recommendationsReadNoZonesWithoutAVerifiedDomain() { + identities.save(new Identity("alice@example.com", "EmailAddress"), REGION); + SesAccountService accounts = + new SesAccountService(new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>()); + accounts.putAccountVdmAttributes(REGION, new AccountVdmAttributes(true, false, false)); + SesRecommendationService recommendations = new SesRecommendationService(identities, accounts, + new RegionResolver(REGION, "000000000000"), new MutableClock()); + + assertEquals(List.of(), recommendations.list(Map.of(), null, null, REGION).items()); + verify(route53Service, never()).listHostedZones(null, Integer.MAX_VALUE); + } + + private static HostedZone zone(String id) { + return new HostedZone(id, DOMAIN + ".", "ref-" + id, null, false); + } + + private static ResourceRecordSet recordSet(String name, String type, String value) { + ResourceRecordSet recordSet = new ResourceRecordSet(); + recordSet.setName(name); + recordSet.setType(type); + recordSet.setRecords(List.of(new ResourceRecord(value))); + return recordSet; + } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/ses/SesRecommendationServiceTest.java b/src/test/java/io/github/hectorvent/floci/services/ses/SesRecommendationServiceTest.java new file mode 100644 index 0000000000..ebf0fcc6d8 --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/ses/SesRecommendationServiceTest.java @@ -0,0 +1,212 @@ +package io.github.hectorvent.floci.services.ses; + +import io.github.hectorvent.floci.core.common.AwsException; +import io.github.hectorvent.floci.core.common.PaginatedResult; +import io.github.hectorvent.floci.core.common.RegionResolver; +import io.github.hectorvent.floci.core.storage.InMemoryStorage; +import io.github.hectorvent.floci.services.ses.SesRecommendationService.Recommendation; +import io.github.hectorvent.floci.services.ses.model.AccountVdmAttributes; +import io.github.hectorvent.floci.services.ses.model.Identity; +import io.github.hectorvent.floci.testing.MutableClock; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import java.time.Duration; +import java.time.Instant; +import java.util.List; +import java.util.Map; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +class SesRecommendationServiceTest { + + private static final String REGION = "us-east-1"; + private static final String ACCOUNT = "000000000000"; + + private MutableClock clock; + private SesIdentityService identities; + private SesAccountService accounts; + private SesRecommendationService service; + + @BeforeEach + void setUp() { + clock = new MutableClock(); + // No Route53, so no domain has DMARC or BIMI records. + identities = new SesIdentityService(new InMemoryStorage<>(), null, clock); + accounts = new SesAccountService(new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>()); + accounts.putAccountVdmAttributes(REGION, new AccountVdmAttributes(true, false, false)); + service = new SesRecommendationService(identities, accounts, new RegionResolver(REGION, ACCOUNT), clock); + } + + private Identity saveDomain(String domain, boolean signing, Instant created) { + Identity identity = new Identity(domain, "Domain"); + identity.setDkimEnabled(signing); + identity.setDkimTokens(List.of("token")); + identity.setCreatedAt(created); + identities.save(identity, REGION); + return identity; + } + + private static String arn(String domain) { + return "arn:aws:ses:" + REGION + ":" + ACCOUNT + ":identity/" + domain; + } + + private List list(Map filter) { + return service.list(filter, null, null, REGION).items(); + } + + private static List codes(List recommendations) { + return recommendations.stream().map(r -> r.resourceArn().substring(r.resourceArn().indexOf('/') + 1) + + ":" + r.description()).toList(); + } + + @Test + void listsNewestIdentityFirstWithCodesOrderedWithin() { + saveDomain("old.example", true, Instant.parse("2024-01-01T00:00:00Z")); + saveDomain("new.example", false, Instant.parse("2025-01-01T00:00:00Z")); + assertEquals(List.of("new.example:BIMI1", "new.example:DKIM1", "new.example:DMARC1", + "old.example:BIMI1", "old.example:DMARC1"), + codes(list(Map.of()))); + } + + @Test + void everyRecommendationIsOpenDatedFromItsIdentityAndUpdatedNow() { + Instant created = Instant.parse("2024-01-01T00:00:00Z"); + saveDomain("example.com", true, created); + Instant before = clock.instant(); + Recommendation recommendation = list(Map.of("TYPE", "DMARC")).getFirst(); + assertEquals(arn("example.com"), recommendation.resourceArn()); + assertEquals("OPEN", recommendation.status()); + assertEquals("HIGH", recommendation.impact()); + assertEquals(created, recommendation.createdTimestamp()); + // MutableClock ticks a millisecond per read, so the list's own read comes after this one. + assertTrue(recommendation.lastUpdatedTimestamp().isAfter(before)); + } + + @Test + void emptyWithoutVdm() { + saveDomain("example.com", false, clock.instant()); + accounts.putAccountVdmAttributes(REGION, new AccountVdmAttributes(false, false, false)); + assertEquals(List.of(), list(Map.of())); + assertEquals(List.of(), service.list(Map.of(), null, null, "eu-west-3").items()); + } + + @Test + void filterIsValidatedWithoutVdm() { + accounts.putAccountVdmAttributes(REGION, new AccountVdmAttributes(false, false, false)); + assertMessage("Invalid recommendation TYPE specified", Map.of("TYPE", "ENGAGEMENT")); + } + + @Test + void unverifiedDomainsAndEmailAddressesAreNotAdvised() { + Identity pending = saveDomain("pending.example", true, clock.instant()); + pending.setVerificationStatus("Pending"); + identities.save(pending, REGION); + identities.save(new Identity("alice@example.com", "EmailAddress"), REGION); + assertEquals(List.of(), list(Map.of())); + } + + @Test + void typeFilterIgnoresImpact() { + saveDomain("example.com", false, clock.instant()); + assertEquals(List.of("example.com:DKIM1"), codes(list(Map.of("TYPE", "DKIM", "IMPACT", "LOW")))); + } + + @Test + void impactFilterAppliesWithoutType() { + saveDomain("example.com", false, clock.instant()); + assertEquals(List.of("example.com:BIMI1"), codes(list(Map.of("IMPACT", "LOW")))); + } + + @Test + void statusFilterFixedIsEmpty() { + saveDomain("example.com", false, clock.instant()); + assertEquals(List.of(), list(Map.of("STATUS", "FIXED"))); + assertEquals(3, list(Map.of("STATUS", "OPEN")).size()); + } + + @Test + void resourceArnFilterMatchesTheIdentityArn() { + saveDomain("a.example", true, clock.instant()); + saveDomain("b.example", true, clock.instant()); + assertEquals(List.of("b.example:BIMI1", "b.example:DMARC1"), + codes(list(Map.of("RESOURCE_ARN", arn("b.example"))))); + assertEquals(List.of(), list(Map.of("RESOURCE_ARN", arn("missing.example")))); + } + + @Test + void invalidFilterValuesNameTheirKey() { + assertMessage("Invalid recommendation TYPE specified", Map.of("TYPE", "ENGAGEMENT")); + assertMessage("Invalid recommendation IMPACT specified", Map.of("IMPACT", "MEDIUM")); + assertMessage("Invalid recommendation STATUS specified", Map.of("STATUS", "open")); + } + + @Test + void impactIsValidatedEvenWhenTypeMakesItIgnored() { + assertMessage("Invalid recommendation IMPACT specified", Map.of("TYPE", "DKIM", "IMPACT", "high")); + } + + @Test + void resourceArnMustBeAnSesArnOfTheCallerAccount() { + assertMessage("Filter resource is invalid", Map.of("RESOURCE_ARN", "not-an-arn")); + assertMessage("Filter resource is invalid", + Map.of("RESOURCE_ARN", "arn:aws:sns:us-east-1:000000000000:identity/example.com")); + assertMessage("Provided resource ARN does not match the caller account", + Map.of("RESOURCE_ARN", "arn:aws:ses:us-east-1:111111111111:identity/example.com")); + } + + @Test + void pagesOfTheDefaultFifty() { + for (int i = 0; i < 26; i++) { + saveDomain("d" + i + ".example", true, clock.instant().plus(Duration.ofSeconds(i))); + } + PaginatedResult first = service.list(Map.of(), null, null, REGION); + assertEquals(50, first.items().size()); + assertNotNull(first.nextToken()); + PaginatedResult second = service.list(Map.of(), null, first.nextToken(), REGION); + assertEquals(2, second.items().size()); + assertNull(second.nextToken()); + } + + @Test + void tokenIsBoundToItsFilter() { + saveDomain("a.example", true, clock.instant()); + saveDomain("b.example", true, clock.instant().plusSeconds(1)); + String token = service.list(Map.of("STATUS", "OPEN"), 1, null, REGION).nextToken(); + assertNotNull(token); + assertEquals(1, service.list(Map.of("STATUS", "OPEN"), 1, token, REGION).items().size()); + assertPagingMessage("Failed to deserialize token.", null, token); + AwsException e = assertThrows(AwsException.class, + () -> service.list(Map.of("TYPE", "BIMI"), 1, token, REGION)); + assertEquals("Failed to deserialize token.", e.getMessage()); + } + + @Test + void pageSizeOutsideItsBounds() { + assertPagingMessage("The PageSize should be between 1 and 1000", 0, null); + assertPagingMessage("The PageSize should be between 1 and 1000", 1001, null); + } + + @Test + void unreadableOrEmptyToken() { + assertPagingMessage("Failed to deserialize token.", null, "garbage"); + assertPagingMessage("Failed to deserialize token.", null, ""); + } + + private void assertMessage(String message, Map filter) { + AwsException e = assertThrows(AwsException.class, () -> service.list(filter, null, null, REGION)); + assertEquals("BadRequestException", e.getErrorCode()); + assertEquals(message, e.getMessage()); + } + + private void assertPagingMessage(String message, Integer pageSize, String nextToken) { + AwsException e = assertThrows(AwsException.class, + () -> service.list(Map.of(), pageSize, nextToken, REGION)); + assertEquals("BadRequestException", e.getErrorCode()); + assertEquals(message, e.getMessage()); + } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/ses/SesRecommendationV2IntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/ses/SesRecommendationV2IntegrationTest.java new file mode 100644 index 0000000000..6f85e76456 --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/ses/SesRecommendationV2IntegrationTest.java @@ -0,0 +1,177 @@ +package io.github.hectorvent.floci.services.ses; + +import io.quarkus.test.junit.QuarkusTest; +import io.restassured.specification.RequestSpecification; +import org.junit.jupiter.api.MethodOrderer; +import org.junit.jupiter.api.Order; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestMethodOrder; + +import static io.restassured.RestAssured.given; +import static org.hamcrest.Matchers.contains; +import static org.hamcrest.Matchers.empty; +import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.everyItem; +import static org.hamcrest.Matchers.hasKey; +import static org.hamcrest.Matchers.instanceOf; +import static org.hamcrest.Matchers.notNullValue; +import static org.hamcrest.Matchers.nullValue; + +/** + * Integration tests for SES v2 ListRecommendations, derived from the verified domains of the region + * and the TXT records their Route53 zones hold. The region is one no other test uses, so Virtual + * Deliverability Manager is off in it until a test enables it. + */ +@QuarkusTest +@TestMethodOrder(MethodOrderer.OrderAnnotation.class) +class SesRecommendationV2IntegrationTest { + + private static final String REGION = "eu-south-2"; + private static final String AUTH = + "AWS4-HMAC-SHA256 Credential=AKID/20260101/" + REGION + "/ses/aws4_request"; + private static final String DOMAIN = "recommend-it.floci.test"; + private static final String ARN = "arn:aws:ses:" + REGION + ":000000000000:identity/" + DOMAIN; + private static final String PATH = "/v2/email/vdm/recommendations"; + + private static String zoneId; + + private static RequestSpecification v2() { + return given().contentType("application/json").header("Authorization", AUTH); + } + + private static void addTxtRecord(String name, String value) { + given() + .contentType("application/xml") + .body(""" + + + + + + CREATE + + %s + TXT + 300 + + "%s" + + + + + + + """.formatted(name, value)) + .when() + .post("/2013-04-01/hostedzone/" + zoneId + "/rrset") + .then() + .statusCode(200); + } + + @Test + @Order(1) + void emptyWithoutIdentities() { + v2().body("{}") + .when().post(PATH).then().statusCode(200) + .body("Recommendations", empty()) + .body("$", hasKey("NextToken")) + .body("NextToken", nullValue()); + } + + @Test + @Order(2) + void pendingDomainIsNotAdvised() { + v2().body("{\"EmailIdentity\":\"pending-" + DOMAIN + "\"}") + .when().post("/v2/email/identities").then().statusCode(200); + v2().body("{}").when().post(PATH).then().statusCode(200).body("Recommendations", empty()); + } + + @Test + @Order(3) + void verifiedDomainWithoutRecordsGetsBimiAndDmarcOnceVdmIsEnabled() { + zoneId = SesDomainIdentityTestHelper.createVerified(DOMAIN, AUTH); + v2().body("{}").when().post(PATH).then().statusCode(200).body("Recommendations", empty()); + v2().body("{\"VdmAttributes\":{\"VdmEnabled\":\"ENABLED\"}}") + .when().put("/v2/email/account/vdm").then().statusCode(200); + v2().body("{}") + .when().post(PATH).then().statusCode(200) + .body("Recommendations.Description", contains("BIMI1", "DMARC1")) + .body("Recommendations.Type", contains("BIMI", "DMARC")) + .body("Recommendations.Impact", contains("LOW", "HIGH")) + .body("Recommendations.Status", everyItem(equalTo("OPEN"))) + .body("Recommendations.ResourceArn", everyItem(equalTo(ARN))) + .body("Recommendations[0].CreatedTimestamp", instanceOf(Number.class)) + .body("Recommendations[0].LastUpdatedTimestamp", notNullValue()); + } + + @Test + @Order(4) + void publishedTxtRecordsClearTheirFindings() { + addTxtRecord("_dmarc." + DOMAIN, "v=DMARC1; p=none"); + v2().body("{\"Filter\":{\"RESOURCE_ARN\":\"" + ARN + "\"}}") + .when().post(PATH).then().statusCode(200) + .body("Recommendations.Description", contains("BIMI1")); + addTxtRecord("default._bimi." + DOMAIN, "v=BIMI1; l=https://example.com/logo.svg"); + v2().body("{}").when().post(PATH).then().statusCode(200).body("Recommendations", empty()); + } + + @Test + @Order(5) + void disabledSigningIsDkim1() { + v2().body("{\"SigningEnabled\":false}") + .when().put("/v2/email/identities/" + DOMAIN + "/dkim").then().statusCode(200); + v2().body("{}") + .when().post(PATH).then().statusCode(200) + .body("Recommendations.Description", contains("DKIM1")) + .body("Recommendations[0].Impact", equalTo("HIGH")); + } + + @Test + @Order(6) + void shortEasyDkimKeyIsDkim3() { + v2().body("{\"SigningEnabled\":true}") + .when().put("/v2/email/identities/" + DOMAIN + "/dkim").then().statusCode(200); + v2().body("{\"SigningAttributesOrigin\":\"AWS_SES\"," + + "\"SigningAttributes\":{\"NextSigningKeyLength\":\"RSA_1024_BIT\"}}") + .when().put("/v2/email/identities/" + DOMAIN + "/dkim/signing").then().statusCode(200); + v2().body("{\"Filter\":{\"TYPE\":\"DKIM\",\"IMPACT\":\"HIGH\"}}") + .when().post(PATH).then().statusCode(200) + .body("Recommendations.Description", contains("DKIM3")) + .body("Recommendations[0].Impact", equalTo("LOW")); + } + + @Test + @Order(7) + void filterSizeIsBoundedByTheModel() { + v2().body("{\"Filter\":{}}") + .when().post(PATH).then().statusCode(400) + .body("message", equalTo("1 validation error detected: Value at 'filter' failed to satisfy " + + "constraint: Member must have length greater than or equal to 1")); + v2().body("{\"Filter\":{\"TYPE\":\"DKIM\",\"IMPACT\":\"LOW\",\"STATUS\":\"OPEN\"}}") + .when().post(PATH).then().statusCode(400) + .body("message", equalTo("1 validation error detected: Value at 'filter' failed to satisfy " + + "constraint: Member must have length less than or equal to 2")); + } + + @Test + @Order(8) + void invalidFilterValuesAndPaging() { + assertBadRequest("{\"Filter\":{\"TYPE\":\"NOPE\"}}", "Invalid recommendation TYPE specified"); + assertBadRequest("{\"Filter\":{\"RESOURCE_ARN\":\"not-an-arn\"}}", "Filter resource is invalid"); + assertBadRequest("{\"Filter\":{\"RESOURCE_ARN\":\"arn:aws:ses:" + REGION + ":111111111111:identity/x.test\"}}", + "Provided resource ARN does not match the caller account"); + assertBadRequest("{\"Filter\":{\"RESOURCE_ARN\":\"" + "a".repeat(513) + "\"}}", + "1 validation error detected: Value at 'filter' failed to satisfy constraint: Map value must " + + "satisfy constraint: [Member must have length less than or equal to 512, " + + "Member must have length greater than or equal to 1]"); + assertBadRequest("{\"PageSize\":0}", "The PageSize should be between 1 and 1000"); + assertBadRequest("{\"NextToken\":\"garbage\"}", "Failed to deserialize token."); + } + + private static void assertBadRequest(String body, String message) { + v2().body(body) + .when().post(PATH).then().statusCode(400) + .body("__type", equalTo("BadRequestException")) + .body("message", equalTo(message)); + } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/ses/SesRecommendationsTest.java b/src/test/java/io/github/hectorvent/floci/services/ses/SesRecommendationsTest.java new file mode 100644 index 0000000000..45797aee10 --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/ses/SesRecommendationsTest.java @@ -0,0 +1,87 @@ +package io.github.hectorvent.floci.services.ses; + +import io.github.hectorvent.floci.services.ses.SesRecommendations.Finding; +import io.github.hectorvent.floci.services.ses.model.Identity; +import org.junit.jupiter.api.Test; + +import java.util.List; + +import static io.github.hectorvent.floci.services.ses.SesRecommendations.BIMI_NOT_FOUND; +import static io.github.hectorvent.floci.services.ses.SesRecommendations.DKIM_NOT_ENABLED; +import static io.github.hectorvent.floci.services.ses.SesRecommendations.DKIM_SHORT_KEY; +import static io.github.hectorvent.floci.services.ses.SesRecommendations.DMARC_NOT_FOUND; +import static org.junit.jupiter.api.Assertions.assertEquals; + +class SesRecommendationsTest { + + private static Identity signingDomain(String keyLength) { + Identity identity = new Identity("example.com", "Domain"); + identity.setDkimEnabled(true); + identity.setDkimCurrentSigningKeyLength(keyLength); + return identity; + } + + @Test + void domainWithoutDnsRecordsGetsDmarcAndBimi() { + assertEquals(List.of(DMARC_NOT_FOUND, BIMI_NOT_FOUND), + SesRecommendations.findings(signingDomain("RSA_2048_BIT"), false, false)); + } + + @Test + void domainWithBothRecordsAndStrongKeyGetsNothing() { + assertEquals(List.of(), SesRecommendations.findings(signingDomain("RSA_2048_BIT"), true, true)); + } + + @Test + void disabledSigningIsDkim1() { + Identity identity = new Identity("example.com", "Domain"); + identity.setDkimEnabled(false); + assertEquals(List.of(DKIM_NOT_ENABLED), SesRecommendations.findings(identity, true, true)); + } + + @Test + void disabledSigningWithShortKeyIsDkim1Only() { + Identity identity = signingDomain("RSA_1024_BIT"); + identity.setDkimEnabled(false); + assertEquals(List.of(DKIM_NOT_ENABLED), SesRecommendations.findings(identity, true, true)); + } + + @Test + void easyDkimWithShortKeyIsDkim3() { + assertEquals(List.of(DKIM_SHORT_KEY), SesRecommendations.findings(signingDomain("RSA_1024_BIT"), true, true)); + } + + @Test + void byoDkimKeyLengthIsNotJudged() { + Identity identity = signingDomain("RSA_1024_BIT"); + identity.setDkimSigningAttributesOrigin("EXTERNAL"); + assertEquals(List.of(), SesRecommendations.findings(identity, true, true)); + } + + @Test + void unverifiedDomainGetsNothing() { + Identity identity = signingDomain("RSA_1024_BIT"); + identity.setVerificationStatus("Pending"); + assertEquals(List.of(), SesRecommendations.findings(identity, false, false)); + } + + @Test + void emailAddressGetsNothing() { + Identity identity = new Identity("alice@example.com", "EmailAddress"); + assertEquals(List.of(), SesRecommendations.findings(identity, false, false)); + } + + @Test + void codesAndImpactsFollowTheProbe() { + assertEquals(new Finding("DKIM", "DKIM1", "HIGH"), DKIM_NOT_ENABLED); + assertEquals(new Finding("DKIM", "DKIM3", "LOW"), DKIM_SHORT_KEY); + assertEquals(new Finding("DMARC", "DMARC1", "HIGH"), DMARC_NOT_FOUND); + assertEquals(new Finding("BIMI", "BIMI1", "LOW"), BIMI_NOT_FOUND); + } + + @Test + void recordNamesAreTheDmarcAndDefaultBimiSelectors() { + assertEquals("_dmarc.example.com", SesRecommendations.dmarcRecordName("example.com")); + assertEquals("default._bimi.example.com", SesRecommendations.bimiRecordName("example.com")); + } +}