fix(cloudfront): store and return a distribution's ConnectionMode (#8934)

* fix(cloudfront): store and return a distribution's ConnectionMode
* test(cloudfront): deploy the ConnectionMode stack with CfnRequests and check refusals store nothing
This commit is contained in:
Joaquín Gamboa authored and GitHub committed 2026-11-18 23:53:11 -04:00
1 parent 9a38bd0bd2
commit afd3107151
9 files changed
+234 -1

No files matched your search

+13
View File
@@ -457,6 +457,16 @@ These operations store what they are given and return it, so code that manages t
created with no `ViewerCertificate` at all reads the same way, the default certificate on `TLSv1`.
The `us-east-1` restriction AWS states for ACM certificates is not enforced: a certificate is
resolved from whatever region its ARN names, as long as it exists.
- `ConnectionMode` is stored and returned by `GetDistribution`, `GetDistributionConfig`,
`ListDistributions` and the create and update responses, and `AWS::CloudFront::Distribution`
passes it through. It is held to `direct` and `tenant-only`; anything else is `InvalidArgument`
400, the code this service answers a member outside its shape with. An omitted mode is reported
as omitted: no published sentence says which mode such a distribution reads back as. A
`tenant-only` distribution is otherwise treated like a standard one. The restrictions the
Developer Guide lists for multi-tenant distributions (only `sni-only`, no `SSLv3`, no IAM
certificate, no `Aliases` or `PriceClass`) are not enforced, because no error code is published
for them, and an omitted `ViewerCertificate` on a `tenant-only` distribution reads as the default
certificate, the same as on a standard one. AWS documents no default for that case.
- Up to 20 custom response headers policies can be created, and one policy can be associated with
up to 100 distributions.
- The five AWS managed response headers policy IDs are available and can be selected with
@@ -688,6 +698,9 @@ signatures must still return 403. Verify those cases through the proxy after con
- `TestFunction` execution (function is stored, not executed)
- Serving RTMP for a streaming distribution (deprecated by AWS)
- VPC origins, Anycast IP lists
- Connection groups and distribution tenants (`CreateConnectionGroup`, `CreateDistributionTenant`,
etc.), their CloudFormation types, `ListDistributionsByConnectionMode`, and serving a
`tenant-only` distribution by a tenant's domain
- Importing keys into a key value store from S3: `CreateKeyValueStore` with an `ImportSource` is rejected with
`InvalidArgument`
- Running CloudFront Functions, so the key value store can only be read and written through its API, not
@@ -523,6 +523,10 @@ public class CloudFrontCfnProvisioner implements CfnResourceProvisioner {
config.setDefaultRootObject(cfnText(dc, "DefaultRootObject", engine));
config.setHttpVersion(cfnTextOrDefault(dc, "HttpVersion", engine, "http2"));
config.setPriceClass(cfnTextOrDefault(dc, "PriceClass", engine, "PriceClass_All"));
String connectionMode = cfnText(dc, "ConnectionMode", engine);
if (!connectionMode.isEmpty()) {
config.setConnectionMode(connectionMode);
}
config.setAliases(cfnStringList(dc.path("Aliases"), engine));
config.setOrigins(cfnOrigins(dc, engine));
config.setDefaultCacheBehavior(cfnDefaultCacheBehavior(dc.path("DefaultCacheBehavior"), engine));
@@ -1964,6 +1964,9 @@ public class CloudFrontController {
xml.raw(xmlViewerCertificate(cfg.getViewerCertificate()));
xml.raw(xmlRestrictions(cfg.getGeoRestriction()));
xml.raw(xmlLogging(cfg.getLogging()));
if (cfg.getConnectionMode() != null) {
xml.elem("ConnectionMode", cfg.getConnectionMode());
}
return xml.build();
}
@@ -2409,6 +2412,9 @@ public class CloudFrontController {
xml.raw(xmlViewerCertificate(cfg != null ? cfg.getViewerCertificate() : null));
xml.raw(xmlRestrictions(cfg != null ? cfg.getGeoRestriction() : null));
if (cfg != null && cfg.getConnectionMode() != null) {
xml.elem("ConnectionMode", cfg.getConnectionMode());
}
xml.end("DistributionSummary");
return xml.build();
@@ -2673,6 +2679,7 @@ public class CloudFrontController {
values.get("ContinuousDeploymentPolicyId"));
cfg.setStaging("true".equalsIgnoreCase(
values.getOrDefault("Staging", "false")));
cfg.setConnectionMode(values.get("ConnectionMode"));
cfg.setOrigins(parseOrigins(body));
cfg.setDefaultCacheBehavior(parseDefaultCacheBehavior(body));
@@ -2750,7 +2757,8 @@ public class CloudFrontController {
"WebACLId",
"WebAclId",
"ContinuousDeploymentPolicyId",
"Staging" -> true;
"Staging",
"ConnectionMode" -> true;
default -> false;
};
}
@@ -90,6 +90,8 @@ public class CloudFrontService implements ServerCertificateReferenceProvider {
"TLSv1.2_2025", "TLSv1.3_2025");
/** The values {@code SSLSupportMethod} admits, the enumeration its shape declares. */
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");
/**
* The forms a member declared {@code boolean} can carry, XML giving such a value as
* {@code true}, {@code false}, {@code 1} or {@code 0}.
@@ -245,6 +247,7 @@ public class CloudFrontService implements ServerCertificateReferenceProvider {
validateResponseHeadersPolicyReferences(dist.getConfig(), null);
validateTrustedKeyGroups(dist.getConfig());
validateOriginAccessControls(dist.getConfig());
validateConnectionMode(dist.getConfig());
validateViewerCertificateSettings(dist.getConfig(), DistributionWrite.CREATE);
applyDefaultCertificateProtocolVersion(dist.getConfig());
return whileCertificatesHeld(dist.getConfig(), () -> {
@@ -282,6 +285,7 @@ public class CloudFrontService implements ServerCertificateReferenceProvider {
validateResponseHeadersPolicyReferences(updated.getConfig(), id);
validateTrustedKeyGroups(updated.getConfig());
validateOriginAccessControls(updated.getConfig());
validateConnectionMode(updated.getConfig());
validateViewerCertificateSettings(updated.getConfig(), DistributionWrite.UPDATE);
applyDefaultCertificateProtocolVersion(updated.getConfig());
return whileCertificatesHeld(updated.getConfig(), () -> {
@@ -377,6 +381,23 @@ public class CloudFrontService implements ServerCertificateReferenceProvider {
return parsed;
}
/**
* {@code ConnectionMode} is held to the enumeration its shape declares, {@code direct} or
* {@code tenant-only}. The member has no code of its own, so a value outside the set reads as
* the {@code InvalidArgument} this service already answers a member outside its shape with, as
* {@code SSLSupportMethod} does. An omitted mode is kept omitted: no published sentence says
* which mode such a distribution reads back as, nor what a {@code tenant-only} distribution
* does with a viewer certificate it leaves out, so neither is filled in here.
*/
private static void validateConnectionMode(DistributionConfig config) {
if (config == null || config.getConnectionMode() == null) {
return;
}
if (!CONNECTION_MODES.contains(config.getConnectionMode())) {
throw new AwsException("InvalidArgument", "The ConnectionMode specified is not valid.", 400);
}
}
/**
* Which distribution write is being validated. The two differ in one answer, the code the
* {@code SSLv3} with {@code sni-only} pair is refused with, which is the code the operation
@@ -26,6 +26,7 @@ public class DistributionConfig {
private Map<String, Object> logging;
private String continuousDeploymentPolicyId;
private boolean staging;
private String connectionMode;
public DistributionConfig() {}
@@ -82,4 +83,7 @@ public class DistributionConfig {
public boolean isStaging() { return staging; }
public void setStaging(boolean staging) { this.staging = staging; }
public String getConnectionMode() { return connectionMode; }
public void setConnectionMode(String connectionMode) { this.connectionMode = connectionMode; }
}
@@ -6,6 +6,7 @@ import io.floci.aws.services.cloudfront.model.KeyGroup;
import io.floci.aws.services.cloudfront.model.OriginAccessControl;
import io.floci.aws.services.cloudfront.model.PublicKey;
import io.floci.aws.services.s3.S3Service;
import io.floci.aws.testing.CfnRequests;
import io.floci.aws.testing.CfnStackWaits;
import io.quarkus.test.junit.QuarkusTest;
import jakarta.inject.Inject;
@@ -21,6 +22,7 @@ import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.containsString;
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;
/**
@@ -380,4 +382,44 @@ class CloudFormationCloudFrontDistributionIntegrationTest {
}
""".formatted(comment, alias, bucket);
}
@Test
void createStackCarriesTheConnectionModeOntoTheDistribution() {
String stackName = "cfn-cloudfront-tenant-only-" + Long.toString(System.nanoTime(), 36);
String template = """
{
"Resources": {
"Dist": {
"Type": "AWS::CloudFront::Distribution",
"Properties": {
"DistributionConfig": {
"Enabled": true,
"ConnectionMode": "tenant-only",
"Origins": [{
"Id": "origin",
"DomainName": "origin.example.com",
"CustomOriginConfig": {"OriginProtocolPolicy": "https-only"}
}],
"DefaultCacheBehavior": {
"TargetOriginId": "origin",
"ViewerProtocolPolicy": "redirect-to-https"
}
}
}
}
}
}
""";
CfnRequests.deploy("CreateStack", stackName, template, CFN_AUTH, "CREATE_COMPLETE");
String distributionId = CfnRequests.physicalId(stackName, "Dist", CFN_AUTH);
given()
.when()
.get("/2020-05-31/distribution/" + distributionId)
.then()
.statusCode(200)
.body(hasXPath("//*[local-name()='DistributionConfig']/*[local-name()='ConnectionMode']",
equalTo("tenant-only")));
}
}
@@ -212,6 +212,43 @@ class CloudFrontCfnProvisionerTest {
assertEquals(Integer.valueOf(120), origin.getCustomOriginConfig().get("OriginKeepaliveTimeout"));
}
@Test
void copiesTheConnectionModeTheTemplateDeclares() throws Exception {
when(cloudFront.createDistribution(any(), any())).thenReturn(distribution("E1DIST", "d111.cloudfront.net"));
StackResource r = resource(DISTRIBUTION);
provisioner.provision(r, json("""
{"DistributionConfig": {
"ConnectionMode": "tenant-only",
"Origins": [{"Id": "o1", "DomainName": "origin.example.com",
"CustomOriginConfig": {"OriginProtocolPolicy": "https-only"}}],
"DefaultCacheBehavior": {"TargetOriginId": "o1", "ViewerProtocolPolicy": "redirect-to-https"}
}}
"""), distributionCtx(null));
ArgumentCaptor<Distribution> sent = ArgumentCaptor.forClass(Distribution.class);
verify(cloudFront).createDistribution(sent.capture(), any());
assertEquals("tenant-only", sent.getValue().getConfig().getConnectionMode());
}
@Test
void leavesTheConnectionModeUnsetWhenTheTemplateOmitsIt() throws Exception {
when(cloudFront.createDistribution(any(), any())).thenReturn(distribution("E1DIST", "d111.cloudfront.net"));
StackResource r = resource(DISTRIBUTION);
provisioner.provision(r, json("""
{"DistributionConfig": {
"Origins": [{"Id": "o1", "DomainName": "origin.example.com",
"CustomOriginConfig": {"OriginProtocolPolicy": "https-only"}}],
"DefaultCacheBehavior": {"TargetOriginId": "o1", "ViewerProtocolPolicy": "redirect-to-https"}
}}
"""), distributionCtx(null));
ArgumentCaptor<Distribution> sent = ArgumentCaptor.forClass(Distribution.class);
verify(cloudFront).createDistribution(sent.capture(), any());
assertNull(sent.getValue().getConfig().getConnectionMode());
}
@Test
void aNonNumericOriginConnectionSettingFailsTheStackInsteadOfAServerError() {
StackResource r = resource(DISTRIBUTION);
@@ -40,6 +40,8 @@ class CloudFrontDistributionConfigMembersTest {
"//*[local-name()='Logging']/*[local-name()='Prefix']";
private static final String WEB_ACL_ID =
"//*[local-name()='WebACLId']";
private static final String CONNECTION_MODE =
"//*[local-name()='DistributionConfig']/*[local-name()='ConnectionMode']";
private final CloudFrontService cloudFrontService;
@@ -344,4 +346,74 @@ class CloudFrontDistributionConfigMembersTest {
.statusCode(200)
.body(hasXPath(WEB_ACL_ID, equalTo("")));
}
@Test
void connectionModeRoundTripsThroughCreateUpdateAndDistributionReads() {
String originId = "origin-connection-mode-" + UUID.randomUUID();
String created = given()
.contentType(ContentType.XML)
.body(distributionConfigBody(originId, "<ConnectionMode>tenant-only</ConnectionMode>"))
.when()
.post(DISTRIBUTIONS)
.then()
.statusCode(201)
.body(hasXPath(CONNECTION_MODE, equalTo("tenant-only")))
.extract().asString();
String id = XmlParser.extractFirst(created, "Id", null);
given().when().get(API + id + "/config").then()
.statusCode(200)
.body(hasXPath("//*[local-name()='ConnectionMode']", equalTo("tenant-only")));
given().when().get(API + id).then()
.statusCode(200)
.body(hasXPath(CONNECTION_MODE, equalTo("tenant-only")));
given().when().get(DISTRIBUTIONS).then()
.statusCode(200)
.body(hasXPath(summaryConnectionMode(id), equalTo("tenant-only")));
updateDistribution(id, distributionConfigBody(originId, "<ConnectionMode>tenant-only</ConnectionMode>"))
.statusCode(200)
.body(hasXPath(CONNECTION_MODE, equalTo("tenant-only")));
}
@Test
void connectionModeIsLeftOutWhenTheRequestOmitsIt() {
// No published sentence says which mode an omitted ConnectionMode reads back as, so
// the member is reported only when the caller set it.
String id = postDistribution(distributionConfigBody(
"origin-no-connection-mode-" + UUID.randomUUID(), ""));
given().when().get(API + id + "/config").then()
.statusCode(200)
.body(hasXPath("count(//*[local-name()='ConnectionMode'])", equalTo("0")));
given().when().get(DISTRIBUTIONS).then()
.statusCode(200)
.body(hasXPath("count(" + summaryConnectionMode(id) + ")", equalTo("0")));
}
@Test
void connectionModeOutsideItsEnumerationIsRefused() {
String originId = "origin-bad-connection-mode-" + UUID.randomUUID();
given()
.contentType(ContentType.XML)
.body(distributionConfigBody(originId, "<ConnectionMode>shared</ConnectionMode>"))
.when()
.post(DISTRIBUTIONS)
.then()
.statusCode(400)
.body(hasXPath("//*[local-name()='Code']", equalTo("InvalidArgument")))
.body(hasXPath("//*[local-name()='Message']",
equalTo("The ConnectionMode specified is not valid.")));
// The refused request created no distribution.
given().when().get(DISTRIBUTIONS).then()
.statusCode(200)
.body(hasXPath("count(//*[local-name()='Origin']/*[local-name()='Id' and text()='"
+ originId + "'])", equalTo("0")));
}
private static String summaryConnectionMode(String id) {
return "//*[local-name()='DistributionSummary']"
+ "[*[local-name()='Id' and text()='" + id + "']]"
+ "/*[local-name()='ConnectionMode']";
}
}
@@ -1843,6 +1843,38 @@ class CloudFrontServiceTest {
LinkedHashMap::new));
}
@Test
void createDistributionKeepsTheConnectionModeTheConfigNames() {
CloudFrontService service = serviceWithDomainSuffix("cloudfront.net");
Distribution tenantOnly = distribution(true, List.of());
tenantOnly.getConfig().setConnectionMode("tenant-only");
Distribution created = service.createDistribution(tenantOnly, Map.of());
assertEquals("tenant-only", service.getDistribution(created.getId()).getConfig().getConnectionMode());
}
@Test
void createAndUpdateDistributionRefuseAConnectionModeOutsideItsEnumeration() {
CloudFrontService service = serviceWithDomainSuffix("cloudfront.net");
Distribution created = service.createDistribution(distribution(true, List.of()), Map.of());
Distribution shared = distribution(true, List.of());
shared.getConfig().setConnectionMode("shared");
AwsException onCreate = assertAws("InvalidArgument",
() -> service.createDistribution(shared, Map.of()));
AwsException onUpdate = assertAws("InvalidArgument",
() -> service.updateDistribution(created.getId(), created.getEtag(), shared));
assertEquals("The ConnectionMode specified is not valid.", onCreate.getMessage());
assertEquals("The ConnectionMode specified is not valid.", onUpdate.getMessage());
// Neither refusal stored anything: no second distribution, and the first is as it was.
assertEquals(1, service.listDistributions(null, 100).size());
Distribution unchanged = service.getDistribution(created.getId());
assertNull(unchanged.getConfig().getConnectionMode());
assertEquals(created.getEtag(), unchanged.getEtag());
}
private static AwsException assertAws(
String code, Executable action) {
AwsException error = assertThrows(AwsException.class, action);