feat(cloudfront): connection groups for multi-tenant distributions (#9214)

This commit is contained in:
Matheus Oliveira authored and GitHub committed 2026-11-23 19:35:45 -04:00
1 parent 9642d7573c
commit 7a8445042b
18 files changed
+2007 -34

No files matched your search

+1 -1
View File
@@ -390,7 +390,7 @@ For operation-level compatibility, see the [Services Overview](https://floci.io/
| AWS Config | In-process | Config rules, evaluation-driven compliance (PutEvaluations, compliance details and summaries), configuration recorders, delivery channels, retention configuration, conformance packs, tagging |
| Organizations | In-process | Organizations, roots, nested OUs, member accounts, all policy types with `FullAWSAccess` and effective-policy inheritance, trusted service access, delegated administrators, resource policy, and the full invitation/handshake flow; created accounts are usable Floci accounts and member accounts can read the organization they belong to |
| CloudTrail | In-process | Trails, event selectors (S3 data events with bucket/prefix matching), `StartLogging`/`StopLogging`, scheduled gzipped log file emission to the destination bucket at AWS-shaped key paths, IAM-deny path emits `AccessDenied` records |
| CloudFront | In-process | Distributions, origins, cache behaviors, invalidations, functions, key value stores, tagging |
| CloudFront | In-process | Distributions, origins, cache behaviors, invalidations, functions, key value stores, tagging, multi-tenant connection groups |
| WAF v2 | In-process | Web ACLs, IP sets, regex pattern sets, rule groups, logging configs, resource associations, tagging (REGIONAL and CLOUDFRONT scopes) |
| AWS Resource Groups | In-process | Five capacity-pool operations: stored groups, verified EC2 reservation membership, scoped pagination and group deletion; no dynamic queries or capacity allocation |
| Resource Explorer 2 | In-process | All 32 management APIs: index and view lifecycle, multi-Region setup tasks, the full search query grammar, and tagging; 30 services expose their resources for search, gathered live rather than from an index |
@@ -0,0 +1,135 @@
package com.floci.test;
import org.junit.jupiter.api.Test;
import software.amazon.awssdk.services.cloudfront.CloudFrontClient;
import software.amazon.awssdk.services.cloudfront.model.ConnectionGroupSummary;
import software.amazon.awssdk.services.cloudfront.model.CreateConnectionGroupResponse;
import software.amazon.awssdk.services.cloudfront.model.EntityAlreadyExistsException;
import software.amazon.awssdk.services.cloudfront.model.EntityNotFoundException;
import software.amazon.awssdk.services.cloudfront.model.GetConnectionGroupByRoutingEndpointResponse;
import software.amazon.awssdk.services.cloudfront.model.GetConnectionGroupResponse;
import software.amazon.awssdk.services.cloudfront.model.InvalidIfMatchVersionException;
import software.amazon.awssdk.services.cloudfront.model.PreconditionFailedException;
import software.amazon.awssdk.services.cloudfront.model.ResourceNotDisabledException;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
class CloudFrontConnectionGroupTest {
@Test
void roundTripsConnectionGroupsWithTheAwsSdk() {
String name = "compat-connection-group-" + TestFixtures.uniqueName();
try (CloudFrontClient cloudFront = TestFixtures.cloudFrontClient()) {
CreateConnectionGroupResponse created =
cloudFront.createConnectionGroup(request -> request
.name(name)
.enabled(true)
.ipv6Enabled(false));
String groupId = created.connectionGroup().id();
String etag = created.eTag();
try {
assertNotNull(groupId);
assertTrue(groupId.startsWith("cg_"));
assertTrue(created.connectionGroup().arn().endsWith(":connection-group/" + groupId));
assertTrue(created.connectionGroup().routingEndpoint().endsWith(".cloudfront.net"));
assertFalse(created.connectionGroup().isDefault());
assertNotNull(created.connectionGroup().createdTime());
assertFalse(created.connectionGroup().ipv6Enabled());
GetConnectionGroupResponse byId =
cloudFront.getConnectionGroup(request -> request.identifier(groupId));
assertEquals(groupId, byId.connectionGroup().id());
assertEquals(etag, byId.eTag());
GetConnectionGroupResponse byName =
cloudFront.getConnectionGroup(request -> request.identifier(name));
assertEquals(groupId, byName.connectionGroup().id());
GetConnectionGroupResponse byArn =
cloudFront.getConnectionGroup(request -> request.identifier(created.connectionGroup().arn()));
assertEquals(groupId, byArn.connectionGroup().id());
GetConnectionGroupByRoutingEndpointResponse byEndpoint =
cloudFront.getConnectionGroupByRoutingEndpoint(request -> request
.routingEndpoint(created.connectionGroup().routingEndpoint()));
assertEquals(groupId, byEndpoint.connectionGroup().id());
ConnectionGroupSummary listed = cloudFront.listConnectionGroups(
request -> request.maxItems(100))
.connectionGroups().stream()
.filter(group -> groupId.equals(group.id()))
.findFirst()
.orElseThrow();
assertEquals(name, listed.name());
assertEquals(etag, listed.eTag());
} finally {
disableAndDelete(cloudFront, groupId, etag);
}
}
}
@Test
void guardedWritesCarryTheirModeledErrors() {
String name = "compat-connection-group-" + TestFixtures.uniqueName();
try (CloudFrontClient cloudFront = TestFixtures.cloudFrontClient()) {
CreateConnectionGroupResponse created =
cloudFront.createConnectionGroup(request -> request.name(name).enabled(true));
String groupId = created.connectionGroup().id();
String etag = created.eTag();
try {
assertThrows(EntityAlreadyExistsException.class,
() -> cloudFront.createConnectionGroup(request -> request.name(name)));
assertThrows(InvalidIfMatchVersionException.class,
() -> cloudFront.updateConnectionGroup(request -> request
.id(groupId).enabled(false)));
assertThrows(PreconditionFailedException.class,
() -> cloudFront.updateConnectionGroup(request -> request
.id(groupId).ifMatch("E000000000000").enabled(false)));
assertThrows(ResourceNotDisabledException.class,
() -> cloudFront.deleteConnectionGroup(request -> request
.id(groupId).ifMatch(etag)));
cloudFront.updateConnectionGroup(request -> request
.id(groupId).ifMatch(etag).enabled(false).ipv6Enabled(false));
GetConnectionGroupResponse updated =
cloudFront.getConnectionGroup(request -> request.identifier(groupId));
assertFalse(updated.connectionGroup().enabled());
assertFalse(updated.connectionGroup().ipv6Enabled());
cloudFront.deleteConnectionGroup(request -> request.id(groupId).ifMatch(updated.eTag()));
assertThrows(EntityNotFoundException.class,
() -> cloudFront.getConnectionGroup(request -> request.identifier(groupId)));
} finally {
disableAndDelete(cloudFront, groupId, updatedEtagFor(cloudFront, groupId));
}
}
}
private static String updatedEtagFor(CloudFrontClient cloudFront, String groupId) {
try {
return cloudFront.getConnectionGroup(request -> request.identifier(groupId)).eTag();
} catch (EntityNotFoundException e) {
return null;
}
}
private static void disableAndDelete(CloudFrontClient cloudFront, String groupId, String etag) {
if (groupId == null || etag == null) {
return;
}
try {
cloudFront.updateConnectionGroup(request -> request.id(groupId).ifMatch(etag).enabled(false));
String freshEtag = cloudFront.getConnectionGroup(request -> request.identifier(groupId)).eTag();
cloudFront.deleteConnectionGroup(request -> request.id(groupId).ifMatch(freshEtag));
} catch (EntityNotFoundException ignored) {
// teardown only: the emulator state is per-test, so a partially cleaned connection group cannot leak into another test
}
}
}
+1 -1
View File
@@ -256,7 +256,7 @@ cross-resource references.
| Kinesis | `Stream` |
| Kinesis Data Firehose | `DeliveryStream` (`DeliveryStreamName`, `Tags` and, from an S3 destination, `BucketARN`, `RoleARN`, `Prefix`, `ErrorOutputPrefix`, `CompressionFormat`, `BufferingHints`, `CloudWatchLoggingOptions` and `ProcessingConfiguration` are applied; other properties are ignored, and a destination member the template drops on update keeps its stored value, as on AWS) |
| IoT Core | `Authorizer`, `DomainConfiguration` (`ServerCertificates` resolves to a JSON string), `Policy` (deleted after detaching it from its principals; on AWS the delete fails with `DeleteConflictException` while the policy is attached), `Thing`, `TopicRule` |
| CloudFront | `CachePolicy`, `Distribution`, `Function` (`KeyValueStoreAssociations` is ignored), `KeyGroup`, `OriginAccessControl`, `OriginRequestPolicy`, `PublicKey`, `ResponseHeadersPolicy` |
| CloudFront | `CachePolicy`, `ConnectionGroup`, `Distribution`, `Function` (`KeyValueStoreAssociations` is ignored), `KeyGroup`, `OriginAccessControl`, `OriginRequestPolicy`, `PublicKey`, `ResponseHeadersPolicy` |
| CloudWatch | `Alarm`, `CompositeAlarm`, `Dashboard`. Composite alarms have backing definitions with name Ref and Arn GetAtt, rollback, and replacement cleanup. Composite actions are stored only; suppression properties are rejected. |
| CloudWatch Logs | `LogGroup`, `LogStream`, `MetricFilter` |
| WAFv2 | `IPSet`, `LoggingConfiguration`, `WebACL`, `WebACLAssociation` |
+26
View File
@@ -25,8 +25,34 @@ OPTIONS, POST, PUT, PATCH and DELETE).
| `UpdateDistribution` | PUT | `/2020-05-31/distribution/{Id}/config` |
| `DeleteDistribution` | DELETE | `/2020-05-31/distribution/{Id}` |
| `ListDistributions` | GET | `/2020-05-31/distribution` |
| `ListDistributionsByConnectionMode` | GET | `/2020-05-31/distributionsByConnectionMode/{ConnectionMode}` |
| `AssociateAlias` | PUT | `/2020-05-31/distribution/{TargetDistributionId}/associate-alias` |
### Connection Groups
Multi-tenant distributions (`ConnectionMode: tenant-only`) are served through a connection group.
The account's default group is created automatically with the first `tenant-only` distribution, as
the [Developer Guide](https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/custom-connection-group.html)
documents, and it can never be deleted. A group is addressable by its id, name or ARN wherever the
API takes an `Identifier`.
| Operation | Method | Path |
|---|---|---|
| `CreateConnectionGroup` | POST | `/2020-05-31/connection-group` |
| `GetConnectionGroup` | GET | `/2020-05-31/connection-group/{Identifier}` |
| `GetConnectionGroupByRoutingEndpoint` | GET | `/2020-05-31/connection-group?RoutingEndpoint` |
| `UpdateConnectionGroup` | PUT | `/2020-05-31/connection-group/{Id}` |
| `DeleteConnectionGroup` | DELETE | `/2020-05-31/connection-group/{Id}` |
| `ListConnectionGroups` | POST | `/2020-05-31/connection-groups` |
`CreateConnectionGroup` requires a unique `Name` and answers `EntityAlreadyExists` otherwise. A
connection group's `RoutingEndpoint` reads like a distribution's domain name and is derived from
the partition's DNS suffix. `UpdateConnectionGroup` and `DeleteConnectionGroup` require `If-Match`
and answer `InvalidIfMatchVersion` without it, `PreconditionFailed` on a stale value, and
`ResourceNotDisabled` on a delete of a group that is still enabled. `ListConnectionGroups` takes
`Marker`, `MaxItems` and an optional `AssociationFilter.AnycastIpListId`, and returns
`ConnectionGroupSummary` items carrying the group's `ETag`.
### Invalidations
| Operation | Method | Path |
+1 -1
View File
@@ -148,7 +148,7 @@ Operation counts are exact. For dispatch-table services (Query and JSON 1.1) eac
| [AWS FIS](fis.md) | `/experimentTemplates/*`, `/experiments/*`, `/actions/*`, `/targetResourceTypes/*`, `/safetyLevers/*`, `/tags/*` | REST JSON | 26 |
| [CodeGuru Reviewer](codegurureviewer.md) | `/associations`, `/associations/{associationArn}`, `/tags/*` | REST JSON | 7 |
| [CodeArtifact](codeartifact.md) | `/v1/domain*`, `/v1/repository*`, `/v1/package`, `/v1/package/version*`, `/v1/package-group*`, `/v1/list-associated-packages`, `/v1/get-associated-package-group`, `/v1/tag*`, `/v1/authorization-token`, `/codeartifact/maven/*`, `/codeartifact/npm/*`, `/codeartifact/pypi/*` | REST JSON | 48 |
| [CloudFront](cloudfront.md) | `/2020-05-31/distribution/*`, `/2020-05-31/cache-policy/*`, `/2020-05-31/function/*`, `/2020-05-31/key-value-store/*` | REST XML | 97 |
| [CloudFront](cloudfront.md) | `/2020-05-31/distribution/*`, `/2020-05-31/cache-policy/*`, `/2020-05-31/function/*`, `/2020-05-31/key-value-store/*` | REST XML | 104 |
| [CloudFront KeyValueStore](cloudfront.md#key-value-stores) | `/key-value-stores/*` | REST JSON | 6 |
| [Route53](route53.md) | `/2013-04-01/hostedzone/*`, `/2013-04-01/healthcheck/*`, `/2013-04-01/change/*`, `/2013-04-01/delegationset/*` | REST XML | 31 |
| [Route 53 Resolver](route53resolver.md) | `POST /` + `X-Amz-Target: Route53Resolver.*` | JSON 1.1 | 25 |
@@ -9,6 +9,7 @@ import io.floci.aws.services.cloudfront.ResponseHeadersPolicyConfigCodec;
import io.floci.aws.services.cloudfront.model.CacheBehavior;
import io.floci.aws.services.cloudfront.model.CachePolicy;
import io.floci.aws.services.cloudfront.model.CloudFrontFunction;
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;
@@ -68,6 +69,7 @@ public class CloudFrontCfnProvisioner implements CfnResourceProvisioner {
static final String PUBLIC_KEY = "AWS::CloudFront::PublicKey";
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 NO_SUCH_RESPONSE_HEADERS_POLICY = "NoSuchResponseHeadersPolicy";
static final String NO_SUCH_CACHE_POLICY = "NoSuchCachePolicy";
@@ -76,6 +78,7 @@ public class CloudFrontCfnProvisioner implements CfnResourceProvisioner {
static final String NO_SUCH_PUBLIC_KEY = "NoSuchPublicKey";
static final String NO_SUCH_KEY_GROUP = "NoSuchResource";
static final String NO_SUCH_FUNCTION = "NoSuchFunctionExists";
static final String ENTITY_NOT_FOUND = "EntityNotFound";
private static final Set<String> MODEL_FIELDS = Set.of("Name", "Comment");
@@ -88,7 +91,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);
ORIGIN_ACCESS_CONTROL, PUBLIC_KEY, KEY_GROUP, FUNCTION, CONNECTION_GROUP);
}
@Override
@@ -103,6 +106,7 @@ public class CloudFrontCfnProvisioner implements CfnResourceProvisioner {
case PUBLIC_KEY -> provisionPublicKey(r, props, ctx);
case KEY_GROUP -> provisionKeyGroup(r, props, ctx);
case FUNCTION -> provisionFunction(r, props, ctx);
case CONNECTION_GROUP -> provisionConnectionGroup(r, props, ctx);
default -> throw new IllegalArgumentException("Unsupported resource type: " + r.getResourceType());
}
ReplacementCleanup.record(r, ctx, attributesBefore);
@@ -186,10 +190,95 @@ public class CloudFrontCfnProvisioner implements CfnResourceProvisioner {
id -> cloudFrontService.getKeyGroup(id).getEtag(),
cloudFrontService::deleteKeyGroup, NO_SUCH_KEY_GROUP);
case FUNCTION -> deleteFunction(physicalId);
case CONNECTION_GROUP -> deleteConnectionGroup(physicalId);
default -> { }
}
}
/**
* An enabled group 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. Only the type's own not-found code is tolerated.
*/
private void deleteConnectionGroup(String physicalId) {
CfnDeletes.safeDelete("connection group", physicalId, () -> {
ConnectionGroup group = cloudFrontService.getConnectionGroup(physicalId);
String etag = group.getEtag();
if (Boolean.TRUE.equals(group.getEnabled())) {
etag = cloudFrontService.updateConnectionGroup(physicalId, etag, null, false, null, null)
.getEtag();
}
cloudFrontService.deleteConnectionGroup(physicalId, etag);
}, ENTITY_NOT_FOUND);
}
/**
* The group 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 group's replaces it, and the engine's replacement
* cleanup deletes the old group through {@link #deleteConnectionGroup} once the update commits.
* Otherwise the physical id only changes when the prior group is already gone. The registry
* schema's read-only members ({@code Id}, {@code Arn}, {@code RoutingEndpoint}, {@code Status},
* {@code IsDefault}, {@code ETag} and the two timestamps) travel to {@code Fn::GetAtt} from the
* provisioned object.
*
* <p>An update drives the tags to the template's desired set and treats a present
* {@code ViewerFallback} property as authoritative, so removing it clears the group's fallback
* distribution; an update whose template drops the property keeps the prior one.
*/
private void provisionConnectionGroup(StackResource r, JsonNode props, ProvisionContext ctx) {
String name = ctx.resolveOptional(props, "Name");
String anycastIpListId = ctx.resolveOptional(props, "AnycastIpListId");
Boolean enabled = ctx.resolveOptionalBoolean(props, "Enabled");
Boolean ipv6Enabled = ctx.resolveOptionalBoolean(props, "Ipv6Enabled");
JsonNode viewerFallbackRaw = props.get("ViewerFallback");
JsonNode viewerFallback = viewerFallbackRaw == null || viewerFallbackRaw.isNull()
? viewerFallbackRaw : ctx.engine().resolveNode(viewerFallbackRaw);
boolean viewerFallbackDeclared = viewerFallback != null;
String viewerFallbackDistributionId =
viewerFallback == null || viewerFallback.isNull() ? null
: text(viewerFallback, "DistributionId");
Boolean clearViewerFallback = viewerFallbackDeclared && viewerFallbackDistributionId == null
? Boolean.TRUE : null;
Map<String, String> tags = ctx.resolveTags(props, "Tags");
ConnectionGroup provisioned;
ConnectionGroup prior = prior(ctx, "connection group",
cloudFrontService::getConnectionGroup, ENTITY_NOT_FOUND);
if (prior == null) {
requireConnectionGroupName(name);
provisioned = cloudFrontService.createConnectionGroup(name, anycastIpListId,
enabled, ipv6Enabled, viewerFallbackDistributionId, tags);
} else if (name != null && !name.isBlank() && !name.equals(prior.getName())) {
requireConnectionGroupName(name);
provisioned = cloudFrontService.createConnectionGroup(name, anycastIpListId,
enabled, ipv6Enabled, viewerFallbackDistributionId, tags);
} else {
provisioned = cloudFrontService.updateConnectionGroup(prior.getId(), prior.getEtag(),
anycastIpListId != null ? anycastIpListId : prior.getAnycastIpListId(),
enabled != null ? enabled : prior.getEnabled(),
ipv6Enabled != null ? ipv6Enabled : prior.getIpv6Enabled(),
viewerFallbackDistributionId, clearViewerFallback, tags);
}
r.setPhysicalId(provisioned.getId());
r.getAttributes().put("Id", provisioned.getId());
r.getAttributes().put("Arn", provisioned.getArn());
r.getAttributes().put("RoutingEndpoint", provisioned.getRoutingEndpoint());
r.getAttributes().put("Status", provisioned.getStatus());
r.getAttributes().put("IsDefault", String.valueOf(provisioned.getIsDefault()));
r.getAttributes().put("ETag", provisioned.getEtag());
r.getAttributes().put("CreatedTime",
provisioned.getCreatedTime() == null ? "" : provisioned.getCreatedTime().toString());
r.getAttributes().put("LastModifiedTime",
provisioned.getLastModifiedTime() == null ? "" : provisioned.getLastModifiedTime().toString());
}
private static void requireConnectionGroupName(String name) {
if (name == null || name.isBlank()) {
throw new AwsException("ValidationError", CONNECTION_GROUP + " requires Name", 400);
}
}
private void provisionResponseHeadersPolicy(StackResource r, JsonNode props, ProvisionContext ctx) {
JsonNode config = requireConfig(RESPONSE_HEADERS_POLICY, "ResponseHeadersPolicyConfig", props, ctx);
ResponseHeadersPolicy policy = new ResponseHeadersPolicy();
@@ -161,20 +161,7 @@ public class CloudFrontController {
maxItems, Distribution::getId);
int totalDistributions =
service.listDistributions(null, Integer.MAX_VALUE).size();
XmlBuilder xml = new XmlBuilder()
.start("DistributionList", NS)
.elem("Marker", marker != null ? marker : "")
.elem("NextMarker", page.nextMarker())
.elem("MaxItems", maxItems)
.elem("IsTruncated", page.truncated())
.elem("Quantity", totalDistributions)
.start("Items");
for (Distribution d : page.items()) {
xml.raw(xmlDistributionSummary(d));
}
xml.end("Items").end("DistributionList");
return Response.ok(xml.build(), XML).build();
return distributionListResponse(page, totalDistributions, marker, maxItems);
} catch (AwsException e) {
return xmlErrorResponse(e);
}
@@ -192,6 +179,156 @@ public class CloudFrontController {
}
}
// ── Connection groups ─────────────────────────────────────────────────────
@POST
@Path("/connection-group")
public Response createConnectionGroup(String body) {
try {
Map<String, String> request = XmlParser.extractGroups(body, "CreateConnectionGroupRequest")
.stream().findFirst().orElse(Map.of());
ConnectionGroup group = service.createConnectionGroup(
request.get("Name"),
blankToNull(request.get("AnycastIpListId")),
xmlBoolean(request.get("Enabled")),
xmlBoolean(request.get("Ipv6Enabled")),
viewerFallbackDistributionId(body),
parseTags(body));
return Response.created(URI.create("/2020-05-31/connection-group/" + group.getId()))
.type(XML)
.header("ETag", group.getEtag())
.entity(xmlConnectionGroup(group, "ConnectionGroup"))
.build();
} catch (AwsException e) {
return xmlErrorResponse(e);
}
}
@GET
@Path("/connection-group/{Identifier}")
public Response getConnectionGroup(@PathParam("Identifier") String identifier) {
try {
ConnectionGroup group = service.getConnectionGroup(identifier);
return Response.ok(xmlConnectionGroup(group, "ConnectionGroup"), XML)
.header("ETag", group.getEtag())
.build();
} catch (AwsException e) {
return xmlErrorResponse(e);
}
}
@GET
@Path("/connection-group")
public Response getConnectionGroupByRoutingEndpoint(@QueryParam("RoutingEndpoint") String endpoint) {
try {
ConnectionGroup group = service.getConnectionGroupByRoutingEndpoint(endpoint);
return Response.ok(xmlConnectionGroup(group, "ConnectionGroup"), XML)
.header("ETag", group.getEtag())
.build();
} catch (AwsException e) {
return xmlErrorResponse(e);
}
}
@PUT
@Path("/connection-group/{Id}")
public Response updateConnectionGroup(@PathParam("Id") String id,
@HeaderParam("If-Match") String ifMatch,
String body) {
try {
Map<String, String> request = XmlParser.extractGroups(body, "UpdateConnectionGroupRequest")
.stream().findFirst().orElse(Map.of());
ConnectionGroup group = service.updateConnectionGroup(id, ifMatch,
blankToNull(request.get("AnycastIpListId")),
xmlBoolean(request.get("Enabled")),
xmlBoolean(request.get("Ipv6Enabled")),
viewerFallbackDistributionId(body));
return Response.ok(xmlConnectionGroup(group, "ConnectionGroup"), XML)
.header("ETag", group.getEtag())
.build();
} catch (AwsException e) {
return xmlErrorResponse(e);
}
}
@DELETE
@Path("/connection-group/{Id}")
public Response deleteConnectionGroup(@PathParam("Id") String id,
@HeaderParam("If-Match") String ifMatch) {
try {
service.deleteConnectionGroup(id, ifMatch);
return Response.noContent().build();
} catch (AwsException e) {
return xmlErrorResponse(e);
}
}
@POST
@Path("/connection-groups")
public Response listConnectionGroups(String body) {
try {
Map<String, String> request = XmlParser.extractGroups(body, "ListConnectionGroupsRequest")
.stream().findFirst().orElse(Map.of());
String marker = request.get("Marker");
Integer maxItems = parseMaxItems(request.get("MaxItems"));
String anycastIpListId = null;
for (Map<String, String> filter : XmlParser.extractGroups(body, "ConnectionGroupAssociationFilter")) {
anycastIpListId = blankToNull(filter.get("AnycastIpListId"));
}
int pageSize = maxItems == null ? 100 : maxItems;
Page<ConnectionGroup> page = page(
service.listConnectionGroups(marker, paginationFetchLimit(pageSize), anycastIpListId),
pageSize, ConnectionGroup::getName);
XmlBuilder xml = new XmlBuilder()
.start("ListConnectionGroupsResult", NS)
.start("ConnectionGroups");
for (ConnectionGroup group : page.items()) {
xml.raw(xmlConnectionGroup(group, "ConnectionGroupSummary"));
}
xml.end("ConnectionGroups")
.elem("NextMarker", page.nextMarker())
.end("ListConnectionGroupsResult");
return Response.ok(xml.build(), XML).build();
} catch (AwsException e) {
return xmlErrorResponse(e);
}
}
@GET
@Path("/distributionsByConnectionMode/{ConnectionMode}")
public Response listDistributionsByConnectionMode(@PathParam("ConnectionMode") String connectionMode,
@QueryParam("Marker") String marker,
@QueryParam("MaxItems") @DefaultValue("100") int maxItems) {
try {
Page<Distribution> page = page(
service.listDistributionsByConnectionMode(connectionMode, marker,
paginationFetchLimit(maxItems)),
maxItems, Distribution::getId);
int totalDistributions = service
.listDistributionsByConnectionMode(connectionMode, null, Integer.MAX_VALUE).size();
return distributionListResponse(page, totalDistributions, marker, maxItems);
} catch (AwsException e) {
return xmlErrorResponse(e);
}
}
private Response distributionListResponse(Page<Distribution> page, int totalDistributions,
String marker, int maxItems) {
XmlBuilder xml = new XmlBuilder()
.start("DistributionList", NS)
.elem("Marker", marker != null ? marker : "")
.elem("NextMarker", page.nextMarker())
.elem("MaxItems", maxItems)
.elem("IsTruncated", page.truncated())
.elem("Quantity", totalDistributions)
.start("Items");
for (Distribution d : page.items()) {
xml.raw(xmlDistributionSummary(d));
}
xml.end("Items").end("DistributionList");
return Response.ok(xml.build(), XML).build();
}
// ── Invalidations ─────────────────────────────────────────────────────────
@POST
@@ -3996,4 +4133,68 @@ public class CloudFrontController {
}
return tags;
}
private String xmlConnectionGroup(ConnectionGroup group, String root) {
XmlBuilder xml = new XmlBuilder().start(root, NS);
if ("ConnectionGroupSummary".equals(root)) {
xml.elem("ETag", group.getEtag());
}
xml.elem("Id", group.getId())
.elem("Arn", group.getArn())
.elem("Name", group.getName())
.elem("AnycastIpListId", group.getAnycastIpListId())
.elem("RoutingEndpoint", group.getRoutingEndpoint())
.elem("Status", group.getStatus())
.elem("Enabled", group.getEnabled())
.elem("Ipv6Enabled", group.getIpv6Enabled())
.elem("IsDefault", group.getIsDefault())
.elem("CreatedTime", group.getCreatedTime() != null ? group.getCreatedTime().toString() : "")
.elem("LastModifiedTime",
group.getLastModifiedTime() != null ? group.getLastModifiedTime().toString() : "");
if (group.getViewerFallbackDistributionId() != null) {
xml.start("ViewerFallback")
.elem("DistributionId", group.getViewerFallbackDistributionId())
.end("ViewerFallback");
}
if (group.getTags() != null && !group.getTags().isEmpty()) {
xml.start("Tags").start("Items");
for (Map.Entry<String, String> tag : group.getTags().entrySet()) {
xml.start("Tag")
.elem("Key", tag.getKey())
.elem("Value", tag.getValue())
.end("Tag");
}
xml.end("Items").end("Tags");
}
return xml.end(root).build();
}
private static String blankToNull(String value) {
return value != null && !value.isBlank() ? value : null;
}
private static Boolean xmlBoolean(String value) {
if (value == null || value.isBlank()) {
return null;
}
return "true".equalsIgnoreCase(value.strip()) || "1".equals(value.strip());
}
private static Integer parseMaxItems(String value) {
if (value == null || value.isBlank()) {
return null;
}
try {
return Integer.parseInt(value.strip());
} catch (NumberFormatException e) {
throw new AwsException("InvalidArgument", "The MaxItems specified is not valid.", 400);
}
}
private static String viewerFallbackDistributionId(String body) {
for (Map<String, String> fallback : XmlParser.extractGroups(body, "ViewerFallback")) {
return blankToNull(fallback.get("DistributionId"));
}
return null;
}
}
@@ -18,6 +18,7 @@ import io.floci.aws.services.cloudfront.model.CacheBehavior;
import io.floci.aws.services.cloudfront.model.CachePolicy;
import io.floci.aws.services.cloudfront.model.CloudFrontFunction;
import io.floci.aws.services.cloudfront.model.CloudFrontOriginAccessIdentity;
import io.floci.aws.services.cloudfront.model.ConnectionGroup;
import io.floci.aws.services.cloudfront.model.ContinuousDeploymentPolicy;
import io.floci.aws.services.cloudfront.model.DefaultCacheBehavior;
import io.floci.aws.services.cloudfront.model.Distribution;
@@ -92,6 +93,10 @@ public class CloudFrontService implements ServerCertificateReferenceProvider {
private static final Set<String> SSL_SUPPORT_METHODS = Set.of("sni-only", "vip", "static-ip");
/** The values {@code ConnectionMode} admits, the enumeration its shape declares. */
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";
/** The documented maximum a connection group's Name may reach (AWS's own limit). */
private static final int CONNECTION_GROUP_NAME_MAX_LENGTH = 256;
/**
* The forms a member declared {@code boolean} can carry, XML giving such a value as
* {@code true}, {@code false}, {@code 1} or {@code 0}.
@@ -151,6 +156,7 @@ public class CloudFrontService implements ServerCertificateReferenceProvider {
private static final String MANAGED_POLICY_ETAG = "E23ZP02F085DFQ";
private final AccountAwareStorageBackend<Distribution> distStore;
private final AccountAwareStorageBackend<ConnectionGroup> connectionGroupStore;
private final StorageBackend<String, List<Invalidation>> invalidationStore;
private final StorageBackend<String, CachePolicy> cachePolicyStore;
private final StorageBackend<String, OriginRequestPolicy> orpStore;
@@ -199,6 +205,8 @@ public class CloudFrontService implements ServerCertificateReferenceProvider {
this.keyValueStores = keyValueStores;
this.distStore = factory.create("cloudfront", "cloudfront-distributions.json",
new TypeReference<Map<String, Distribution>>() {});
this.connectionGroupStore = factory.create("cloudfront", "cloudfront-connection-groups.json",
new TypeReference<Map<String, ConnectionGroup>>() {});
this.invalidationStore = factory.create("cloudfront", "cloudfront-invalidations.json",
new TypeReference<Map<String, List<Invalidation>>>() {});
this.cachePolicyStore = factory.create("cloudfront", "cloudfront-cache-policies.json",
@@ -264,6 +272,7 @@ public class CloudFrontService implements ServerCertificateReferenceProvider {
tagStore.put(dist.getArn(), tags);
}
distStore.put(id, dist);
ensureDefaultConnectionGroupForTenantOnly(dist.getConfig());
return dist;
});
}
@@ -298,10 +307,21 @@ public class CloudFrontService implements ServerCertificateReferenceProvider {
updated.setEtag(UUID.randomUUID().toString());
updated.setTags(existing.getTags());
distStore.put(id, updated);
ensureDefaultConnectionGroupForTenantOnly(updated.getConfig());
return updated;
});
}
/**
* The account's default connection group stands behind every {@code tenant-only} distribution, so
* it is minted when a distribution first selects the mode, on the create as on the update.
*/
private void ensureDefaultConnectionGroupForTenantOnly(DistributionConfig config) {
if (config != null && "tenant-only".equals(config.getConnectionMode())) {
ensureDefaultConnectionGroup();
}
}
@Override
public List<Reference> serverCertificateReferences() {
List<Reference> references = new ArrayList<>();
@@ -716,6 +736,7 @@ public class CloudFrontService implements ServerCertificateReferenceProvider {
invalidationStore.delete(id);
tagStore.delete(existing.getArn());
tagStore.delete("distribution/" + id);
clearViewerFallbackReferences(id);
}
/**
@@ -731,6 +752,21 @@ public class CloudFrontService implements ServerCertificateReferenceProvider {
tagStore.delete(existing.getArn());
}
tagStore.delete("distribution/" + id);
clearViewerFallbackReferences(id);
}
/**
* Drops the {@code ViewerFallback} reference of every connection group that named the deleted
* distribution. AWS documents no in-use error for a fallback distribution, so the delete
* succeeds and the groups it stood behind read back without a fallback.
*/
private void clearViewerFallbackReferences(String distributionId) {
for (ConnectionGroup group : connectionGroupStore.scan(k -> true)) {
if (distributionId.equals(group.getViewerFallbackDistributionId())) {
group.setViewerFallbackDistributionId(null);
connectionGroupStore.put(group.getId(), group);
}
}
}
public List<Distribution> listDistributions(String marker, int maxItems) {
@@ -920,6 +956,271 @@ public class CloudFrontService implements ServerCertificateReferenceProvider {
return host;
}
// ── Connection groups ─────────────────────────────────────────────────────
/**
* {@code tenant-only} distributions are served through a connection group, so the first one an
* account creates mints the account's default group (AWS documents this: "CloudFront creates
* the default connection group for you when you create a multi-tenant distribution"). It comes
* out enabled and {@code Deployed} like the AWS CLI example of a real account's default group,
* and it can never be deleted.
*/
public synchronized ConnectionGroup ensureDefaultConnectionGroup() {
for (ConnectionGroup group : connectionGroupStore.scan(k -> true)) {
if (Boolean.TRUE.equals(group.getIsDefault())) {
return group;
}
}
ConnectionGroup group = new ConnectionGroup();
fillNewConnectionGroup(group, DEFAULT_CONNECTION_GROUP_NAME, null, true, true, null);
group.setIsDefault(true);
connectionGroupStore.put(group.getId(), group);
return group;
}
public synchronized ConnectionGroup createConnectionGroup(String name, String anycastIpListId,
Boolean enabled, Boolean ipv6Enabled,
String viewerFallbackDistributionId,
Map<String, String> tags) {
if (name == null || name.isBlank()) {
throw new AwsException("InvalidArgument", "The Name specified is not valid.", 400);
}
if (name.length() > CONNECTION_GROUP_NAME_MAX_LENGTH) {
throw new AwsException("InvalidArgument", "The Name specified is not valid.", 400);
}
for (ConnectionGroup group : connectionGroupStore.scan(k -> true)) {
if (name.equals(group.getName())) {
throw new AwsException("EntityAlreadyExists",
"The connection group " + name + " already exists.", 409);
}
}
requireDistributionExists(viewerFallbackDistributionId);
ConnectionGroup group = new ConnectionGroup();
fillNewConnectionGroup(group, name, anycastIpListId, enabled, ipv6Enabled, viewerFallbackDistributionId);
if (tags != null && !tags.isEmpty()) {
group.setTags(tags);
tagStore.put(group.getArn(), tags);
}
connectionGroupStore.put(group.getId(), group);
return group;
}
/** AWS issues connection group ids as cg_ + 24 characters (see the AWS CLI examples). */
private void fillNewConnectionGroup(ConnectionGroup group, String name, String anycastIpListId,
Boolean enabled, Boolean ipv6Enabled,
String viewerFallbackDistributionId) {
String id = "cg_" + randomIdSuffix(24);
group.setId(id);
group.setArn(regionResolver.buildGlobalArn("cloudfront", "connection-group/" + id));
group.setName(name);
group.setAnycastIpListId(anycastIpListId);
group.setEnabled(enabled != null && enabled);
group.setIpv6Enabled(ipv6Enabled == null || ipv6Enabled);
group.setIsDefault(false);
group.setStatus("Deployed");
group.setRoutingEndpoint(routingEndpointFor());
group.setCreatedTime(Instant.now());
group.setLastModifiedTime(group.getCreatedTime());
group.setEtag("E" + randomIdSuffix(12));
group.setViewerFallbackDistributionId(viewerFallbackDistributionId);
}
private ConnectionGroup requireConnectionGroup(String id) {
ConnectionGroup group = connectionGroupStore.get(id).orElse(null);
if (group == null) {
throw notFound(id);
}
return group;
}
/**
* A connection group is addressed by its id, name or ARN everywhere the API documents
* {@code Identifier}, and by its routing endpoint in the one lookup that takes it.
*/
public ConnectionGroup getConnectionGroup(String identifier) {
if (identifier == null || identifier.isBlank()) {
throw new AwsException("InvalidArgument", "The Identifier specified is not valid.", 400);
}
if (AwsArnUtils.looksLikeArn(identifier)) {
for (ConnectionGroup group : connectionGroupStore.scan(k -> true)) {
if (identifier.equals(group.getArn())) {
return group;
}
}
throw notFound(identifier);
}
ConnectionGroup group = connectionGroupStore.get(identifier).orElse(null);
if (group != null) {
return group;
}
for (ConnectionGroup candidate : connectionGroupStore.scan(k -> true)) {
if (identifier.equals(candidate.getName())) {
return candidate;
}
}
throw notFound(identifier);
}
public ConnectionGroup getConnectionGroupByRoutingEndpoint(String routingEndpoint) {
if (routingEndpoint == null || routingEndpoint.isBlank()) {
throw new AwsException("InvalidArgument", "The RoutingEndpoint specified is not valid.", 400);
}
for (ConnectionGroup group : connectionGroupStore.scan(k -> true)) {
if (routingEndpoint.equalsIgnoreCase(group.getRoutingEndpoint())) {
return group;
}
}
throw new AwsException("EntityNotFound",
"No connection group was found for routing endpoint " + routingEndpoint + ".", 404);
}
public synchronized ConnectionGroup updateConnectionGroup(String id, String ifMatch,
String anycastIpListId, Boolean enabled,
Boolean ipv6Enabled,
String viewerFallbackDistributionId) {
return updateConnectionGroup(id, ifMatch, anycastIpListId, enabled, ipv6Enabled,
viewerFallbackDistributionId, null, null);
}
/**
* The extended form the CloudFormation provisioner drives, where a template's presence of
* {@code ViewerFallback} and of {@code Tags} is known. {@code clearViewerFallback} removes the
* fallback distribution instead of keeping the stored one, and a non-null {@code tags} replaces
* the group's tags wholesale (an empty map removes them all); null leaves each as it is.
*/
public synchronized ConnectionGroup updateConnectionGroup(String id, String ifMatch,
String anycastIpListId, Boolean enabled,
Boolean ipv6Enabled,
String viewerFallbackDistributionId,
Boolean clearViewerFallback,
Map<String, String> tags) {
requireIfMatch(ifMatch);
ConnectionGroup group = requireConnectionGroup(id);
requireCurrentEtag(group, ifMatch);
requireDistributionExists(viewerFallbackDistributionId);
if (anycastIpListId != null) {
group.setAnycastIpListId(anycastIpListId);
}
if (enabled != null) {
group.setEnabled(enabled);
}
if (ipv6Enabled != null) {
group.setIpv6Enabled(ipv6Enabled);
}
if (Boolean.TRUE.equals(clearViewerFallback)) {
group.setViewerFallbackDistributionId(null);
} else if (viewerFallbackDistributionId != null) {
group.setViewerFallbackDistributionId(viewerFallbackDistributionId);
}
if (tags != null) {
replaceConnectionGroupTags(group, tags);
}
group.setLastModifiedTime(Instant.now());
group.setEtag("E" + randomIdSuffix(12));
connectionGroupStore.put(id, group);
return group;
}
/** Drives the group's tags to the desired set, the model field echoing what the store keeps. */
private void replaceConnectionGroupTags(ConnectionGroup group, Map<String, String> tags) {
if (tags.isEmpty()) {
tagStore.delete(group.getArn());
group.setTags(null);
return;
}
tagStore.put(group.getArn(), new LinkedHashMap<>(tags));
group.setTags(new LinkedHashMap<>(tags));
}
/** One copy of the stale-If-Match refusal the group writes share. */
private static void requireCurrentEtag(ConnectionGroup group, String ifMatch) {
if (!group.getEtag().equals(ifMatch)) {
throw new AwsException("PreconditionFailed",
"The specified If-Match didn't match the ETag header.", 412);
}
}
public synchronized void deleteConnectionGroup(String id, String ifMatch) {
requireIfMatch(ifMatch);
ConnectionGroup group = requireConnectionGroup(id);
requireCurrentEtag(group, ifMatch);
if (Boolean.TRUE.equals(group.getIsDefault())) {
throw new AwsException("CannotDeleteEntityWhileInUse",
"The default connection group cannot be deleted.", 409);
}
if (Boolean.TRUE.equals(group.getEnabled())) {
throw new AwsException("ResourceNotDisabled",
"The connection group has not been disabled.", 409);
}
connectionGroupStore.delete(id);
tagStore.delete(group.getArn());
}
public List<ConnectionGroup> listConnectionGroups(String marker, int maxItems,
String anycastIpListIdFilter) {
List<ConnectionGroup> all = new ArrayList<>(connectionGroupStore.scan(k -> true));
all.removeIf(group -> anycastIpListIdFilter != null
&& !anycastIpListIdFilter.equals(group.getAnycastIpListId()));
all.sort((a, b) -> a.getName().compareTo(b.getName()));
return paginate(all, marker, maxItems, ConnectionGroup::getName);
}
/**
* The distributions whose configuration selects one connection mode, listed like
* {@link #listDistributions(String, int)} lists all of them. The mode is held to the
* enumeration the shape declares, and a distribution stored without a mode reads as
* {@code direct}: an omitted member is what an ordinary distribution sends.
*/
public List<Distribution> listDistributionsByConnectionMode(String connectionMode, String marker,
int maxItems) {
if (!CONNECTION_MODES.contains(connectionMode)) {
throw new AwsException("InvalidArgument", "The ConnectionMode specified is not valid.", 400);
}
List<Distribution> all = new ArrayList<>(distStore.scan(k -> true));
all.removeIf(dist -> !connectionMode.equals(effectiveConnectionMode(dist)));
all.sort((a, b) -> a.getId().compareTo(b.getId()));
return paginate(all, marker, maxItems, Distribution::getId);
}
private static String effectiveConnectionMode(Distribution dist) {
String mode = dist.getConfig() == null ? null : dist.getConfig().getConnectionMode();
return mode == null ? "direct" : mode;
}
/** A connection group's routing endpoint reads like a distribution's domain name. */
private String routingEndpointFor() {
return "d" + randomIdSuffix(13).toLowerCase(Locale.ROOT) + "."
+ CloudFrontEdgeDomain.domainSuffix(configuredDomainSuffix, regionResolver.getPartition());
}
private void requireDistributionExists(String distributionId) {
if (distributionId == null) {
return;
}
getDistribution(distributionId);
}
private static void requireIfMatch(String ifMatch) {
if (ifMatch == null || ifMatch.isEmpty()) {
throw new AwsException("InvalidIfMatchVersion",
"The If-Match version is missing or not valid for the resource.", 400);
}
}
private static AwsException notFound(String identifier) {
return new AwsException("EntityNotFound",
"The connection group " + identifier + " does not exist.", 404);
}
/** Distributions section shared characters, reused for ids and etags. */
private static String randomIdSuffix(int length) {
StringBuilder sb = new StringBuilder(length);
for (int i = 0; i < length; i++) {
sb.append(CHARS.charAt(RANDOM.nextInt(CHARS.length())));
}
return sb.toString();
}
// ── Invalidations ─────────────────────────────────────────────────────────
public synchronized Invalidation createInvalidation(String distributionId, Invalidation inv) {
@@ -2720,28 +3021,16 @@ public class CloudFrontService implements ServerCertificateReferenceProvider {
}
private static String generateDistributionId() {
StringBuilder sb = new StringBuilder("E");
for (int i = 0; i < 13; i++) {
sb.append(CHARS.charAt(RANDOM.nextInt(CHARS.length())));
}
return sb.toString();
return "E" + randomIdSuffix(13);
}
/** AWS issues public key ids as K + 13 characters; the value travels in Key-Pair-Id. */
private static String generatePublicKeyId() {
StringBuilder sb = new StringBuilder("K");
for (int i = 0; i < 13; i++) {
sb.append(CHARS.charAt(RANDOM.nextInt(CHARS.length())));
}
return sb.toString();
return "K" + randomIdSuffix(13);
}
private static String generateInvalidationId() {
StringBuilder sb = new StringBuilder("I");
for (int i = 0; i < 13; i++) {
sb.append(CHARS.charAt(RANDOM.nextInt(CHARS.length())));
}
return sb.toString();
return "I" + randomIdSuffix(13);
}
private static <T> List<T> mergeCustomAndManaged(String type, String policyLabel,
@@ -0,0 +1,71 @@
package io.floci.aws.services.cloudfront.model;
import io.quarkus.runtime.annotations.RegisterForReflection;
import java.time.Instant;
import java.util.Map;
@RegisterForReflection
public class ConnectionGroup {
private String id;
private String arn;
private String name;
private String anycastIpListId;
private Boolean enabled;
private Boolean ipv6Enabled;
private Boolean isDefault;
private String status;
private String routingEndpoint;
private Instant createdTime;
private Instant lastModifiedTime;
private String etag;
private String viewerFallbackDistributionId;
private Map<String, String> tags;
public ConnectionGroup() {}
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 getAnycastIpListId() { return anycastIpListId; }
public void setAnycastIpListId(String anycastIpListId) { this.anycastIpListId = anycastIpListId; }
public Boolean getEnabled() { return enabled; }
public void setEnabled(Boolean enabled) { this.enabled = enabled; }
public Boolean getIpv6Enabled() { return ipv6Enabled; }
public void setIpv6Enabled(Boolean ipv6Enabled) { this.ipv6Enabled = ipv6Enabled; }
public Boolean getIsDefault() { return isDefault; }
public void setIsDefault(Boolean isDefault) { this.isDefault = isDefault; }
public String getStatus() { return status; }
public void setStatus(String status) { this.status = status; }
public String getRoutingEndpoint() { return routingEndpoint; }
public void setRoutingEndpoint(String routingEndpoint) { this.routingEndpoint = routingEndpoint; }
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; }
public String getViewerFallbackDistributionId() { return viewerFallbackDistributionId; }
public void setViewerFallbackDistributionId(String viewerFallbackDistributionId) {
this.viewerFallbackDistributionId = viewerFallbackDistributionId;
}
public Map<String, String> getTags() { return tags; }
public void setTags(Map<String, String> tags) { this.tags = tags; }
}
@@ -201,6 +201,9 @@
"StackSetName"
],
"AWS::CloudFront::CachePolicy": [],
"AWS::CloudFront::ConnectionGroup": [
"Name"
],
"AWS::CloudFront::Distribution": [],
"AWS::CloudFront::Function": [
"Name"
@@ -0,0 +1,197 @@
package io.floci.aws.services.cloudformation;
import io.floci.aws.core.common.AwsException;
import io.floci.aws.services.cloudfront.CloudFrontService;
import io.floci.aws.services.cloudfront.model.ConnectionGroup;
import io.floci.aws.services.cloudfront.model.Distribution;
import io.floci.aws.services.cloudfront.model.DistributionConfig;
import io.floci.aws.testing.CfnRequests;
import io.floci.aws.testing.CfnStackWaits;
import io.quarkus.test.junit.QuarkusTest;
import jakarta.inject.Inject;
import org.junit.jupiter.api.Test;
import java.util.Map;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* AWS::CloudFront::ConnectionGroup through the stack lifecycle: the exact {@code Ref} and
* {@code Fn::GetAtt} values from the registry schema's read-only members, an in-place update with
* its tags and {@code ViewerFallback} handling, a replacement when the create-only {@code Name}
* changes, and DeleteStack of a group that is still enabled.
*/
@QuarkusTest
class CloudFormationCloudFrontConnectionGroupIntegrationTest {
private static final String CFN_AUTH =
"AWS4-HMAC-SHA256 Credential=test/20260205/us-east-1/cloudformation/aws4_request";
@Inject
CloudFrontService cloudFrontService;
@Test
void connectionGroupFollowsTheStackLifecycle() {
String suffix = Long.toString(System.nanoTime(), 36);
String stackName = "cfn-cloudfront-connection-group-" + suffix;
CfnRequests.deploy("CreateStack", stackName, template(subName(suffix), true,
"[{\"Key\": \"Env\", \"Value\": \"test\"}]", null), CFN_AUTH, "CREATE_COMPLETE");
String groupId = output(stackName, "GroupRef");
assertEquals(groupId, output(stackName, "GroupId"));
ConnectionGroup group = cloudFrontService.getConnectionGroup(groupId);
assertEquals("cfn-connection-group-" + suffix, group.getName());
assertTrue(group.getEnabled());
assertTrue(group.getIpv6Enabled());
assertTrue(group.getArn().endsWith(":connection-group/" + groupId));
assertEquals(group.getArn(), output(stackName, "GroupArn"));
assertEquals(group.getRoutingEndpoint(), output(stackName, "GroupRoutingEndpoint"));
assertEquals(group.getStatus(), output(stackName, "GroupStatus"));
assertEquals(String.valueOf(group.getIsDefault()), output(stackName, "GroupIsDefault"));
assertEquals(group.getEtag(), output(stackName, "GroupEtag"));
assertEquals(group.getCreatedTime().toString(), output(stackName, "GroupCreatedTime"));
assertEquals(group.getLastModifiedTime().toString(), output(stackName, "GroupLastModifiedTime"));
assertEquals(Map.of("Env", "test"), cloudFrontService.listTagsForResource(group.getArn()));
CfnRequests.deploy("UpdateStack", stackName, template(subName(suffix), false,
"[{\"Key\": \"Team\", \"Value\": \"edge\"}]", null), CFN_AUTH, "UPDATE_COMPLETE");
ConnectionGroup updated = cloudFrontService.getConnectionGroup(groupId);
assertEquals(groupId, output(stackName, "GroupRef"), "an update keeps the group");
assertFalse(updated.getEnabled());
assertTrue(updated.getIpv6Enabled());
assertEquals(Map.of("Team", "edge"), cloudFrontService.listTagsForResource(updated.getArn()));
assertEquals(Map.of("Team", "edge"), updated.getTags());
deleteStack(stackName);
assertEquals("EntityNotFound",
assertThrows(AwsException.class, () -> cloudFrontService.getConnectionGroup(groupId)).getErrorCode());
}
@Test
void viewerFallbackPresenceOnTheTemplateIsAuthoritative() {
String suffix = Long.toString(System.nanoTime(), 36);
String stackName = "cfn-cloudfront-connection-group-fallback-" + suffix;
String distributionId = createdDistributionId(suffix);
try {
CfnRequests.deploy("CreateStack", stackName, template(subName(suffix), false, "[]", null),
CFN_AUTH, "CREATE_COMPLETE");
String groupId = output(stackName, "GroupRef");
CfnRequests.deploy("UpdateStack", stackName, template(subName(suffix), false, "[]",
"{\"DistributionId\": \"" + distributionId + "\"}"), CFN_AUTH, "UPDATE_COMPLETE");
assertEquals(distributionId,
cloudFrontService.getConnectionGroup(groupId).getViewerFallbackDistributionId());
CfnRequests.deploy("UpdateStack", stackName, template(subName(suffix), false, "[]", null),
CFN_AUTH, "UPDATE_COMPLETE");
assertEquals(distributionId,
cloudFrontService.getConnectionGroup(groupId).getViewerFallbackDistributionId(),
"an update that drops ViewerFallback keeps the fallback");
CfnRequests.deploy("UpdateStack", stackName, template(subName(suffix), false, "[]",
"{}"), CFN_AUTH, "UPDATE_COMPLETE");
assertNull(cloudFrontService.getConnectionGroup(groupId).getViewerFallbackDistributionId(),
"a ViewerFallback the template still declares is authoritative");
deleteStack(stackName);
} finally {
cloudFrontService.removeDistribution(distributionId);
}
}
@Test
void aChangedNameReplacesTheGroup() {
String suffix = Long.toString(System.nanoTime(), 36);
String stackName = "cfn-cloudfront-connection-group-rename-" + suffix;
CfnRequests.deploy("CreateStack", stackName, template(subName(suffix), true, "[]", null),
CFN_AUTH, "CREATE_COMPLETE");
String firstId = output(stackName, "GroupRef");
String renamed = "renamed-" + suffix;
CfnRequests.deploy("UpdateStack", stackName, template(subName(renamed), true, "[]", null),
CFN_AUTH, "UPDATE_COMPLETE");
String secondId = output(stackName, "GroupRef");
assertEquals("cfn-connection-group-" + renamed, cloudFrontService.getConnectionGroup(secondId).getName());
assertEquals("EntityNotFound",
assertThrows(AwsException.class,
() -> cloudFrontService.getConnectionGroup(firstId)).getErrorCode(),
"the displaced group is deleted once the update commits");
deleteStack(stackName);
}
@Test
void aStackWithAnEnabledGroupDeletesIt() {
String suffix = Long.toString(System.nanoTime(), 36);
String stackName = "cfn-cloudfront-connection-group-enabled-" + suffix;
CfnRequests.deploy("CreateStack", stackName, template(subName(suffix), true, "[]", null),
CFN_AUTH, "CREATE_COMPLETE");
String groupId = output(stackName, "GroupRef");
assertTrue(cloudFrontService.getConnectionGroup(groupId).getEnabled());
deleteStack(stackName);
assertEquals("EntityNotFound",
assertThrows(AwsException.class, () -> cloudFrontService.getConnectionGroup(groupId)).getErrorCode());
}
/** The name routes through an intrinsic, as a parameterized template would. */
private static String subName(String suffix) {
return "{\"Fn::Sub\": [\"cfn-connection-group-${Suffix}\", {\"Suffix\": \"" + suffix + "\"}]}";
}
private String createdDistributionId(String suffix) {
DistributionConfig config = new DistributionConfig();
config.setCallerReference("cfn-fallback-" + suffix);
Distribution dist = new Distribution();
dist.setConfig(config);
return cloudFrontService.createDistribution(dist, Map.of()).getId();
}
private static String output(String stackName, String key) {
return CfnRequests.output(CfnRequests.describe(stackName, CFN_AUTH), key);
}
private static String template(String nameJson, boolean enabled, String tagsJson,
String viewerFallbackJson) {
String viewerFallback = viewerFallbackJson == null ? ""
: "\"ViewerFallback\": " + viewerFallbackJson + ",";
return """
{
"Resources": {
"Group": {
"Type": "AWS::CloudFront::ConnectionGroup",
"Properties": {
"Name": %s,
"Enabled": %s,
"Ipv6Enabled": true,
%s
"Tags": %s
}
}
},
"Outputs": {
"GroupRef": {"Value": {"Ref": "Group"}},
"GroupId": {"Value": {"Fn::GetAtt": "Group.Id"}},
"GroupArn": {"Value": {"Fn::GetAtt": "Group.Arn"}},
"GroupRoutingEndpoint": {"Value": {"Fn::GetAtt": "Group.RoutingEndpoint"}},
"GroupStatus": {"Value": {"Fn::GetAtt": "Group.Status"}},
"GroupIsDefault": {"Value": {"Fn::GetAtt": "Group.IsDefault"}},
"GroupEtag": {"Value": {"Fn::GetAtt": "Group.ETag"}},
"GroupCreatedTime": {"Value": {"Fn::GetAtt": "Group.CreatedTime"}},
"GroupLastModifiedTime": {"Value": {"Fn::GetAtt": "Group.LastModifiedTime"}}
}
}
""".formatted(nameJson, enabled, viewerFallback, tagsJson);
}
private static void deleteStack(String stackName) {
CfnStackWaits.deleteStack(stackName, CFN_AUTH);
}
}
@@ -8,6 +8,7 @@ import io.floci.aws.services.cloudformation.model.StackResource;
import io.floci.aws.services.cloudfront.CloudFrontService;
import io.floci.aws.services.cloudfront.model.CachePolicy;
import io.floci.aws.services.cloudfront.model.CloudFrontFunction;
import io.floci.aws.services.cloudfront.model.ConnectionGroup;
import io.floci.aws.services.cloudfront.model.Distribution;
import io.floci.aws.services.cloudfront.model.DistributionConfig;
import io.floci.aws.services.cloudfront.model.KeyGroup;
@@ -18,6 +19,7 @@ import io.floci.aws.services.cloudfront.model.PublicKey;
import io.floci.aws.services.cloudfront.model.ResponseHeadersPolicy;
import org.junit.jupiter.api.Test;
import org.mockito.ArgumentCaptor;
import org.mockito.ArgumentMatchers;
import org.mockito.Mockito;
import java.nio.charset.StandardCharsets;
@@ -59,6 +61,7 @@ class CloudFrontCfnProvisionerTest {
private static final String PUBLIC_KEY = "AWS::CloudFront::PublicKey";
private static final String KEY_GROUP = "AWS::CloudFront::KeyGroup";
private static final String FUNCTION = "AWS::CloudFront::Function";
private static final String CONNECTION_GROUP_TYPE = "AWS::CloudFront::ConnectionGroup";
private static final String FUNCTION_ARN = "arn:aws:cloudfront::000000000000:function/my-function";
private static final String REGION = "us-east-1";
private static final String ID = "5cc3b908-e619-4b99-88e5-2cf7f45965bd";
@@ -119,7 +122,8 @@ class CloudFrontCfnProvisionerTest {
@Test
void servesTheDistributionAndTheTypesItReferences() {
assertEquals(Set.of(DISTRIBUTION, RESPONSE_HEADERS_POLICY, CACHE_POLICY, ORIGIN_REQUEST_POLICY,
ORIGIN_ACCESS_CONTROL, PUBLIC_KEY, KEY_GROUP, FUNCTION), provisioner.resourceTypes());
ORIGIN_ACCESS_CONTROL, PUBLIC_KEY, KEY_GROUP, FUNCTION, "AWS::CloudFront::ConnectionGroup"),
provisioner.resourceTypes());
}
/**
@@ -1163,4 +1167,249 @@ class CloudFrontCfnProvisionerTest {
}
verify(cloudFront, never()).createFunction(any());
}
@Test
void provisionsConnectionGroupWithEveryReadOnlyGetAttTheSchemaDeclares() throws Exception {
when(cloudFront.createConnectionGroup(any(), any(), any(), any(), any(), any()))
.thenAnswer(inv -> {
ConnectionGroup g = new ConnectionGroup();
g.setName(inv.getArgument(0, String.class));
g.setAnycastIpListId(inv.getArgument(1, String.class));
g.setEnabled(inv.getArgument(2, Boolean.class));
g.setIpv6Enabled(inv.getArgument(3, Boolean.class));
g.setViewerFallbackDistributionId(inv.getArgument(4, String.class));
g.setTags(inv.getArgument(5));
g.setId("cg_2yb6uj74B4PCbfhT31WFdiS");
g.setArn("arn:aws:cloudfront::000000000000:connection-group/cg_2yb6uj74B4PCbfhT31WFdiS");
g.setRoutingEndpoint("d111111abcdef8.cloudfront.net");
g.setStatus("Deployed");
g.setIsDefault(false);
g.setEtag(ETAG);
g.setCreatedTime(MODIFIED);
g.setLastModifiedTime(MODIFIED);
return g;
});
StackResource r = resource(CONNECTION_GROUP_TYPE);
provisioner.provision(r, json("""
{"Name": "edge-group", "Enabled": true, "Ipv6Enabled": false}
"""), connectionCtx(null));
ArgumentCaptor<String> name = ArgumentCaptor.forClass(String.class);
ArgumentCaptor<Boolean> enabled = ArgumentCaptor.forClass(Boolean.class);
ArgumentCaptor<Boolean> ipv6 = ArgumentCaptor.forClass(Boolean.class);
verify(cloudFront).createConnectionGroup(name.capture(), any(), enabled.capture(),
ipv6.capture(), any(), any());
assertEquals("edge-group", name.getValue());
assertEquals(Boolean.TRUE, enabled.getValue());
assertEquals(Boolean.FALSE, ipv6.getValue());
verify(cloudFront, never()).updateConnectionGroup(any(), any(), any(), any(), any(), any());
assertEquals("cg_2yb6uj74B4PCbfhT31WFdiS", r.getPhysicalId());
assertEquals(Map.of("Id", "cg_2yb6uj74B4PCbfhT31WFdiS",
"Arn", "arn:aws:cloudfront::000000000000:connection-group/cg_2yb6uj74B4PCbfhT31WFdiS",
"RoutingEndpoint", "d111111abcdef8.cloudfront.net",
"Status", "Deployed",
"IsDefault", "false",
"ETag", ETAG,
"CreatedTime", MODIFIED.toString(),
"LastModifiedTime", MODIFIED.toString()), r.getAttributes());
}
/**
* The connection-group members are scalars the template may hand an intrinsic, so the context's
* {@code resolveOptional} answers them: an object node reads as its resolved value, as
* {@code Ref} and {@code Fn::Sub} names and booleans do.
*/
private ProvisionContext connectionCtx(String priorPhysicalId) {
CloudFormationTemplateEngine engine = mock(CloudFormationTemplateEngine.class);
when(engine.resolveNode(any())).thenAnswer(inv -> inv.getArgument(0));
when(engine.resolve(any())).thenAnswer(inv -> {
JsonNode node = inv.getArgument(0);
if (node == null || node.isMissingNode() || node.isNull()) {
return "";
}
return node.isValueNode() ? node.asText() : "resolved-name";
});
return new ProvisionContext(engine, REGION, "000000000000", "my-stack", priorPhysicalId);
}
@Test
void aRefResolvedNameAndBooleansCreateTheGroup() throws Exception {
when(cloudFront.createConnectionGroup(eq("resolved-name"), any(), eq(Boolean.TRUE), any(),
any(), any())).thenReturn(connectionGroup("cg_new", ETAG));
StackResource r = resource(CONNECTION_GROUP_TYPE);
provisioner.provision(r, json("""
{"Name": {"Fn::Sub": "${AWS::StackName}-group"}, "Enabled": true, "Ipv6Enabled": false}
"""), connectionCtx(null));
assertEquals("cg_new", r.getPhysicalId());
verify(cloudFront, never()).updateConnectionGroup(any(), any(), any(), any(), any(), any(),
any(), any());
}
private static ConnectionGroup connectionGroup(String id, String etag) {
ConnectionGroup g = new ConnectionGroup();
g.setId(id);
g.setEtag(etag);
return g;
}
@Test
void updatesConnectionGroupInPlaceWithThePriorEtagAndCarriesItsViewerFallback() throws Exception {
ConnectionGroup prior = connectionGroup("cg_prior", ETAG);
prior.setName("edge-group");
prior.setAnycastIpListId("aip_prior");
prior.setEnabled(true);
prior.setIpv6Enabled(true);
prior.setLastModifiedTime(MODIFIED);
when(cloudFront.getConnectionGroup("cg_prior")).thenReturn(prior);
when(cloudFront.updateConnectionGroup(eq("cg_prior"), eq(ETAG), eq("aip_prior"), eq(Boolean.FALSE),
eq(Boolean.TRUE), eq("E12X3MPWexample"), ArgumentMatchers.isNull(), any()))
.thenAnswer(inv -> withIdentity(prior, g -> g.setEtag(NEW_ETAG)));
StackResource r = resource(CONNECTION_GROUP_TYPE, "cg_prior", Map.of("Id", "cg_prior"));
provisioner.provision(r, json("""
{"Name": "edge-group", "Enabled": false, "ViewerFallback": {"DistributionId": "E12X3MPWexample"}}
"""), connectionCtx("cg_prior"));
verify(cloudFront, never()).createConnectionGroup(any(), any(), any(), any(), any(), any());
assertEquals("cg_prior", r.getPhysicalId());
assertEquals(NEW_ETAG, r.getAttributes().get("ETag"));
}
@Test
@SuppressWarnings("unchecked")
void anUpdateReconcilesTheGroupsTags() throws Exception {
ConnectionGroup prior = connectionGroup("cg_prior", ETAG);
prior.setName("edge-group");
prior.setArn("arn:aws:cloudfront::000000000000:connection-group/cg_prior");
when(cloudFront.getConnectionGroup("cg_prior")).thenReturn(prior);
when(cloudFront.updateConnectionGroup(eq("cg_prior"), eq(ETAG), ArgumentMatchers.isNull(),
ArgumentMatchers.isNull(), ArgumentMatchers.isNull(), ArgumentMatchers.isNull(),
ArgumentMatchers.isNull(), any())).thenReturn(prior);
StackResource r = resource(CONNECTION_GROUP_TYPE, "cg_prior", Map.of("Id", "cg_prior"));
provisioner.provision(r, json("""
{"Name": "edge-group", "Tags": [{"Key": "Env", "Value": "test"}]}
"""), connectionCtx("cg_prior"));
ArgumentCaptor<Map<String, String>> tags =
ArgumentCaptor.forClass((Class<Map<String, String>>) (Class<?>) Map.class);
verify(cloudFront).updateConnectionGroup(eq("cg_prior"), eq(ETAG), ArgumentMatchers.isNull(),
ArgumentMatchers.isNull(), ArgumentMatchers.isNull(), ArgumentMatchers.isNull(),
ArgumentMatchers.isNull(), tags.capture());
assertEquals(Map.of("Env", "test"), tags.getValue());
}
@Test
void anUpdateWithAnExplicitlyNullViewerFallbackClearsIt() throws Exception {
ConnectionGroup prior = connectionGroup("cg_prior", ETAG);
prior.setName("edge-group");
prior.setViewerFallbackDistributionId("E12X3MPWexample");
when(cloudFront.getConnectionGroup("cg_prior")).thenReturn(prior);
when(cloudFront.updateConnectionGroup(eq("cg_prior"), eq(ETAG), ArgumentMatchers.isNull(),
ArgumentMatchers.isNull(), ArgumentMatchers.isNull(), ArgumentMatchers.isNull(),
eq(Boolean.TRUE), any())).thenReturn(prior);
StackResource r = resource(CONNECTION_GROUP_TYPE, "cg_prior", Map.of("Id", "cg_prior"));
provisioner.provision(r, json("""
{"Name": "edge-group", "ViewerFallback": null}
"""), connectionCtx("cg_prior"));
verify(cloudFront).updateConnectionGroup(eq("cg_prior"), eq(ETAG), ArgumentMatchers.isNull(),
ArgumentMatchers.isNull(), ArgumentMatchers.isNull(), ArgumentMatchers.isNull(),
eq(Boolean.TRUE), any());
}
@Test
void aChangedNameCreatesANewGroupAndOwesTheOldOneCleanup() throws Exception {
ConnectionGroup prior = connectionGroup("cg_prior", ETAG);
prior.setName("edge-group");
prior.setEnabled(false);
when(cloudFront.getConnectionGroup("cg_prior")).thenReturn(prior);
ConnectionGroup created = connectionGroup("cg_new", NEW_ETAG);
created.setEnabled(false);
when(cloudFront.createConnectionGroup(eq("renamed-group"), any(), any(), any(), any(), any()))
.thenReturn(created);
when(cloudFront.getConnectionGroup("cg_new")).thenReturn(created);
StackResource r = resource(CONNECTION_GROUP_TYPE, "cg_prior", Map.of("Id", "cg_prior"));
provisioner.provision(r, json("""
{"Name": "renamed-group", "Enabled": false}
"""), connectionCtx("cg_prior"));
verify(cloudFront, never()).updateConnectionGroup(any(), any(), any(), any(), any(), any(),
any(), any());
assertEquals("cg_new", r.getPhysicalId());
assertTrue(provisioner.hasReplacementUpdate(r), "the old group is owed a cleanup");
assertEquals("cg_prior", provisioner.updateCleanupPhysicalId(r));
provisioner.completeUpdate(r);
verify(cloudFront).deleteConnectionGroup("cg_prior", ETAG);
}
@Test
void rollingBackANameReplacementDeletesTheNewGroupAndRestoresThePriorId() throws Exception {
ConnectionGroup prior = connectionGroup("cg_prior", ETAG);
prior.setName("edge-group");
prior.setEnabled(false);
when(cloudFront.getConnectionGroup("cg_prior")).thenReturn(prior);
ConnectionGroup created = connectionGroup("cg_new", NEW_ETAG);
created.setEnabled(false);
when(cloudFront.createConnectionGroup(eq("renamed-group"), any(), any(), any(), any(), any()))
.thenReturn(created);
when(cloudFront.getConnectionGroup("cg_new")).thenReturn(created);
StackResource r = resource(CONNECTION_GROUP_TYPE, "cg_prior", Map.of("Id", "cg_prior"));
provisioner.provision(r, json("""
{"Name": "renamed-group", "Enabled": false}
"""), connectionCtx("cg_prior"));
assertEquals("cg_new", r.getPhysicalId());
assertTrue(provisioner.rollbackUpdate(r));
verify(cloudFront).deleteConnectionGroup("cg_new", NEW_ETAG);
assertEquals("cg_prior", r.getPhysicalId(), "the prior id is named again");
assertEquals("cg_prior", r.getAttributes().get("Id"));
}
@Test
void deleteOfAnEnabledGroupDisablesItFirstAndDeletesWithTheNewEtag() {
ConnectionGroup group = connectionGroup(ID, ETAG);
group.setEnabled(true);
when(cloudFront.getConnectionGroup(ID)).thenReturn(group);
ConnectionGroup disabled = connectionGroup(ID, NEW_ETAG);
disabled.setEnabled(false);
when(cloudFront.updateConnectionGroup(ID, ETAG, null, false, null, null)).thenReturn(disabled);
provisioner.delete(CONNECTION_GROUP_TYPE, ID, REGION);
verify(cloudFront).updateConnectionGroup(ID, ETAG, null, false, null, null);
verify(cloudFront).deleteConnectionGroup(ID, NEW_ETAG);
}
@Test
void deleteOfADisabledGroupGoesStraightToTheService() {
ConnectionGroup group = connectionGroup(ID, ETAG);
group.setEnabled(false);
when(cloudFront.getConnectionGroup(ID)).thenReturn(group);
provisioner.delete(CONNECTION_GROUP_TYPE, ID, REGION);
verify(cloudFront, never()).updateConnectionGroup(any(), any(), any(), any(), any(), any());
verify(cloudFront).deleteConnectionGroup(ID, ETAG);
}
@Test
void deletesConnectionGroupWithItsOwnNotFoundCodeTolerated() throws Exception {
when(cloudFront.getConnectionGroup(ID)).thenReturn(connectionGroup(ID, ETAG));
provisioner.delete(CONNECTION_GROUP_TYPE, ID, REGION);
verify(cloudFront).deleteConnectionGroup(ID, ETAG);
when(cloudFront.getConnectionGroup(ID)).thenThrow(
new AwsException("EntityNotFound", "The connection group " + ID + " does not exist.", 404));
provisioner.delete(CONNECTION_GROUP_TYPE, ID, REGION);
verify(cloudFront, Mockito.times(1)).deleteConnectionGroup(any(), any());
}
}
@@ -0,0 +1,327 @@
package io.floci.aws.services.cloudfront;
import io.floci.aws.core.common.XmlParser;
import io.floci.aws.testing.AwsTestClients;
import io.quarkus.test.common.http.TestHTTPResource;
import io.quarkus.test.junit.QuarkusTest;
import org.junit.jupiter.api.Test;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.cloudfront.CloudFrontClient;
import software.amazon.awssdk.services.cloudfront.model.CannotDeleteEntityWhileInUseException;
import software.amazon.awssdk.services.cloudfront.model.ConnectionGroup;
import software.amazon.awssdk.services.cloudfront.model.ConnectionGroupSummary;
import software.amazon.awssdk.services.cloudfront.model.CreateConnectionGroupResponse;
import software.amazon.awssdk.services.cloudfront.model.CreateDistributionResponse;
import software.amazon.awssdk.services.cloudfront.model.DefaultCacheBehavior;
import software.amazon.awssdk.services.cloudfront.model.DistributionConfig;
import software.amazon.awssdk.services.cloudfront.model.DistributionSummary;
import software.amazon.awssdk.services.cloudfront.model.EntityAlreadyExistsException;
import software.amazon.awssdk.services.cloudfront.model.EntityNotFoundException;
import software.amazon.awssdk.services.cloudfront.model.GetConnectionGroupByRoutingEndpointResponse;
import software.amazon.awssdk.services.cloudfront.model.GetConnectionGroupResponse;
import software.amazon.awssdk.services.cloudfront.model.InvalidIfMatchVersionException;
import software.amazon.awssdk.services.cloudfront.model.NoSuchDistributionException;
import software.amazon.awssdk.services.cloudfront.model.Origin;
import software.amazon.awssdk.services.cloudfront.model.Origins;
import software.amazon.awssdk.services.cloudfront.model.PreconditionFailedException;
import software.amazon.awssdk.services.cloudfront.model.ResourceNotDisabledException;
import software.amazon.awssdk.services.cloudfront.model.S3OriginConfig;
import software.amazon.awssdk.services.cloudfront.model.ViewerCertificate;
import java.net.URI;
import java.util.List;
import static io.floci.aws.testing.AwsSdkErrors.assertAwsError;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.not;
import static org.hamcrest.xml.HasXPath.hasXPath;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* The multi-tenant connection-group management plane, validated with the real CloudFront SDK:
* a group is readable by id, name, ARN and routing endpoint, the account's default group is
* minted with the first {@code tenant-only} distribution, and the If-Match guarded writes carry
* their modeled errors.
*/
@QuarkusTest
class CloudFrontConnectionGroupSdkIntegrationTest {
private static final String API = "/2020-05-31/";
@TestHTTPResource("/")
URI endpoint;
@Test
void aGroupIsReadableByIdNameArnAndRoutingEndpoint() {
try (CloudFrontClient client = client()) {
CreateConnectionGroupResponse created = client.createConnectionGroup(request -> request
.name("cg-sdk-read-" + stamp())
.enabled(true)
.ipv6Enabled(false));
ConnectionGroup group = created.connectionGroup();
try {
assertEquals(201, created.sdkHttpResponse().statusCode());
assertTrue(group.id().startsWith("cg_"));
assertTrue(group.arn().endsWith(":connection-group/" + group.id()));
assertTrue(group.routingEndpoint().endsWith(".cloudfront.net"));
assertFalse(group.isDefault());
assertNotNull(group.createdTime());
GetConnectionGroupResponse byId =
client.getConnectionGroup(request -> request.identifier(group.id()));
assertEquals(group.id(), byId.connectionGroup().id());
assertEquals(created.eTag(), byId.eTag());
GetConnectionGroupResponse byName =
client.getConnectionGroup(request -> request.identifier(group.name()));
assertEquals(group.id(), byName.connectionGroup().id());
GetConnectionGroupResponse byArn =
client.getConnectionGroup(request -> request.identifier(group.arn()));
assertEquals(group.id(), byArn.connectionGroup().id());
GetConnectionGroupByRoutingEndpointResponse byEndpoint =
client.getConnectionGroupByRoutingEndpoint(
request -> request.routingEndpoint(group.routingEndpoint()));
assertEquals(group.id(), byEndpoint.connectionGroup().id());
assertAwsError("EntityNotFound", 404,
() -> client.getConnectionGroup(request -> request.identifier("cg_doesnotexist")));
assertAwsError("EntityNotFound", 404,
() -> client.getConnectionGroupByRoutingEndpoint(
request -> request.routingEndpoint("d0000000000000.cloudfront.net")));
} finally {
disableAndDeleteIfPresent(client, group.id(), created.eTag());
}
}
}
@Test
void duplicateNamesAndIfMatchGuardedWritesCarryTheirModeledErrors() {
try (CloudFrontClient client = client()) {
String name = "cg-sdk-guard-" + stamp();
CreateConnectionGroupResponse created =
client.createConnectionGroup(request -> request.name(name).enabled(true));
String id = created.connectionGroup().id();
try {
assertAwsError("EntityAlreadyExists", 409,
() -> client.createConnectionGroup(request -> request.name(name)));
assertAwsError("InvalidIfMatchVersion", 400,
() -> client.updateConnectionGroup(request -> request.id(id).enabled(false)));
assertAwsError("PreconditionFailed", 412,
() -> client.updateConnectionGroup(request -> request.id(id)
.ifMatch("E000000000000").enabled(false)));
assertAwsError("ResourceNotDisabled", 409,
() -> client.deleteConnectionGroup(request -> request.id(id).ifMatch(created.eTag())));
client.updateConnectionGroup(request -> request.id(id)
.ifMatch(created.eTag()).enabled(false).ipv6Enabled(false));
GetConnectionGroupResponse updated =
client.getConnectionGroup(request -> request.identifier(id));
assertFalse(updated.connectionGroup().enabled());
assertTrue(updated.eTag() != null && !updated.eTag().equals(created.eTag()));
client.deleteConnectionGroup(request -> request.id(id).ifMatch(updated.eTag()));
assertAwsError("EntityNotFound", 404,
() -> client.getConnectionGroup(request -> request.identifier(id)));
} finally {
disableAndDeleteIfPresent(client, id, created.eTag());
}
}
}
@Test
void aTenantOnlyDistributionMintsTheDefaultGroupWhichCannotBeDeleted() {
try (CloudFrontClient client = client()) {
String distributionId = client.createDistribution(request -> request
.distributionConfig(tenantOnlyConfig()))
.distribution().id();
try {
List<ConnectionGroupSummary> after = client.listConnectionGroups(
request -> request.maxItems(100)).connectionGroups();
ConnectionGroupSummary defaultGroup = after.stream()
.filter(ConnectionGroupSummary::isDefault)
.findFirst().orElseThrow(() -> new AssertionError(
"the tenant-only distribution must mint the account's default group"));
assertTrue(defaultGroup.enabled());
assertEquals("Deployed", defaultGroup.status());
assertNotNull(defaultGroup.eTag());
assertAwsError("CannotDeleteEntityWhileInUse", 409,
() -> client.deleteConnectionGroup(request -> request
.id(defaultGroup.id()).ifMatch(defaultGroup.eTag())));
List<String> tenantOnlyIds = client.listDistributionsByConnectionMode(
request -> request.connectionMode("tenant-only"))
.distributionList().items().stream()
.map(summary -> summary.id()).toList();
assertTrue(tenantOnlyIds.contains(distributionId));
assertTrue(client.listDistributionsByConnectionMode(
request -> request.connectionMode("direct"))
.distributionList().items().stream()
.map(summary -> summary.id()).noneMatch(distributionId::equals));
} finally {
disableAndDeleteDistribution(client, distributionId);
}
}
}
@Test
void anUnknownConnectionModeIsRefusedAndAnOmittedModeListsUnderDirect() {
try (CloudFrontClient client = client()) {
assertAwsError("InvalidArgument", 400,
() -> client.listDistributionsByConnectionMode(
request -> request.connectionMode("bogus")));
String distributionId = client.createDistribution(request -> request
.distributionConfig(distributionConfig(null)))
.distribution().id();
try {
List<String> directIds = client.listDistributionsByConnectionMode(
request -> request.connectionMode("direct"))
.distributionList().items().stream()
.map(DistributionSummary::id).toList();
assertTrue(directIds.contains(distributionId));
assertTrue(client.listDistributionsByConnectionMode(
request -> request.connectionMode("tenant-only"))
.distributionList().items().stream()
.map(DistributionSummary::id).noneMatch(distributionId::equals));
} finally {
disableAndDeleteDistribution(client, distributionId);
}
}
}
@Test
void deletingAFallbackDistributionClearsTheGroupsViewerFallback() {
try (CloudFrontClient client = client()) {
String distributionId = client.createDistribution(request -> request
.distributionConfig(distributionConfig(null)))
.distribution().id();
try {
String body = """
<CreateConnectionGroupRequest xmlns="http://cloudfront.amazonaws.com/doc/2020-05-31/">
<Name>cg-sdk-fallback-%s</Name>
<Enabled>false</Enabled>
<ViewerFallback><DistributionId>%s</DistributionId></ViewerFallback>
</CreateConnectionGroupRequest>
""".formatted(stamp(), distributionId);
String groupId = XmlParser.extractFirst(given().contentType("application/xml").body(body)
.when().post(API + "connection-group").then().statusCode(201)
.extract().asString(), "Id", null);
given()
.when().get(API + "connection-group/" + groupId)
.then().statusCode(200)
.body(hasXPath("//*[local-name()='ViewerFallback']/*[local-name()='DistributionId']/text()",
equalTo(distributionId)));
disableAndDeleteDistribution(client, distributionId);
given()
.when().get(API + "connection-group/" + groupId)
.then().statusCode(200)
.body(not(hasXPath("//*[local-name()='ViewerFallback']")));
} finally {
disableAndDeleteDistribution(client, distributionId);
}
}
}
@Test
void aGroupCreatedUnderAnotherAccountCarriesThatAccountInItsArn() {
try (CloudFrontClient client = AwsTestClients.create(
CloudFrontClient.builder(), "111111111111", Region.US_EAST_1, endpoint)) {
CreateConnectionGroupResponse created = client.createConnectionGroup(request -> request
.name("cg-sdk-account-" + stamp())
.enabled(false));
String id = created.connectionGroup().id();
try {
assertTrue(created.connectionGroup().arn()
.startsWith("arn:aws:cloudfront::111111111111:connection-group/" + id));
GetConnectionGroupResponse fetched = client.getConnectionGroup(
request -> request.identifier(created.connectionGroup().arn()));
assertEquals(created.connectionGroup().arn(), fetched.connectionGroup().arn());
assertTrue(client.listConnectionGroups(request -> request.maxItems(100))
.connectionGroups().stream()
.allMatch(group -> group.arn().startsWith("arn:aws:cloudfront::111111111111:")));
} finally {
disableAndDeleteIfPresent(client, id, created.eTag());
}
}
}
private DistributionConfig distributionConfig(String connectionMode) {
DistributionConfig.Builder config = DistributionConfig.builder()
.callerReference("saas-config-" + stamp())
.comment("multi-tenant")
.enabled(true)
.origins(Origins.builder().quantity(1).items(Origin.builder()
.id("origin1")
.domainName("example-bucket.s3.us-east-1.amazonaws.com")
.s3OriginConfig(S3OriginConfig.builder().originAccessIdentity("").build())
.build()).build())
.defaultCacheBehavior(DefaultCacheBehavior.builder()
.targetOriginId("origin1")
.viewerProtocolPolicy("redirect-to-https")
.build())
.viewerCertificate(ViewerCertificate.builder()
.cloudFrontDefaultCertificate(true)
.build());
if (connectionMode != null) {
config.connectionMode(connectionMode);
}
return config.build();
}
private DistributionConfig tenantOnlyConfig() {
return distributionConfig("tenant-only");
}
private void disableAndDeleteDistribution(CloudFrontClient client, String distributionId) {
if (distributionId == null) {
return;
}
try {
String etag = client.getDistribution(request -> request.id(distributionId)).eTag();
client.updateDistribution(request -> request.id(distributionId).ifMatch(etag)
.distributionConfig(client.getDistributionConfig(byId -> byId.id(distributionId))
.distributionConfig().toBuilder().enabled(false).build()));
String freshEtag = client.getDistribution(request -> request.id(distributionId)).eTag();
client.deleteDistribution(request -> request.id(distributionId).ifMatch(freshEtag));
} catch (NoSuchDistributionException | EntityNotFoundException | InvalidIfMatchVersionException
| PreconditionFailedException | ResourceNotDisabledException
| CannotDeleteEntityWhileInUseException | EntityAlreadyExistsException ignored) {
// teardown only: the emulator state is per-test, so a partially cleaned distribution cannot leak into another test
}
}
private void disableAndDeleteIfPresent(CloudFrontClient client, String id, String etag) {
if (id == null) {
return;
}
try {
client.updateConnectionGroup(request -> request.id(id).ifMatch(etag).enabled(false));
String freshEtag = client.getConnectionGroup(request -> request.identifier(id)).eTag();
client.deleteConnectionGroup(request -> request.id(id).ifMatch(freshEtag));
} catch (EntityNotFoundException | InvalidIfMatchVersionException | PreconditionFailedException
| ResourceNotDisabledException | CannotDeleteEntityWhileInUseException
| EntityAlreadyExistsException ignored) {
// teardown only: the emulator state is per-test, so a partially cleaned connection group cannot leak into another test
}
}
private static String stamp() {
return Long.toString(System.nanoTime(), 36);
}
private CloudFrontClient client() {
return AwsTestClients.create(CloudFrontClient.builder(), "000000000000", Region.US_EAST_1, endpoint);
}
}
@@ -0,0 +1,300 @@
package io.floci.aws.services.cloudfront;
import io.floci.aws.config.EmulatorConfig;
import io.floci.aws.core.common.AwsException;
import io.floci.aws.core.common.RegionResolver;
import io.floci.aws.core.storage.AccountAwareStorageBackend;
import io.floci.aws.core.storage.StorageFactory;
import io.floci.aws.services.cloudfront.model.ConnectionGroup;
import io.floci.aws.services.cloudfront.model.Distribution;
import io.floci.aws.services.cloudfront.model.DistributionConfig;
import org.junit.jupiter.api.Test;
import java.time.Instant;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
/**
* Connection groups in isolation: one account, one mocked storage factory. Multi-tenant
* distributions are served through a connection group, so the account's default group is minted
* with the first {@code tenant-only} distribution and can never be deleted, as AWS documents.
*/
class CloudFrontConnectionGroupServiceTest {
private static final String ACCOUNT = "000000000000";
private final Map<String, AccountAwareStorageBackend<?>> stores = new HashMap<>();
private CloudFrontService service() {
StorageFactory storageFactory = mock(StorageFactory.class);
when(storageFactory.create(anyString(), anyString(), any()))
.thenAnswer(invocation -> stores.computeIfAbsent(invocation.getArgument(1, String.class),
ignored -> AccountAwareStorageBackend.inMemory("000000000000")));
EmulatorConfig config = mock(EmulatorConfig.class);
EmulatorConfig.DnsConfig dnsConfig = mock(EmulatorConfig.DnsConfig.class);
EmulatorConfig.ServicesConfig servicesConfig = mock(EmulatorConfig.ServicesConfig.class);
EmulatorConfig.CloudFrontServiceConfig cloudFrontConfig = mock(EmulatorConfig.CloudFrontServiceConfig.class);
when(config.defaultAccountId()).thenReturn(ACCOUNT);
when(config.hostname()).thenReturn(Optional.empty());
when(config.effectiveBaseUrl()).thenReturn("http://localhost:4566");
when(config.dns()).thenReturn(dnsConfig);
when(dnsConfig.extraSuffixes()).thenReturn(Optional.empty());
when(config.services()).thenReturn(servicesConfig);
when(servicesConfig.cloudfront()).thenReturn(cloudFrontConfig);
when(cloudFrontConfig.domainSuffix()).thenReturn(Optional.empty());
return new CloudFrontService(storageFactory, config, new RegionResolver("us-east-1", ACCOUNT));
}
private Distribution distributionWithConnectionMode(String connectionMode) {
DistributionConfig config = new DistributionConfig();
config.setCallerReference("connection-group-test-" + connectionMode);
config.setConnectionMode(connectionMode);
Distribution dist = new Distribution();
dist.setConfig(config);
return dist;
}
@Test
void aTenantOnlyDistributionMintsTheAccountsDefaultConnectionGroup() {
CloudFrontService service = service();
service.createDistribution(distributionWithConnectionMode("tenant-only"), Map.of());
List<ConnectionGroup> groups = service.listConnectionGroups(null, 100, null);
assertEquals(1, groups.size());
ConnectionGroup group = groups.getFirst();
assertTrue(group.getIsDefault());
assertTrue(group.getEnabled());
assertEquals("default", group.getName());
assertEquals("Deployed", group.getStatus());
assertTrue(group.getId().startsWith("cg_"));
assertTrue(group.getArn().endsWith(":connection-group/" + group.getId()));
assertTrue(group.getArn().startsWith("arn:aws:cloudfront::" + ACCOUNT + ":"));
assertTrue(group.getRoutingEndpoint().endsWith(".cloudfront.net"));
assertFalse(group.getRoutingEndpoint().contains(group.getId().toLowerCase()));
assertNotNullTime(group);
}
private static void assertNotNullTime(ConnectionGroup group) {
assertTrue(group.getCreatedTime() instanceof Instant);
assertEquals(group.getCreatedTime(), group.getLastModifiedTime());
}
@Test
void aDirectDistributionMintsNoConnectionGroup() {
CloudFrontService service = service();
service.createDistribution(distributionWithConnectionMode("direct"), Map.of());
assertEquals(0, service.listConnectionGroups(null, 100, null).size());
}
@Test
void theDefaultConnectionGroupIsMintedOnlyOnceAndCannotBeDeleted() {
CloudFrontService service = service();
service.createDistribution(distributionWithConnectionMode("tenant-only"), Map.of());
ConnectionGroup first = service.listConnectionGroups(null, 100, null).getFirst();
service.createDistribution(distributionWithConnectionMode("tenant-only"), Map.of());
assertEquals(1, service.listConnectionGroups(null, 100, null).size());
AwsException e = assertThrows(AwsException.class,
() -> service.deleteConnectionGroup(first.getId(), first.getEtag()));
assertEquals("CannotDeleteEntityWhileInUse", e.getErrorCode());
assertEquals(1, service.listConnectionGroups(null, 100, null).size());
}
@Test
void createConnectionGroupStoresWhatTheRequestCarried() {
CloudFrontService service = service();
service.createDistribution(distributionWithConnectionMode("tenant-only"), Map.of());
String distributionId = service.listDistributions(null, 10).getFirst().getId();
ConnectionGroup group = service.createConnectionGroup("edge-group", null, true, false,
distributionId, Map.of("team", "edge"));
assertFalse(group.getIsDefault());
assertTrue(group.getEnabled());
assertFalse(group.getIpv6Enabled());
assertEquals("edge-group", group.getName());
assertEquals(distributionId, group.getViewerFallbackDistributionId());
assertEquals("edge", group.getTags().get("team"));
}
@Test
void duplicateNamesAndMissingFallbackDistributionsAreRefused() {
CloudFrontService service = service();
service.createConnectionGroup("group-a", null, null, null, null, Map.of());
AwsException duplicate = assertThrows(AwsException.class,
() -> service.createConnectionGroup("group-a", null, null, null, null, Map.of()));
assertEquals("EntityAlreadyExists", duplicate.getErrorCode());
AwsException missing = assertThrows(AwsException.class,
() -> service.createConnectionGroup("group-b", null, null, null, "nonexistent-dist", Map.of()));
assertEquals("NoSuchDistribution", missing.getErrorCode());
}
@Test
void aGroupIsReadableByIdNameArnAndRoutingEndpoint() {
CloudFrontService service = service();
ConnectionGroup created = service.createConnectionGroup("readable-group", null, null, null, null, Map.of());
assertEquals(created, service.getConnectionGroup(created.getId()));
assertEquals(created, service.getConnectionGroup(created.getName()));
assertEquals(created, service.getConnectionGroup(created.getArn()));
assertEquals(created, service.getConnectionGroupByRoutingEndpoint(created.getRoutingEndpoint()));
AwsException byId = assertThrows(AwsException.class,
() -> service.getConnectionGroup("cg_doesnotexist"));
assertEquals("EntityNotFound", byId.getErrorCode());
AwsException byEndpoint = assertThrows(AwsException.class,
() -> service.getConnectionGroupByRoutingEndpoint("d0000000000000.cloudfront.net"));
assertEquals("EntityNotFound", byEndpoint.getErrorCode());
}
@Test
void updateRequiresTheCurrentEtagAndChangesTheOptionalMembers() {
CloudFrontService service = service();
ConnectionGroup created = service.createConnectionGroup("update-group", null, true, true, null, Map.of());
String etagBefore = created.getEtag();
Instant modifiedBefore = created.getLastModifiedTime();
AwsException missing = assertThrows(AwsException.class,
() -> service.updateConnectionGroup(created.getId(), null, null, false, null, null));
assertEquals("InvalidIfMatchVersion", missing.getErrorCode());
AwsException stale = assertThrows(AwsException.class,
() -> service.updateConnectionGroup(created.getId(), "E000000000000", null, false, null, null));
assertEquals("PreconditionFailed", stale.getErrorCode());
ConnectionGroup updated = service.updateConnectionGroup(created.getId(), created.getEtag(),
null, false, false, null);
assertFalse(updated.getEnabled());
assertFalse(updated.getIpv6Enabled());
assertNotEquals(etagBefore, updated.getEtag());
assertTrue(updated.getLastModifiedTime().isAfter(modifiedBefore));
assertEquals("update-group", updated.getName());
}
@Test
void deleteRequiresDisabledAndTheCurrentEtag() {
CloudFrontService service = service();
ConnectionGroup created = service.createConnectionGroup("delete-group", null, true, null, null, Map.of());
AwsException enabled = assertThrows(AwsException.class,
() -> service.deleteConnectionGroup(created.getId(), created.getEtag()));
assertEquals("ResourceNotDisabled", enabled.getErrorCode());
AwsException stale = assertThrows(AwsException.class,
() -> service.deleteConnectionGroup(created.getId(), "E000000000000"));
assertEquals("PreconditionFailed", stale.getErrorCode());
service.updateConnectionGroup(created.getId(), created.getEtag(), null, false, null, null);
ConnectionGroup disabled = service.getConnectionGroup(created.getId());
service.deleteConnectionGroup(disabled.getId(), disabled.getEtag());
AwsException gone = assertThrows(AwsException.class,
() -> service.getConnectionGroup(created.getId()));
assertEquals("EntityNotFound", gone.getErrorCode());
}
@Test
void listConnectionGroupsSortsFiltersAndPaginates() {
CloudFrontService service = service();
service.createConnectionGroup("zeta", "aip_list-1", null, null, null, Map.of());
service.createConnectionGroup("alpha", "aip_list-2", null, null, null, Map.of());
service.createConnectionGroup("mike", null, null, null, null, Map.of());
List<ConnectionGroup> all = service.listConnectionGroups(null, 100, null);
assertEquals(List.of("alpha", "mike", "zeta"), all.stream().map(ConnectionGroup::getName).toList());
List<ConnectionGroup> filtered = service.listConnectionGroups(null, 100, "aip_list-1");
assertEquals(List.of("zeta"), filtered.stream().map(ConnectionGroup::getName).toList());
List<ConnectionGroup> page = service.listConnectionGroups("alpha", 1, null);
assertEquals(List.of("mike"), page.stream().map(ConnectionGroup::getName).toList());
}
@Test
void listDistributionsByConnectionModeReturnsOnlyTheMatchingMode() {
CloudFrontService service = service();
Distribution tenantOnly = service.createDistribution(distributionWithConnectionMode("tenant-only"), Map.of());
service.createDistribution(distributionWithConnectionMode("direct"), Map.of());
List<Distribution> tenantOnlyList = service.listDistributionsByConnectionMode("tenant-only", null, 100);
assertEquals(1, tenantOnlyList.size());
assertEquals(tenantOnly.getId(), tenantOnlyList.getFirst().getId());
List<Distribution> direct = service.listDistributionsByConnectionMode("direct", null, 100);
assertEquals(1, direct.size());
assertNotEquals(tenantOnly.getId(), direct.getFirst().getId());
// A marker at the mode's only id leaves nothing after it.
assertEquals(0, service.listDistributionsByConnectionMode("tenant-only", tenantOnly.getId(), 100).size());
}
@Test
void anUnknownConnectionModeIsRefusedWithInvalidArgument() {
CloudFrontService service = service();
service.createDistribution(distributionWithConnectionMode("direct"), Map.of());
AwsException e = assertThrows(AwsException.class,
() -> service.listDistributionsByConnectionMode("bogus", null, 100));
assertEquals("InvalidArgument", e.getErrorCode());
}
@Test
void aDistributionStoredWithoutConnectionModeListsUnderDirect() {
CloudFrontService service = service();
Distribution dist = service.createDistribution(distributionWithConnectionMode(null), Map.of());
List<Distribution> direct = service.listDistributionsByConnectionMode("direct", null, 100);
assertEquals(List.of(dist.getId()), direct.stream().map(Distribution::getId).toList());
assertEquals(0, service.listDistributionsByConnectionMode("tenant-only", null, 100).size());
}
@Test
void updatingADistributionToTenantOnlyMintsTheDefaultGroup() {
CloudFrontService service = service();
Distribution created = service.createDistribution(distributionWithConnectionMode("direct"), Map.of());
assertEquals(0, service.listConnectionGroups(null, 100, null).size());
created.getConfig().setConnectionMode("tenant-only");
service.updateDistribution(created.getId(), created.getEtag(), created);
List<ConnectionGroup> groups = service.listConnectionGroups(null, 100, null);
assertEquals(1, groups.size());
assertTrue(groups.getFirst().getIsDefault());
}
@Test
void deletingAFallbackDistributionClearsTheGroupsViewerFallback() {
CloudFrontService service = service();
Distribution dist = service.createDistribution(distributionWithConnectionMode("direct"), Map.of());
String groupId = service.createConnectionGroup("fallback-group", null, null, null, dist.getId(), Map.of())
.getId();
service.deleteDistribution(dist.getId(), dist.getEtag());
assertNull(service.getConnectionGroup(groupId).getViewerFallbackDistributionId());
}
@Test
void theCloudFormationRemovalAlsoClearsTheGroupsViewerFallback() {
CloudFrontService service = service();
Distribution dist = service.createDistribution(distributionWithConnectionMode("direct"), Map.of());
String groupId = service.createConnectionGroup("fallback-group", null, null, null, dist.getId(), Map.of())
.getId();
service.removeDistribution(dist.getId());
assertNull(service.getConnectionGroup(groupId).getViewerFallbackDistributionId());
}
}
@@ -2,6 +2,7 @@ package io.floci.aws.services.cloudfront;
import io.floci.aws.core.common.XmlParser;
import io.floci.aws.services.cloudfront.model.CloudFrontFunction;
import io.floci.aws.services.cloudfront.model.ConnectionGroup;
import io.floci.aws.services.cloudfront.model.ContinuousDeploymentPolicy;
import io.floci.aws.services.cloudfront.model.Distribution;
import jakarta.ws.rs.core.Response;
@@ -800,6 +801,88 @@ class CloudFrontControllerTest {
""".formatted(defaultCacheBehaviorExtra);
}
@Test
void listDistributionsByConnectionModeSetsTheTruncationMembers() {
CloudFrontService service = mock(CloudFrontService.class);
Distribution first = distribution("A");
Distribution second = distribution("B");
Distribution third = distribution("C");
Distribution fourth = distribution("D");
when(service.listDistributionsByConnectionMode("direct", null, 3))
.thenReturn(List.of(first, second, third));
when(service.listDistributionsByConnectionMode("direct", "B", 3))
.thenReturn(List.of(third, fourth));
when(service.listDistributionsByConnectionMode("direct", null, Integer.MAX_VALUE))
.thenReturn(List.of(first, second, third, fourth));
CloudFrontController controller = new CloudFrontController(service);
try (Response firstPage = controller.listDistributionsByConnectionMode("direct", null, 2);
Response secondPage = controller.listDistributionsByConnectionMode("direct", "B", 2)) {
String firstXml = (String) firstPage.getEntity();
String secondXml = (String) secondPage.getEntity();
assertEquals("true", XmlParser.extractFirst(firstXml, "IsTruncated", null));
assertEquals("B", XmlParser.extractFirst(firstXml, "NextMarker", null));
assertEquals("4", XmlParser.extractFirst(firstXml, "Quantity", null));
assertEquals(List.of("A", "B"), XmlParser.extractAll(firstXml, "Id"));
assertEquals("false", XmlParser.extractFirst(secondXml, "IsTruncated", null));
assertTrue(XmlParser.extractAll(secondXml, "NextMarker").isEmpty());
assertEquals("4", XmlParser.extractFirst(secondXml, "Quantity", null));
assertEquals(List.of("C", "D"), XmlParser.extractAll(secondXml, "Id"));
}
}
@Test
void listConnectionGroupsStopsAtTheExactEndOfASecondPage() {
CloudFrontService service = mock(CloudFrontService.class);
ConnectionGroup alpha = connectionGroup("alpha");
ConnectionGroup beta = connectionGroup("beta");
ConnectionGroup gamma = connectionGroup("gamma");
when(service.listConnectionGroups(null, 3, null)).thenReturn(List.of(alpha, beta, gamma));
when(service.listConnectionGroups("beta", 3, null)).thenReturn(List.of(gamma));
when(service.listConnectionGroups("gamma", 3, null)).thenReturn(List.of());
CloudFrontController controller = new CloudFrontController(service);
try (Response firstPage = controller.listConnectionGroups(listConnectionGroupsBody(null, 2));
Response secondPage = controller.listConnectionGroups(listConnectionGroupsBody("beta", 2));
Response lastPage = controller.listConnectionGroups(listConnectionGroupsBody("gamma", 2))) {
String firstXml = (String) firstPage.getEntity();
String secondXml = (String) secondPage.getEntity();
String lastXml = (String) lastPage.getEntity();
assertEquals(List.of("alpha", "beta"), XmlParser.extractAll(firstXml, "Name"));
assertEquals("beta", XmlParser.extractFirst(firstXml, "NextMarker", null));
assertEquals(List.of("gamma"), XmlParser.extractAll(secondXml, "Name"));
assertTrue(XmlParser.extractAll(secondXml, "NextMarker").isEmpty(),
"the final page carries no next marker");
assertTrue(XmlParser.extractAll(lastXml, "Name").isEmpty(),
"a marker past the last group answers an empty page");
assertTrue(XmlParser.extractAll(lastXml, "NextMarker").isEmpty());
}
}
private static String listConnectionGroupsBody(String marker, int maxItems) {
return """
<ListConnectionGroupsRequest xmlns="http://cloudfront.amazonaws.com/doc/2020-05-31/">
%s<MaxItems>%d</MaxItems>
</ListConnectionGroupsRequest>
""".formatted(marker == null ? "" : "<Marker>" + marker + "</Marker>", maxItems);
}
private static ConnectionGroup connectionGroup(String name) {
ConnectionGroup group = new ConnectionGroup();
group.setName(name);
group.setEnabled(true);
group.setIpv6Enabled(true);
group.setIsDefault(false);
return group;
}
private static Distribution distribution(String id) {
Distribution distribution = new Distribution();
distribution.setId(id);
@@ -44,6 +44,7 @@ AWS::CertificateManager::Certificate update not yet on the engine's changes (#66
AWS::CloudFormation::CustomResource update not yet on the engine's changes (#6606)
AWS::CloudFormation::StackSet update not yet on the engine's changes (#6606)
AWS::CloudFront::CachePolicy update not yet on the engine's changes (#6606)
AWS::CloudFront::ConnectionGroup update not yet on the engine's changes (#6606)
AWS::CloudFront::Distribution update not yet on the engine's changes (#6606)
AWS::CloudFront::Function update not yet on the engine's changes (#6606)
AWS::CloudFront::KeyGroup update not yet on the engine's changes (#6606)
1 AWS::ApiGateway::Account update not yet on the engine's changes (#6606)
44 AWS::CloudFormation::CustomResource update not yet on the engine's changes (#6606)
45 AWS::CloudFormation::StackSet update not yet on the engine's changes (#6606)
46 AWS::CloudFront::CachePolicy update not yet on the engine's changes (#6606)
47 AWS::CloudFront::ConnectionGroup update not yet on the engine's changes (#6606)
48 AWS::CloudFront::Distribution update not yet on the engine's changes (#6606)
49 AWS::CloudFront::Function update not yet on the engine's changes (#6606)
50 AWS::CloudFront::KeyGroup update not yet on the engine's changes (#6606)
@@ -48,6 +48,7 @@ AWS::CertificateManager::Certificate CertificateArn CertificateAuthorityArn,Cert
AWS::CloudFormation::CustomResource Id ServiceTimeout,ServiceToken
AWS::CloudFormation::StackSet StackSetId AdministrationRoleARN,AutoDeployment,CallAs,Capabilities,Description,ExecutionRoleName,ManagedExecution,OperationPreferences,Parameters,PermissionModel,StackInstancesGroup,StackSetName,Tags,TemplateBody,TemplateURL
AWS::CloudFront::CachePolicy Id,LastModifiedTime CachePolicyConfig
AWS::CloudFront::ConnectionGroup Arn,CreatedTime,ETag,Id,IsDefault,LastModifiedTime,RoutingEndpoint,Status AnycastIpListId,Enabled,Ipv6Enabled,Name,Tags,ViewerFallback
AWS::CloudFront::Distribution DomainName,Id DistributionConfig,Tags
AWS::CloudFront::Function FunctionARN,Stage AutoPublish,FunctionCode,FunctionConfig,FunctionMetadata,Name,Tags
AWS::CloudFront::KeyGroup Id,LastModifiedTime KeyGroupConfig
1 AWS::ApiGateway::Account Id CloudWatchRoleArn
48 AWS::CloudFormation::CustomResource Id ServiceTimeout,ServiceToken
49 AWS::CloudFormation::StackSet StackSetId AdministrationRoleARN,AutoDeployment,CallAs,Capabilities,Description,ExecutionRoleName,ManagedExecution,OperationPreferences,Parameters,PermissionModel,StackInstancesGroup,StackSetName,Tags,TemplateBody,TemplateURL
50 AWS::CloudFront::CachePolicy Id,LastModifiedTime CachePolicyConfig
51 AWS::CloudFront::ConnectionGroup Arn,CreatedTime,ETag,Id,IsDefault,LastModifiedTime,RoutingEndpoint,Status AnycastIpListId,Enabled,Ipv6Enabled,Name,Tags,ViewerFallback
52 AWS::CloudFront::Distribution DomainName,Id DistributionConfig,Tags
53 AWS::CloudFront::Function FunctionARN,Stage AutoPublish,FunctionCode,FunctionConfig,FunctionMetadata,Name,Tags
54 AWS::CloudFront::KeyGroup Id,LastModifiedTime KeyGroupConfig
@@ -49,6 +49,7 @@ AWS::CertificateManager::Certificate AcmCfnProvisioner
AWS::CloudFormation::CustomResource CustomResourceCfnProvisioner
AWS::CloudFormation::StackSet StackSetCfnProvisioner
AWS::CloudFront::CachePolicy CloudFrontCfnProvisioner
AWS::CloudFront::ConnectionGroup CloudFrontCfnProvisioner
AWS::CloudFront::Distribution CloudFrontCfnProvisioner
AWS::CloudFront::Function CloudFrontCfnProvisioner
AWS::CloudFront::KeyGroup CloudFrontCfnProvisioner
1 AWS::ApiGateway::Account ApiGatewayAccountCfnProvisioner
49 AWS::CloudFormation::CustomResource CustomResourceCfnProvisioner
50 AWS::CloudFormation::StackSet StackSetCfnProvisioner
51 AWS::CloudFront::CachePolicy CloudFrontCfnProvisioner
52 AWS::CloudFront::ConnectionGroup CloudFrontCfnProvisioner
53 AWS::CloudFront::Distribution CloudFrontCfnProvisioner
54 AWS::CloudFront::Function CloudFrontCfnProvisioner
55 AWS::CloudFront::KeyGroup CloudFrontCfnProvisioner