mirror of
https://github.com/floci-io/floci.git
synced 2026-11-24 06:20:24 -05:00
feat(ses): support v2 tenant resource associations (#2710)
* feat(ses): support v2 tenant resource associations * fix(ses): reject nameless association ARNs and stop key-suffix resource matching
This commit is contained in:
1 parent
2a7c94b04d
commit
67f75c7e1d
9 files changed
+1106
-23
No files matched your search
@@ -27,6 +27,7 @@ import io.github.hectorvent.floci.services.ses.model.SuppressedDestination;
|
||||
import io.github.hectorvent.floci.services.ses.model.SuppressionOptions;
|
||||
import io.github.hectorvent.floci.services.ses.model.Tag;
|
||||
import io.github.hectorvent.floci.services.ses.model.Tenant;
|
||||
import io.github.hectorvent.floci.services.ses.model.TenantResourceAssociation;
|
||||
import io.github.hectorvent.floci.services.ses.model.TrackingOptions;
|
||||
import io.github.hectorvent.floci.services.ses.model.VdmOptions;
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
@@ -945,6 +946,126 @@ public class SesController {
|
||||
}
|
||||
}
|
||||
|
||||
// Phase 2: tenant→resource associations. AWS's wire format for ResourceType — in responses and as
|
||||
// the RESOURCE_TYPE filter value — is the ARN segment (identity / configuration-set / template),
|
||||
// not the SDK's EMAIL_IDENTITY-style enum spelling; real AWS rejects the enum spelling.
|
||||
|
||||
@POST
|
||||
@Path("/tenants/resources")
|
||||
public Response createTenantResourceAssociation(@Context HttpHeaders headers, String body) {
|
||||
String region = regionResolver.resolveRegion(headers);
|
||||
try {
|
||||
JsonNode request = (body == null || body.isBlank())
|
||||
? objectMapper.createObjectNode()
|
||||
: objectMapper.readTree(body);
|
||||
requireJsonObject(request);
|
||||
String tenantName = stringMemberOrAbsent(request, "TenantName");
|
||||
String resourceArn = stringMemberOrAbsent(request, "ResourceArn");
|
||||
sesService.createTenantResourceAssociation(tenantName, resourceArn,
|
||||
regionResolver.getAccountId(), region);
|
||||
return Response.ok(objectMapper.createObjectNode()).build();
|
||||
} catch (AwsException e) {
|
||||
throw remapV1Exception(e);
|
||||
} catch (com.fasterxml.jackson.core.JsonProcessingException e) {
|
||||
throw new AwsException("SerializationException", null, 400);
|
||||
}
|
||||
}
|
||||
|
||||
@POST
|
||||
@Path("/tenants/resources/delete")
|
||||
public Response deleteTenantResourceAssociation(@Context HttpHeaders headers, String body) {
|
||||
String region = regionResolver.resolveRegion(headers);
|
||||
try {
|
||||
JsonNode request = (body == null || body.isBlank())
|
||||
? objectMapper.createObjectNode()
|
||||
: objectMapper.readTree(body);
|
||||
requireJsonObject(request);
|
||||
String tenantName = stringMemberOrAbsent(request, "TenantName");
|
||||
String resourceArn = stringMemberOrAbsent(request, "ResourceArn");
|
||||
sesService.deleteTenantResourceAssociation(tenantName, resourceArn,
|
||||
regionResolver.getAccountId(), region);
|
||||
return Response.ok(objectMapper.createObjectNode()).build();
|
||||
} catch (AwsException e) {
|
||||
throw remapV1Exception(e);
|
||||
} catch (com.fasterxml.jackson.core.JsonProcessingException e) {
|
||||
throw new AwsException("SerializationException", null, 400);
|
||||
}
|
||||
}
|
||||
|
||||
@POST
|
||||
@Path("/tenants/resources/list")
|
||||
public Response listTenantResources(@Context HttpHeaders headers, String body) {
|
||||
String region = regionResolver.resolveRegion(headers);
|
||||
try {
|
||||
JsonNode request = (body == null || body.isBlank())
|
||||
? objectMapper.createObjectNode()
|
||||
: objectMapper.readTree(body);
|
||||
requireJsonObject(request);
|
||||
String tenantName = stringMemberOrAbsent(request, "TenantName");
|
||||
String resourceTypeFilter = null;
|
||||
JsonNode filter = request.path("Filter");
|
||||
if (!filter.isMissingNode() && !filter.isNull()) {
|
||||
if (!filter.isObject()) {
|
||||
throw new AwsException("SerializationException", null, 400);
|
||||
}
|
||||
resourceTypeFilter = stringMemberOrAbsent(filter, "RESOURCE_TYPE");
|
||||
}
|
||||
Integer pageSize = intMemberOrAbsent(request, "PageSize");
|
||||
String nextToken = stringMemberOrAbsent(request, "NextToken");
|
||||
List<TenantResourceAssociation> associations = sesService.listTenantResources(
|
||||
tenantName, resourceTypeFilter, pageSize, nextToken, region);
|
||||
ObjectNode result = objectMapper.createObjectNode();
|
||||
// AWS renders NextToken as an explicit null on the last (here: only) page.
|
||||
result.putNull("NextToken");
|
||||
ArrayNode resources = result.putArray("TenantResources");
|
||||
for (TenantResourceAssociation a : associations) {
|
||||
ObjectNode item = resources.addObject();
|
||||
item.put("ResourceArn", a.resourceArn());
|
||||
item.put("ResourceType", a.resourceType());
|
||||
}
|
||||
return Response.ok(result).build();
|
||||
} catch (AwsException e) {
|
||||
throw remapV1Exception(e);
|
||||
} catch (com.fasterxml.jackson.core.JsonProcessingException e) {
|
||||
throw new AwsException("SerializationException", null, 400);
|
||||
}
|
||||
}
|
||||
|
||||
@POST
|
||||
@Path("/resources/tenants/list")
|
||||
public Response listResourceTenants(@Context HttpHeaders headers, String body) {
|
||||
String region = regionResolver.resolveRegion(headers);
|
||||
try {
|
||||
JsonNode request = (body == null || body.isBlank())
|
||||
? objectMapper.createObjectNode()
|
||||
: objectMapper.readTree(body);
|
||||
requireJsonObject(request);
|
||||
String resourceArn = stringMemberOrAbsent(request, "ResourceArn");
|
||||
Integer pageSize = intMemberOrAbsent(request, "PageSize");
|
||||
String nextToken = stringMemberOrAbsent(request, "NextToken");
|
||||
List<TenantResourceAssociation> associations = sesService.listResourceTenants(
|
||||
resourceArn, pageSize, nextToken, regionResolver.getAccountId(), region);
|
||||
ObjectNode result = objectMapper.createObjectNode();
|
||||
result.putNull("NextToken");
|
||||
ArrayNode tenants = result.putArray("ResourceTenants");
|
||||
for (TenantResourceAssociation a : associations) {
|
||||
// ResourceTenantMetadata has no TenantArn (probe-confirmed).
|
||||
ObjectNode item = tenants.addObject();
|
||||
item.put("TenantName", a.tenantName());
|
||||
item.put("TenantId", a.tenantId());
|
||||
item.put("ResourceArn", a.resourceArn());
|
||||
if (a.associatedTimestamp() != null) {
|
||||
item.put("AssociatedTimestamp", a.associatedTimestamp().toEpochMilli() / 1000.0);
|
||||
}
|
||||
}
|
||||
return Response.ok(result).build();
|
||||
} catch (AwsException e) {
|
||||
throw remapV1Exception(e);
|
||||
} catch (com.fasterxml.jackson.core.JsonProcessingException e) {
|
||||
throw new AwsException("SerializationException", null, 400);
|
||||
}
|
||||
}
|
||||
|
||||
// Read a typed string member: absent/null returns null, but a present value of the wrong JSON type
|
||||
// is rejected rather than coerced (asText would turn 123 into "123"), matching AWS.
|
||||
private static String stringMemberOrAbsent(JsonNode parent, String field) {
|
||||
@@ -2141,6 +2262,20 @@ public class SesController {
|
||||
return n.textValue();
|
||||
}
|
||||
|
||||
// Integer variant of stringMemberOrAbsent: absent/null returns null, non-integral JSON is
|
||||
// rejected rather than coerced, and so is an integral value outside the int range (intValue
|
||||
// would silently truncate it).
|
||||
private static Integer intMemberOrAbsent(JsonNode parent, String field) {
|
||||
JsonNode n = parent.path(field);
|
||||
if (n.isMissingNode() || n.isNull()) {
|
||||
return null;
|
||||
}
|
||||
if (!n.isIntegralNumber() || !n.canConvertToInt()) {
|
||||
throw new AwsException("SerializationException", null, 400);
|
||||
}
|
||||
return n.intValue();
|
||||
}
|
||||
|
||||
// Parse an AWS FeatureStatus (ENABLED/DISABLED) field. A required member that is absent, or any
|
||||
// value outside the enum, is a Smithy BadRequestException the way AWS returns it; an absent
|
||||
// optional member defaults to DISABLED (false).
|
||||
|
||||
@@ -36,6 +36,7 @@ import io.github.hectorvent.floci.services.ses.model.TrackingOptions;
|
||||
import io.github.hectorvent.floci.services.ses.model.VdmOptions;
|
||||
import io.github.hectorvent.floci.services.ses.model.SentEmail;
|
||||
import io.github.hectorvent.floci.services.ses.model.Tenant;
|
||||
import io.github.hectorvent.floci.services.ses.model.TenantResourceAssociation;
|
||||
import io.github.hectorvent.floci.services.ses.model.SuppressedDestination;
|
||||
import io.github.hectorvent.floci.services.ses.model.SuppressionOptions;
|
||||
import io.github.hectorvent.floci.services.ses.model.Tag;
|
||||
@@ -260,6 +261,11 @@ public class SesService {
|
||||
if (identityValue == null || identityValue.isBlank()) {
|
||||
return;
|
||||
}
|
||||
tenantService.deleteBackingResource(SesTenantService.RESOURCE_TYPE_IDENTITY, identityValue,
|
||||
region, () -> doDeleteIdentity(identityValue, region));
|
||||
}
|
||||
|
||||
private void doDeleteIdentity(String identityValue, String region) {
|
||||
String key = identityKey(region, identityValue);
|
||||
identityStore.delete(key);
|
||||
invalidateDkimLookupCache(region, identityValue);
|
||||
@@ -1185,7 +1191,8 @@ public class SesService {
|
||||
}
|
||||
|
||||
public void deleteTemplate(String templateName, String region) {
|
||||
templateService.deleteTemplate(templateName, region);
|
||||
tenantService.deleteBackingResource(SesTenantService.RESOURCE_TYPE_TEMPLATE, templateName,
|
||||
region, () -> templateService.deleteTemplate(templateName, region));
|
||||
}
|
||||
|
||||
public List<EmailTemplate> listTemplates(String region) {
|
||||
@@ -1634,8 +1641,11 @@ public class SesService {
|
||||
throw new AwsException("ConfigurationSetDoesNotExist",
|
||||
"Configuration set <" + name + "> does not exist.", 400);
|
||||
}
|
||||
configSetStore.delete(key);
|
||||
LOG.infov("Deleted SES configuration set: {0} in region {1}", name, region);
|
||||
tenantService.deleteBackingResource(SesTenantService.RESOURCE_TYPE_CONFIGURATION_SET, name,
|
||||
region, () -> {
|
||||
configSetStore.delete(key);
|
||||
LOG.infov("Deleted SES configuration set: {0} in region {1}", name, region);
|
||||
});
|
||||
}
|
||||
|
||||
private static final Pattern CONFIG_SET_NAME = Pattern.compile("^[A-Za-z0-9_-]{1,64}$");
|
||||
@@ -1664,6 +1674,77 @@ public class SesService {
|
||||
tenantService.deleteTenant(tenantName, region);
|
||||
}
|
||||
|
||||
// The association operations validate resource existence here in the facade — the tenant domain
|
||||
// owns the association store, but only this class can reach the identity/configuration-set/template
|
||||
// stores without a service→service dependency.
|
||||
|
||||
public void createTenantResourceAssociation(String tenantName, String resourceArn,
|
||||
String accountId, String region) {
|
||||
SesTenantService.AssociationResource ref =
|
||||
SesTenantService.parseResourceArn(resourceArn, accountId, region);
|
||||
Tenant tenant = tenantService.tenantForAssociation(tenantName, region);
|
||||
// The existence check runs inside the association lock so it stays atomic with the
|
||||
// backing-resource delete guards.
|
||||
tenantService.associate(tenant, ref, region, () -> requireTenantResourceExists(ref, region));
|
||||
}
|
||||
|
||||
public void deleteTenantResourceAssociation(String tenantName, String resourceArn,
|
||||
String accountId, String region) {
|
||||
SesTenantService.AssociationResource ref =
|
||||
SesTenantService.parseResourceArn(resourceArn, accountId, region);
|
||||
Tenant tenant = tenantService.tenantForAssociation(tenantName, region);
|
||||
// AWS still 404s on a missing resource even though removing a missing association succeeds.
|
||||
requireTenantResourceExists(ref, region);
|
||||
tenantService.disassociate(tenant, ref, region);
|
||||
}
|
||||
|
||||
public List<TenantResourceAssociation> listTenantResources(String tenantName,
|
||||
String resourceTypeFilter,
|
||||
Integer pageSize, String nextToken,
|
||||
String region) {
|
||||
SesTenantService.validateListPaging(pageSize, nextToken);
|
||||
SesTenantService.validateResourceTypeFilter(resourceTypeFilter);
|
||||
Tenant tenant = tenantService.tenantForAssociation(tenantName, region);
|
||||
return tenantService.listTenantResources(tenant, resourceTypeFilter, region);
|
||||
}
|
||||
|
||||
public List<TenantResourceAssociation> listResourceTenants(String resourceArn, Integer pageSize,
|
||||
String nextToken, String accountId,
|
||||
String region) {
|
||||
SesTenantService.validateListPaging(pageSize, nextToken);
|
||||
SesTenantService.AssociationResource ref =
|
||||
SesTenantService.parseResourceArn(resourceArn, accountId, region);
|
||||
requireTenantResourceExists(ref, region);
|
||||
return tenantService.listResourceTenants(ref, region);
|
||||
}
|
||||
|
||||
// The association APIs 404 with a per-type message when the referenced resource is missing; the
|
||||
// trailing colon on the configuration-set variant is AWS's own.
|
||||
private void requireTenantResourceExists(SesTenantService.AssociationResource ref, String region) {
|
||||
boolean exists = switch (ref.type()) {
|
||||
case SesTenantService.RESOURCE_TYPE_IDENTITY ->
|
||||
identityStore.get(identityKey(region, ref.name())).isPresent();
|
||||
case SesTenantService.RESOURCE_TYPE_CONFIGURATION_SET ->
|
||||
CONFIG_SET_NAME.matcher(ref.name()).matches()
|
||||
&& configSetStore.get(configSetKey(region, ref.name())).isPresent();
|
||||
case SesTenantService.RESOURCE_TYPE_TEMPLATE ->
|
||||
templateService.find(ref.name(), region).isPresent();
|
||||
default -> false;
|
||||
};
|
||||
if (exists) {
|
||||
return;
|
||||
}
|
||||
String message = switch (ref.type()) {
|
||||
case SesTenantService.RESOURCE_TYPE_IDENTITY ->
|
||||
"Identity <" + ref.name() + "> does not exist";
|
||||
case SesTenantService.RESOURCE_TYPE_CONFIGURATION_SET ->
|
||||
"Configuration set <" + ref.name() + "> does not exist:";
|
||||
default -> "Email template <" + ref.name() + "> does not exist";
|
||||
};
|
||||
throw new AwsException("NotFoundException", message, 404);
|
||||
}
|
||||
|
||||
|
||||
// ──────────────────────── Receipt rule sets (inbound) ────────────────────────
|
||||
//
|
||||
// Receipt rule sets live in SesReceiptRuleService; this facade
|
||||
|
||||
@@ -6,6 +6,7 @@ import io.github.hectorvent.floci.core.storage.StorageBackend;
|
||||
import io.github.hectorvent.floci.core.storage.StorageFactory;
|
||||
import io.github.hectorvent.floci.services.ses.model.Tag;
|
||||
import io.github.hectorvent.floci.services.ses.model.Tenant;
|
||||
import io.github.hectorvent.floci.services.ses.model.TenantResourceAssociation;
|
||||
import jakarta.enterprise.context.ApplicationScoped;
|
||||
import jakarta.inject.Inject;
|
||||
import org.jboss.logging.Logger;
|
||||
@@ -28,8 +29,9 @@ import java.util.regex.Pattern;
|
||||
* built here carry only region and tenant name. The caller's account is used for the ARN (and the
|
||||
* AlreadyExists message), not the key.
|
||||
*
|
||||
* <p>This is Phase 1 (tenant CRUD); resource associations, tenant suppression, and tenant-scoped
|
||||
* sending are separate follow-ups.
|
||||
* <p>Phase 2 adds tenant→resource associations, owned here as well ({@code associationStore}); the
|
||||
* facade validates that the referenced resource exists before delegating. Tenant suppression and
|
||||
* tenant-scoped sending are separate follow-ups.
|
||||
*/
|
||||
@ApplicationScoped
|
||||
public class SesTenantService {
|
||||
@@ -40,7 +42,26 @@ public class SesTenantService {
|
||||
private static final Pattern TENANT_NAME_CHARS = Pattern.compile("[A-Za-z0-9_-]+");
|
||||
private static final char[] HEX = "0123456789abcdef".toCharArray();
|
||||
|
||||
// The wire values for ResourceType — the ARN segment, not the SDK enum spelling. Real AWS both
|
||||
// returns these and requires them as Filter values; the SDK's EMAIL_IDENTITY-style enum constants
|
||||
// are rejected by the service (probe-confirmed 2026-08-28).
|
||||
static final String RESOURCE_TYPE_IDENTITY = "identity";
|
||||
static final String RESOURCE_TYPE_CONFIGURATION_SET = "configuration-set";
|
||||
static final String RESOURCE_TYPE_TEMPLATE = "template";
|
||||
private static final List<String> SUPPORTED_RESOURCE_TYPES =
|
||||
List.of(RESOURCE_TYPE_IDENTITY, RESOURCE_TYPE_CONFIGURATION_SET, RESOURCE_TYPE_TEMPLATE);
|
||||
|
||||
/**
|
||||
* A parsed, format-validated SES resource ARN for the association operations; {@code type} is one
|
||||
* of the wire resource types. Deliberately separate from the tag dispatch's {@code parseSesArn}
|
||||
* in {@code SesService}: the association APIs have their own probe-confirmed error messages and
|
||||
* validation precedence (type before region before account), so the parsers must not be merged.
|
||||
*/
|
||||
record AssociationResource(String type, String name, String arn) {
|
||||
}
|
||||
|
||||
private final StorageBackend<String, Tenant> tenantStore;
|
||||
private final StorageBackend<String, TenantResourceAssociation> associationStore;
|
||||
private final Clock clock;
|
||||
private final SecureRandom random;
|
||||
// Serializes the per-name check-then-put so concurrent creates for the same tenant can't both
|
||||
@@ -50,11 +71,17 @@ public class SesTenantService {
|
||||
@Inject
|
||||
public SesTenantService(StorageFactory storageFactory, Clock clock) {
|
||||
this(storageFactory.create("ses", "ses-tenants.json",
|
||||
new TypeReference<Map<String, Tenant>>() {}), clock, new SecureRandom());
|
||||
new TypeReference<Map<String, Tenant>>() {}),
|
||||
storageFactory.create("ses", "ses-tenant-associations.json",
|
||||
new TypeReference<Map<String, TenantResourceAssociation>>() {}),
|
||||
clock, new SecureRandom());
|
||||
}
|
||||
|
||||
SesTenantService(StorageBackend<String, Tenant> tenantStore, Clock clock, SecureRandom random) {
|
||||
SesTenantService(StorageBackend<String, Tenant> tenantStore,
|
||||
StorageBackend<String, TenantResourceAssociation> associationStore,
|
||||
Clock clock, SecureRandom random) {
|
||||
this.tenantStore = tenantStore;
|
||||
this.associationStore = associationStore;
|
||||
this.clock = clock;
|
||||
this.random = random;
|
||||
}
|
||||
@@ -101,8 +128,16 @@ public class SesTenantService {
|
||||
validateTenantName(tenantName);
|
||||
String key = tenantKey(region, tenantName);
|
||||
synchronized (tenantMutationLock) {
|
||||
if (tenantStore.get(key).isEmpty()) {
|
||||
throw tenantNotFound(tenantName);
|
||||
Tenant tenant = tenantStore.get(key).orElseThrow(() -> tenantNotFound(tenantName));
|
||||
// AWS cascades: deleting a tenant silently removes its resource associations
|
||||
// (probe-confirmed 2026-08-28). Keys carry the TenantId, so a recreated same-name tenant
|
||||
// never sees the old associations. The associations go first — persistent/wal backends
|
||||
// apply each deletion durably, so a crash mid-cascade must leave the tenant record (a
|
||||
// retryable DeleteTenant) rather than orphan associations no API call can remove.
|
||||
String assocPrefix = associationKeyPrefix(region, tenant.tenantId());
|
||||
for (String assocKey : associationStore.keys().stream()
|
||||
.filter(k -> k.startsWith(assocPrefix)).toList()) {
|
||||
associationStore.delete(assocKey);
|
||||
}
|
||||
tenantStore.delete(key);
|
||||
}
|
||||
@@ -115,6 +150,200 @@ public class SesTenantService {
|
||||
return tenantStore.get(tenantKey(region, tenantName));
|
||||
}
|
||||
|
||||
// ──────────────────────── Resource associations (Phase 2) ────────────────────────
|
||||
// Behavior and messages probe-confirmed against real AWS us-east-1, 2026-08-28.
|
||||
|
||||
/**
|
||||
* Resolves the tenant for the association operations. Unlike the CRUD operations, the association
|
||||
* request shapes carry no Smithy min-length on TenantName, so an empty value gets the
|
||||
* service-level message instead of the Smithy one.
|
||||
*/
|
||||
public Tenant tenantForAssociation(String tenantName, String region) {
|
||||
if (tenantName == null) {
|
||||
throw new AwsException("BadRequestException",
|
||||
"1 validation error detected: Value at 'tenantName' failed to satisfy constraint: "
|
||||
+ "Member must not be null", 400);
|
||||
}
|
||||
if (tenantName.isBlank()) {
|
||||
throw new AwsException("BadRequestException", "TenantName cannot be empty", 400);
|
||||
}
|
||||
return tenantStore.get(tenantKey(region, tenantName))
|
||||
.orElseThrow(() -> tenantNotFound(tenantName));
|
||||
}
|
||||
|
||||
/**
|
||||
* Parses and format-validates a resource ARN for the association operations. Check order matches
|
||||
* the observed AWS precedence: not an ARN at all, then not an SES ARN, then an unsupported SES
|
||||
* resource type, then region and account mismatches. Existence is the facade's job.
|
||||
*/
|
||||
public static AssociationResource parseResourceArn(String resourceArn, String accountId, String region) {
|
||||
if (resourceArn == null) {
|
||||
throw new AwsException("BadRequestException",
|
||||
"1 validation error detected: Value at 'resourceArn' failed to satisfy constraint: "
|
||||
+ "Member must not be null", 400);
|
||||
}
|
||||
String[] parts = resourceArn.split(":", 6);
|
||||
if (parts.length < 6 || !"arn".equals(parts[0])) {
|
||||
throw new AwsException("BadRequestException",
|
||||
"Provided resource identifier is not an SES resource", 400);
|
||||
}
|
||||
if (!"ses".equals(parts[2])) {
|
||||
throw new AwsException("BadRequestException",
|
||||
"Provided ARN is not in SES resource ARN format", 400);
|
||||
}
|
||||
String resource = parts[5];
|
||||
int slash = resource.indexOf('/');
|
||||
String type = slash < 0 ? resource : resource.substring(0, slash);
|
||||
if (!SUPPORTED_RESOURCE_TYPES.contains(type)) {
|
||||
throw new AwsException("BadRequestException", "Unsupported resource type: " + type, 400);
|
||||
}
|
||||
if (slash < 0 || slash == resource.length() - 1) {
|
||||
// A supported type with no name segment can never reference a resource; reject it as
|
||||
// malformed rather than letting it 404 with an empty name.
|
||||
throw new AwsException("BadRequestException",
|
||||
"Provided resource identifier is not an SES resource", 400);
|
||||
}
|
||||
if (!region.equals(parts[3])) {
|
||||
throw new AwsException("BadRequestException",
|
||||
"Resource <" + resourceArn + "> must be in the same region", 400);
|
||||
}
|
||||
if (!accountId.equals(parts[4])) {
|
||||
throw new AwsException("BadRequestException",
|
||||
"Resource <" + resourceArn + "> must be in the same account", 400);
|
||||
}
|
||||
return new AssociationResource(type, resource.substring(slash + 1), resourceArn);
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates the association under the shared lock. The tenant is revalidated (a concurrent
|
||||
* {@code DeleteTenant} may have cascaded since the caller resolved it) and
|
||||
* {@code resourceExistenceCheck} — the facade's throwing existence check — runs inside the lock
|
||||
* too, so a backing resource cannot slip through {@link #deleteBackingResource} concurrently and
|
||||
* leave an association pointing at a deleted resource.
|
||||
*/
|
||||
public void associate(Tenant tenant, AssociationResource ref, String region,
|
||||
Runnable resourceExistenceCheck) {
|
||||
String key = associationKey(region, tenant.tenantId(), ref);
|
||||
synchronized (tenantMutationLock) {
|
||||
Tenant current = tenantStore.get(tenantKey(region, tenant.tenantName())).orElse(null);
|
||||
if (current == null || !tenant.tenantId().equals(current.tenantId())) {
|
||||
throw tenantNotFound(tenant.tenantName());
|
||||
}
|
||||
resourceExistenceCheck.run();
|
||||
if (associationStore.get(key).isPresent()) {
|
||||
// "Resources" is AWS's own grammar for this message.
|
||||
throw new AwsException("AlreadyExistsException",
|
||||
"Resources " + ref.arn() + " has already been associated with tenant "
|
||||
+ tenant.tenantName(), 400);
|
||||
}
|
||||
associationStore.put(key, new TenantResourceAssociation(tenant.tenantName(),
|
||||
tenant.tenantId(), ref.arn(), ref.type(), Instant.now(clock)));
|
||||
}
|
||||
LOG.infov("Associated SES resource {0} with tenant {1} in region {2}",
|
||||
ref.arn(), tenant.tenantName(), region);
|
||||
}
|
||||
|
||||
/**
|
||||
* Runs a backing-resource deletion under the same lock as association creation: AWS refuses to
|
||||
* delete an identity, configuration set, or template that still has tenant associations, and the
|
||||
* shared lock keeps that guard atomic with {@link #associate}'s existence check.
|
||||
*/
|
||||
public void deleteBackingResource(String resourceType, String resourceName, String region,
|
||||
Runnable deleteAction) {
|
||||
synchronized (tenantMutationLock) {
|
||||
findAssociationForResource(resourceType, resourceName, region).ifPresent(a -> {
|
||||
throw new AwsException("BadRequestException",
|
||||
"Cannot delete <" + a.resourceArn() + "> because it has tenant associations. "
|
||||
+ "Remove all tenant associations and try again.", 400);
|
||||
});
|
||||
deleteAction.run();
|
||||
}
|
||||
}
|
||||
|
||||
/** Removing an association that does not exist is a silent success on AWS. */
|
||||
public void disassociate(Tenant tenant, AssociationResource ref, String region) {
|
||||
associationStore.delete(associationKey(region, tenant.tenantId(), ref));
|
||||
LOG.infov("Disassociated SES resource {0} from tenant {1} in region {2}",
|
||||
ref.arn(), tenant.tenantName(), region);
|
||||
}
|
||||
|
||||
/** AWS returns the tenant's resources ordered by ARN. */
|
||||
public List<TenantResourceAssociation> listTenantResources(Tenant tenant, String typeFilter,
|
||||
String region) {
|
||||
String prefix = associationKeyPrefix(region, tenant.tenantId());
|
||||
return associationStore.scan(k -> k.startsWith(prefix)).stream()
|
||||
.filter(a -> typeFilter == null || typeFilter.equals(a.resourceType()))
|
||||
.sorted(Comparator.comparing(TenantResourceAssociation::resourceArn,
|
||||
Comparator.nullsLast(Comparator.naturalOrder())))
|
||||
.toList();
|
||||
}
|
||||
|
||||
// The resource lookups match on the stored record, not on a key suffix: a resource name may
|
||||
// itself contain the "::" delimiter (Floci barely restricts identity and template names), so a
|
||||
// suffix match on the key could alias one resource's associations to another's.
|
||||
|
||||
/** AWS returns a resource's tenants ordered by association time. */
|
||||
public List<TenantResourceAssociation> listResourceTenants(AssociationResource ref, String region) {
|
||||
String regionPrefix = "tenantAssoc::" + region + "::";
|
||||
return associationStore.scan(k -> k.startsWith(regionPrefix)).stream()
|
||||
.filter(a -> ref.arn().equals(a.resourceArn()))
|
||||
.sorted(Comparator.comparing(TenantResourceAssociation::associatedTimestamp,
|
||||
Comparator.nullsLast(Comparator.naturalOrder()))
|
||||
.thenComparing(TenantResourceAssociation::tenantName,
|
||||
Comparator.nullsLast(Comparator.naturalOrder())))
|
||||
.toList();
|
||||
}
|
||||
|
||||
/**
|
||||
* Finds any association for the given resource, for the facade's delete guards: AWS refuses to
|
||||
* delete an identity, configuration set, or template that still has tenant associations.
|
||||
*/
|
||||
public Optional<TenantResourceAssociation> findAssociationForResource(String resourceType,
|
||||
String resourceName,
|
||||
String region) {
|
||||
String regionPrefix = "tenantAssoc::" + region + "::";
|
||||
return associationStore.scan(k -> k.startsWith(regionPrefix)).stream()
|
||||
.filter(a -> resourceType.equals(a.resourceType())
|
||||
&& resourceName.equals(resourceNameFromArn(a.resourceArn())))
|
||||
.findFirst();
|
||||
}
|
||||
|
||||
// Stored ARNs were validated by parseResourceArn, so the resource part always has a name segment.
|
||||
private static String resourceNameFromArn(String arn) {
|
||||
String resource = arn.split(":", 6)[5];
|
||||
return resource.substring(resource.indexOf('/') + 1);
|
||||
}
|
||||
|
||||
public static void validateResourceTypeFilter(String value) {
|
||||
if (value != null && !SUPPORTED_RESOURCE_TYPES.contains(value)) {
|
||||
throw new AwsException("BadRequestException",
|
||||
"Invalid resource type " + value + " specified.", 400);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The list operations return everything in one page, so any client-supplied NextToken is invalid —
|
||||
* which is also what AWS answers for a token it cannot decrypt. PageSize is still range-checked.
|
||||
*/
|
||||
public static void validateListPaging(Integer pageSize, String nextToken) {
|
||||
if (pageSize != null && pageSize < 1) {
|
||||
throw new AwsException("BadRequestException",
|
||||
"1 validation error detected: Value '" + pageSize + "' at 'pageSize' failed to "
|
||||
+ "satisfy constraint: Member must have value greater than or equal to 1", 400);
|
||||
}
|
||||
if (nextToken != null) {
|
||||
throw new AwsException("BadRequestException", "Invalid Next Token", 400);
|
||||
}
|
||||
}
|
||||
|
||||
private static String associationKey(String region, String tenantId, AssociationResource ref) {
|
||||
return associationKeyPrefix(region, tenantId) + ref.type() + "::" + ref.name();
|
||||
}
|
||||
|
||||
private static String associationKeyPrefix(String region, String tenantId) {
|
||||
return "tenantAssoc::" + region + "::" + tenantId + "::";
|
||||
}
|
||||
|
||||
// Validation order and messages verified against real AWS (2026-08-22): an empty string is the
|
||||
// Smithy min-length violation, a whitespace-only value is "cannot be empty", then length, then the
|
||||
// character-set rule.
|
||||
|
||||
+18
@@ -0,0 +1,18 @@
|
||||
package io.github.hectorvent.floci.services.ses.model;
|
||||
|
||||
import io.quarkus.runtime.annotations.RegisterForReflection;
|
||||
|
||||
import java.time.Instant;
|
||||
|
||||
/**
|
||||
* A SES v2 tenant→resource association, created by {@code CreateTenantResourceAssociation}.
|
||||
* {@code resourceType} is the wire value AWS uses for these APIs — the ARN segment
|
||||
* ({@code identity} / {@code configuration-set} / {@code template}), not the SDK enum spelling.
|
||||
*/
|
||||
@RegisterForReflection
|
||||
public record TenantResourceAssociation(String tenantName,
|
||||
String tenantId,
|
||||
String resourceArn,
|
||||
String resourceType,
|
||||
Instant associatedTimestamp) {
|
||||
}
|
||||
Reference in new issue
Block a user