feat(ses): implement identity (sending authorization) policies for v1 and v2 (#1750)

* feat(ses): implement identity (sending authorization) policies for v1 and v2

Add the SES identity-policy APIs across both protocols, backed by one shared
StorageFactory store (key policy::<region>::<identity>::<policyName>):

- v1 Query: PutIdentityPolicy (upsert), GetIdentityPolicies, ListIdentityPolicies,
  DeleteIdentityPolicy (idempotent).
- v2 REST JSON: CreateEmailIdentityPolicy (fails on duplicate),
  GetEmailIdentityPolicies, UpdateEmailIdentityPolicy (fails when missing),
  DeleteEmailIdentityPolicy.

Behaviour and error shapes were verified against real AWS: the per-identity
limit of 20, the v1/v2 create/update/delete strictness asymmetry, PolicyName
constraints, and the shared v1<->v2 store. Floci stores and returns policies but
does not enforce the authorization (Principal-account existence, Resource-ARN
match) or gate sending on them.

* test(ses): inject policyStore into the test SesService constructor

Thread the identity-policy store through the package-private constructors as a
parameter instead of hardcoding a new InMemoryStorage, matching every other
store and keeping the test constructor aligned with the production wiring.
This commit is contained in:
Kenshin Okinaka authored and GitHub committed 2026-07-27 22:36:47 -05:00
1 parent 4c9f61dfe8
commit 881c45b393
13 files changed
+827 -3

No files matched your search

@@ -391,6 +391,7 @@ public class AwsQueryController {
"SetIdentityHeadersInNotificationsEnabled",
"SetIdentityMailFromDomain", "GetIdentityMailFromDomainAttributes",
"GetIdentityDkimAttributes",
"PutIdentityPolicy", "GetIdentityPolicies", "ListIdentityPolicies", "DeleteIdentityPolicy",
"CreateTemplate", "UpdateTemplate", "GetTemplate", "DeleteTemplate",
"ListTemplates", "SendTemplatedEmail", "SendBulkTemplatedEmail",
"TestRenderTemplate",
@@ -48,6 +48,7 @@ import org.jboss.logging.Logger;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
/**
* REST JSON controller for the AWS SES V2 API.
@@ -175,6 +176,85 @@ public class SesController {
return Response.ok(objectMapper.createObjectNode()).build();
}
// ────────────────── Identity policies (sending authorization) ────────────────
@POST
@Path("/identities/{emailIdentity}/policies/{policyName}")
public Response createEmailIdentityPolicy(@Context HttpHeaders headers,
@PathParam("emailIdentity") String emailIdentity,
@PathParam("policyName") String policyName, String body) {
String region = regionResolver.resolveRegion(headers);
try {
String policy = readPolicyBody(body);
sesService.createEmailIdentityPolicy(emailIdentity, policyName, policy, region);
return Response.ok(objectMapper.createObjectNode()).build();
} catch (AwsException e) {
throw remapV1Exception(e);
} catch (com.fasterxml.jackson.core.JsonProcessingException e) {
throw new AwsException("BadRequestException", e.getMessage(), 400);
}
}
@PUT
@Path("/identities/{emailIdentity}/policies/{policyName}")
public Response updateEmailIdentityPolicy(@Context HttpHeaders headers,
@PathParam("emailIdentity") String emailIdentity,
@PathParam("policyName") String policyName, String body) {
String region = regionResolver.resolveRegion(headers);
try {
String policy = readPolicyBody(body);
sesService.updateEmailIdentityPolicy(emailIdentity, policyName, policy, region);
return Response.ok(objectMapper.createObjectNode()).build();
} catch (AwsException e) {
throw remapV1Exception(e);
} catch (com.fasterxml.jackson.core.JsonProcessingException e) {
throw new AwsException("BadRequestException", e.getMessage(), 400);
}
}
@GET
@Path("/identities/{emailIdentity}/policies")
public Response getEmailIdentityPolicies(@Context HttpHeaders headers,
@PathParam("emailIdentity") String emailIdentity) {
String region = regionResolver.resolveRegion(headers);
Map<String, String> policies = sesService.getEmailIdentityPolicies(emailIdentity, region);
ObjectNode result = objectMapper.createObjectNode();
ObjectNode policiesNode = result.putObject("Policies");
policies.forEach(policiesNode::put);
return Response.ok(result).build();
}
@DELETE
@Path("/identities/{emailIdentity}/policies/{policyName}")
public Response deleteEmailIdentityPolicy(@Context HttpHeaders headers,
@PathParam("emailIdentity") String emailIdentity,
@PathParam("policyName") String policyName) {
String region = regionResolver.resolveRegion(headers);
sesService.deleteEmailIdentityPolicy(emailIdentity, policyName, region);
return Response.ok(objectMapper.createObjectNode()).build();
}
private String readPolicyBody(String body) throws com.fasterxml.jackson.core.JsonProcessingException {
if (body == null || body.isBlank()) {
throw new AwsException("BadRequestException", "Request body is required.", 400);
}
JsonNode request = objectMapper.readTree(body);
requireJsonObject(request);
JsonNode policyNode = request.path("Policy");
if (policyNode.isMissingNode() || policyNode.isNull()) {
// Verified against AWS: a missing/null required member is a Smithy validation error.
throw new AwsException("BadRequestException",
"1 validation error detected: Value at 'policy' failed to satisfy constraint: "
+ "Member must not be null", 400);
}
if (!policyNode.isTextual()) {
// Policy is a String; AWS rejects a non-string with an empty-bodied 400. Don't coerce
// (asText would turn 123 into "123"); surface a serialization error instead.
throw new AwsException("SerializationException", null, 400);
}
return policyNode.textValue();
}
// ──────────────────────── Identity DKIM ─────────────────────────
@PUT
@@ -2116,7 +2196,7 @@ public class SesController {
private static AwsException remapV1Exception(AwsException e) {
return switch (e.getErrorCode()) {
case "InvalidParameterValue", "InvalidTemplate",
case "InvalidParameterValue", "InvalidTemplate", "ValidationError",
"InvalidRenderingParameter", "MissingRenderingAttribute" ->
new AwsException("BadRequestException", e.getMessage(), 400);
case "TemplateDoesNotExist", "ConfigurationSetDoesNotExist" ->
@@ -27,6 +27,7 @@ import org.jboss.logging.Logger;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.Map;
/**
* Query-protocol handler for SES actions.
@@ -72,6 +73,10 @@ public class SesQueryHandler {
case "SetIdentityMailFromDomain" -> handleSetIdentityMailFromDomain(params, region);
case "GetIdentityMailFromDomainAttributes" -> handleGetIdentityMailFromDomainAttributes(params, region);
case "GetIdentityDkimAttributes" -> handleGetIdentityDkimAttributes(params, region);
case "PutIdentityPolicy" -> handlePutIdentityPolicy(params, region);
case "GetIdentityPolicies" -> handleGetIdentityPolicies(params, region);
case "ListIdentityPolicies" -> handleListIdentityPolicies(params, region);
case "DeleteIdentityPolicy" -> handleDeleteIdentityPolicy(params, region);
case "CreateTemplate" -> handleCreateTemplate(params, region);
case "UpdateTemplate" -> handleUpdateTemplate(params, region);
case "GetTemplate" -> handleGetTemplate(params, region);
@@ -399,6 +404,43 @@ public class SesQueryHandler {
return Response.ok(AwsQueryResponse.envelope("GetIdentityMailFromDomainAttributes", AwsNamespaces.SES, xml.build())).build();
}
// --- Identity (sending authorization) policies ---
private Response handlePutIdentityPolicy(MultivaluedMap<String, String> params, String region) {
String identity = requireParam(params, "Identity");
String policyName = requireParam(params, "PolicyName");
String policy = requireParam(params, "Policy");
sesService.putIdentityPolicy(identity, policyName, policy, region);
return Response.ok(AwsQueryResponse.envelopeEmptyResult("PutIdentityPolicy", AwsNamespaces.SES)).build();
}
private Response handleGetIdentityPolicies(MultivaluedMap<String, String> params, String region) {
String identity = requireParam(params, "Identity");
List<String> names = extractMembers(params, "PolicyNames");
Map<String, String> policies = sesService.getIdentityPolicies(identity, names, region);
var xml = new XmlBuilder().start("Policies");
policies.forEach((name, doc) -> xml.start("entry").elem("key", name).elem("value", doc).end("entry"));
xml.end("Policies");
return Response.ok(AwsQueryResponse.envelope("GetIdentityPolicies", AwsNamespaces.SES, xml.build())).build();
}
private Response handleListIdentityPolicies(MultivaluedMap<String, String> params, String region) {
String identity = requireParam(params, "Identity");
var xml = new XmlBuilder().start("PolicyNames");
for (String name : sesService.listIdentityPolicyNames(identity, region)) {
xml.elem("member", name);
}
xml.end("PolicyNames");
return Response.ok(AwsQueryResponse.envelope("ListIdentityPolicies", AwsNamespaces.SES, xml.build())).build();
}
private Response handleDeleteIdentityPolicy(MultivaluedMap<String, String> params, String region) {
String identity = requireParam(params, "Identity");
String policyName = requireParam(params, "PolicyName");
sesService.deleteIdentityPolicy(identity, policyName, region);
return Response.ok(AwsQueryResponse.envelopeEmptyResult("DeleteIdentityPolicy", AwsNamespaces.SES)).build();
}
// --- Templates ---
private Response handleCreateTemplate(MultivaluedMap<String, String> params, String region) {
@@ -87,11 +87,17 @@ public class SesService {
private final StorageBackend<String, DedicatedIpPool> dedicatedIpPoolStore;
private final StorageBackend<String, ContactList> contactListStore;
private final StorageBackend<String, Contact> contactStore;
// Identity (sending authorization) policies: key policy::<region>::<identity>::<policyName>,
// value the (normalized) policy JSON. One store shared by the v1 and v2 policy APIs.
private final StorageBackend<String, String> policyStore;
// Guards the one-list-per-account check-then-create so concurrent creates can't both pass.
private final Object contactListCreateLock = new Object();
// Serializes contact create/update against contact-list deletion so a concurrent delete
// can't purge the list between validation and the write, leaving an orphaned contact.
private final Object contactMutationLock = new Object();
// Serializes the per-identity policy count check-then-put so concurrent creates can't both pass.
private final Object policyMutationLock = new Object();
static final int MAX_POLICIES_PER_IDENTITY = 20;
private final SmtpRelay smtpRelay;
private final ObjectMapper objectMapper;
private final SesEventPublisher eventPublisher;
@@ -124,6 +130,8 @@ public class SesService {
new TypeReference<Map<String, ContactList>>() {});
this.contactStore = storageFactory.create("ses", "ses-contacts.json",
new TypeReference<Map<String, Contact>>() {});
this.policyStore = storageFactory.create("ses", "ses-identity-policies.json",
new TypeReference<Map<String, String>>() {});
this.smtpRelay = smtpRelay;
this.objectMapper = objectMapper;
this.eventPublisher = eventPublisher;
@@ -142,11 +150,12 @@ public class SesService {
StorageBackend<String, DedicatedIpPool> dedicatedIpPoolStore,
StorageBackend<String, ContactList> contactListStore,
StorageBackend<String, Contact> contactStore,
StorageBackend<String, String> policyStore,
SmtpRelay smtpRelay,
ObjectMapper objectMapper,
Clock clock) {
this(identityStore, emailStore, accountSettingsStore, templateStore, configSetStore, suppressionStore,
accountSuppressionStore, dedicatedIpPoolStore, contactListStore, contactStore, smtpRelay,
accountSuppressionStore, dedicatedIpPoolStore, contactListStore, contactStore, policyStore, smtpRelay,
objectMapper, null, clock);
}
@@ -160,6 +169,7 @@ public class SesService {
StorageBackend<String, DedicatedIpPool> dedicatedIpPoolStore,
StorageBackend<String, ContactList> contactListStore,
StorageBackend<String, Contact> contactStore,
StorageBackend<String, String> policyStore,
SmtpRelay smtpRelay,
ObjectMapper objectMapper,
Route53Service route53Service,
@@ -174,6 +184,7 @@ public class SesService {
this.dedicatedIpPoolStore = dedicatedIpPoolStore;
this.contactListStore = contactListStore;
this.contactStore = contactStore;
this.policyStore = policyStore;
this.smtpRelay = smtpRelay;
this.objectMapper = objectMapper;
this.eventPublisher = null;
@@ -235,6 +246,17 @@ public class SesService {
}
}
// Policies are sub-resources of the identity; drop them too so they can't resurrect into a
// same-named identity recreated later (and so the per-identity count stays correct).
synchronized (policyMutationLock) {
String policyPrefix = policyPrefix(region, identityValue);
for (String policyKey : new ArrayList<>(policyStore.keys())) {
if (policyKey.startsWith(policyPrefix)) {
policyStore.delete(policyKey);
}
}
}
LOG.infov("Deleted identity: {0}", identityValue);
}
@@ -1434,6 +1456,171 @@ public class SesService {
}
}
// ──────────────── Identity (sending authorization) policies ────────────────
// One shared store behind the v1 (PutIdentityPolicy/GetIdentityPolicies/ListIdentityPolicies/
// DeleteIdentityPolicy) and v2 (Create/Get/Update/DeleteEmailIdentityPolicy) APIs. Verified
// against real AWS. Floci stores and returns policies but does not enforce the authorization
// (Principal-account existence, Resource-ARN match, or send-time checks) — it has no account
// registry and does not gate sending, so these are treated as metadata.
private static final Pattern POLICY_NAME_CHARS = Pattern.compile("[A-Za-z0-9_-]+");
// v1 PutIdentityPolicy: upsert (create or overwrite); v1 does not require the identity to exist.
public void putIdentityPolicy(String identity, String policyName, String policy, String region) {
validatePolicyName(policyName);
String normalized = normalizePolicy(policy);
String key = policyKey(region, identity, policyName);
synchronized (policyMutationLock) {
if (policyStore.get(key).isEmpty()) {
enforcePolicyLimit(region, identity, false);
}
policyStore.put(key, normalized);
}
LOG.infov("SES PutIdentityPolicy: {0} on {1} (region {2})", policyName, identity, region);
}
// v2 CreateEmailIdentityPolicy: fails if the name already exists; requires the identity.
public void createEmailIdentityPolicy(String identity, String policyName, String policy, String region) {
requireIdentityExists(identity, region);
validatePolicyName(policyName);
String normalized = normalizePolicy(policy);
String key = policyKey(region, identity, policyName);
synchronized (policyMutationLock) {
if (policyStore.get(key).isPresent()) {
throw new AwsException("AlreadyExistsException",
"Policy <" + policyName + "> already exists", 400);
}
enforcePolicyLimit(region, identity, true);
policyStore.put(key, normalized);
}
LOG.infov("SES v2 CreateEmailIdentityPolicy: {0} on {1} (region {2})", policyName, identity, region);
}
// v2 UpdateEmailIdentityPolicy: fails if the name is missing; requires the identity.
public void updateEmailIdentityPolicy(String identity, String policyName, String policy, String region) {
requireIdentityExists(identity, region);
validatePolicyName(policyName);
String normalized = normalizePolicy(policy);
String key = policyKey(region, identity, policyName);
synchronized (policyMutationLock) {
if (policyStore.get(key).isEmpty()) {
throw policyNotFound(policyName);
}
policyStore.put(key, normalized);
}
LOG.infov("SES v2 UpdateEmailIdentityPolicy: {0} on {1} (region {2})", policyName, identity, region);
}
// v2 GetEmailIdentityPolicies: all policies for the identity; requires the identity.
public Map<String, String> getEmailIdentityPolicies(String identity, String region) {
requireIdentityExists(identity, region);
return listPolicies(region, identity);
}
// v1 GetIdentityPolicies: requested names only, missing silently omitted; no identity check.
public Map<String, String> getIdentityPolicies(String identity, List<String> policyNames, String region) {
Map<String, String> out = new LinkedHashMap<>();
for (String name : policyNames) {
policyStore.get(policyKey(region, identity, name)).ifPresent(doc -> out.put(name, doc));
}
return out;
}
// v1 ListIdentityPolicies: policy names (sorted); no identity check.
public List<String> listIdentityPolicyNames(String identity, String region) {
return listPolicies(region, identity).keySet().stream().sorted().toList();
}
// v2 DeleteEmailIdentityPolicy: requires the identity; NotFound if the policy is missing.
public void deleteEmailIdentityPolicy(String identity, String policyName, String region) {
requireIdentityExists(identity, region);
String key = policyKey(region, identity, policyName);
synchronized (policyMutationLock) {
if (policyStore.get(key).isEmpty()) {
throw policyNotFound(policyName);
}
policyStore.delete(key);
}
LOG.infov("SES v2 DeleteEmailIdentityPolicy: {0} on {1} (region {2})", policyName, identity, region);
}
// v1 DeleteIdentityPolicy: idempotent; no identity check, no error on a missing policy.
public void deleteIdentityPolicy(String identity, String policyName, String region) {
policyStore.delete(policyKey(region, identity, policyName));
LOG.infov("SES DeleteIdentityPolicy: {0} on {1} (region {2})", policyName, identity, region);
}
private Map<String, String> listPolicies(String region, String identity) {
String prefix = policyPrefix(region, identity);
Map<String, String> out = new LinkedHashMap<>();
for (String key : policyStore.keys()) {
if (key.startsWith(prefix)) {
policyStore.get(key).ifPresent(doc -> out.put(key.substring(prefix.length()), doc));
}
}
return out;
}
private void enforcePolicyLimit(String region, String identity, boolean v2) {
long count = policyStore.keys().stream()
.filter(k -> k.startsWith(policyPrefix(region, identity))).count();
if (count >= MAX_POLICIES_PER_IDENTITY) {
String msg = "Number of policies for <" + identity
+ "> exceeds max allowed number of policies per resource";
throw new AwsException(v2 ? "LimitExceededException" : "InvalidParameterValue", msg, 400);
}
}
private void requireIdentityExists(String identity, String region) {
if (identityStore.get(identityKey(region, identity)).isEmpty()) {
throw new AwsException("NotFoundException",
"Email identity <" + identity + "> does not exist.", 404);
}
}
// Error codes are the v1 (Query) codes verified against AWS; the v2 controller remaps them to
// BadRequestException. The messages are identical across v1 and v2.
private static void validatePolicyName(String policyName) {
if (policyName == null || policyName.isBlank()) {
throw new AwsException("InvalidParameterValue", "PolicyName is required.", 400);
}
if (policyName.length() > 64) {
throw new AwsException("ValidationError",
"1 validation error detected: Value at 'policyName' failed to satisfy constraint: "
+ "Member must have length less than or equal to 64", 400);
}
if (!POLICY_NAME_CHARS.matcher(policyName).matches()) {
throw new AwsException("InvalidParameterValue",
"PolicyName is invalid. Policy names must only include alpha-numeric characters, "
+ "dashes, and underscores.", 400);
}
}
private String normalizePolicy(String policy) {
if (policy == null || policy.isBlank()) {
throw new AwsException("InvalidParameterValue", "Policy is required.", 400);
}
try {
// AWS returns the policy with insignificant whitespace stripped; compact it to match.
return objectMapper.readTree(policy).toString();
} catch (com.fasterxml.jackson.core.JsonProcessingException e) {
// Floci does not validate policy semantics; keep an unparseable document verbatim.
LOG.debugv("Identity policy is not valid JSON, storing as-is: {0}", e.getMessage());
return policy;
}
}
private static AwsException policyNotFound(String policyName) {
return new AwsException("NotFoundException", "Policy <" + policyName + "> does not exist", 404);
}
private static String policyKey(String region, String identity, String policyName) {
return policyPrefix(region, identity) + policyName;
}
private static String policyPrefix(String region, String identity) {
return "policy::" + region + "::" + identity + "::";
}
// Validates Create/Update input in the same two-phase order as real AWS (verified by probe):
// protocol-layer (Smithy) checks across all fields first, then service-level constraints with
// ContactListName ahead of topic/description constraints.