feat(ses): add the v2 reputation entity operations (#6407)

* feat(ses): add the v2 reputation entity operations

Implement ListReputationEntities, GetReputationEntity,
UpdateReputationEntityPolicy and UpdateReputationEntityCustomerManagedStatus.
Every tenant is a reputation entity referenced by its full ARN. The policy
and the customer-managed status live on the tenant record, and the status
is the tenant's aggregate SendingStatus. A tenant whose status is DISABLED
is now refused on SendEmail and SendBulkEmail with MessageRejected.

Shapes, messages and validation order follow probes against real SES.

* test(ses): surface unexpected tenant cleanup failures in the reputation compat test
This commit is contained in:
Kenshin Okinaka authored and GitHub committed 2026-10-24 08:16:23 -04:00
1 parent 84727e3f2f
commit 5a9f9cbbd6
22 files changed
+1371 -62

No files matched your search

@@ -112,6 +112,21 @@ public final class Pagination {
}
}
/**
* True when {@code token} decodes to a cursor that starts with {@code prefix}, for callers that
* need to tell a token they issued under another scope from one that is not theirs at all.
*/
public static boolean tokenStartsWith(String token, String prefix) {
if (token == null || token.isEmpty()) {
return false;
}
try {
return new String(Base64.getUrlDecoder().decode(token), StandardCharsets.UTF_8).startsWith(prefix);
} catch (IllegalArgumentException e) {
return false;
}
}
private static String encodeToken(String cursor) {
return Base64Url.encode(cursor);
}
@@ -78,6 +78,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.SesReputationEntityController;
import io.github.hectorvent.floci.services.ses.SesSendController;
import io.github.hectorvent.floci.services.ses.SesSuppressionController;
import io.github.hectorvent.floci.services.ses.SesTagController;
@@ -338,7 +339,7 @@ public class ResolvedServiceCatalog {
SesDedicatedIpController.class, SesExportJobController.class,
SesIdentityController.class,
SesInsightsController.class, SesMetricsController.class,
SesSendController.class,
SesReputationEntityController.class, SesSendController.class,
SesSuppressionController.class, SesTagController.class,
SesTemplateController.class, SesImportJobController.class,
SesTenantController.class)),
@@ -137,6 +137,16 @@ public enum SesListPaging {
token -> new AwsException("InvalidNextTokenException", "Token is invalid.", 400),
true),
/**
* ListReputationEntities (probed 2026-10-23): an empty token is refused like an unreadable one,
* and a token from another filter has its own message, which the service renders. Three entities
* came back whole without a PageSize, so the default is taken to be the bound.
*/
V2_LIST_REPUTATION_ENTITIES(Namespace.REPUTATION_ENTITY, 1000, 1000,
size -> badRequest("The page size must 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.
@@ -162,6 +172,7 @@ public enum SesListPaging {
static final String DEDICATED_IP = "dedicated-ip";
static final String SUPPRESSED_DESTINATION = "suppressed-destination";
static final String RECEIPT_RULE_SET = "receipt-rule-set";
static final String REPUTATION_ENTITY = "reputation-entity";
}
/** What the tenant lists share, and ListImportJobs borrows: the bound and Smithy's messages. */
@@ -273,6 +284,16 @@ public enum SesListPaging {
return limit;
}
/**
* True when {@code token} is one this list issued in {@code region}, whatever it was bound to, so
* a list whose tokens SES refuses with a message of their own once the filter changes can tell
* that case from an unreadable token.
*/
boolean issuedInRegion(String token, String region) {
String issuer = namespace + "@" + region;
return Pagination.tokenStartsWith(token, issuer + ":") || Pagination.tokenStartsWith(token, issuer + "#");
}
int pageSize(Integer requested) {
if (requested == null) {
return defaultPageSize;
@@ -0,0 +1,138 @@
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.services.ses.SesReputationEntityService.ReputationEntity;
import io.github.hectorvent.floci.services.ses.model.ReputationStatusRecord;
import jakarta.inject.Inject;
import jakarta.ws.rs.Consumes;
import jakarta.ws.rs.GET;
import jakarta.ws.rs.POST;
import jakarta.ws.rs.PUT;
import jakarta.ws.rs.Path;
import jakarta.ws.rs.PathParam;
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 reputation entity endpoints ({@code /v2/email/reputation/entities}). The reference is an
* ARN, which the SDKs send percent-encoded as one path segment. The router matches the encoded
* path, so the reference stays one segment there and is decoded only as a parameter; a reference
* sent with literal slashes reaches no route, as on SES, and so cannot pass the IAM route rules
* as an unknown action.
*/
@Path("/v2/email/reputation/entities")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public class SesReputationEntityController {
/** In the order SES prints them when it refuses a key. */
private static final List<String> FILTER_KEYS =
List.of("ENTITY_REFERENCE_PREFIX", "REPUTATION_IMPACT", "ENTITY_TYPE", "SENDING_STATUS");
private static final int FILTER_VALUE_MAX = 512;
private final SesReputationEntityService reputationService;
private final RegionResolver regionResolver;
private final ObjectMapper objectMapper;
@Inject
public SesReputationEntityController(SesReputationEntityService reputationService,
RegionResolver regionResolver, ObjectMapper objectMapper) {
this.reputationService = reputationService;
this.regionResolver = regionResolver;
this.objectMapper = objectMapper;
}
@POST
public Response listReputationEntities(@Context HttpHeaders headers, String body) {
String region = regionResolver.resolveRegion(headers);
JsonNode request = readOptionBody(objectMapper, body);
SesV2RequestShapes.check("ListReputationEntities", request);
Map<String, String> filter = filterValues(stringMapMemberOrAbsent(request, "Filter"), FILTER_KEYS,
FILTER_VALUE_MAX);
Integer pageSize = intMemberOrAbsent(request, "PageSize");
String nextToken = stringMemberOrAbsent(request, "NextToken");
PaginatedResult<ReputationEntity> page = reputationService.list(filter, pageSize, nextToken, region);
ObjectNode result = objectMapper.createObjectNode();
result.put("NextToken", page.nextToken());
ArrayNode entities = result.putArray("ReputationEntities");
for (ReputationEntity entity : page.items()) {
entities.add(entityJson(entity));
}
return Response.ok(result).build();
}
@GET
@Path("/{type}/{reference}")
public Response getReputationEntity(@Context HttpHeaders headers, @PathParam("type") String type,
@PathParam("reference") String reference) {
String region = regionResolver.resolveRegion(headers);
ObjectNode result = objectMapper.createObjectNode();
result.set("ReputationEntity", entityJson(reputationService.get(type, reference, region)));
return Response.ok(result).build();
}
@PUT
@Path("/{type}/{reference}/policy")
public Response updateReputationEntityPolicy(@Context HttpHeaders headers, @PathParam("type") String type,
@PathParam("reference") String reference, String body) {
String region = regionResolver.resolveRegion(headers);
JsonNode request = readOptionBody(objectMapper, body);
SesV2RequestShapes.check("UpdateReputationEntityPolicy", request);
String policy = stringMemberOrAbsent(request, "ReputationEntityPolicy");
reputationService.updatePolicy(type, reference, policy, region);
return Response.ok(objectMapper.createObjectNode()).build();
}
@PUT
@Path("/{type}/{reference}/customer-managed-status")
public Response updateReputationEntityCustomerManagedStatus(@Context HttpHeaders headers,
@PathParam("type") String type,
@PathParam("reference") String reference,
String body) {
String region = regionResolver.resolveRegion(headers);
JsonNode request = readOptionBody(objectMapper, body);
SesV2RequestShapes.check("UpdateReputationEntityCustomerManagedStatus", request);
String status = stringMemberOrAbsent(request, "SendingStatus");
reputationService.updateCustomerManagedStatus(type, reference, status, region);
return Response.ok(objectMapper.createObjectNode()).build();
}
/** SES renders every member, an unset one as an explicit null. */
private ObjectNode entityJson(ReputationEntity entity) {
ObjectNode node = objectMapper.createObjectNode();
node.putNull("AwsSesManagedStatus");
ReputationStatusRecord status = entity.customerManagedStatus();
if (status == null) {
node.putNull("CustomerManagedStatus");
} else {
ObjectNode record = node.putObject("CustomerManagedStatus");
record.put("Cause", status.cause());
putTimestamp(record, "LastUpdatedTimestamp", status.lastUpdatedTimestamp());
record.put("Status", status.status());
}
node.put("ReputationEntityReference", entity.reference());
node.put("ReputationEntityType", SesReputationEntityService.ENTITY_TYPE);
node.put("ReputationImpact", SesReputationEntityService.NO_IMPACT);
node.put("ReputationManagementPolicy", entity.policy());
node.put("SendingStatusAggregate", entity.sendingStatusAggregate());
return node;
}
}
@@ -0,0 +1,199 @@
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.SmithyValidationErrors;
import io.github.hectorvent.floci.services.ses.model.ReputationStatusRecord;
import io.github.hectorvent.floci.services.ses.model.Tenant;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import org.jboss.logging.Logger;
import java.time.Clock;
import java.time.Instant;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.function.Predicate;
/**
* SES v2 reputation entities. SES makes every tenant one, of type {@code RESOURCE}, referenced by
* the tenant's full ARN, so the state lives on the {@link Tenant} record in
* {@link SesTenantService}; this service validates the requests and derives the entity view.
*
* <p>Behaviour probe-confirmed against real SES (us-west-2, 2026-10-23): every error is a 400
* {@code BadRequestException}, an unknown entity included. Floci has no reputation findings, so
* the impact is always {@code NONE} and SES never manages a status of its own: the customer-managed
* status is the aggregate.
*/
@ApplicationScoped
public class SesReputationEntityService {
private static final Logger LOG = Logger.getLogger(SesReputationEntityService.class);
static final String ENTITY_TYPE = "RESOURCE";
static final String NO_IMPACT = "NONE";
private static final String DEFAULT_POLICY = "standard";
private static final Set<String> POLICIES = Set.of("standard", "strict", "none");
private static final String POLICY_PREFIX = "reputation-policy/";
private static final String POLICY_ACCOUNT = "aws"; // partition-literal: the account SES-managed policies belong to
private static final List<String> SENDING_STATUSES = List.of("ENABLED", "REINSTATED", "DISABLED");
// SES refuses any other impact, but MEDIUM is accepted as a filter although no entity carries it.
private static final Set<String> IMPACTS = Set.of("NONE", "LOW", "MEDIUM", "HIGH");
private static final String MANUAL_CAUSE = "Status manually updated.";
/** A tenant seen as a reputation entity. */
record ReputationEntity(String reference, String policy, ReputationStatusRecord customerManagedStatus,
String sendingStatusAggregate) {
}
private final SesTenantService tenantService;
private final Clock clock;
@Inject
public SesReputationEntityService(SesTenantService tenantService, Clock clock) {
this.tenantService = tenantService;
this.clock = clock;
}
public ReputationEntity get(String type, String reference, String region) {
requireType(type);
requireReference(reference);
return tenantService.findByArn(reference, region)
.map(t -> entity(t, region))
.orElseThrow(() -> entityNotFound(reference));
}
/**
* SES checks the policy before anything else, the entity type included, and answers a missing
* or unknown policy as it answers a reference that is not an ARN. Only the account and the
* resource are checked: a policy of any partition or region, even a blank or unknown one, is
* accepted and stored as given.
*/
public void updatePolicy(String type, String reference, String policy, String region) {
requirePolicy(policy);
requireType(type);
requireReference(reference);
tenantService.updateByArn(reference, region, t -> t.withReputationPolicy(policy))
.orElseThrow(() -> entityNotFound(reference));
LOG.infov("Set reputation policy {0} on SES tenant {1}", policy, reference);
}
/** Setting the status it already has is accepted, and still refreshes the timestamp. */
public void updateCustomerManagedStatus(String type, String reference, String status, String region) {
requireType(type);
requireReference(reference);
if (status == null) {
throw SmithyValidationErrors.badRequest(
"Value at 'sendingStatus' failed to satisfy constraint: Member must not be null");
}
if (!SENDING_STATUSES.contains(status)) {
throw SmithyValidationErrors.badRequest("Value at 'sendingStatus' failed to satisfy constraint: "
+ "Member must satisfy enum value set: [" + String.join(", ", SENDING_STATUSES) + "]");
}
ReputationStatusRecord record = new ReputationStatusRecord(status, MANUAL_CAUSE, Instant.now(clock));
tenantService.updateByArn(reference, region, t -> t.withCustomerManagedStatus(record))
.orElseThrow(() -> entityNotFound(reference));
LOG.infov("Set customer-managed sending status {0} on SES tenant {1}", status, reference);
}
/**
* SES checks the page size and an empty token first, then the filter, then the token. The filter
* holds one key at most, its values are case-sensitive, and a token is bound to the filter it
* came from. Entities are listed by reference.
*/
public PaginatedResult<ReputationEntity> list(Map<String, String> filter, Integer pageSize, String nextToken,
String region) {
SesListPaging paging = SesListPaging.V2_LIST_REPUTATION_ENTITIES;
paging.checkRequest(pageSize, nextToken);
if (filter.size() > 1) {
throw new AwsException("BadRequestException", "Too many filters provided.", 400);
}
Map.Entry<String, String> only = filter.isEmpty() ? null : filter.entrySet().iterator().next();
Predicate<ReputationEntity> matches = filterPredicate(only);
List<ReputationEntity> entities = tenantService.listTenants(region).stream()
.map(t -> entity(t, region))
.filter(matches)
.toList();
String scope = only == null ? "" : only.getKey() + "=" + only.getValue();
try {
return paging.page(region, scope, entities, ReputationEntity::reference, pageSize, nextToken);
} catch (AwsException e) {
if (paging.issuedInRegion(nextToken, region)) {
throw new AwsException("BadRequestException",
"Pagination token is bound to a different set of filtering parameters", 400);
}
throw e;
}
}
private static Predicate<ReputationEntity> filterPredicate(Map.Entry<String, String> entry) {
if (entry == null) {
return e -> true;
}
String value = entry.getValue();
return switch (entry.getKey()) {
case "SENDING_STATUS" -> {
requireFilterValue(entry.getKey(), SENDING_STATUSES.contains(value));
yield e -> value.equals(e.sendingStatusAggregate());
}
case "ENTITY_TYPE" -> {
requireFilterValue(entry.getKey(), ENTITY_TYPE.equals(value));
yield e -> true;
}
case "REPUTATION_IMPACT" -> {
requireFilterValue(entry.getKey(), IMPACTS.contains(value));
yield e -> NO_IMPACT.equals(value);
}
default -> e -> e.reference().startsWith(value);
};
}
private static void requireFilterValue(String key, boolean valid) {
if (!valid) {
throw new AwsException("BadRequestException", "Invalid reputation entity " + key + " specified", 400);
}
}
private static ReputationEntity entity(Tenant tenant, String region) {
String policy = tenant.reputationPolicy() != null
? tenant.reputationPolicy()
: AwsArnUtils.Arn.of("ses", region, POLICY_ACCOUNT, POLICY_PREFIX + DEFAULT_POLICY).toString();
return new ReputationEntity(tenant.tenantArn(), policy, tenant.customerManagedStatus(),
tenant.sendingStatus());
}
private static void requireType(String type) {
if (!ENTITY_TYPE.equals(type)) {
throw SmithyValidationErrors.badRequest("Value at 'reputationEntityType' failed to satisfy "
+ "constraint: Member must satisfy enum value set: [" + ENTITY_TYPE + "]");
}
}
private static void requireReference(String reference) {
if (!AwsArnUtils.isArnFor(reference, "ses")) {
throw invalidIdentifier();
}
}
private static void requirePolicy(String policy) {
if (!AwsArnUtils.isArnFor(policy, "ses")) {
throw invalidIdentifier();
}
AwsArnUtils.Arn arn = AwsArnUtils.parse(policy);
if (!POLICY_ACCOUNT.equals(arn.accountId())
|| !arn.resource().startsWith(POLICY_PREFIX)
|| !POLICIES.contains(arn.resource().substring(POLICY_PREFIX.length()))) {
throw invalidIdentifier();
}
}
private static AwsException invalidIdentifier() {
return new AwsException("BadRequestException", "Provided resource identifier is invalid", 400);
}
private static AwsException entityNotFound(String reference) {
return new AwsException("BadRequestException", "ReputationEntity <" + reference + "> does not exist", 400);
}
}
@@ -160,12 +160,12 @@ public class SesSendController {
List<MessageAttachment> attachments =
parseAttachmentsArray(simple.path("Attachments"), "content.simple.attachments");
requireNoNullAddress(toAddresses, ccAddresses, bccAddresses, replyToAddresses);
sesService.checkTenantSendAccess(tenantName, fromEmailAddress, configurationSetName,
null, regionResolver.getAccountId(), region);
messageId = sesService.sendEmail(sendRequest
SendEmailRequest simpleRequest = sendRequest
.content(new EmailContent.Simple(subject, bodyText, bodyHtml, additionalHeaders,
attachments))
.build());
.build();
sesService.checkTenantSendAccess(simpleRequest, null, regionResolver.getAccountId());
messageId = sesService.sendEmail(simpleRequest);
} else if (content.has("Template")) {
if (fromEmailAddress == null || fromEmailAddress.isBlank()) {
throw new AwsException("BadRequestException", "Source cannot be empty", 400);
@@ -194,11 +194,11 @@ public class SesSendController {
? templateName
: SesTemplateService.templateNameFromArn(templateArn);
requireNoNullAddress(toAddresses, ccAddresses, bccAddresses, replyToAddresses);
sesService.checkTenantSendAccess(tenantName, fromEmailAddress,
configurationSetName, resolvedName, regionResolver.getAccountId(), region);
messageId = sesService.sendEmail(sendRequest
SendEmailRequest templateRequest = sendRequest
.content(new EmailContent.Template(resolvedName, templateData, additionalHeaders))
.build());
.build();
sesService.checkTenantSendAccess(templateRequest, resolvedName, regionResolver.getAccountId());
messageId = sesService.sendEmail(templateRequest);
} else {
JsonNode inline = template.path("TemplateContent");
String subject = inline.path("Subject").asText(null);
@@ -209,12 +209,12 @@ public class SesSendController {
// configuration set pass through the gate.
SesService.requireInlineTemplateContent(subject, text, html);
requireNoNullAddress(toAddresses, ccAddresses, bccAddresses, replyToAddresses);
sesService.checkTenantSendAccess(tenantName, fromEmailAddress,
configurationSetName, null, regionResolver.getAccountId(), region);
messageId = sesService.sendEmail(sendRequest
SendEmailRequest inlineRequest = sendRequest
.content(new EmailContent.InlineTemplate(subject, text, html, templateData,
additionalHeaders))
.build());
.build();
sesService.checkTenantSendAccess(inlineRequest, null, regionResolver.getAccountId());
messageId = sesService.sendEmail(inlineRequest);
}
} else {
throw new AwsException("BadRequestException",
@@ -299,10 +299,9 @@ public class SesSendController {
? templateName
: SesTemplateService.templateNameFromArn(templateArn);
gateTemplateName = resolvedName;
EmailTemplate stored = templateService.getTemplate(resolvedName, region);
subject = stored.getSubject();
text = stored.getTextPart();
html = stored.getHtmlPart();
subject = null;
text = null;
html = null;
}
JsonNode defaultTemplateData = parseTemplateData(template, "TemplateData");
@@ -338,8 +337,15 @@ public class SesSendController {
// The tenant gate runs only after every part of the request has been parsed and
// validated — AWS reports malformed content before a missing tenant (probe-confirmed).
sesService.checkTenantSendAccess(tenantName, fromEmailAddress, configurationSetName,
gateTemplateName, regionResolver.getAccountId(), region);
sesService.checkTenantBulkSendAccess(tenantName, fromEmailAddress, configurationSetName,
gateTemplateName, entries, regionResolver.getAccountId(), region);
// SES reports an unknown or DISABLED tenant before an unknown stored template (probe-confirmed).
if (gateTemplateName != null) {
EmailTemplate stored = templateService.getTemplate(gateTemplateName, region);
subject = stored.getSubject();
text = stored.getTextPart();
html = stored.getHtmlPart();
}
List<BulkEmailEntryResult> results = sesService.sendBulkEmail(SendBulkEmailRequest.builder()
.source(fromEmailAddress)
@@ -379,15 +379,19 @@ public class SesService {
private String validateEnvelope(SendEmailRequest request) {
String source = request.source();
if (!request.hasRecipients()) {
throw new AwsException("InvalidParameterValue", "At least one destination address is required.", 400);
}
requireRecipients(request);
String effectiveConfigSet = resolveDefaultConfigurationSet(request.configurationSetName(), source,
request.region());
configSetService.validateForSending(effectiveConfigSet, request.region());
return effectiveConfigSet;
}
private static void requireRecipients(SendEmailRequest request) {
if (!request.hasRecipients()) {
throw new AwsException("InvalidParameterValue", "At least one destination address is required.", 400);
}
}
private String sendSimpleEmail(SendEmailRequest request, EmailContent.Simple content, String effectiveConfigSet) {
String source = request.source();
String region = request.region();
@@ -1131,20 +1135,58 @@ public class SesService {
/**
* The tenant send gate (Phase 4): resolves the tenant with the send-flavored not-found wording,
* then requires every resource the send uses to be associated with it. The tenant's
* SendingStatus is not checked — no API can move it off ENABLED, so the DISABLED gate is not
* emulated. Placement is probe-confirmed: request-shape validation (a missing Content, an empty
* inline template, a missing FromEmailAddress on Simple, the bulk template-content checks) runs
* before the tenant lookup, while the recipient checks, the raw MIME-From derivation, and
* identity verification all lose to the tenant 404.
* refuses a tenant whose sending is DISABLED, then requires every resource the send uses to be
* associated with it. Placement is probe-confirmed: request-shape validation (a missing Content,
* an empty inline template, a missing FromEmailAddress on Simple, the bulk template-content
* checks) runs before the tenant lookup, while the recipient checks, the raw MIME-From
* derivation, and identity verification all lose to the tenant 404. The DISABLED refusal also
* beats identity verification, the association check and a raw message's missing recipients,
* but an unknown configuration set named by the request is reported before it, and so are the
* address and recipient checks of a Simple or Template send, which goes through the overload
* that takes its envelope.
*/
public void checkTenantSendAccess(String tenantName, String fromEmailAddress,
String configurationSetName, String templateName,
String accountId, String region) {
checkTenantSendAccess(tenantName, fromEmailAddress, configurationSetName, templateName, accountId,
region, null, configurationSetName);
}
/**
* The send gate for SendBulkEmail, which refuses a DISABLED tenant before it looks up the
* configuration set, unlike SendEmail. A request in which no entry names a recipient skips the
* gate altogether, even for an unknown tenant: each entry is answered on its own instead
* (probe-confirmed).
*/
public void checkTenantBulkSendAccess(String tenantName, String fromEmailAddress,
String configurationSetName, String templateName,
List<BulkEmailEntry> entries, String accountId, String region) {
if (!anyBulkRecipient(entries)) {
return;
}
checkTenantSendAccess(tenantName, fromEmailAddress, configurationSetName, templateName, accountId,
region, null, null);
}
/**
* The send gate for a Simple or Template send, whose envelope SES validates before it refuses a
* DISABLED tenant: a malformed address and a request with no recipient are reported first
* (probe-confirmed), while a tenant that may send still meets the gate before them.
*/
public void checkTenantSendAccess(SendEmailRequest envelope, String templateName, String accountId) {
checkTenantSendAccess(envelope.tenantName(), envelope.source(), envelope.configurationSetName(),
templateName, accountId, envelope.region(), envelope, envelope.configurationSetName());
}
private void checkTenantSendAccess(String tenantName, String fromEmailAddress,
String configurationSetName, String templateName,
String accountId, String region, SendEmailRequest envelope,
String configurationSetBeforeRefusal) {
if (tenantName == null) {
return;
}
Tenant tenant = tenantService.tenantForSending(tenantName, region, accountId);
requireSendingEnabled(tenant, configurationSetBeforeRefusal, region, envelope);
String arnPrefix = "arn:" + AwsRegions.partitionFor(region) + ":ses:" + region + ":" + accountId + ":";
List<SesTenantService.AssociationResource> used = new ArrayList<>();
if (fromEmailAddress != null && !fromEmailAddress.isBlank()) {
@@ -1175,7 +1217,8 @@ public class SesService {
* the effective sender comes from the MIME {@code From} header, the same derivation
* {@code sendRawEmail} applies, so the gate must resolve it the same way before checking.
* {@code hasDestination} says whether the request named any recipient; when it did not and the
* MIME To, Cc and Bcc headers are empty too, only the tenant's existence is checked.
* MIME To, Cc and Bcc headers are empty too, only the tenant's existence and sending status
* are checked.
*/
public void checkTenantRawSendAccess(String tenantName, String fromEmailAddress,
String rawMessage, boolean hasDestination,
@@ -1184,10 +1227,12 @@ public class SesService {
return;
}
SmtpRelay.RawMessageHeaders headers = SmtpRelay.parseRawHeaders(rawMessage);
// AWS checks that the tenant exists, then reports a message with no recipients anywhere
// ahead of the association gate (probe-confirmed), so that error is left to sendRawEmail.
// AWS checks that the tenant exists and may send, then reports a message with no recipients
// anywhere ahead of the association gate (probe-confirmed), so that error is left to
// sendRawEmail.
if (!hasDestination && SendEmailRequest.recipients(headers.to(), headers.cc(), headers.bcc()).isEmpty()) {
tenantService.tenantForSending(tenantName, region, accountId);
requireSendingEnabled(tenantService.tenantForSending(tenantName, region, accountId),
firstNonBlank(configurationSetName, headers.configurationSet()), region, null);
return;
}
String effectiveSource = fromEmailAddress;
@@ -1201,6 +1246,22 @@ public class SesService {
accountId, region);
}
private void requireSendingEnabled(Tenant tenant, String configurationSetName, String region,
SendEmailRequest envelope) {
if (!"DISABLED".equals(tenant.sendingStatus())) {
return;
}
if (envelope != null) {
SesAddressSyntax.requireEnvelope(envelope);
requireRecipients(envelope);
}
if (configurationSetName != null && !configurationSetName.isBlank()) {
configSetService.get(configurationSetName, region);
}
throw new AwsException("MessageRejected", "Sending disabled for <" + tenant.tenantArn()
+ ">. For more information, please check the resource configuration and status.", 400);
}
// The gate names the identity the way AWS did in the probed error: the exact address identity
// when one exists, otherwise the domain identity the address falls under. The sender may carry
// display-name syntax ("Name <a@b>"), so the bare address is extracted first.
@@ -1682,11 +1743,18 @@ public class SesService {
}
}
boolean requestHasRecipient = request.entries().stream().anyMatch(SesService::hasNonNullRecipient);
// When no entry names a recipient, SES answers every entry the same, whatever its lists hold
// (probe-confirmed for null elements, empty lists and an empty Destination).
if (!anyBulkRecipient(request.entries())) {
return request.entries().stream()
.map(entry -> BulkEmailEntryResult.failure(BulkEmailEntryResult.Status.INVALID_PARAMETER,
"Destination cannot be empty"))
.toList();
}
List<BulkEmailEntryResult> results = new ArrayList<>(request.entries().size());
for (BulkEmailEntry entry : request.entries()) {
try {
SesAddressSyntax.requireBulkDestination(entry, request.replyToAddresses(), requestHasRecipient);
SesAddressSyntax.requireBulkDestination(entry, request.replyToAddresses());
JsonNode merged = mergeTemplateData(template.templateData(), entry.replacementTemplateData());
List<MessageTag> mergedTags = mergeEmailTags(request.defaultEmailTags(), entry.replacementEmailTags());
List<MessageHeader> mergedHeaders = mergeHeaders(template.headers(), entry.replacementHeaders());
@@ -1723,8 +1791,9 @@ public class SesService {
return results;
}
private static boolean hasNonNullRecipient(BulkEmailEntry entry) {
return Stream.of(entry.toAddresses(), entry.ccAddresses(), entry.bccAddresses())
private static boolean anyBulkRecipient(List<BulkEmailEntry> entries) {
return entries.stream()
.flatMap(entry -> Stream.of(entry.toAddresses(), entry.ccAddresses(), entry.bccAddresses()))
.filter(Objects::nonNull)
.flatMap(List::stream)
.anyMatch(Objects::nonNull);
@@ -114,7 +114,7 @@ public class SesTenantService implements SesTaggable {
String tenantId = generateTenantId();
String tenantArn = AwsArnUtils.Arn.of("ses", region, accountId, "tenant/" + tenantName + "/" + tenantId).toString();
Tenant tenant = new Tenant(tenantName, tenantId, tenantArn, Instant.now(clock), tags,
"ENABLED", attrs);
"ENABLED", attrs, null, null);
// Only the check-then-put needs to be atomic, so two concurrent creates for the same name can't
// both observe the key as absent; the id/ARN/record are built outside the lock.
synchronized (tenantMutationLock) {
@@ -241,6 +241,33 @@ public class SesTenantService implements SesTaggable {
.findFirst();
}
/**
* Resolves a tenant by its full ARN, for the reputation entity operations: unlike the tag
* operations, SES matches the whole ARN there, name and id both (probe-confirmed).
*/
public Optional<Tenant> findByArn(String tenantArn, String region) {
String resource = AwsArnUtils.resourceIfArnFor(tenantArn, "ses").orElse("");
String[] segments = resource.split("/", -1);
if (segments.length != 3 || !"tenant".equals(segments[0])) {
return Optional.empty();
}
return tenantStore.get(tenantKey(region, segments[1]))
.filter(t -> t.tenantArn().equals(tenantArn));
}
/**
* Applies {@code mutation} to the tenant with this ARN under the shared lock, so a concurrent
* tag, suppression-attribute or reputation update is not overwritten by a stale copy. Returns
* the updated tenant, empty when no tenant has the ARN.
*/
public Optional<Tenant> updateByArn(String tenantArn, String region, UnaryOperator<Tenant> mutation) {
synchronized (tenantMutationLock) {
Optional<Tenant> updated = findByArn(tenantArn, region).map(mutation);
updated.ifPresent(t -> tenantStore.put(tenantKey(region, t.tenantName()), t));
return updated;
}
}
/**
* The name/id decomposition of a tenant tag ARN's resource remainder ({@code <name>/<tenantId>}
* after the generic dispatch split off the {@code tenant/} type segment). AWS parses a remainder
@@ -15,6 +15,7 @@ import java.util.LinkedHashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.function.Predicate;
/**
* Helpers shared by the SES v2 REST JSON controllers: body and member shape checks that answer
@@ -207,6 +208,22 @@ final class SesV2Json {
* an empty one.
*/
static Map<String, String> filterValues(Map<String, String> filter, List<String> keys) {
return filterValues(filter, keys, String::isEmpty, "Member must have length greater than or equal to 1");
}
/**
* As above, for a filter whose values are bounded above too. SES printed both bounds for an
* empty value, so a value over the bound is taken to be answered the same way.
*/
static Map<String, String> filterValues(Map<String, String> filter, List<String> keys, int maxValueLength) {
return filterValues(filter, keys,
v -> v.isEmpty() || v.codePointCount(0, v.length()) > maxValueLength,
"Member must have length less than or equal to " + maxValueLength
+ ", Member must have length greater than or equal to 1");
}
private static Map<String, String> filterValues(Map<String, String> filter, List<String> keys,
Predicate<String> invalidValue, String valueConstraint) {
if (filter == null) {
return Map.of();
}
@@ -215,10 +232,10 @@ final class SesV2Json {
+ "failed to satisfy constraint: Map keys must satisfy constraint: "
+ "[Member must satisfy enum value set: [" + String.join(", ", keys) + "]]");
}
if (filter.containsValue("")) {
if (filter.values().stream().anyMatch(v -> v != null && invalidValue.test(v))) {
throw SmithyValidationErrors.badRequest( "Value at 'filter' "
+ "failed to satisfy constraint: Map value must satisfy constraint: "
+ "[Member must have length greater than or equal to 1]");
+ "[" + valueConstraint + "]");
}
Map<String, String> values = new LinkedHashMap<>();
filter.forEach((key, value) -> {
@@ -17,7 +17,9 @@ import java.util.Set;
*
* <p>An operation calls this when its body nests a structure in a structure or holds a list of
* structures, where member-by-member checks drift apart. A flat body, a {@code Tags}-only body and
* a list operation's map {@code Filter} keep the {@link SesV2Json} member helpers.
* a list operation's map {@code Filter} keep the {@link SesV2Json} member helpers, except in the
* reputation entity operations, which were added after this check and call it although their
* bodies are flat.
*
* <p>AWS reads the body in order and reports the first bad member, without naming it. A map
* container answers like a structure, except that a scalar for it is "Expected map or null". Only
@@ -32,7 +32,6 @@ public final class SesAddressSyntax {
private static final List<String> RAW_CHECKED_HEADERS = List.of("To", "Cc", "Bcc");
private static final String MISSING_FINAL_DOMAIN = "Missing final '@domain'";
private static final String NULL_ADDRESS = "Invalid email address null.";
private static final String EMPTY_DESTINATION = "Destination cannot be empty";
private static final String PHRASE_SPECIALS = "()<>@,;:\\\".[]";
private static final String ADDRESS_SPECIALS = "()<>,;:\\\"[]";
@@ -198,26 +197,24 @@ public final class SesAddressSyntax {
* every entry, not as a request error (probe-confirmed). An address list of the wrong JSON type
* never reaches this check: the controller rejects the whole request with SerializationException.
*
* <p>A null element passes deserialization and fails here as "Invalid email address null.",
* unless no entry of the request has a non-null recipient: then an entry holding one answers
* "Destination cannot be empty" (probe-confirmed for To lists of nulls; how SES words an entry
* whose lists are merely empty was not probed, so that case is left as it was).
* <p>A null element passes deserialization and fails here as "Invalid email address null.".
* A request in which no entry has a non-null recipient never reaches this check: the caller
* answers every entry "Destination cannot be empty" instead.
*/
public static void requireBulkDestination(BulkEmailEntry entry, List<String> replyToAddresses,
boolean requestHasRecipient) {
public static void requireBulkDestination(BulkEmailEntry entry, List<String> replyToAddresses) {
for (List<String> addresses : Arrays.asList(entry.toAddresses(), entry.ccAddresses(), entry.bccAddresses())) {
requireBulkAddresses(addresses, requestHasRecipient ? NULL_ADDRESS : EMPTY_DESTINATION);
requireBulkAddresses(addresses);
}
requireBulkAddresses(replyToAddresses, NULL_ADDRESS);
requireBulkAddresses(replyToAddresses);
}
private static void requireBulkAddresses(List<String> addresses, String nullMessage) {
private static void requireBulkAddresses(List<String> addresses) {
if (addresses == null) {
return;
}
for (String address : addresses) {
if (address == null) {
throw new AwsException("InvalidParameterValue", nullMessage, 400);
throw new AwsException("InvalidParameterValue", NULL_ADDRESS, 400);
}
require(address);
}
@@ -0,0 +1,13 @@
package io.github.hectorvent.floci.services.ses.model;
import io.quarkus.runtime.annotations.RegisterForReflection;
import java.time.Instant;
/**
* The SES v2 {@code StatusRecord} of a reputation entity: a {@code SendingStatus} (ENABLED /
* REINSTATED / DISABLED), its cause and when it last changed.
*/
@RegisterForReflection
public record ReputationStatusRecord(String status, String cause, Instant lastUpdatedTimestamp) {
}
@@ -8,7 +8,11 @@ import java.util.List;
/**
* A SES v2 tenant (multi-tenancy). Created by {@code CreateTenant} and returned by
* {@code GetTenant}/{@code ListTenants}. {@code sendingStatus} is the AWS {@code SendingStatus} enum
* (ENABLED / REINSTATED / DISABLED); a freshly created tenant is ENABLED.
* (ENABLED / REINSTATED / DISABLED): the tenant's aggregate status as a reputation entity, ENABLED
* for a freshly created tenant. {@code reputationPolicy} is the policy ARN set by
* {@code UpdateReputationEntityPolicy}, null for the default Standard policy, and
* {@code customerManagedStatus} the record set by {@code UpdateReputationEntityCustomerManagedStatus},
* null until the first update.
*/
@RegisterForReflection
public record Tenant(String tenantName,
@@ -17,16 +21,34 @@ public record Tenant(String tenantName,
Instant createdTimestamp,
List<Tag> tags,
String sendingStatus,
TenantSuppressionAttributes suppressionAttributes) {
TenantSuppressionAttributes suppressionAttributes,
String reputationPolicy,
ReputationStatusRecord customerManagedStatus) {
/** Copy with different tags (records are immutable; the store is replace-only). */
public Tenant withTags(List<Tag> newTags) {
return new Tenant(tenantName, tenantId, tenantArn, createdTimestamp, newTags, sendingStatus,
suppressionAttributes);
suppressionAttributes, reputationPolicy, customerManagedStatus);
}
/** Copy with different suppression attributes (records are immutable; the store is replace-only). */
public Tenant withSuppressionAttributes(TenantSuppressionAttributes attrs) {
return new Tenant(tenantName, tenantId, tenantArn, createdTimestamp, tags, sendingStatus, attrs);
return new Tenant(tenantName, tenantId, tenantArn, createdTimestamp, tags, sendingStatus, attrs,
reputationPolicy, customerManagedStatus);
}
/** Copy with a different reputation management policy ARN. */
public Tenant withReputationPolicy(String policy) {
return new Tenant(tenantName, tenantId, tenantArn, createdTimestamp, tags, sendingStatus,
suppressionAttributes, policy, customerManagedStatus);
}
/**
* Copy with a different customer-managed status. SES manages no status of its own here, so the
* customer-managed one is the aggregate the tenant reports as its {@code sendingStatus}.
*/
public Tenant withCustomerManagedStatus(ReputationStatusRecord status) {
return new Tenant(tenantName, tenantId, tenantArn, createdTimestamp, tags, status.status(),
suppressionAttributes, reputationPolicy, status);
}
}