feat(ses): add SES v2 ListRecommendations (#6817)

This commit is contained in:
Kenshin Okinaka authored and GitHub committed 2026-10-28 21:55:19 -04:00
1 parent 0e87e6f1de
commit 4dbe3731a9
14 files changed
+1079 -33

No files matched your search

@@ -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)),
@@ -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<AccountVdmAttributes> 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);
}
@@ -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<ResourceRecord> 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<String> 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<ResourceRecordSet> 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<ResourceRecordSet> 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<String> normalizedTokens = identity.getDkimTokens().stream()
.map(this::normalizeDnsName)
.map(SesIdentityService::normalizeDnsName)
.sorted()
.toList();
return region + "::" + normalizeDnsName(identity.getIdentity()) + "::" + String.join(",", normalizedTokens);
@@ -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. */
@@ -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<String> 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<String, String> 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<String, String> filter = filterValues(requested, FILTER_KEYS, FILTER_VALUE_MAX);
Integer pageSize = intMemberOrAbsent(request, "PageSize");
String nextToken = stringMemberOrAbsent(request, "NextToken");
PaginatedResult<Recommendation> 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();
}
}
@@ -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).
*
* <p>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<String> TYPES =
List.of("DKIM", "DMARC", "SPF", "BIMI", "COMPLAINT", "BOUNCE", "FEEDBACK_3P", "IP_LISTING");
private static final List<String> IMPACTS = List.of("LOW", "HIGH");
private static final List<String> 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<Recommendation> list(Map<String, String> filter, Integer pageSize, String nextToken,
String region) {
SesListPaging paging = SesListPaging.V2_LIST_RECOMMENDATIONS;
paging.checkRequest(pageSize, nextToken);
Predicate<Recommendation> matches = filterPredicate(filter);
List<Recommendation> 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<String, String> 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<Recommendation> derive(String region) {
Instant now = Instant.now(clock);
String accountId = regionResolver.getAccountId();
List<Identity> advised = identityService.listIdentities("Domain", region).stream()
.map(identity -> identityService.withCurrentStatus(identity, region))
.filter(SesRecommendations::isAdvised)
.toList();
if (advised.isEmpty()) {
return List.of();
}
Set<String> txtRecordNames = identityService.txtRecordNames();
List<Recommendation> recommendations = new ArrayList<>();
for (Identity identity : advised) {
String domain = identity.getIdentity();
String arn = AwsArnUtils.Arn.of("ses", region, accountId, "identity/" + domain).toString();
List<Finding> 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<Recommendation> filterPredicate(Map<String, String> filter) {
Predicate<Recommendation> 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);
}
}
}
@@ -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:
*
* <ul>
* <li>{@code DKIM1}, HIGH: DKIM signing is disabled.</li>
* <li>{@code DKIM3}, LOW: Easy DKIM signs with a 1024-bit key; a domain that does not sign gets
* none, whatever its next key length.</li>
* <li>{@code DMARC1}, HIGH: no {@code _dmarc} TXT record.</li>
* <li>{@code BIMI1}, LOW: no {@code default._bimi} TXT record.</li>
* </ul>
*
* <p>{@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<Finding> findings(Identity identity, boolean hasDmarcRecord, boolean hasBimiRecord) {
if (!isAdvised(identity)) {
return List.of();
}
List<Finding> 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;
}
}