feat(cloudfront): distribution tenants for multi-tenant distributions (#9398)

This commit is contained in:
Joaquín Gamboa authored and GitHub committed 2026-11-24 23:40:15 -04:00
1 parent b3c8db3022
commit a0123f8f69
21 files changed
+2395 -13

No files matched your search

@@ -13,12 +13,14 @@ import io.floci.aws.services.cloudfront.model.ConnectionGroup;
import io.floci.aws.services.cloudfront.model.DefaultCacheBehavior;
import io.floci.aws.services.cloudfront.model.Distribution;
import io.floci.aws.services.cloudfront.model.DistributionConfig;
import io.floci.aws.services.cloudfront.model.DistributionTenant;
import io.floci.aws.services.cloudfront.model.KeyGroup;
import io.floci.aws.services.cloudfront.model.Origin;
import io.floci.aws.services.cloudfront.model.OriginAccessControl;
import io.floci.aws.services.cloudfront.model.OriginRequestPolicy;
import io.floci.aws.services.cloudfront.model.PublicKey;
import io.floci.aws.services.cloudfront.model.ResponseHeadersPolicy;
import io.floci.aws.services.cloudfront.model.TenantCustomizations;
import jakarta.enterprise.context.ApplicationScoped;
import org.jboss.logging.Logger;
@@ -70,6 +72,7 @@ public class CloudFrontCfnProvisioner implements CfnResourceProvisioner {
static final String KEY_GROUP = "AWS::CloudFront::KeyGroup";
static final String FUNCTION = "AWS::CloudFront::Function";
static final String CONNECTION_GROUP = "AWS::CloudFront::ConnectionGroup";
static final String DISTRIBUTION_TENANT = "AWS::CloudFront::DistributionTenant";
static final String NO_SUCH_RESPONSE_HEADERS_POLICY = "NoSuchResponseHeadersPolicy";
static final String NO_SUCH_CACHE_POLICY = "NoSuchCachePolicy";
@@ -91,7 +94,7 @@ public class CloudFrontCfnProvisioner implements CfnResourceProvisioner {
@Override
public Set<String> resourceTypes() {
return Set.of(DISTRIBUTION, RESPONSE_HEADERS_POLICY, CACHE_POLICY, ORIGIN_REQUEST_POLICY,
ORIGIN_ACCESS_CONTROL, PUBLIC_KEY, KEY_GROUP, FUNCTION, CONNECTION_GROUP);
ORIGIN_ACCESS_CONTROL, PUBLIC_KEY, KEY_GROUP, FUNCTION, CONNECTION_GROUP, DISTRIBUTION_TENANT);
}
@Override
@@ -107,6 +110,7 @@ public class CloudFrontCfnProvisioner implements CfnResourceProvisioner {
case KEY_GROUP -> provisionKeyGroup(r, props, ctx);
case FUNCTION -> provisionFunction(r, props, ctx);
case CONNECTION_GROUP -> provisionConnectionGroup(r, props, ctx);
case DISTRIBUTION_TENANT -> provisionDistributionTenant(r, props, ctx);
default -> throw new IllegalArgumentException("Unsupported resource type: " + r.getResourceType());
}
ReplacementCleanup.record(r, ctx, attributesBefore);
@@ -191,6 +195,7 @@ public class CloudFrontCfnProvisioner implements CfnResourceProvisioner {
cloudFrontService::deleteKeyGroup, NO_SUCH_KEY_GROUP);
case FUNCTION -> deleteFunction(physicalId);
case CONNECTION_GROUP -> deleteConnectionGroup(physicalId);
case DISTRIBUTION_TENANT -> deleteDistributionTenant(physicalId);
default -> { }
}
}
@@ -273,6 +278,128 @@ public class CloudFrontCfnProvisioner implements CfnResourceProvisioner {
provisioned.getLastModifiedTime() == null ? "" : provisioned.getLastModifiedTime().toString());
}
/**
* An enabled tenant refuses its delete with {@code ResourceNotDisabled}, so a stack delete, a
* replacement cleanup or a rollback disables it first with the etag it carries and deletes it
* with the fresh one the disable minted, as the registry schema's delete handler does (it asks
* for {@code UpdateDistributionTenant} as well as {@code DeleteDistributionTenant}). The tags
* kept under the ARN go with the tenant. Only the type's own not-found code is tolerated.
*/
private void deleteDistributionTenant(String physicalId) {
CfnDeletes.safeDelete("distribution tenant", physicalId, () -> {
DistributionTenant tenant = cloudFrontService.getDistributionTenant(physicalId);
String etag = tenant.getEtag();
if (Boolean.TRUE.equals(tenant.getEnabled())) {
etag = cloudFrontService.updateDistributionTenant(physicalId, etag, null, null, null, null,
null, false).getEtag();
}
cloudFrontService.deleteDistributionTenant(physicalId, etag);
}, ENTITY_NOT_FOUND);
}
/**
* The tenant the template names is created on first use and updated in place afterwards:
* {@code Name} is the only create-only property the registry schema declares, so an update whose
* resolved {@code Name} differs from the prior tenant's replaces it, and the engine's
* replacement cleanup deletes the old tenant through {@link #deleteDistributionTenant} once the
* update commits. Otherwise the physical id only changes when the prior tenant is already gone.
* The schema's read-only members ({@code Id}, {@code Arn}, {@code ETag}, {@code Status} and the
* two timestamps) travel to {@code Fn::GetAtt} from the provisioned object; {@code DomainResults}
* is a list, which attributes as Floci keeps them (text) cannot hold.
*
* <p>An update is declarative: it drives the tags, {@code Customizations} and {@code Parameters}
* to the template's set, so a template that drops one clears it, and it reads an absent
* {@code Enabled} as the default, true, and a dropped {@code ConnectionGroupId} as the account's
* default connection group, which is what a create picks. {@code ManagedCertificateRequest},
* {@code DomainMappings} and {@code OnDomainTakeover} are accepted and ignored: Floci issues no
* managed certificates and serves every domain the same way.
*/
private void provisionDistributionTenant(StackResource r, JsonNode props, ProvisionContext ctx) {
String distributionId = requireText(DISTRIBUTION_TENANT, "DistributionId", props, ctx);
String name = requireText(DISTRIBUTION_TENANT, "Name", props, ctx);
List<String> domains = tenantDomains(props, ctx);
TenantCustomizations customizations = tenantCustomizations(props, ctx);
Map<String, String> parameters = tenantParameters(props, ctx);
String connectionGroupId = ctx.resolveOptional(props, "ConnectionGroupId");
Boolean enabled = ctx.resolveOptionalBoolean(props, "Enabled");
Map<String, String> tags = ctx.resolveTags(props, "Tags");
DistributionTenant provisioned;
DistributionTenant prior = prior(ctx, "distribution tenant",
cloudFrontService::getDistributionTenant, ENTITY_NOT_FOUND);
if (prior == null || !name.equals(prior.getName())) {
provisioned = cloudFrontService.createDistributionTenant(distributionId, name, domains, tags,
customizations, parameters, connectionGroupId, enabled);
} else {
String groupId = connectionGroupId == null || connectionGroupId.isBlank()
? cloudFrontService.ensureDefaultConnectionGroup().getId() : connectionGroupId;
provisioned = cloudFrontService.updateDistributionTenant(prior.getId(), prior.getEtag(),
distributionId, domains, customizations == null ? new TenantCustomizations() : customizations,
parameters == null ? Map.of() : parameters, groupId,
enabled == null ? Boolean.TRUE : enabled);
reconcileTags(provisioned.getArn(), tags);
}
r.setPhysicalId(provisioned.getId());
r.getAttributes().put("Id", provisioned.getId());
r.getAttributes().put("Arn", provisioned.getArn());
r.getAttributes().put("ETag", provisioned.getEtag());
r.getAttributes().put("Status", provisioned.getStatus());
r.getAttributes().put("CreatedTime",
provisioned.getCreatedTime() == null ? "" : provisioned.getCreatedTime().toString());
r.getAttributes().put("LastModifiedTime",
provisioned.getLastModifiedTime() == null ? "" : provisioned.getLastModifiedTime().toString());
}
private static List<String> tenantDomains(JsonNode props, ProvisionContext ctx) {
JsonNode raw = props.get("Domains");
JsonNode resolved = raw == null || raw.isNull() ? null : ctx.engine().resolveNode(raw);
if (resolved == null || !resolved.isArray() || resolved.isEmpty()) {
throw new AwsException("ValidationError", DISTRIBUTION_TENANT + " requires Domains", 400);
}
List<String> domains = new ArrayList<>();
for (JsonNode domain : resolved) {
domains.add(domain.asText());
}
return domains;
}
private static Map<String, String> tenantParameters(JsonNode props, ProvisionContext ctx) {
JsonNode raw = props.get("Parameters");
JsonNode resolved = raw == null || raw.isNull() ? null : ctx.engine().resolveNode(raw);
if (resolved == null || !resolved.isArray()) {
return null;
}
Map<String, String> parameters = new LinkedHashMap<>();
for (JsonNode parameter : resolved) {
parameters.put(text(parameter, "Name"), text(parameter, "Value"));
}
return parameters;
}
private static TenantCustomizations tenantCustomizations(JsonNode props, ProvisionContext ctx) {
JsonNode raw = props.get("Customizations");
JsonNode resolved = raw == null || raw.isNull() ? null : ctx.engine().resolveNode(raw);
if (resolved == null || !resolved.isObject()) {
return null;
}
TenantCustomizations customizations = new TenantCustomizations();
JsonNode webAcl = resolved.get("WebAcl");
if (webAcl != null && webAcl.isObject()) {
customizations.setWebAclAction(text(webAcl, "Action"));
customizations.setWebAclArn(text(webAcl, "Arn"));
}
JsonNode certificate = resolved.get("Certificate");
if (certificate != null && certificate.isObject()) {
customizations.setCertificateArn(text(certificate, "Arn"));
}
JsonNode geo = resolved.get("GeoRestrictions");
if (geo != null && geo.isObject()) {
customizations.setGeoRestrictionType(text(geo, "RestrictionType"));
customizations.setGeoLocations(textList(geo, "Locations"));
}
return customizations;
}
private static void requireConnectionGroupName(String name) {
if (name == null || name.isBlank()) {
throw new AwsException("ValidationError", CONNECTION_GROUP + " requires Name", 400);
@@ -415,7 +542,7 @@ public class CloudFrontCfnProvisioner implements CfnResourceProvisioner {
if (autoPublish) {
cloudFrontService.publishFunction(name, provisioned.getEtag());
}
reconcileFunctionTags(arn, tags);
reconcileTags(arn, tags);
} catch (RuntimeException failure) {
if (prior == null) {
// The stack keeps its prior id when this resource fails, so nothing else would
@@ -454,7 +581,7 @@ public class CloudFrontCfnProvisioner implements CfnResourceProvisioner {
return arn.substring(arn.lastIndexOf('/') + 1);
}
private void reconcileFunctionTags(String arn, Map<String, String> desired) {
private void reconcileTags(String arn, Map<String, String> desired) {
List<String> stale = ProvisionContext.staleTagKeys(cloudFrontService.listTagsForResource(arn), desired);
if (!stale.isEmpty()) {
cloudFrontService.untagResource(arn, stale);
@@ -329,6 +329,149 @@ public class CloudFrontController {
return Response.ok(xml.build(), XML).build();
}
// ── Distribution tenants ──────────────────────────────────────────────────
@POST
@Path("/distribution-tenant")
public Response createDistributionTenant(String body) {
try {
XmlParser.XmlElement request = XmlParser.extractElementTree(body, "CreateDistributionTenantRequest");
DistributionTenant tenant = service.createDistributionTenant(
tenantText(request, "DistributionId"),
tenantText(request, "Name"),
tenantDomains(request),
parseTags(body),
tenantCustomizations(request),
tenantParameters(request),
tenantText(request, "ConnectionGroupId"),
xmlBoolean(tenantText(request, "Enabled")));
return Response.created(URI.create("/2020-05-31/distribution-tenant/" + tenant.getId()))
.type(XML)
.header("ETag", tenant.getEtag())
.entity(xmlDistributionTenant(tenant))
.build();
} catch (AwsException e) {
return xmlErrorResponse(e);
}
}
@GET
@Path("/distribution-tenant/{Identifier}")
public Response getDistributionTenant(@PathParam("Identifier") String identifier) {
try {
DistributionTenant tenant = service.getDistributionTenant(identifier);
return Response.ok(xmlDistributionTenant(tenant), XML)
.header("ETag", tenant.getEtag())
.build();
} catch (AwsException e) {
return xmlErrorResponse(e);
}
}
@GET
@Path("/distribution-tenant")
public Response getDistributionTenantByDomain(@QueryParam("domain") String domain) {
try {
DistributionTenant tenant = service.getDistributionTenantByDomain(domain);
return Response.ok(xmlDistributionTenant(tenant), XML)
.header("ETag", tenant.getEtag())
.build();
} catch (AwsException e) {
return xmlErrorResponse(e);
}
}
@PUT
@Path("/distribution-tenant/{Id}")
public Response updateDistributionTenant(@PathParam("Id") String id,
@HeaderParam("If-Match") String ifMatch,
String body) {
try {
XmlParser.XmlElement request = XmlParser.extractElementTree(body, "UpdateDistributionTenantRequest");
DistributionTenant tenant = service.updateDistributionTenant(id, ifMatch,
tenantText(request, "DistributionId"),
tenantDomains(request),
tenantCustomizations(request),
tenantParameters(request),
tenantText(request, "ConnectionGroupId"),
xmlBoolean(tenantText(request, "Enabled")));
return Response.ok(xmlDistributionTenant(tenant), XML)
.header("ETag", tenant.getEtag())
.build();
} catch (AwsException e) {
return xmlErrorResponse(e);
}
}
@DELETE
@Path("/distribution-tenant/{Id}")
public Response deleteDistributionTenant(@PathParam("Id") String id,
@HeaderParam("If-Match") String ifMatch) {
try {
service.deleteDistributionTenant(id, ifMatch);
return Response.noContent().build();
} catch (AwsException e) {
return xmlErrorResponse(e);
}
}
@POST
@Path("/distribution-tenants")
public Response listDistributionTenants(String body) {
try {
Map<String, String> request = XmlParser.extractGroups(body, "ListDistributionTenantsRequest")
.stream().findFirst().orElse(Map.of());
String distributionId = null;
String connectionGroupId = null;
for (Map<String, String> filter : XmlParser.extractGroups(body, "AssociationFilter")) {
distributionId = blankToNull(filter.get("DistributionId"));
connectionGroupId = blankToNull(filter.get("ConnectionGroupId"));
}
int pageSize = pageSizeOf(parseMaxItems(request.get("MaxItems")));
Page<DistributionTenant> page = page(
service.listDistributionTenants(request.get("Marker"), paginationFetchLimit(pageSize),
distributionId, connectionGroupId),
pageSize, DistributionTenant::getName);
return distributionTenantListResponse("ListDistributionTenantsResult", page);
} catch (AwsException e) {
return xmlErrorResponse(e);
}
}
@POST
@Path("/distribution-tenants-by-customization")
public Response listDistributionTenantsByCustomization(String body) {
try {
Map<String, String> request =
XmlParser.extractGroups(body, "ListDistributionTenantsByCustomizationRequest")
.stream().findFirst().orElse(Map.of());
int pageSize = pageSizeOf(parseMaxItems(request.get("MaxItems")));
Page<DistributionTenant> page = page(
service.listDistributionTenantsByCustomization(request.get("Marker"),
paginationFetchLimit(pageSize), blankToNull(request.get("WebACLArn")),
blankToNull(request.get("CertificateArn"))),
pageSize, DistributionTenant::getName);
return distributionTenantListResponse("ListDistributionTenantsByCustomizationResult", page);
} catch (AwsException e) {
return xmlErrorResponse(e);
}
}
private static int pageSizeOf(Integer maxItems) {
return maxItems == null ? 100 : maxItems;
}
private Response distributionTenantListResponse(String root, Page<DistributionTenant> page) {
XmlBuilder xml = new XmlBuilder()
.start(root, NS)
.elem("NextMarker", page.nextMarker())
.start("DistributionTenantList");
for (DistributionTenant tenant : page.items()) {
xml.raw(xmlDistributionTenantSummary(tenant));
}
return Response.ok(xml.end("DistributionTenantList").end(root).build(), XML).build();
}
// ── Invalidations ─────────────────────────────────────────────────────────
@POST
@@ -4197,4 +4340,165 @@ public class CloudFrontController {
}
return null;
}
private static String tenantText(XmlParser.XmlElement request, String name) {
XmlParser.XmlElement child = request == null ? null : request.child(name);
return child == null || child.text().isEmpty() ? null : child.text();
}
/** The {@code Domains} members, or null when the request carries no {@code Domains}. */
private static List<String> tenantDomains(XmlParser.XmlElement request) {
XmlParser.XmlElement domains = request == null ? null : request.child("Domains");
if (domains == null) {
return null;
}
List<String> result = new ArrayList<>();
for (XmlParser.XmlElement item : domains.children()) {
XmlParser.XmlElement domain = item.child("Domain");
result.add(domain == null ? null : domain.text());
}
return result;
}
private static Map<String, String> tenantParameters(XmlParser.XmlElement request) {
XmlParser.XmlElement parameters = request == null ? null : request.child("Parameters");
if (parameters == null) {
return null;
}
Map<String, String> result = new LinkedHashMap<>();
for (XmlParser.XmlElement parameter : parameters.children()) {
result.put(tenantText(parameter, "Name"), tenantText(parameter, "Value"));
}
return result;
}
private static TenantCustomizations tenantCustomizations(XmlParser.XmlElement request) {
XmlParser.XmlElement element = request == null ? null : request.child("Customizations");
if (element == null) {
return null;
}
TenantCustomizations customizations = new TenantCustomizations();
XmlParser.XmlElement webAcl = element.child("WebAcl");
if (webAcl != null) {
customizations.setWebAclAction(tenantText(webAcl, "Action"));
customizations.setWebAclArn(tenantText(webAcl, "Arn"));
}
XmlParser.XmlElement certificate = element.child("Certificate");
if (certificate != null) {
customizations.setCertificateArn(tenantText(certificate, "Arn"));
}
XmlParser.XmlElement geo = element.child("GeoRestrictions");
if (geo != null) {
customizations.setGeoRestrictionType(tenantText(geo, "RestrictionType"));
XmlParser.XmlElement locations = geo.child("Locations");
if (locations != null) {
List<String> codes = new ArrayList<>();
for (XmlParser.XmlElement location : locations.children()) {
codes.add(location.text());
}
customizations.setGeoLocations(codes);
}
}
return customizations;
}
private String xmlDistributionTenant(DistributionTenant tenant) {
XmlBuilder xml = new XmlBuilder().start("DistributionTenant", NS)
.elem("Id", tenant.getId())
.elem("DistributionId", tenant.getDistributionId())
.elem("Name", tenant.getName())
.elem("Arn", tenant.getArn());
appendTenantDomains(xml, tenant);
Map<String, String> tags = service.listTagsForResource(tenant.getArn());
if (!tags.isEmpty()) {
xml.start("Tags").start("Items");
for (Map.Entry<String, String> tag : tags.entrySet()) {
xml.start("Tag")
.elem("Key", tag.getKey())
.elem("Value", tag.getValue())
.end("Tag");
}
xml.end("Items").end("Tags");
}
appendTenantCustomizations(xml, tenant);
if (tenant.getParameters() != null && !tenant.getParameters().isEmpty()) {
xml.start("Parameters");
for (Map.Entry<String, String> parameter : tenant.getParameters().entrySet()) {
xml.start("member")
.elem("Name", parameter.getKey())
.elem("Value", parameter.getValue())
.end("member");
}
xml.end("Parameters");
}
xml.elem("ConnectionGroupId", tenant.getConnectionGroupId())
.elem("CreatedTime", tenant.getCreatedTime().toString())
.elem("LastModifiedTime", tenant.getLastModifiedTime().toString())
.elem("Enabled", tenant.getEnabled())
.elem("Status", tenant.getStatus());
return xml.end("DistributionTenant").build();
}
private static String xmlDistributionTenantSummary(DistributionTenant tenant) {
XmlBuilder xml = new XmlBuilder().start("DistributionTenantSummary", NS)
.elem("Id", tenant.getId())
.elem("DistributionId", tenant.getDistributionId())
.elem("Name", tenant.getName())
.elem("Arn", tenant.getArn());
appendTenantDomains(xml, tenant);
xml.elem("ConnectionGroupId", tenant.getConnectionGroupId());
appendTenantCustomizations(xml, tenant);
xml.elem("CreatedTime", tenant.getCreatedTime().toString())
.elem("LastModifiedTime", tenant.getLastModifiedTime().toString())
.elem("ETag", tenant.getEtag())
.elem("Enabled", tenant.getEnabled())
.elem("Status", tenant.getStatus());
return xml.end("DistributionTenantSummary").build();
}
/**
* Every domain reads back {@code active}: Floci performs no DNS or certificate validation. The
* {@code Domains} and {@code Parameters} lists declare no member name, so the SDKs read their
* items as {@code member} elements; requests are read by position, whatever the items are called.
*/
private static void appendTenantDomains(XmlBuilder xml, DistributionTenant tenant) {
xml.start("Domains");
for (String domain : tenant.getDomains()) {
xml.start("member")
.elem("Domain", domain)
.elem("Status", "active")
.end("member");
}
xml.end("Domains");
}
private static void appendTenantCustomizations(XmlBuilder xml, DistributionTenant tenant) {
TenantCustomizations customizations = tenant.getCustomizations();
if (customizations == null || customizations.isEmpty()) {
return;
}
xml.start("Customizations");
if (customizations.getWebAclAction() != null) {
xml.start("WebAcl").elem("Action", customizations.getWebAclAction());
if (customizations.getWebAclArn() != null) {
xml.elem("Arn", customizations.getWebAclArn());
}
xml.end("WebAcl");
}
if (customizations.getCertificateArn() != null) {
xml.start("Certificate").elem("Arn", customizations.getCertificateArn()).end("Certificate");
}
if (customizations.getGeoRestrictionType() != null) {
xml.start("GeoRestrictions").elem("RestrictionType", customizations.getGeoRestrictionType());
if (customizations.getGeoLocations() != null && !customizations.getGeoLocations().isEmpty()) {
xml.start("Locations");
for (String location : customizations.getGeoLocations()) {
xml.elem("Location", location);
}
xml.end("Locations");
}
xml.end("GeoRestrictions");
}
xml.end("Customizations");
}
}
@@ -23,6 +23,7 @@ import io.floci.aws.services.cloudfront.model.ContinuousDeploymentPolicy;
import io.floci.aws.services.cloudfront.model.DefaultCacheBehavior;
import io.floci.aws.services.cloudfront.model.Distribution;
import io.floci.aws.services.cloudfront.model.DistributionConfig;
import io.floci.aws.services.cloudfront.model.DistributionTenant;
import io.floci.aws.services.cloudfront.model.FieldLevelEncryptionConfig;
import io.floci.aws.services.cloudfront.model.FieldLevelEncryptionProfile;
import io.floci.aws.services.cloudfront.model.Invalidation;
@@ -36,6 +37,7 @@ import io.floci.aws.services.cloudfront.model.PublicKey;
import io.floci.aws.services.cloudfront.model.RealtimeLogConfig;
import io.floci.aws.services.cloudfront.model.ResponseHeadersPolicy;
import io.floci.aws.services.cloudfront.model.StreamingDistribution;
import io.floci.aws.services.cloudfront.model.TenantCustomizations;
import io.floci.aws.services.iam.IamService;
import io.floci.aws.services.iam.ServerCertificateReferenceProvider;
import jakarta.enterprise.context.ApplicationScoped;
@@ -95,6 +97,15 @@ public class CloudFrontService implements ServerCertificateReferenceProvider {
private static final Set<String> CONNECTION_MODES = Set.of("direct", "tenant-only");
/** AWS names the account's automatically created connection group "default". */
private static final String DEFAULT_CONNECTION_GROUP_NAME = "default";
/** A distribution tenant's Name: the pattern its request shape declares (3 to 128 characters). */
private static final Pattern TENANT_NAME = Pattern.compile("[a-zA-Z0-9][a-zA-Z0-9-.]{1,126}[a-zA-Z0-9]");
/** The pattern a tenant parameter's Name declares, and the length its Value is held to. */
private static final Pattern TENANT_PARAMETER_NAME = Pattern.compile("[a-zA-Z0-9-_]{1,128}");
private static final int TENANT_PARAMETER_VALUE_MAX_LENGTH = 256;
/** UpdateDistributionTenant documents "up to 5 domains" for a tenant. */
private static final int TENANT_MAX_DOMAINS = 5;
private static final Set<String> TENANT_WEB_ACL_ACTIONS = Set.of("override", "disable");
private static final Set<String> TENANT_GEO_RESTRICTION_TYPES = Set.of("blacklist", "whitelist", "none");
/** The documented maximum a connection group's Name may reach (AWS's own limit). */
private static final int CONNECTION_GROUP_NAME_MAX_LENGTH = 256;
/**
@@ -157,6 +168,7 @@ public class CloudFrontService implements ServerCertificateReferenceProvider {
private final AccountAwareStorageBackend<Distribution> distStore;
private final AccountAwareStorageBackend<ConnectionGroup> connectionGroupStore;
private final AccountAwareStorageBackend<DistributionTenant> tenantStore;
private final StorageBackend<String, List<Invalidation>> invalidationStore;
private final StorageBackend<String, CachePolicy> cachePolicyStore;
private final StorageBackend<String, OriginRequestPolicy> orpStore;
@@ -207,6 +219,8 @@ public class CloudFrontService implements ServerCertificateReferenceProvider {
new TypeReference<Map<String, Distribution>>() {});
this.connectionGroupStore = factory.create("cloudfront", "cloudfront-connection-groups.json",
new TypeReference<Map<String, ConnectionGroup>>() {});
this.tenantStore = factory.create("cloudfront", "cloudfront-distribution-tenants.json",
new TypeReference<Map<String, DistributionTenant>>() {});
this.invalidationStore = factory.create("cloudfront", "cloudfront-invalidations.json",
new TypeReference<Map<String, List<Invalidation>>>() {});
this.cachePolicyStore = factory.create("cloudfront", "cloudfront-cache-policies.json",
@@ -783,6 +797,9 @@ public class CloudFrontService implements ServerCertificateReferenceProvider {
if (dist.getConfig() == null) {
throw new AwsException("InvalidArgument", "The target distribution has no configuration.", 400);
}
if (tenantHoldsDomain(alias)) {
throw domainTaken();
}
for (Distribution candidate : distStore.scan(k -> true)) {
if (targetDistributionId.equals(candidate.getId()) || candidate.getConfig() == null
|| candidate.getConfig().getAliases() == null) {
@@ -913,6 +930,9 @@ public class CloudFrontService implements ServerCertificateReferenceProvider {
if (requested == null || requested.isBlank()) {
continue;
}
if (tenantHoldsDomain(requested)) {
throw domainTaken();
}
for (Distribution existing : distStore.scan(k -> true)) {
if (existing.getId().equals(currentDistributionId) || existing.getConfig() == null
|| existing.getConfig().getAliases() == null) {
@@ -920,8 +940,7 @@ public class CloudFrontService implements ServerCertificateReferenceProvider {
}
for (String assigned : existing.getConfig().getAliases()) {
if (requested.equalsIgnoreCase(assigned)) {
throw new AwsException("CNAMEAlreadyExists",
"The CNAME you provided is already associated with a different resource.", 409);
throw domainTaken();
}
}
}
@@ -1148,6 +1167,12 @@ public class CloudFrontService implements ServerCertificateReferenceProvider {
throw new AwsException("CannotDeleteEntityWhileInUse",
"The default connection group cannot be deleted.", 409);
}
for (DistributionTenant tenant : tenantStore.scan(k -> true)) {
if (id.equals(tenant.getConnectionGroupId())) {
throw new AwsException("CannotDeleteEntityWhileInUse",
"The connection group is still used by a distribution tenant.", 409);
}
}
if (Boolean.TRUE.equals(group.getEnabled())) {
throw new AwsException("ResourceNotDisabled",
"The connection group has not been disabled.", 409);
@@ -1221,6 +1246,330 @@ public class CloudFrontService implements ServerCertificateReferenceProvider {
return sb.toString();
}
// ── Distribution tenants ──────────────────────────────────────────────────
public synchronized DistributionTenant createDistributionTenant(String distributionId, String name,
List<String> domains,
Map<String, String> tags,
TenantCustomizations customizations,
Map<String, String> parameters,
String connectionGroupId,
Boolean enabled) {
requireTenantName(name);
requireTenantDomains(domains);
requireTenantOnlyDistribution(distributionId);
String groupId = connectionGroupId == null || connectionGroupId.isBlank()
? ensureDefaultConnectionGroup().getId()
: getConnectionGroup(connectionGroupId).getId();
validateTenantCustomizations(customizations);
validateTenantParameters(parameters);
for (DistributionTenant existing : tenantStore.scan(k -> true)) {
if (name.equals(existing.getName())) {
throw new AwsException("EntityAlreadyExists",
"The distribution tenant " + name + " already exists.", 409);
}
}
ensureTenantDomainsAvailable(domains, null);
DistributionTenant tenant = new DistributionTenant();
String id = "dt_" + randomIdSuffix(24);
tenant.setId(id);
tenant.setArn(regionResolver.buildGlobalArn("cloudfront", "distribution-tenant/" + id));
tenant.setName(name);
tenant.setDistributionId(distributionId);
tenant.setConnectionGroupId(groupId);
tenant.setDomains(new ArrayList<>(domains));
tenant.setCustomizations(customizations);
tenant.setParameters(parameters == null || parameters.isEmpty() ? null : new LinkedHashMap<>(parameters));
tenant.setEnabled(enabled == null || enabled);
tenant.setStatus("Deployed");
tenant.setCreatedTime(Instant.now());
tenant.setLastModifiedTime(tenant.getCreatedTime());
tenant.setEtag("E" + randomIdSuffix(12));
if (tags != null && !tags.isEmpty()) {
tagStore.put(tenant.getArn(), new LinkedHashMap<>(tags));
}
tenantStore.put(id, tenant);
return tenant;
}
/**
* A tenant is addressed by its id, name or ARN wherever the API documents {@code Identifier}
* ("You can specify the ARN, ID, or name of the distribution tenant").
*/
public DistributionTenant getDistributionTenant(String identifier) {
if (identifier == null || identifier.isBlank()) {
throw tenantNotFound();
}
if (AwsArnUtils.looksLikeArn(identifier)) {
for (DistributionTenant tenant : tenantStore.scan(k -> true)) {
if (identifier.equals(tenant.getArn())) {
return tenant;
}
}
throw tenantNotFound();
}
DistributionTenant tenant = tenantStore.get(identifier).orElse(null);
if (tenant != null) {
return tenant;
}
for (DistributionTenant candidate : tenantStore.scan(k -> true)) {
if (identifier.equals(candidate.getName())) {
return candidate;
}
}
throw tenantNotFound();
}
public DistributionTenant getDistributionTenantByDomain(String domain) {
if (domain != null) {
for (DistributionTenant tenant : tenantStore.scan(k -> true)) {
if (containsIgnoreCase(tenant.getDomains(), domain)) {
return tenant;
}
}
}
throw tenantNotFound();
}
/**
* A member the request omits keeps its stored value; one it carries replaces the stored one
* ({@code Domains}, {@code Parameters} and {@code Customizations} wholesale). {@code Name} is
* immutable and {@code Tags} change through TagResource, so neither is a parameter here.
*/
public synchronized DistributionTenant updateDistributionTenant(String id, String ifMatch,
String distributionId,
List<String> domains,
TenantCustomizations customizations,
Map<String, String> parameters,
String connectionGroupId,
Boolean enabled) {
requireIfMatch(ifMatch);
DistributionTenant tenant = requireDistributionTenant(id);
if (!tenant.getEtag().equals(ifMatch)) {
throw new AwsException("PreconditionFailed",
"The specified If-Match didn't match the ETag header.", 412);
}
if (domains != null) {
requireTenantDomains(domains);
ensureTenantDomainsAvailable(domains, id);
}
if (distributionId != null && !distributionId.isBlank()) {
requireTenantOnlyDistribution(distributionId);
}
String groupId = connectionGroupId == null || connectionGroupId.isBlank() ? null
: getConnectionGroup(connectionGroupId).getId();
validateTenantCustomizations(customizations);
validateTenantParameters(parameters);
if (distributionId != null && !distributionId.isBlank()) {
tenant.setDistributionId(distributionId);
}
if (groupId != null) {
tenant.setConnectionGroupId(groupId);
}
if (domains != null) {
tenant.setDomains(new ArrayList<>(domains));
}
if (customizations != null) {
tenant.setCustomizations(customizations);
}
if (parameters != null) {
tenant.setParameters(parameters.isEmpty() ? null : new LinkedHashMap<>(parameters));
}
if (enabled != null) {
tenant.setEnabled(enabled);
}
tenant.setLastModifiedTime(Instant.now());
tenant.setEtag("E" + randomIdSuffix(12));
tenantStore.put(id, tenant);
return tenant;
}
public synchronized void deleteDistributionTenant(String id, String ifMatch) {
requireIfMatch(ifMatch);
DistributionTenant tenant = requireDistributionTenant(id);
if (!tenant.getEtag().equals(ifMatch)) {
throw new AwsException("PreconditionFailed",
"Your request is missing requirements for this operation. Update your request and try again.",
412);
}
if (Boolean.TRUE.equals(tenant.getEnabled())) {
throw new AwsException("ResourceNotDisabled",
"You must disable the distribution tenant before you can delete it.", 409);
}
tenantStore.delete(id);
tagStore.delete(tenant.getArn());
}
public List<DistributionTenant> listDistributionTenants(String marker, int maxItems,
String distributionIdFilter,
String connectionGroupIdFilter) {
List<DistributionTenant> all = new ArrayList<>(tenantStore.scan(k -> true));
all.removeIf(tenant -> distributionIdFilter != null
&& !distributionIdFilter.equals(tenant.getDistributionId()));
all.removeIf(tenant -> connectionGroupIdFilter != null
&& !connectionGroupIdFilter.equals(tenant.getConnectionGroupId()));
all.sort((a, b) -> a.getName().compareTo(b.getName()));
return paginate(all, marker, maxItems, DistributionTenant::getName);
}
/** AWS: "You must specify either the CertificateArn parameter or WebACLArn parameter, but not both". */
public List<DistributionTenant> listDistributionTenantsByCustomization(String marker, int maxItems,
String webAclArn,
String certificateArn) {
boolean byWebAcl = webAclArn != null && !webAclArn.isBlank();
boolean byCertificate = certificateArn != null && !certificateArn.isBlank();
if (byWebAcl == byCertificate) {
throw new AwsException("InvalidArgument",
"You must specify either WebACLArn or CertificateArn, but not both.", 400);
}
List<DistributionTenant> all = new ArrayList<>(tenantStore.scan(k -> true));
all.removeIf(tenant -> {
TenantCustomizations customizations = tenant.getCustomizations();
if (customizations == null) {
return true;
}
return byWebAcl ? !webAclArn.equals(customizations.getWebAclArn())
: !certificateArn.equals(customizations.getCertificateArn());
});
all.sort((a, b) -> a.getName().compareTo(b.getName()));
return paginate(all, marker, maxItems, DistributionTenant::getName);
}
private DistributionTenant requireDistributionTenant(String id) {
DistributionTenant tenant = id == null ? null : tenantStore.get(id).orElse(null);
if (tenant == null) {
throw tenantNotFound();
}
return tenant;
}
private static AwsException tenantNotFound() {
return new AwsException("EntityNotFound", "The specified distribution tenant doesn't exist.", 404);
}
/**
* Only a multi-tenant distribution ({@code ConnectionMode: tenant-only}) can have tenants.
* The API declares no code for a standard distribution, so Floci reads it as
* {@code InvalidArgument}; a distribution that does not exist is {@code EntityNotFound}.
*/
private void requireTenantOnlyDistribution(String distributionId) {
Distribution dist = distributionId == null || distributionId.isBlank() ? null
: distStore.get(distributionId).orElse(null);
if (dist == null) {
throw new AwsException("EntityNotFound", "The specified distribution does not exist.", 404);
}
if (!"tenant-only".equals(effectiveConnectionMode(dist))) {
throw new AwsException("InvalidArgument",
"The distribution " + distributionId + " is not a multi-tenant distribution.", 400);
}
}
private static void requireTenantName(String name) {
if (name == null || !TENANT_NAME.matcher(name).matches()) {
throw new AwsException("InvalidArgument", "The Name specified is not valid.", 400);
}
}
private static void requireTenantDomains(List<String> domains) {
if (domains == null || domains.isEmpty()) {
throw new AwsException("InvalidArgument", "At least one domain must be specified.", 400);
}
if (domains.size() > TENANT_MAX_DOMAINS) {
throw new AwsException("EntityLimitExceeded",
"A distribution tenant can have up to " + TENANT_MAX_DOMAINS + " domains.", 400);
}
Set<String> seen = new HashSet<>();
for (String domain : domains) {
if (domain == null || domain.isBlank()) {
throw new AwsException("InvalidArgument", "The Domain specified is not valid.", 400);
}
if (!seen.add(domain.toLowerCase(Locale.ROOT))) {
throw new AwsException("InvalidArgument",
"The domain " + domain + " is specified more than once.", 400);
}
}
}
/** A domain belongs to one tenant or one distribution alias; the check is case-insensitive. */
private void ensureTenantDomainsAvailable(List<String> domains, String currentTenantId) {
for (String domain : domains) {
if (tenantHoldsDomain(domain, currentTenantId)) {
throw domainTaken();
}
}
for (Distribution dist : distStore.scan(k -> true)) {
if (dist.getConfig() == null) {
continue;
}
for (String domain : domains) {
if (containsIgnoreCase(dist.getConfig().getAliases(), domain)) {
throw domainTaken();
}
}
}
}
private boolean tenantHoldsDomain(String domain) {
return tenantHoldsDomain(domain, null);
}
private boolean tenantHoldsDomain(String domain, String exceptTenantId) {
for (DistributionTenant tenant : tenantStore.scan(k -> true)) {
if (!tenant.getId().equals(exceptTenantId) && containsIgnoreCase(tenant.getDomains(), domain)) {
return true;
}
}
return false;
}
private static AwsException domainTaken() {
return new AwsException("CNAMEAlreadyExists",
"One or more of the CNAMEs you provided are already associated with a different resource.", 409);
}
private static boolean containsIgnoreCase(List<String> values, String candidate) {
if (values == null) {
return false;
}
for (String value : values) {
if (candidate != null && candidate.equalsIgnoreCase(value)) {
return true;
}
}
return false;
}
private static void validateTenantCustomizations(TenantCustomizations customizations) {
if (customizations == null) {
return;
}
if (customizations.getWebAclArn() != null && customizations.getWebAclAction() == null) {
throw new AwsException("InvalidArgument", "The WebAcl Action must be specified.", 400);
}
if (customizations.getWebAclAction() != null
&& !TENANT_WEB_ACL_ACTIONS.contains(customizations.getWebAclAction())) {
throw new AwsException("InvalidArgument", "The WebAcl Action specified is not valid.", 400);
}
if (customizations.getGeoRestrictionType() != null
&& !TENANT_GEO_RESTRICTION_TYPES.contains(customizations.getGeoRestrictionType())) {
throw new AwsException("InvalidArgument", "The GeoRestrictions RestrictionType is not valid.", 400);
}
}
private static void validateTenantParameters(Map<String, String> parameters) {
if (parameters == null) {
return;
}
for (Map.Entry<String, String> parameter : parameters.entrySet()) {
String value = parameter.getValue();
if (parameter.getKey() == null || !TENANT_PARAMETER_NAME.matcher(parameter.getKey()).matches()
|| value == null || value.isEmpty() || value.length() > TENANT_PARAMETER_VALUE_MAX_LENGTH) {
throw new AwsException("InvalidArgument",
"The Parameter " + parameter.getKey() + " is not valid.", 400);
}
}
}
// ── Invalidations ─────────────────────────────────────────────────────────
public synchronized Invalidation createInvalidation(String distributionId, Invalidation inv) {
@@ -0,0 +1,66 @@
package io.floci.aws.services.cloudfront.model;
import io.quarkus.runtime.annotations.RegisterForReflection;
import java.time.Instant;
import java.util.List;
import java.util.Map;
@RegisterForReflection
public class DistributionTenant {
private String id;
private String arn;
private String name;
private String distributionId;
private String connectionGroupId;
private List<String> domains;
private TenantCustomizations customizations;
private Map<String, String> parameters;
private Boolean enabled;
private String status;
private Instant createdTime;
private Instant lastModifiedTime;
private String etag;
public DistributionTenant() {}
public String getId() { return id; }
public void setId(String id) { this.id = id; }
public String getArn() { return arn; }
public void setArn(String arn) { this.arn = arn; }
public String getName() { return name; }
public void setName(String name) { this.name = name; }
public String getDistributionId() { return distributionId; }
public void setDistributionId(String distributionId) { this.distributionId = distributionId; }
public String getConnectionGroupId() { return connectionGroupId; }
public void setConnectionGroupId(String connectionGroupId) { this.connectionGroupId = connectionGroupId; }
public List<String> getDomains() { return domains; }
public void setDomains(List<String> domains) { this.domains = domains; }
public TenantCustomizations getCustomizations() { return customizations; }
public void setCustomizations(TenantCustomizations customizations) { this.customizations = customizations; }
public Map<String, String> getParameters() { return parameters; }
public void setParameters(Map<String, String> parameters) { this.parameters = parameters; }
public Boolean getEnabled() { return enabled; }
public void setEnabled(Boolean enabled) { this.enabled = enabled; }
public String getStatus() { return status; }
public void setStatus(String status) { this.status = status; }
public Instant getCreatedTime() { return createdTime; }
public void setCreatedTime(Instant createdTime) { this.createdTime = createdTime; }
public Instant getLastModifiedTime() { return lastModifiedTime; }
public void setLastModifiedTime(Instant lastModifiedTime) { this.lastModifiedTime = lastModifiedTime; }
public String getEtag() { return etag; }
public void setEtag(String etag) { this.etag = etag; }
}
@@ -0,0 +1,41 @@
package io.floci.aws.services.cloudfront.model;
import io.quarkus.runtime.annotations.RegisterForReflection;
import java.util.List;
/**
* The customizations of a distribution tenant: the WAF web ACL and ACM certificate it overrides
* from its multi-tenant distribution, and its geographic restriction. A null member is a
* customization the tenant does not set.
*/
@RegisterForReflection
public class TenantCustomizations {
private String webAclAction;
private String webAclArn;
private String certificateArn;
private String geoRestrictionType;
private List<String> geoLocations;
public TenantCustomizations() {}
public String getWebAclAction() { return webAclAction; }
public void setWebAclAction(String webAclAction) { this.webAclAction = webAclAction; }
public String getWebAclArn() { return webAclArn; }
public void setWebAclArn(String webAclArn) { this.webAclArn = webAclArn; }
public String getCertificateArn() { return certificateArn; }
public void setCertificateArn(String certificateArn) { this.certificateArn = certificateArn; }
public String getGeoRestrictionType() { return geoRestrictionType; }
public void setGeoRestrictionType(String geoRestrictionType) { this.geoRestrictionType = geoRestrictionType; }
public List<String> getGeoLocations() { return geoLocations; }
public void setGeoLocations(List<String> geoLocations) { this.geoLocations = geoLocations; }
public boolean isEmpty() {
return webAclAction == null && certificateArn == null && geoRestrictionType == null;
}
}