feat(cloudfront): serve distribution requests from S3 and custom origins (#1820)

* feat(cloudfront): serve distribution requests from S3 and custom origins

* chore: re-run CI

The Build and Test failure on the previous head was RuntimeApiServerTest's
extension/stop race, a pre-existing flake unrelated to this change — it also failed
on #1820, #1823 and on #2131's own branch (the PR that tried to de-flake it).
Reproduced locally under `--cpus=1` and fixed separately.

* fix(cloudfront): wildcard aliases match exactly one subdomain level

wildcardAliasMatches did a plain suffix check, so "*.example.com" also matched
a.b.example.com. AWS is explicit that a wildcard alternate domain name replaces the
wildcard at that level only:

  "you can't add alternate domain names that are at levels higher or lower than the
   wildcard. For example, you can't add the alternate domain names example.com or
   marketing.product.example.com."

  https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/CNAMEs.html

Practical effect: a distribution owning "*.example.com" would answer for
a.b.example.com, which on AWS belongs to whoever owns "*.b.example.com" — or to
nobody. Require the label standing in for the wildcard to contain no dot.

wildcardAliasesMatchSubdomainsAndPreferMoreSpecificNames asserted the old behaviour
(a.b.example.test resolving to the *.example.test distribution); it now asserts no
match, plus the same for a deeper wildcard.

* test(dynamodb): retain Quarkus port for cleanup

* fix(cloudfront): isolate mocked storage backends
This commit is contained in:
Alex Banna authored and GitHub committed 2026-08-12 19:34:18 -04:00
1 parent 527615bdf0
commit 82f80165fb
37 files changed
+4339 -158

No files matched your search

@@ -0,0 +1,206 @@
package io.github.hectorvent.floci.services.cloudformation;
import io.github.hectorvent.floci.services.cloudfront.CloudFrontService;
import io.github.hectorvent.floci.services.cloudfront.model.Distribution;
import io.github.hectorvent.floci.services.cloudfront.model.OriginAccessControl;
import io.github.hectorvent.floci.services.s3.S3Service;
import io.quarkus.test.junit.QuarkusTest;
import jakarta.inject.Inject;
import org.junit.jupiter.api.Test;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.Map;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.not;
import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* End-to-end check that CloudFormation provisions an {@code AWS::CloudFront::Distribution} for real
* (into {@link io.github.hectorvent.floci.services.cloudfront.CloudFrontService}) rather than stubbing
* it: {@code Fn::GetAtt DomainName} resolves to the assigned {@code *.cloudfront.net} domain (closes
* #1147, where it previously returned the raw {@code LogicalId.DomainName} token), and the provisioned
* distribution actually serves its S3 origin.
*/
@QuarkusTest
class CloudFormationCloudFrontDistributionIntegrationTest {
private static final String CFN_AUTH =
"AWS4-HMAC-SHA256 Credential=test/20260205/us-east-1/cloudformation/aws4_request";
@Inject
S3Service s3Service;
@Inject
CloudFrontService cloudFrontService;
@Test
void createStackProvisionsBrowsableDistributionWithResolvedDomainName() {
String suffix = Long.toString(System.nanoTime(), 36);
String bucket = "cfn-cf-content-" + suffix;
String alias = "cfn-viewer-" + suffix + ".example.test";
String stackName = "cfn-cloudfront-stack-" + suffix;
s3Service.createBucket(bucket, "us-east-1");
s3Service.putObject(bucket, "index.html",
("CFN-INDEX-" + suffix).getBytes(StandardCharsets.UTF_8), "text/html", Map.of());
OriginAccessControl oac = new OriginAccessControl();
oac.setName("cfn-oac-" + suffix);
oac.setSigningBehavior("always");
oac.setSigningProtocol("sigv4");
oac.setOriginAccessControlOriginType("s3");
oac = cloudFrontService.createOriginAccessControl(oac);
String template = """
{
"Resources": {
"Dist": {
"Type": "AWS::CloudFront::Distribution",
"Properties": {
"DistributionConfig": {
"Enabled": true,
"DefaultRootObject": "index.html",
"Aliases": ["%s"],
"Origins": [
{
"Id": "s3-origin",
"DomainName": "%s.s3.us-east-1.amazonaws.com",
"OriginAccessControlId": "%s",
"S3OriginConfig": { "OriginAccessIdentity": "" }
}
],
"DefaultCacheBehavior": {
"TargetOriginId": "s3-origin",
"ViewerProtocolPolicy": "allow-all"
}
}
}
}
},
"Outputs": {
"DistDomain": {"Value": {"Fn::GetAtt": ["Dist", "DomainName"]}},
"DistId": {"Value": {"Ref": "Dist"}}
}
}
""".formatted(alias, bucket, oac.getId());
given()
.contentType("application/x-www-form-urlencoded")
.header("Authorization", CFN_AUTH)
.formParam("Action", "CreateStack")
.formParam("StackName", stackName)
.formParam("TemplateBody", template)
.when()
.post("/")
.then()
.statusCode(200);
// Stack completes and Fn::GetAtt(Dist, DomainName) resolves to a real *.cloudfront.net domain
// (not the unresolved "Dist.DomainName" token).
given()
.contentType("application/x-www-form-urlencoded")
.header("Authorization", CFN_AUTH)
.formParam("Action", "DescribeStacks")
.formParam("StackName", stackName)
.when()
.post("/")
.then()
.statusCode(200)
.body(containsString("<StackStatus>CREATE_COMPLETE</StackStatus>"))
.body(containsString(".cloudfront.net"))
.body(not(containsString("Dist.DomainName")));
Distribution provisioned = distributionsWithAlias(alias).getFirst();
assertEquals(
oac.getId(),
provisioned.getConfig().getOrigins().getFirst().getOriginAccessControlId());
// The provisioned distribution is browsable: a request to its alias serves the S3 origin's
// default root object.
given()
.header("Host", alias)
.when()
.get("/")
.then()
.statusCode(200)
.body(containsString("CFN-INDEX-" + suffix));
}
@Test
void updateStackUpdatesDistributionInPlace() {
String suffix = Long.toString(System.nanoTime(), 36);
String bucket = "cfn-cf-update-" + suffix;
String alias = "cfn-update-" + suffix + ".example.test";
String stackName = "cfn-cloudfront-update-" + suffix;
s3Service.createBucket(bucket, "us-east-1");
given()
.contentType("application/x-www-form-urlencoded")
.header("Authorization", CFN_AUTH)
.formParam("Action", "CreateStack")
.formParam("StackName", stackName)
.formParam("TemplateBody", updateTemplate(alias, bucket, "before-" + suffix))
.when()
.post("/")
.then()
.statusCode(200);
Distribution original = distributionsWithAlias(alias).getFirst();
given()
.contentType("application/x-www-form-urlencoded")
.header("Authorization", CFN_AUTH)
.formParam("Action", "UpdateStack")
.formParam("StackName", stackName)
.formParam("TemplateBody", updateTemplate(alias, bucket, "after-" + suffix))
.when()
.post("/")
.then()
.statusCode(200);
List<Distribution> matching = distributionsWithAlias(alias);
assertEquals(1, matching.size(), "UpdateStack must not leak a second distribution");
Distribution updated = matching.getFirst();
assertEquals(original.getId(), updated.getId());
assertEquals(original.getDomainName(), updated.getDomainName());
assertEquals("after-" + suffix, updated.getConfig().getComment());
}
private List<Distribution> distributionsWithAlias(String alias) {
return cloudFrontService.listDistributions(null, 1000).stream()
.filter(distribution -> distribution.getConfig() != null
&& distribution.getConfig().getAliases() != null
&& distribution.getConfig().getAliases().contains(alias))
.toList();
}
private static String updateTemplate(String alias, String bucket, String comment) {
return """
{
"Resources": {
"Dist": {
"Type": "AWS::CloudFront::Distribution",
"Properties": {
"DistributionConfig": {
"Enabled": true,
"Comment": "%s",
"Aliases": ["%s"],
"Origins": [{
"Id": "s3-origin",
"DomainName": "%s.s3.us-east-1.amazonaws.com",
"S3OriginConfig": {"OriginAccessIdentity": ""}
}],
"DefaultCacheBehavior": {
"TargetOriginId": "s3-origin",
"ViewerProtocolPolicy": "allow-all"
}
}
}
}
}
}
""".formatted(comment, alias, bucket);
}
}
@@ -36,7 +36,7 @@ class CloudFormationDeleteIdempotencyTest {
new ObjectMapper(),
null, null, null, null, null, null, null,
null, null, null, null, null, null, null,
null,
null, null,
new CloudFormationResourceRegistry(List.of()));
}
@@ -53,7 +53,7 @@ class CloudFormationIamAttachmentProvisionerTest {
mapper,
null, null, null, null, null, null, null,
null, null, null, null, null, null, null,
null,
null, null,
new CloudFormationResourceRegistry(List.of(new IamRoleCfnProvisioner(iamService))));
}
@@ -47,7 +47,7 @@ class CloudFormationLogGroupProvisionerTest {
mapper,
null, null, null, null, null, null, null,
null, null, logsService, null, null, null, null,
null,
null, null,
new CloudFormationResourceRegistry(List.of()));
}
@@ -49,7 +49,7 @@ class CustomResourceProvisionerTest {
provisioner = new CloudFormationResourceProvisioner(
null, null, null, null, lambdaService, null, null, null, null, null,
null, null, null, null, null, null, mapper, store, endpoint, null, null, null, null, null, null, null, null, null, null, null, null,
null,
null, null,
new io.github.hectorvent.floci.services.cloudformation.provisioners.CloudFormationResourceRegistry(java.util.List.of()));
}
@@ -47,7 +47,7 @@ class RdsCfnProvisionerTest {
mapper,
null, null, null, null, null, null, null,
rdsService, null, null, null, null, null, null,
null,
null, null,
new io.github.hectorvent.floci.services.cloudformation.provisioners.CloudFormationResourceRegistry(java.util.List.of()));
}
@@ -70,7 +70,7 @@ class SecretTargetAttachmentCfnProvisionerTest {
mapper,
null, null, null, null, null, null, null,
rdsService, null, null, null, null, null, null,
docDbService,
docDbService, null,
new CloudFormationResourceRegistry(List.of()));
}
@@ -0,0 +1,124 @@
package io.github.hectorvent.floci.services.cloudfront;
import io.github.hectorvent.floci.core.common.XmlParser;
import io.github.hectorvent.floci.services.cloudfront.model.CloudFrontFunction;
import io.github.hectorvent.floci.services.cloudfront.model.ContinuousDeploymentPolicy;
import io.github.hectorvent.floci.services.cloudfront.model.Distribution;
import jakarta.ws.rs.core.Response;
import org.junit.jupiter.api.Test;
import java.util.List;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
class CloudFrontControllerTest {
@Test
void listDistributionsStopsAtTheExactEndOfASecondPage() {
CloudFrontService service = mock(CloudFrontService.class);
Distribution first = distribution("A");
Distribution second = distribution("B");
Distribution third = distribution("C");
Distribution fourth = distribution("D");
when(service.listDistributions(null, 3))
.thenReturn(List.of(first, second, third));
when(service.listDistributions("B", 3))
.thenReturn(List.of(third, fourth));
when(service.listDistributions(null, Integer.MAX_VALUE))
.thenReturn(List.of(first, second, third, fourth));
CloudFrontController controller = new CloudFrontController(service);
try (Response firstPage = controller.listDistributions(null, 2);
Response secondPage = controller.listDistributions("B", 2)) {
String firstXml = (String) firstPage.getEntity();
String secondXml = (String) secondPage.getEntity();
assertTrue(firstXml.startsWith("<DistributionList "));
assertEquals("true", XmlParser.extractFirst(firstXml, "IsTruncated", null));
assertEquals("B", XmlParser.extractFirst(firstXml, "NextMarker", null));
assertEquals("4", XmlParser.extractFirst(firstXml, "Quantity", null));
assertTrue(secondXml.startsWith("<DistributionList "));
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 listFunctionsHonorsMaxItemsAndMarker() {
CloudFrontService service = mock(CloudFrontService.class);
CloudFrontFunction first = function("alpha");
CloudFrontFunction second = function("beta");
CloudFrontFunction third = function("gamma");
CloudFrontFunction fourth = function("omega");
when(service.getAccountId()).thenReturn("000000000000");
when(service.listFunctions(null, null, 3))
.thenReturn(List.of(first, second, third));
when(service.listFunctions(null, "beta", 3))
.thenReturn(List.of(third, fourth));
CloudFrontController controller = new CloudFrontController(service);
try (Response firstPage = controller.listFunctions(null, null, 2);
Response secondPage = controller.listFunctions(null, "beta", 2)) {
String firstXml = (String) firstPage.getEntity();
String secondXml = (String) secondPage.getEntity();
assertEquals("beta", XmlParser.extractFirst(firstXml, "NextMarker", null));
assertEquals(List.of("alpha", "beta"), XmlParser.extractAll(firstXml, "Name"));
assertTrue(XmlParser.extractAll(secondXml, "NextMarker").isEmpty());
assertEquals(List.of("gamma", "omega"), XmlParser.extractAll(secondXml, "Name"));
}
}
@Test
void continuousDeploymentPolicyQuantityReportsTheAccountTotal() {
CloudFrontService service = mock(CloudFrontService.class);
ContinuousDeploymentPolicy first = continuousDeploymentPolicy("A");
ContinuousDeploymentPolicy second = continuousDeploymentPolicy("B");
when(service.listContinuousDeploymentPolicies(null, 2))
.thenReturn(List.of(first, second));
when(service.listContinuousDeploymentPolicies(null, Integer.MAX_VALUE))
.thenReturn(List.of(first, second));
when(service.listContinuousDeploymentPolicies("A", 2))
.thenReturn(List.of(second));
CloudFrontController controller = new CloudFrontController(service);
try (Response firstPage = controller.listContinuousDeploymentPolicies(null, 1);
Response secondPage = controller.listContinuousDeploymentPolicies("A", 1)) {
String firstXml = (String) firstPage.getEntity();
String secondXml = (String) secondPage.getEntity();
assertEquals("2", XmlParser.extractFirst(firstXml, "Quantity", null));
assertEquals("A", XmlParser.extractFirst(firstXml, "NextMarker", null));
assertEquals("2", XmlParser.extractFirst(secondXml, "Quantity", null));
assertTrue(XmlParser.extractAll(secondXml, "NextMarker").isEmpty());
}
}
private static Distribution distribution(String id) {
Distribution distribution = new Distribution();
distribution.setId(id);
return distribution;
}
private static CloudFrontFunction function(String name) {
CloudFrontFunction function = new CloudFrontFunction();
function.setName(name);
return function;
}
private static ContinuousDeploymentPolicy continuousDeploymentPolicy(String id) {
ContinuousDeploymentPolicy policy = new ContinuousDeploymentPolicy();
policy.setId(id);
return policy;
}
}
@@ -0,0 +1,144 @@
package io.github.hectorvent.floci.services.cloudfront;
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpServer;
import io.github.hectorvent.floci.services.cloudfront.model.DefaultCacheBehavior;
import io.github.hectorvent.floci.services.cloudfront.model.Distribution;
import io.github.hectorvent.floci.services.cloudfront.model.DistributionConfig;
import io.github.hectorvent.floci.services.cloudfront.model.Origin;
import io.quarkus.test.junit.QuarkusTest;
import io.quarkus.test.junit.QuarkusTestProfile;
import io.quarkus.test.junit.TestProfile;
import jakarta.inject.Inject;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Test;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.charset.StandardCharsets;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicReference;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.equalTo;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
@QuarkusTest
@TestProfile(CloudFrontCustomOriginServingTest.PrivateOriginProfile.class)
class CloudFrontCustomOriginServingTest {
@Inject
CloudFrontService cloudFrontService;
private HttpServer originServer;
@AfterEach
void stopOrigin() {
if (originServer != null) {
originServer.stop(0);
}
}
@Test
void omitsQueryByDefaultAndForwardsResponseHeadersAndHeadMetadata() throws Exception {
AtomicReference<String> receivedQuery = new AtomicReference<>();
AtomicReference<String> receivedPath = new AtomicReference<>();
originServer = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0);
originServer.createContext("/", exchange -> respond(exchange, receivedQuery, receivedPath));
originServer.start();
Origin customOrigin = new Origin();
customOrigin.setId("custom-origin");
// The embedded port is deliberately wrong. CustomOriginConfig.HTTPPort is authoritative.
customOrigin.setDomainName("127.0.0.1:1");
customOrigin.setCustomOriginConfig(customOriginConfig(originServer.getAddress().getPort()));
DistributionConfig config = new DistributionConfig();
config.setEnabled(true);
config.setOrigins(List.of(customOrigin));
config.setDefaultCacheBehavior(defaultBehavior("custom-origin"));
Distribution distribution = new Distribution();
distribution.setConfig(config);
Distribution created = cloudFrontService.createDistribution(distribution, Map.of());
given()
.urlEncodingEnabled(false)
.header("Host", created.getDomainName())
.when()
.get("/resource?x=1&x=2&encoded=a%2Fb")
.then()
.statusCode(200)
.body(equalTo("origin-body"))
.header("Access-Control-Allow-Origin", equalTo("https://viewer.example"))
.header("Cache-Control", equalTo("public, max-age=60"))
.header("ETag", equalTo("\"origin-etag\""))
.header("X-Origin-Header", equalTo("preserved"));
assertNull(receivedQuery.get());
given()
.urlEncodingEnabled(false)
.header("Host", created.getDomainName())
.when()
.get("/encoded%2Fpath")
.then()
.statusCode(200);
assertEquals("/encoded%2Fpath", receivedPath.get());
given()
.header("Host", created.getDomainName())
.when()
.head("/resource")
.then()
.statusCode(200)
.header("Content-Length", equalTo("123"))
.body(equalTo(""));
}
private static void respond(HttpExchange exchange, AtomicReference<String> receivedQuery,
AtomicReference<String> receivedPath) throws IOException {
receivedQuery.set(exchange.getRequestURI().getRawQuery());
receivedPath.set(exchange.getRequestURI().getRawPath());
exchange.getResponseHeaders().add("Content-Type", "text/plain");
exchange.getResponseHeaders().add("Access-Control-Allow-Origin", "https://viewer.example");
exchange.getResponseHeaders().add("Cache-Control", "public, max-age=60");
exchange.getResponseHeaders().add("ETag", "\"origin-etag\"");
exchange.getResponseHeaders().add("X-Origin-Header", "preserved");
if ("HEAD".equals(exchange.getRequestMethod())) {
exchange.getResponseHeaders().add("Content-Length", "123");
exchange.sendResponseHeaders(200, -1);
} else {
byte[] body = "origin-body".getBytes(StandardCharsets.UTF_8);
exchange.sendResponseHeaders(200, body.length);
exchange.getResponseBody().write(body);
}
exchange.close();
}
private static Map<String, Object> customOriginConfig(int port) {
Map<String, Object> config = new LinkedHashMap<>();
config.put("HTTPPort", String.valueOf(port));
config.put("HTTPSPort", "443");
config.put("OriginProtocolPolicy", "http-only");
return config;
}
private static DefaultCacheBehavior defaultBehavior(String originId) {
DefaultCacheBehavior behavior = new DefaultCacheBehavior();
behavior.setTargetOriginId(originId);
behavior.setViewerProtocolPolicy("allow-all");
return behavior;
}
public static final class PrivateOriginProfile implements QuarkusTestProfile {
@Override
public Map<String, String> getConfigOverrides() {
return Map.of("floci.services.cloudfront.allowed-private-origin-hosts", "127.0.0.1");
}
}
}
@@ -0,0 +1,68 @@
package io.github.hectorvent.floci.services.cloudfront;
import io.github.hectorvent.floci.services.cloudfront.model.DefaultCacheBehavior;
import io.github.hectorvent.floci.services.cloudfront.model.Distribution;
import io.github.hectorvent.floci.services.cloudfront.model.DistributionConfig;
import io.github.hectorvent.floci.services.cloudfront.model.Origin;
import io.github.hectorvent.floci.services.s3.S3Service;
import io.quarkus.test.junit.QuarkusTest;
import io.quarkus.test.junit.QuarkusTestProfile;
import io.quarkus.test.junit.TestProfile;
import jakarta.inject.Inject;
import org.junit.jupiter.api.Test;
import java.nio.charset.StandardCharsets;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.containsString;
@QuarkusTest
@TestProfile(CloudFrontDisabledServingTest.CloudFrontDisabledProfile.class)
class CloudFrontDisabledServingTest {
@Inject
CloudFrontService cloudFrontService;
@Inject
S3Service s3Service;
@Test
void serviceDisablementBlocksViewerAndInternalRoutes() {
String suffix = Long.toString(System.nanoTime(), 36);
String bucket = "cf-service-disabled-" + suffix;
s3Service.createBucket(bucket, "us-east-1");
s3Service.putObject(bucket, "index.html", "MUST-NOT-SERVE".getBytes(StandardCharsets.UTF_8),
"text/html", Map.of());
Origin origin = new Origin();
origin.setId("s3-origin");
origin.setDomainName(bucket + ".s3.us-east-1.amazonaws.com");
origin.setS3OriginConfig(new LinkedHashMap<>(Map.of("OriginAccessIdentity", "")));
DefaultCacheBehavior behavior = new DefaultCacheBehavior();
behavior.setTargetOriginId(origin.getId());
behavior.setViewerProtocolPolicy("allow-all");
DistributionConfig config = new DistributionConfig();
config.setEnabled(true);
config.setDefaultRootObject("index.html");
config.setOrigins(List.of(origin));
config.setDefaultCacheBehavior(behavior);
Distribution distribution = new Distribution();
distribution.setConfig(config);
Distribution created = cloudFrontService.createDistribution(distribution, Map.of());
given().header("Host", created.getDomainName()).when().get("/")
.then().statusCode(400).body(containsString("ServiceNotAvailableException"));
given().when().get("/_cloudfront/" + created.getId() + "/")
.then().statusCode(400).body(containsString("ServiceNotAvailableException"));
}
public static final class CloudFrontDisabledProfile implements QuarkusTestProfile {
@Override
public Map<String, String> getConfigOverrides() {
return Map.of("floci.services.cloudfront.enabled", "false");
}
}
}
@@ -0,0 +1,438 @@
package io.github.hectorvent.floci.services.cloudfront;
import com.sun.net.httpserver.HttpServer;
import io.github.hectorvent.floci.services.cloudfront.model.CacheBehavior;
import io.github.hectorvent.floci.services.cloudfront.model.DefaultCacheBehavior;
import io.github.hectorvent.floci.services.cloudfront.model.Distribution;
import io.github.hectorvent.floci.services.cloudfront.model.DistributionConfig;
import io.github.hectorvent.floci.services.cloudfront.model.Origin;
import io.github.hectorvent.floci.services.s3.S3Service;
import io.github.hectorvent.floci.services.s3.model.PutObjectOptions;
import io.github.hectorvent.floci.services.s3.model.S3Object;
import io.quarkus.test.junit.QuarkusTest;
import jakarta.inject.Inject;
import org.junit.jupiter.api.Test;
import java.net.InetSocketAddress;
import java.nio.charset.StandardCharsets;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.nullValue;
import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* End-to-end tests for CloudFront distribution request-serving: a viewer request addressed to a
* distribution's domain (or alias) is routed to the matching origin and the content is returned,
* per the AWS CloudFront data-plane spec (default root object, path-pattern routing, custom-error
* SPA fallback, S3 and custom origins).
*
* <p>S3 origin content is seeded through the shared {@link S3Service} bean; distributions are created
* through the shared {@link CloudFrontService} bean; requests are driven over HTTP with a spoofed
* {@code Host} header so the {@link CloudFrontDistributionFilter} routes them.
*/
@QuarkusTest
class CloudFrontDistributionServingTest {
private static final String REGION = "us-east-1";
@Inject
S3Service s3Service;
@Inject
CloudFrontService cloudFrontService;
@Test
void servesRootObjectSubdirSpaFallbackAndPathRouting() {
String suffix = suffix();
String contentBucket = "cf-content-" + suffix;
String apiBucket = "cf-api-" + suffix;
String alias = "viewer-" + suffix + ".example.test";
String s3ShapedAlias = "viewer-" + suffix + ".localhost";
createBucket(contentBucket);
createBucket(apiBucket);
putObject(contentBucket, "index.html", "INDEX-ROOT-" + suffix, "text/html");
putObject(contentBucket, "assets/app.js", "APP-JS-" + suffix, "application/javascript");
putObject(contentBucket, "encoded key.txt", "ENCODED-KEY-" + suffix, "text/plain");
putObject(apiBucket, "api/data.json", "API-DATA-" + suffix, "application/json");
putObject(apiBucket, "/api//raw-data.json", "RAW-PATH-" + suffix, "application/json");
putObject(apiBucket, "question?v1", "ENCODED-QUESTION-" + suffix, "application/json");
DistributionConfig cfg = new DistributionConfig();
cfg.setEnabled(true);
cfg.setDefaultRootObject("index.html");
cfg.setAliases(List.of(alias, s3ShapedAlias));
cfg.setOrigins(List.of(
s3Origin("content-origin", contentBucket),
s3Origin("api-origin", apiBucket)));
cfg.setDefaultCacheBehavior(defaultBehavior("content-origin"));
cfg.setCacheBehaviors(List.of(
behavior("/api/*", "api-origin"),
behavior("question?*", "api-origin")));
cfg.setCustomErrorResponses(List.of(
customError(403, 200, "/index.html"),
customError(404, 200, "/index.html")));
Distribution dist = cloudFrontService.createDistribution(distribution(cfg), Map.of());
String host = dist.getDomainName();
// Root request → default root object from the S3 origin.
given().header("Host", host).when().get("/")
.then().statusCode(200).body(containsString("INDEX-ROOT-" + suffix));
// Subdirectory object, served as-is with its stored content type.
given().header("Host", host).when().get("/assets/app.js")
.then().statusCode(200)
.header("Content-Type", containsString("javascript"))
.body(containsString("APP-JS-" + suffix));
// URI encoding is decoded once for the in-process S3 key lookup.
given().urlEncodingEnabled(false).header("Host", host).when().get("/encoded%20key.txt")
.then().statusCode(200).body(containsString("ENCODED-KEY-" + suffix));
// Unknown deep path (a client-side SPA route) → 404 rewritten to 200 /index.html.
given().header("Host", host).when().get("/deep/spa/route")
.then().statusCode(200).body(containsString("INDEX-ROOT-" + suffix));
// Path-pattern behavior routes /api/* to the second origin.
given().header("Host", host).when().get("/api/data.json")
.then().statusCode(200).body(containsString("API-DATA-" + suffix));
// CloudFront normalizes the viewer path only for behavior selection. The selected origin
// still receives the original path, including repeated slashes.
given().urlEncodingEnabled(false).header("Host", host).when().get("/%2Fapi/%2Fraw-data.json")
.then().statusCode(200).body(containsString("RAW-PATH-" + suffix));
// An encoded question mark is object-key data, not the start of the already-separated query.
given().urlEncodingEnabled(false).header("Host", host).when().get("/question%3Fv1")
.then().statusCode(200).body(containsString("ENCODED-QUESTION-" + suffix));
// The same distribution is reachable via its alternate domain name (CNAME alias).
given().header("Host", alias).when().get("/")
.then().statusCode(200).body(containsString("INDEX-ROOT-" + suffix));
// A CloudFront alias that resembles an S3 virtual host must remain CloudFront-routed.
given().header("Host", s3ShapedAlias).when().get("/")
.then().statusCode(200).body(containsString("INDEX-ROOT-" + suffix));
// HEAD returns headers without a body.
given().header("Host", host).when().head("/assets/app.js")
.then().statusCode(200);
// The implementation-only controller path is not an alternate public endpoint.
given().when().get("/_cloudfront/" + dist.getId() + "/")
.then().statusCode(404);
}
@Test
void returnsNotFoundWhenNoCustomErrorResponseConfigured() {
String suffix = suffix();
String bucket = "cf-plain-" + suffix;
createBucket(bucket);
putObject(bucket, "index.html", "PLAIN-INDEX-" + suffix, "text/html");
DistributionConfig cfg = new DistributionConfig();
cfg.setEnabled(true);
cfg.setDefaultRootObject("index.html");
cfg.setOrigins(List.of(s3Origin("only-origin", bucket)));
cfg.setDefaultCacheBehavior(defaultBehavior("only-origin"));
Distribution dist = cloudFrontService.createDistribution(distribution(cfg), Map.of());
String host = dist.getDomainName();
// Sanity: the root object is served.
given().header("Host", host).when().get("/")
.then().statusCode(200).body(containsString("PLAIN-INDEX-" + suffix));
// Missing object with no matching CustomErrorResponse → the origin 404 is returned.
given().header("Host", host).when().get("/missing-object.txt")
.then().statusCode(404);
}
@Test
void doesNotServeDisabledDistributionThroughInternalRoute() {
String suffix = suffix();
String bucket = "cf-disabled-" + suffix;
String alias = bucket + ".localhost";
createBucket(bucket);
putObject(bucket, "index.html", "DISABLED-INDEX-" + suffix, "text/html");
DistributionConfig cfg = new DistributionConfig();
cfg.setEnabled(false);
cfg.setDefaultRootObject("index.html");
cfg.setAliases(List.of(alias));
cfg.setOrigins(List.of(s3Origin("only-origin", bucket)));
cfg.setDefaultCacheBehavior(defaultBehavior("only-origin"));
Distribution dist = cloudFrontService.createDistribution(distribution(cfg), Map.of());
given().header("Host", dist.getDomainName()).when().get("/")
.then().statusCode(404);
// The disabled alias remains owned by CloudFront and must not fall through to the S3
// virtual-host filter, even though it names a real bucket.
given().header("Host", alias).when().get("/index.html")
.then().statusCode(404);
given().when().get("/_cloudfront/" + dist.getId() + "/")
.then().statusCode(404).body(equalTo("Distribution not found."));
}
@Test
void servesDottedS3BucketWhoseNameContainsAnEndpointMarker() {
String suffix = suffix();
String shortBucket = "assets-" + suffix;
String dottedBucket = shortBucket + ".s3.example";
createBucket(shortBucket);
createBucket(dottedBucket);
putObject(shortBucket, "asset.txt", "WRONG-BUCKET", "text/plain");
putObject(dottedBucket, "asset.txt", "DOTTED-BUCKET", "text/plain");
DistributionConfig cfg = new DistributionConfig();
cfg.setEnabled(true);
cfg.setOrigins(List.of(s3Origin("dotted-origin", dottedBucket)));
cfg.setDefaultCacheBehavior(defaultBehavior("dotted-origin"));
Distribution dist = cloudFrontService.createDistribution(distribution(cfg), Map.of());
given().header("Host", dist.getDomainName()).when().get("/asset.txt")
.then().statusCode(200).body(equalTo("DOTTED-BUCKET"));
}
@Test
void rejectsUnrecognizedDottedS3OriginHost() {
String suffix = suffix();
String bucket = "sensitive-" + suffix;
createBucket(bucket);
putObject(bucket, "asset.txt", "MUST-NOT-SERVE", "text/plain");
Origin origin = new Origin();
origin.setId("invalid-origin");
origin.setDomainName(bucket + ".s3.attacker.invalid");
origin.setS3OriginConfig(new LinkedHashMap<>(Map.of("OriginAccessIdentity", "")));
DistributionConfig cfg = new DistributionConfig();
cfg.setEnabled(true);
cfg.setOrigins(List.of(origin));
cfg.setDefaultCacheBehavior(defaultBehavior(origin.getId()));
Distribution dist = cloudFrontService.createDistribution(distribution(cfg), Map.of());
given().header("Host", dist.getDomainName()).when().get("/asset.txt")
.then().statusCode(502);
}
@Test
void forwardsSafeS3ObjectHeadersWithoutStorageInternals() {
String suffix = suffix();
String bucket = "cf-object-headers-" + suffix;
String body = "S3-OBJECT-HEADERS-" + suffix;
createBucket(bucket);
S3Object object = s3Service.putObject(
bucket, "asset.txt", body.getBytes(StandardCharsets.UTF_8), "text/plain",
Map.of("source", "origin"),
new PutObjectOptions()
.withStorageClass("STANDARD_IA")
.withContentEncoding("identity")
.withContentDisposition("inline")
.withCacheControl("public, max-age=60")
.withServerSideEncryption("AES256")
.withChecksumAlgorithm("SHA256"));
DistributionConfig cfg = new DistributionConfig();
cfg.setEnabled(true);
cfg.setOrigins(List.of(s3Origin("only-origin", bucket)));
cfg.setDefaultCacheBehavior(defaultBehavior("only-origin"));
Distribution dist = cloudFrontService.createDistribution(distribution(cfg), Map.of());
String lastModified = DateTimeFormatter.RFC_1123_DATE_TIME
.withZone(ZoneOffset.UTC)
.format(object.getLastModified());
given().header("Host", dist.getDomainName()).when().get("/asset.txt")
.then().statusCode(200)
.header("Content-Type", containsString("text/plain"))
.header("Accept-Ranges", equalTo("bytes"))
.header("ETag", equalTo(object.getETag()))
.header("Last-Modified", equalTo(lastModified))
.header("Cache-Control", equalTo("public, max-age=60"))
.header("Content-Encoding", equalTo("identity"))
.header("Content-Disposition", equalTo("inline"))
.header("x-amz-storage-class", equalTo("STANDARD_IA"))
.header("x-amz-meta-source", equalTo("origin"))
.header("x-amz-server-side-encryption", nullValue())
.header("x-amz-checksum-sha256", nullValue())
.body(equalTo(body));
given().header("Host", dist.getDomainName()).when().head("/asset.txt")
.then().statusCode(200)
.header("ETag", equalTo(object.getETag()))
.header("Content-Length", equalTo(Integer.toString(body.getBytes(StandardCharsets.UTF_8).length)));
}
@Test
void returnsErrorPageOriginStatusWhenCustomErrorPageIsMissing() {
// AWS: if the configured custom error page is itself unavailable, CloudFront returns the
// status received from the error-page origin (here 404) — not the ResponseCode (200) override.
String suffix = suffix();
String bucket = "cf-missing-errpage-" + suffix;
createBucket(bucket);
putObject(bucket, "index.html", "ROOT-" + suffix, "text/html");
DistributionConfig cfg = new DistributionConfig();
cfg.setEnabled(true);
cfg.setDefaultRootObject("index.html");
cfg.setOrigins(List.of(s3Origin("only-origin", bucket)));
cfg.setDefaultCacheBehavior(defaultBehavior("only-origin"));
cfg.setCustomErrorResponses(List.of(customError(404, 200, "/does-not-exist.html")));
Distribution dist = cloudFrontService.createDistribution(distribution(cfg), Map.of());
given().header("Host", dist.getDomainName()).when().get("/some/missing/route")
.then().statusCode(404);
}
@Test
void blocksPrivateCustomOriginBeforeConnecting() throws Exception {
String suffix = suffix();
AtomicInteger hits = new AtomicInteger();
HttpServer privateOrigin = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0);
privateOrigin.createContext("/", exchange -> {
hits.incrementAndGet();
exchange.sendResponseHeaders(200, 0);
exchange.close();
});
privateOrigin.start();
try {
Map<String, Object> customOriginConfig = new LinkedHashMap<>();
customOriginConfig.put("HTTPPort", String.valueOf(privateOrigin.getAddress().getPort()));
customOriginConfig.put("HTTPSPort", "443");
customOriginConfig.put("OriginProtocolPolicy", "http-only");
Origin custom = new Origin();
custom.setId("custom-origin");
custom.setDomainName("127.0.0.1");
custom.setCustomOriginConfig(customOriginConfig);
DistributionConfig cfg = new DistributionConfig();
cfg.setEnabled(true);
cfg.setDefaultRootObject("index.html");
cfg.setOrigins(List.of(custom));
cfg.setDefaultCacheBehavior(defaultBehavior("custom-origin"));
Distribution dist = cloudFrontService.createDistribution(distribution(cfg), Map.of());
given().header("Host", dist.getDomainName()).when().get("/")
.then().statusCode(502);
assertEquals(0, hits.get(), "blocked private origins must not receive a connection");
} finally {
privateOrigin.stop(0);
}
}
@Test
void roundTripsCustomErrorResponsesThroughTheApi() {
// Validates that the CloudFront API parses and re-serializes CustomErrorResponses (needed for
// the SPA fallback) rather than dropping them (Quantity 0) as it did before.
String body = """
<?xml version="1.0" encoding="UTF-8"?>
<DistributionConfig xmlns="http://cloudfront.amazonaws.com/doc/2020-05-31/">
<CallerReference>cf-cer-roundtrip</CallerReference>
<DefaultRootObject>index.html</DefaultRootObject>
<Origins>
<Quantity>1</Quantity>
<Items>
<Origin>
<Id>o1</Id>
<DomainName>cer-bucket.s3.us-east-1.amazonaws.com</DomainName>
<OriginPath></OriginPath>
<S3OriginConfig><OriginAccessIdentity></OriginAccessIdentity></S3OriginConfig>
</Origin>
</Items>
</Origins>
<DefaultCacheBehavior>
<TargetOriginId>o1</TargetOriginId>
<ViewerProtocolPolicy>allow-all</ViewerProtocolPolicy>
</DefaultCacheBehavior>
<CustomErrorResponses>
<Quantity>1</Quantity>
<Items>
<CustomErrorResponse>
<ErrorCode>403</ErrorCode>
<ResponsePagePath>/index.html</ResponsePagePath>
<ResponseCode>200</ResponseCode>
<ErrorCachingMinTTL>10</ErrorCachingMinTTL>
</CustomErrorResponse>
</Items>
</CustomErrorResponses>
<Comment>cer round-trip</Comment>
<Enabled>true</Enabled>
</DistributionConfig>
""";
given()
.contentType("application/xml")
.body(body)
.when()
.post("/2020-05-31/distribution")
.then()
.statusCode(201)
.body(containsString("<CustomErrorResponse>"))
.body(containsString("<ErrorCode>403</ErrorCode>"))
.body(containsString("<ResponseCode>200</ResponseCode>"))
.body(containsString("<ResponsePagePath>/index.html</ResponsePagePath>"));
}
// ── Helpers ──────────────────────────────────────────────────────────────────
private void createBucket(String bucket) {
s3Service.createBucket(bucket, REGION);
}
private void putObject(String bucket, String key, String body, String contentType) {
s3Service.putObject(bucket, key, body.getBytes(StandardCharsets.UTF_8), contentType, Map.of());
}
private static Distribution distribution(DistributionConfig cfg) {
Distribution dist = new Distribution();
dist.setConfig(cfg);
return dist;
}
private static Origin s3Origin(String id, String bucket) {
Origin origin = new Origin();
origin.setId(id);
origin.setDomainName(bucket + ".s3." + REGION + ".amazonaws.com");
origin.setS3OriginConfig(new LinkedHashMap<>(Map.of("OriginAccessIdentity", "")));
return origin;
}
private static DefaultCacheBehavior defaultBehavior(String originId) {
DefaultCacheBehavior dcb = new DefaultCacheBehavior();
dcb.setTargetOriginId(originId);
dcb.setViewerProtocolPolicy("allow-all");
return dcb;
}
private static CacheBehavior behavior(String pattern, String originId) {
CacheBehavior cb = new CacheBehavior();
cb.setPathPattern(pattern);
cb.setTargetOriginId(originId);
cb.setViewerProtocolPolicy("allow-all");
return cb;
}
private static Map<String, Object> customError(int errorCode, int responseCode, String pagePath) {
Map<String, Object> cer = new LinkedHashMap<>();
cer.put("ErrorCode", String.valueOf(errorCode));
cer.put("ResponseCode", String.valueOf(responseCode));
cer.put("ResponsePagePath", pagePath);
return cer;
}
private static String suffix() {
return Long.toString(System.nanoTime(), 36);
}
}
@@ -0,0 +1,102 @@
package io.github.hectorvent.floci.services.cloudfront;
import io.quarkus.test.junit.QuarkusTest;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.CsvSource;
import org.junit.jupiter.params.provider.ValueSource;
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;
/** Verifies CloudFront REST XML payload roots against the AWS service model. */
@QuarkusTest
class CloudFrontManagementProtocolTest {
private static final String API = "/2020-05-31/";
@ParameterizedTest(name = "{0} returns {1}")
@CsvSource({
"distribution, DistributionList",
"cache-policy, CachePolicyList",
"origin-request-policy, OriginRequestPolicyList",
"response-headers-policy, ResponseHeadersPolicyList",
"origin-access-control, OriginAccessControlList",
"origin-access-identity/cloudfront, CloudFrontOriginAccessIdentityList",
"function, FunctionList",
"tagging?Resource=arn%3Aaws%3Acloudfront%3A%3A000000000000%3Adistribution%2Fmissing, Tags",
"continuous-deployment-policy, ContinuousDeploymentPolicyList",
"public-key, PublicKeyList",
"key-group, KeyGroupList",
"realtime-log-config, RealtimeLogConfigs",
"field-level-encryption, FieldLevelEncryptionList",
"field-level-encryption-profile, FieldLevelEncryptionProfileList"
})
void listOperationsUseTheirModeledPayloadRoot(String endpoint, String expectedRoot) {
given()
.when()
.get(API + endpoint)
.then()
.statusCode(200)
.body(hasXPath("local-name(/*)", equalTo(expectedRoot)))
.body(hasXPath("namespace-uri(/*)", equalTo(
"http://cloudfront.amazonaws.com/doc/2020-05-31/")));
}
@ParameterizedTest(name = "{0} omits unmodeled Marker and IsTruncated members")
@ValueSource(strings = {
"cache-policy",
"origin-request-policy",
"response-headers-policy",
"function",
"continuous-deployment-policy",
"public-key",
"key-group",
"field-level-encryption",
"field-level-encryption-profile"
})
void compactListPayloadsUseOnlyTheirModeledPaginationMembers(String endpoint) {
given()
.when()
.get(API + endpoint)
.then()
.statusCode(200)
.body(not(hasXPath("/*/*[local-name()='Marker']")))
.body(not(hasXPath("/*/*[local-name()='IsTruncated']")));
}
@Test
void realtimeLogListOmitsTheUnmodeledQuantityMember() {
given()
.when()
.get(API + "realtime-log-config")
.then()
.statusCode(200)
.body(not(hasXPath("/*/*[local-name()='Quantity']")))
.body(hasXPath("/*/*[local-name()='Marker']"))
.body(hasXPath("/*/*[local-name()='IsTruncated']"));
}
@Test
void createOriginAccessControlDoesNotDefaultRequiredConfiguration() {
String body = """
<OriginAccessControlConfig
xmlns="http://cloudfront.amazonaws.com/doc/2020-05-31/">
<Name>missing-required-fields</Name>
</OriginAccessControlConfig>
""";
given()
.contentType("application/xml")
.body(body)
.when()
.post(API + "origin-access-control")
.then()
.statusCode(400)
.body(hasXPath(
"//*[local-name()='Code']/text()",
equalTo("InvalidArgument")));
}
}
@@ -0,0 +1,255 @@
package io.github.hectorvent.floci.services.cloudfront;
import com.sun.net.httpserver.HttpServer;
import com.sun.net.httpserver.HttpsConfigurator;
import com.sun.net.httpserver.HttpsExchange;
import com.sun.net.httpserver.HttpsServer;
import io.github.hectorvent.floci.services.acm.CertificateGenerator;
import io.github.hectorvent.floci.services.acm.model.KeyAlgorithm;
import org.apache.hc.client5.http.DnsResolver;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.junit.jupiter.api.Test;
import javax.net.ssl.ExtendedSSLSession;
import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SNIHostName;
import javax.net.ssl.SNIServerName;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManagerFactory;
import java.io.IOException;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.UnknownHostException;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.charset.StandardCharsets;
import java.security.KeyStore;
import java.security.Security;
import java.security.cert.X509Certificate;
import java.time.Duration;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
class CloudFrontOriginHttpClientTest {
@Test
void rejectsPrivateAddressBeforeConnecting() throws Exception {
AtomicInteger hits = new AtomicInteger();
HttpServer server = server(hits);
try (CloudFrontOriginHttpClient client = new CloudFrontOriginHttpClient(
resolver(InetAddress.getByName("127.0.0.1")), List.of())) {
HttpRequest request = request("http://blocked.invalid:" + server.getAddress().getPort() + "/");
assertThrows(UnknownHostException.class,
() -> client.send(request, HttpResponse.BodyHandlers.ofByteArray()));
assertEquals(0, hits.get());
} finally {
server.stop(0);
}
}
@Test
void rejectsEveryMixedAnswerContainingABlockedAddress() throws Exception {
DnsResolver resolver = resolver(
InetAddress.getByName("8.8.8.8"),
InetAddress.getByName("127.0.0.1"));
try (CloudFrontOriginHttpClient client = new CloudFrontOriginHttpClient(resolver, List.of())) {
assertThrows(UnknownHostException.class, () -> client.send(
request("http://mixed.invalid:8080/"),
HttpResponse.BodyHandlers.ofByteArray()));
}
}
@Test
void connectsWithTheSingleValidatedResolutionAndPreservesHostHeader() throws Exception {
AtomicInteger hits = new AtomicInteger();
AtomicReference<String> hostHeader = new AtomicReference<>();
HttpServer server = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0);
server.createContext("/", exchange -> {
hits.incrementAndGet();
hostHeader.set(exchange.getRequestHeaders().getFirst("Host"));
byte[] body = "origin-ok".getBytes(StandardCharsets.UTF_8);
exchange.sendResponseHeaders(200, body.length);
exchange.getResponseBody().write(body);
exchange.close();
});
server.start();
AtomicInteger resolutions = new AtomicInteger();
DnsResolver resolver = new DnsResolver() {
@Override
public InetAddress[] resolve(String host) throws UnknownHostException {
if (resolutions.incrementAndGet() > 1) {
return new InetAddress[] { InetAddress.getByName("203.0.113.10") };
}
return new InetAddress[] { InetAddress.getByName("127.0.0.1") };
}
@Override
public String resolveCanonicalHostname(String host) {
return host;
}
};
try (CloudFrontOriginHttpClient client = new CloudFrontOriginHttpClient(
resolver, List.of("rebind.invalid"))) {
HttpResponse<byte[]> response = client.send(
request("http://rebind.invalid:" + server.getAddress().getPort() + "/"),
HttpResponse.BodyHandlers.ofByteArray());
assertEquals(200, response.statusCode());
assertArrayEquals("origin-ok".getBytes(StandardCharsets.UTF_8), response.body());
assertEquals(1, resolutions.get());
assertEquals(1, hits.get());
assertEquals("rebind.invalid:" + server.getAddress().getPort(), hostHeader.get());
} finally {
server.stop(0);
}
}
@Test
void doesNotFollowOriginRedirects() throws Exception {
AtomicInteger redirectedHits = new AtomicInteger();
HttpServer server = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0);
server.createContext("/start", exchange -> {
exchange.getResponseHeaders().add("Location", "/target");
exchange.sendResponseHeaders(302, -1);
exchange.close();
});
server.createContext("/target", exchange -> {
redirectedHits.incrementAndGet();
exchange.sendResponseHeaders(200, -1);
exchange.close();
});
server.start();
try (CloudFrontOriginHttpClient client = new CloudFrontOriginHttpClient(
resolver(InetAddress.getByName("127.0.0.1")), List.of("redirect.invalid"))) {
HttpResponse<byte[]> response = client.send(
request("http://redirect.invalid:" + server.getAddress().getPort() + "/start"),
HttpResponse.BodyHandlers.ofByteArray());
assertEquals(302, response.statusCode());
assertEquals(0, redirectedHits.get());
} finally {
server.stop(0);
}
}
@Test
void httpsPinningPreservesSniAndHostnameVerification() throws Exception {
if (Security.getProvider(BouncyCastleProvider.PROVIDER_NAME) == null) {
Security.addProvider(new BouncyCastleProvider());
}
CertificateGenerator generator = new CertificateGenerator();
CertificateGenerator.GeneratedCertificate generated = generator.generateSelfSignedCertificate(
"origin.invalid", List.of("origin.invalid"), KeyAlgorithm.RSA_2048);
X509Certificate certificate = generator.parseCertificate(generated.certificatePem());
SSLContext serverContext = serverSslContext(
certificate, generator.parsePrivateKey(generated.privateKeyPem()));
SSLContext clientContext = clientSslContext(certificate);
AtomicReference<String> hostHeader = new AtomicReference<>();
AtomicReference<String> requestedSni = new AtomicReference<>();
HttpsServer server = HttpsServer.create(new InetSocketAddress("127.0.0.1", 0), 0);
server.setHttpsConfigurator(new HttpsConfigurator(serverContext));
server.createContext("/", exchange -> {
hostHeader.set(exchange.getRequestHeaders().getFirst("Host"));
if (exchange instanceof HttpsExchange httpsExchange
&& httpsExchange.getSSLSession() instanceof ExtendedSSLSession sslSession) {
for (SNIServerName name : sslSession.getRequestedServerNames()) {
if (name instanceof SNIHostName sniHostName) {
requestedSni.set(sniHostName.getAsciiName());
}
}
}
exchange.sendResponseHeaders(200, -1);
exchange.close();
});
server.start();
DnsResolver resolver = resolver(InetAddress.getByName("127.0.0.1"));
try (CloudFrontOriginHttpClient client = new CloudFrontOriginHttpClient(
resolver, List.of("origin.invalid", "wrong.invalid"), clientContext)) {
int port = server.getAddress().getPort();
HttpResponse<byte[]> response = client.send(
request("https://origin.invalid:" + port + "/"),
HttpResponse.BodyHandlers.ofByteArray());
assertEquals(200, response.statusCode());
assertEquals("origin.invalid:" + port, hostHeader.get());
assertEquals("origin.invalid", requestedSni.get());
assertThrows(IOException.class, () -> client.send(
request("https://wrong.invalid:" + port + "/"),
HttpResponse.BodyHandlers.ofByteArray()));
} finally {
server.stop(0);
}
}
private static HttpServer server(AtomicInteger hits) throws Exception {
HttpServer server = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0);
server.createContext("/", exchange -> {
hits.incrementAndGet();
exchange.sendResponseHeaders(200, -1);
exchange.close();
});
server.start();
return server;
}
private static HttpRequest request(String uri) {
return HttpRequest.newBuilder(java.net.URI.create(uri))
.timeout(Duration.ofSeconds(5))
.GET()
.build();
}
private static DnsResolver resolver(InetAddress... addresses) {
return new DnsResolver() {
@Override
public InetAddress[] resolve(String host) {
return addresses.clone();
}
@Override
public String resolveCanonicalHostname(String host) {
return host;
}
};
}
private static SSLContext serverSslContext(
X509Certificate certificate, java.security.PrivateKey privateKey) throws Exception {
char[] password = "changeit".toCharArray();
KeyStore keyStore = KeyStore.getInstance("PKCS12");
keyStore.load(null, password);
keyStore.setKeyEntry("origin", privateKey, password,
new java.security.cert.Certificate[] { certificate });
KeyManagerFactory keyManagers = KeyManagerFactory.getInstance(
KeyManagerFactory.getDefaultAlgorithm());
keyManagers.init(keyStore, password);
SSLContext context = SSLContext.getInstance("TLS");
context.init(keyManagers.getKeyManagers(), null, null);
return context;
}
private static SSLContext clientSslContext(X509Certificate certificate) throws Exception {
KeyStore trustStore = KeyStore.getInstance("PKCS12");
trustStore.load(null, null);
trustStore.setCertificateEntry("origin", certificate);
TrustManagerFactory trustManagers = TrustManagerFactory.getInstance(
TrustManagerFactory.getDefaultAlgorithm());
trustManagers.init(trustStore);
SSLContext context = SSLContext.getInstance("TLS");
context.init(null, trustManagers.getTrustManagers(), null);
return context;
}
}
@@ -0,0 +1,129 @@
package io.github.hectorvent.floci.services.cloudfront;
import io.github.hectorvent.floci.services.cloudfront.model.Origin;
import org.junit.jupiter.api.Test;
import java.net.InetAddress;
import java.net.Inet6Address;
import java.net.URI;
import java.util.LinkedHashMap;
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.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
class CloudFrontOriginSecurityTest {
@Test
void blocksPrivateAndSpecialUseAddresses() throws Exception {
for (String address : new String[] {
"0.0.0.0", "127.0.0.1", "10.0.0.1", "172.16.0.1", "192.168.0.1",
"169.254.169.254", "100.64.0.1", "224.0.0.1", "240.0.0.1",
"::1", "fe80::1", "fc00::1", "2001:db8::1"
}) {
assertTrue(CloudFrontServingController.isBlockedOriginAddress(InetAddress.getByName(address)),
address + " must not be reachable as a default custom origin");
}
}
@Test
void permitsPublicAddresses() throws Exception {
assertFalse(CloudFrontServingController.isBlockedOriginAddress(InetAddress.getByName("8.8.8.8")));
assertFalse(CloudFrontServingController.isBlockedOriginAddress(
InetAddress.getByName("2606:4700:4700::1111")));
assertFalse(CloudFrontServingController.isBlockedOriginAddress(ipv4MappedAddress("8.8.8.8")));
}
@Test
void blocksPrivateAndSpecialUseIpv4MappedAddresses() throws Exception {
for (String address : new String[] {
"0.0.0.0", "127.0.0.1", "10.0.0.1", "172.16.0.1", "192.168.0.1",
"169.254.169.254", "100.64.0.1", "192.0.0.1", "192.0.2.1", "198.18.0.1",
"198.51.100.1", "203.0.113.1", "224.0.0.1", "240.0.0.1"
}) {
assertTrue(CloudFrontServingController.isBlockedOriginAddress(ipv4MappedAddress(address)),
"IPv4-mapped " + address + " must not be reachable as a default custom origin");
}
}
@Test
void configuredPortOverridesEmbeddedDomainPortAndRawQueryIsPreserved() {
URI target = CloudFrontServingController.buildCustomOriginUri(
"http", "127.0.0.1:1", 8080, "/a%2Fb", "x=1&x=2&encoded=a%2Fb");
assertEquals("127.0.0.1", target.getHost());
assertEquals(8080, target.getPort());
assertEquals("/a%2Fb", target.getRawPath());
assertEquals("x=1&x=2&encoded=a%2Fb", target.getRawQuery());
}
@Test
void matchViewerUsesTheViewerProtocolAndMatchingPort() {
Origin origin = customOrigin("match-viewer", 8080, 8443);
URI http = CloudFrontServingController.buildCustomOriginUri(
origin, "http", "/asset", null);
URI https = CloudFrontServingController.buildCustomOriginUri(
origin, "https", "/asset", null);
assertEquals("http", http.getScheme());
assertEquals(8080, http.getPort());
assertEquals("https", https.getScheme());
assertEquals(8443, https.getPort());
}
@Test
void extractsRawViewerPathWithoutDecodingOrNormalizingIt() {
String raw = CloudFrontServingController.rawViewerPath(
"//api//data%2Fraw.json?token=redacted");
assertEquals("//api//data%2Fraw.json", raw);
assertEquals("//api//data/raw.json", CloudFrontServingController.decodedViewerPath(raw));
}
@Test
void supportsBracketedIpv6Authorities() {
URI target = CloudFrontServingController.buildCustomOriginUri(
"https", "[2606:4700:4700::1111]:80", 443, "/", null);
assertEquals("[2606:4700:4700::1111]", target.getHost());
assertEquals(443, target.getPort());
}
@Test
void rejectsAuthorityInjectionAndMalformedPorts() {
assertThrows(IllegalArgumentException.class, () ->
CloudFrontServingController.buildCustomOriginUri(
"http", "user@example.com", 80, "/", null));
assertThrows(IllegalArgumentException.class, () ->
CloudFrontServingController.buildCustomOriginUri(
"http", "example.com/path", 80, "/", null));
assertThrows(IllegalArgumentException.class, () ->
CloudFrontServingController.buildCustomOriginUri(
"http", "example.com?token=secret", 80, "/", null));
assertThrows(IllegalArgumentException.class, () ->
CloudFrontServingController.buildCustomOriginUri(
"http", "example.com", 0, "/", null));
}
private static InetAddress ipv4MappedAddress(String address) throws Exception {
byte[] mapped = new byte[16];
mapped[10] = (byte) 0xff;
mapped[11] = (byte) 0xff;
System.arraycopy(InetAddress.getByName(address).getAddress(), 0, mapped, 12, 4);
return Inet6Address.getByAddress(null, mapped, -1);
}
private static Origin customOrigin(String policy, int httpPort, int httpsPort) {
Map<String, Object> config = new LinkedHashMap<>();
config.put("HTTPPort", Integer.toString(httpPort));
config.put("HTTPSPort", Integer.toString(httpsPort));
config.put("OriginProtocolPolicy", policy);
Origin origin = new Origin();
origin.setDomainName("origin.example.test");
origin.setCustomOriginConfig(config);
return origin;
}
}
@@ -0,0 +1,184 @@
package io.github.hectorvent.floci.services.cloudfront;
import io.github.hectorvent.floci.services.cloudfront.model.CacheBehavior;
import io.github.hectorvent.floci.services.cloudfront.model.DefaultCacheBehavior;
import io.github.hectorvent.floci.services.cloudfront.model.DistributionConfig;
import io.github.hectorvent.floci.services.cloudfront.model.Origin;
import org.junit.jupiter.api.Test;
import java.util.List;
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.assertTrue;
/** Verifies the CloudFront data-plane routing rules against the AWS spec. */
class CloudFrontRequestRouterTest {
// ── Path normalization (RFC 3986; collapse //, resolve ./..) ──────────────────
@Test
void normalizePathCollapsesSlashesAndResolvesDotSegments() {
assertEquals("/", CloudFrontRequestRouter.normalizePath(""));
assertEquals("/", CloudFrontRequestRouter.normalizePath("/"));
assertEquals("/a/b", CloudFrontRequestRouter.normalizePath("//a//b"));
assertEquals("/b", CloudFrontRequestRouter.normalizePath("/a/../b"));
assertEquals("/a/", CloudFrontRequestRouter.normalizePath("/a/b/.."));
assertEquals("/a/b", CloudFrontRequestRouter.normalizePath("/a/./b"));
assertEquals("/a/", CloudFrontRequestRouter.normalizePath("/a/."));
assertEquals("/", CloudFrontRequestRouter.normalizePath("/a/.."));
assertEquals("/a/b/", CloudFrontRequestRouter.normalizePath("/a/b/")); // trailing slash preserved
assertEquals("/a/b?x=1&y=2", CloudFrontRequestRouter.normalizePath("/a/b?x=1&y=2"));
}
// ── Path pattern matching: * / ? , case-sensitive, leading slash optional ─────
@Test
void pathPatternWildcardsMatchPerSpec() {
assertTrue(CloudFrontRequestRouter.pathPatternMatches("*.jpg", "/images/logo.jpg"));
assertTrue(CloudFrontRequestRouter.pathPatternMatches("images/*.jpg", "/images/logo.jpg"));
assertTrue(CloudFrontRequestRouter.pathPatternMatches("images/*.jpg", "/images/product1/logo.jpg"));
// ? matches exactly one character
assertTrue(CloudFrontRequestRouter.pathPatternMatches("a??.jpg", "/abe.jpg"));
assertFalse(CloudFrontRequestRouter.pathPatternMatches("a??.jpg", "/ant2.jpg"));
// case-sensitive: *.jpg does not match LOGO.JPG
assertFalse(CloudFrontRequestRouter.pathPatternMatches("*.jpg", "/LOGO.JPG"));
// leading slash is optional / ignored on the pattern
assertTrue(CloudFrontRequestRouter.pathPatternMatches("/images/*", "/images/a.png"));
// '*' (default behavior) matches everything
assertTrue(CloudFrontRequestRouter.pathPatternMatches("*", "/anything/at/all"));
// dot in the pattern is literal, not a regex wildcard
assertFalse(CloudFrontRequestRouter.pathPatternMatches("a.jpg", "/axjpg"));
}
@Test
void compiledPatternCacheReusesEntriesAndRemainsBounded() {
CloudFrontRequestRouter.clearPatternCache();
try {
assertTrue(CloudFrontRequestRouter.pathPatternMatches("assets/*.js", "/assets/app.js"));
assertEquals(1, CloudFrontRequestRouter.patternCacheSize());
assertTrue(CloudFrontRequestRouter.pathPatternMatches("assets/*.js", "/assets/vendor.js"));
assertEquals(1, CloudFrontRequestRouter.patternCacheSize());
for (int i = 0; i < 300; i++) {
CloudFrontRequestRouter.pathPatternMatches("tenant-" + i + "/*", "/unmatched");
}
assertEquals(256, CloudFrontRequestRouter.patternCacheSize());
} finally {
CloudFrontRequestRouter.clearPatternCache();
}
}
// ── Behavior selection: first match wins, default behavior evaluated LAST ─────
@Test
void matchTargetOriginIdEvaluatesBehaviorsInOrderThenDefaultLast() {
DistributionConfig cfg = new DistributionConfig();
cfg.setCacheBehaviors(List.of(
behavior("images/*.jpg", "jpg-origin"),
behavior("images/*", "images-origin")));
cfg.setDefaultCacheBehavior(defaultBehavior("default-origin"));
// /images/sample.gif fails the first pattern, matches the second (not the default).
assertEquals("images-origin", CloudFrontRequestRouter.matchTargetOriginId(cfg, "/images/sample.gif"));
// /images/photo.jpg matches the FIRST behavior (order matters).
assertEquals("jpg-origin", CloudFrontRequestRouter.matchTargetOriginId(cfg, "/images/photo.jpg"));
// No behavior matches → default behavior (processed last).
assertEquals("default-origin", CloudFrontRequestRouter.matchTargetOriginId(cfg, "/index.html"));
}
@Test
void normalizedDirectoryPathRetainsSlashForBehaviorMatching() {
DistributionConfig cfg = new DistributionConfig();
cfg.setCacheBehaviors(List.of(behavior("a/", "directory-origin")));
cfg.setDefaultCacheBehavior(defaultBehavior("default-origin"));
String normalized = CloudFrontRequestRouter.normalizePath("/a/b/..");
assertEquals("/a/", normalized);
assertEquals("directory-origin", CloudFrontRequestRouter.matchTargetOriginId(cfg, normalized));
}
// ── Default root object: ROOT ONLY (never appended to subdirectories) ─────────
@Test
void defaultRootObjectAppliesOnlyToTheRoot() {
// root → default root object, with origin path prepended
assertEquals("app/index.html",
CloudFrontRequestRouter.resolveOriginKey(null, "/", "app/index.html"));
assertEquals("prod/index.html",
CloudFrontRequestRouter.resolveOriginKey("/prod", "/", "index.html"));
// subdirectory does NOT get the default root object appended (differs from S3 website)
assertEquals("install/",
CloudFrontRequestRouter.resolveOriginKey(null, "/install/", "index.html"));
// a normal object request is served as-is under the origin path
assertEquals("prod/shell/bootstrap.js",
CloudFrontRequestRouter.resolveOriginKey("/prod", "/shell/bootstrap.js", "index.html"));
}
@Test
void resolveForwardUriKeepsLeadingSlashAndAppliesRootObjectAtRootOnly() {
// Forward URI keeps its leading slash (custom-origin form) and applies the default root
// object only at the root — for custom origins as well as S3.
assertEquals("/index.html",
CloudFrontRequestRouter.resolveForwardUri(null, "/", "index.html"));
assertEquals("/prod/index.html",
CloudFrontRequestRouter.resolveForwardUri("/prod", "/", "index.html"));
assertEquals("/shell/bootstrap.js",
CloudFrontRequestRouter.resolveForwardUri(null, "/shell/bootstrap.js", "index.html"));
// no default root object at the root → the root path is forwarded unchanged
assertEquals("/", CloudFrontRequestRouter.resolveForwardUri(null, "/", null));
}
// ── Origin resolution + S3 bucket extraction ─────────────────────────────────
@Test
void findsOriginByIdAndClassifiesS3() {
Origin s3 = new Origin();
s3.setId("s3-origin");
s3.setDomainName("my-bucket.s3.us-east-1.amazonaws.com");
s3.setS3OriginConfig(java.util.Map.of("originAccessIdentity", ""));
DistributionConfig cfg = new DistributionConfig();
cfg.setOrigins(List.of(s3));
assertEquals(s3, CloudFrontRequestRouter.findOrigin(cfg, "s3-origin"));
assertNull(CloudFrontRequestRouter.findOrigin(cfg, "missing"));
assertTrue(CloudFrontRequestRouter.isS3Origin(s3));
}
@Test
void extractsBucketFromS3OriginDomainForms() {
assertEquals("my-bucket",
CloudFrontRequestRouter.bucketFromS3Domain("my-bucket.s3.us-east-1.amazonaws.com"));
assertEquals("my-bucket",
CloudFrontRequestRouter.bucketFromS3Domain("my-bucket.s3.amazonaws.com"));
assertEquals("my-bucket",
CloudFrontRequestRouter.bucketFromS3Domain("my-bucket.s3-website-us-east-1.amazonaws.com"));
assertEquals("assets.s3.example",
CloudFrontRequestRouter.bucketFromS3Domain(
"assets.s3.example.s3.us-east-1.amazonaws.com"));
assertEquals("foo.s3-website-bar",
CloudFrontRequestRouter.bucketFromS3Domain(
"foo.s3-website-bar.s3.us-east-1.amazonaws.com"));
assertNull(CloudFrontRequestRouter.bucketFromS3Domain("sensitive.attacker.invalid"));
assertNull(CloudFrontRequestRouter.bucketFromS3Domain("sensitive.s3.attacker.invalid"));
assertNull(CloudFrontRequestRouter.bucketFromS3Domain("sensitive.s3-attacker.invalid"));
assertNull(CloudFrontRequestRouter.bucketFromS3Domain("sensitive.s3.amazonaws.com:invalid"));
assertNull(CloudFrontRequestRouter.bucketFromS3Domain("https://sensitive.s3.amazonaws.com"));
}
private static CacheBehavior behavior(String pattern, String originId) {
CacheBehavior b = new CacheBehavior();
b.setPathPattern(pattern);
b.setTargetOriginId(originId);
return b;
}
private static DefaultCacheBehavior defaultBehavior(String originId) {
DefaultCacheBehavior b = new DefaultCacheBehavior();
b.setTargetOriginId(originId);
return b;
}
}
@@ -0,0 +1,235 @@
package io.github.hectorvent.floci.services.cloudfront;
import io.github.hectorvent.floci.services.cloudfront.model.DefaultCacheBehavior;
import io.github.hectorvent.floci.services.cloudfront.model.CloudFrontOriginAccessIdentity;
import io.github.hectorvent.floci.services.cloudfront.model.Distribution;
import io.github.hectorvent.floci.services.cloudfront.model.DistributionConfig;
import io.github.hectorvent.floci.services.cloudfront.model.Origin;
import io.github.hectorvent.floci.services.cloudfront.model.OriginAccessControl;
import io.github.hectorvent.floci.services.s3.S3Service;
import io.quarkus.test.junit.QuarkusTest;
import io.quarkus.test.junit.QuarkusTestProfile;
import io.quarkus.test.junit.TestProfile;
import jakarta.inject.Inject;
import org.junit.jupiter.api.Test;
import java.nio.charset.StandardCharsets;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.equalTo;
@QuarkusTest
@TestProfile(CloudFrontS3AuthServingTest.S3AuthProfile.class)
class CloudFrontS3AuthServingTest {
@Inject
CloudFrontService cloudFrontService;
@Inject
S3Service s3Service;
@Test
void enforcesAnonymousS3OriginReadAccess() {
String suffix = Long.toString(System.nanoTime(), 36);
Distribution privateDistribution =
distribution("cf-private-" + suffix, false, null, null);
Distribution publicDistribution =
distribution("cf-public-" + suffix, true, null, null);
given().header("Host", privateDistribution.getDomainName()).when().get("/index.html")
.then().statusCode(403);
given().header("Host", publicDistribution.getDomainName()).when().get("/index.html")
.then().statusCode(200).body(equalTo("PUBLIC-ORIGIN"));
}
@Test
void servesPrivateS3OriginThroughOacPolicyGrant() {
String suffix = Long.toString(System.nanoTime(), 36);
String bucket = "cf-oac-" + suffix;
OriginAccessControl oac = new OriginAccessControl();
oac.setName("oac-" + suffix);
oac.setSigningBehavior("always");
oac.setSigningProtocol("sigv4");
oac.setOriginAccessControlOriginType("s3");
oac = cloudFrontService.createOriginAccessControl(oac);
Distribution distribution = distribution(bucket, false, oac.getId(), null);
s3Service.putBucketPolicy(
bucket, oacReadPolicy(bucket, distribution.getArn()));
given().header("Host", distribution.getDomainName()).when().get("/index.html")
.then().statusCode(200).body(equalTo("PRIVATE-ORIGIN"));
}
@Test
void servesPrivateS3OriginThroughOaiObjectAclGrant() {
String suffix = Long.toString(System.nanoTime(), 36);
String bucket = "cf-oai-" + suffix;
CloudFrontOriginAccessIdentity oai = new CloudFrontOriginAccessIdentity();
oai.setCallerReference("oai-" + suffix);
oai.setComment("Private origin access");
oai = cloudFrontService.createCloudFrontOriginAccessIdentity(oai);
Distribution distribution = distribution(
bucket,
false,
null,
"origin-access-identity/cloudfront/" + oai.getId());
s3Service.putObjectAcl(
bucket,
"index.html",
null,
canonicalReadAcl(oai.getS3CanonicalUserId()),
null,
null,
null,
null,
null,
null);
given().header("Host", distribution.getDomainName()).when().get("/index.html")
.then().statusCode(200).body(equalTo("PRIVATE-ORIGIN"));
}
@Test
void oacNeverSigningRequiresPublicS3Access() {
String suffix = Long.toString(System.nanoTime(), 36);
String bucket = "cf-oac-never-" + suffix;
OriginAccessControl oac = new OriginAccessControl();
oac.setName("oac-never-" + suffix);
oac.setSigningBehavior("never");
oac.setSigningProtocol("sigv4");
oac.setOriginAccessControlOriginType("s3");
oac = cloudFrontService.createOriginAccessControl(oac);
Distribution distribution = distribution(bucket, false, oac.getId(), null);
s3Service.putBucketPolicy(
bucket, oacReadPolicy(bucket, distribution.getArn()));
given().header("Host", distribution.getDomainName()).when().get("/index.html")
.then().statusCode(403);
}
@Test
void oacNoOverridePreservesViewerAuthorization() {
String suffix = Long.toString(System.nanoTime(), 36);
String bucket = "cf-oac-viewer-auth-" + suffix;
OriginAccessControl oac = new OriginAccessControl();
oac.setName("oac-viewer-auth-" + suffix);
oac.setSigningBehavior("no-override");
oac.setSigningProtocol("sigv4");
oac.setOriginAccessControlOriginType("s3");
oac = cloudFrontService.createOriginAccessControl(oac);
Distribution distribution = distribution(bucket, false, oac.getId(), null);
given()
.header("Host", distribution.getDomainName())
.header("Authorization", viewerAuthorization("test"))
.when()
.get("/index.html")
.then()
.statusCode(200)
.body(equalTo("PRIVATE-ORIGIN"));
given()
.header("Host", distribution.getDomainName())
.header("Authorization", viewerAuthorization("unknown"))
.when()
.get("/index.html")
.then()
.statusCode(403);
}
private Distribution distribution(
String bucket, boolean publicRead, String oacId, String originAccessIdentity) {
s3Service.createBucket(bucket, "us-east-1");
String body = publicRead ? "PUBLIC-ORIGIN" : "PRIVATE-ORIGIN";
s3Service.putObject(bucket, "index.html", body.getBytes(StandardCharsets.UTF_8),
"text/html", Map.of());
if (publicRead) {
s3Service.putBucketPolicy(bucket, publicReadPolicy(bucket));
}
Origin origin = new Origin();
origin.setId("s3-origin");
origin.setDomainName(bucket + ".s3.us-east-1.amazonaws.com");
origin.setOriginAccessControlId(oacId);
origin.setS3OriginConfig(new LinkedHashMap<>(Map.of(
"OriginAccessIdentity",
originAccessIdentity != null ? originAccessIdentity : "")));
DefaultCacheBehavior behavior = new DefaultCacheBehavior();
behavior.setTargetOriginId(origin.getId());
behavior.setViewerProtocolPolicy("allow-all");
DistributionConfig config = new DistributionConfig();
config.setEnabled(true);
config.setOrigins(List.of(origin));
config.setDefaultCacheBehavior(behavior);
Distribution distribution = new Distribution();
distribution.setConfig(config);
return cloudFrontService.createDistribution(distribution, Map.of());
}
private static String publicReadPolicy(String bucket) {
return """
{
"Version": "2012-10-17",
"Statement": {
"Effect": "Allow",
"Principal": "*",
"Action": "s3:GetObject",
"Resource": "arn:aws:s3:::%s/*"
}
}
""".formatted(bucket);
}
private static String oacReadPolicy(String bucket, String distributionArn) {
return """
{
"Version": "2012-10-17",
"Statement": {
"Effect": "Allow",
"Principal": {"Service": "cloudfront.amazonaws.com"},
"Action": "s3:GetObject",
"Resource": "arn:aws:s3:::%s/*",
"Condition": {
"StringEquals": {"AWS:SourceArn": "%s"}
}
}
}
""".formatted(bucket, distributionArn);
}
private static String canonicalReadAcl(String canonicalUserId) {
return """
<AccessControlPolicy>
<AccessControlList>
<Grant>
<Grantee xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:type="CanonicalUser">
<ID>%s</ID>
</Grantee>
<Permission>READ</Permission>
</Grant>
</AccessControlList>
</AccessControlPolicy>
""".formatted(canonicalUserId);
}
private static String viewerAuthorization(String accessKeyId) {
return "AWS4-HMAC-SHA256 Credential=" + accessKeyId
+ "/20260730/us-east-1/s3/aws4_request, "
+ "SignedHeaders=host;x-amz-date, Signature=abc123";
}
public static final class S3AuthProfile implements QuarkusTestProfile {
@Override
public Map<String, String> getConfigOverrides() {
return Map.of("floci.services.s3.enforce-auth", "true");
}
}
}
@@ -1,16 +1,24 @@
package io.github.hectorvent.floci.services.cloudfront;
import io.github.hectorvent.floci.config.EmulatorConfig;
import io.github.hectorvent.floci.core.storage.InMemoryStorage;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend;
import io.github.hectorvent.floci.core.storage.StorageFactory;
import io.github.hectorvent.floci.services.cloudfront.model.CloudFrontOriginAccessIdentity;
import io.github.hectorvent.floci.services.cloudfront.model.Distribution;
import io.github.hectorvent.floci.services.cloudfront.model.DistributionConfig;
import io.github.hectorvent.floci.services.cloudfront.model.Origin;
import io.github.hectorvent.floci.services.cloudfront.model.OriginAccessControl;
import io.github.hectorvent.floci.services.cloudfront.model.StreamingDistribution;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
import java.util.List;
import java.util.Map;
import static org.junit.jupiter.api.Assertions.assertEquals;
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.Mockito.when;
@@ -21,7 +29,7 @@ class CloudFrontServiceTest {
private CloudFrontService serviceWithDomainSuffix(String domainSuffix) {
StorageFactory storageFactory = Mockito.mock(StorageFactory.class);
when(storageFactory.create(Mockito.anyString(), Mockito.anyString(), Mockito.any()))
.thenReturn(AccountAwareStorageBackend.inMemory("000000000000"));
.thenAnswer(invocation -> AccountAwareStorageBackend.inMemory("000000000000"));
EmulatorConfig config = Mockito.mock(EmulatorConfig.class);
var servicesConfig = Mockito.mock(EmulatorConfig.ServicesConfig.class);
@@ -64,4 +72,227 @@ class CloudFrontServiceTest {
assertTrue(sd.getDomainName().endsWith(".cloudfront.local"),
"Expected configured suffix, got: " + sd.getDomainName());
}
@Test
void findByHostMatchesDomainNameAndAliasIgnoringPort() {
CloudFrontService service = serviceWithDomainSuffix("cloudfront.net");
DistributionConfig cfg = new DistributionConfig();
cfg.setEnabled(true);
cfg.setAliases(List.of("viewer.example.test"));
Distribution dist = new Distribution();
dist.setConfig(cfg);
dist = service.createDistribution(dist, Map.of());
// Matches the assigned CloudFront domain name, with or without a port.
assertEquals(dist.getId(), service.findByHost(dist.getDomainName()).getId());
assertEquals(dist.getId(), service.findByHost(dist.getDomainName() + ":4566").getId());
// Matches a configured alias, case-insensitively and ignoring the port.
assertEquals(dist.getId(), service.findByHost("viewer.example.test").getId());
assertEquals(dist.getId(), service.findByHost("VIEWER.EXAMPLE.TEST:8443").getId());
// No match for an unrelated host.
assertNull(service.findByHost("unrelated.example.test"));
assertNull(service.findByHost(null));
}
@Test
void findByHostRetainsOwnershipForDisabledDistribution() {
CloudFrontService service = serviceWithDomainSuffix("cloudfront.net");
DistributionConfig cfg = new DistributionConfig();
cfg.setEnabled(false);
cfg.setAliases(List.of("disabled.example.test"));
Distribution dist = new Distribution();
dist.setConfig(cfg);
dist = service.createDistribution(dist, Map.of());
assertEquals(dist.getId(), service.findByHost(dist.getDomainName()).getId());
assertEquals(dist.getId(), service.findByHost("disabled.example.test").getId());
}
@Test
void rejectsDuplicateAliasOnCreateAndUpdate() {
CloudFrontService service = serviceWithDomainSuffix("cloudfront.net");
Distribution owner = service.createDistribution(
distribution(true, List.of("shared.example.test")), Map.of());
AwsException createError = assertThrows(AwsException.class, () -> service.createDistribution(
distribution(true, List.of("SHARED.EXAMPLE.TEST")), Map.of()));
assertEquals("CNAMEAlreadyExists", createError.getErrorCode());
Distribution other = service.createDistribution(
distribution(true, List.of("other.example.test")), Map.of());
AwsException updateError = assertThrows(AwsException.class, () -> service.updateDistribution(
other.getId(), other.getEtag(), distribution(true, List.of("shared.example.test"))));
assertEquals("CNAMEAlreadyExists", updateError.getErrorCode());
assertEquals(owner.getId(), service.findByHost("shared.example.test").getId());
assertEquals(other.getId(), service.findByHost("other.example.test").getId());
}
@Test
void associateAliasTransfersOwnershipAtomically() {
CloudFrontService service = serviceWithDomainSuffix("cloudfront.net");
Distribution owner = service.createDistribution(
distribution(false, List.of("move.example.test")), Map.of());
Distribution target = service.createDistribution(distribution(true, List.of()), Map.of());
service.associateAlias(target.getId(), "MOVE.EXAMPLE.TEST");
assertTrue(service.getDistribution(owner.getId()).getConfig().getAliases().isEmpty());
assertEquals(target.getId(), service.findByHost("move.example.test").getId());
}
@Test
void wildcardAliasesMatchSubdomainsAndPreferMoreSpecificNames() {
CloudFrontService service = serviceWithDomainSuffix("cloudfront.net");
Distribution wildcard = service.createDistribution(
distribution(true, List.of("*.example.test")), Map.of());
Distribution specificWildcard = service.createDistribution(
distribution(true, List.of("*.shop.example.test")), Map.of());
Distribution exact = service.createDistribution(
distribution(true, List.of("marketing.example.test")), Map.of());
assertEquals(wildcard.getId(), service.findByHost("www.example.test").getId());
assertEquals(specificWildcard.getId(), service.findByHost("item.shop.example.test").getId());
assertEquals(exact.getId(), service.findByHost("marketing.example.test").getId());
// A wildcard replaces exactly one label, so it covers neither a higher nor a lower level:
// "*.example.test" matches www.example.test but not a.b.example.test, and not the apex.
// Per AWS: "you can't add alternate domain names that are at levels higher or lower than
// the wildcard. For example, you can't add ... example.com or marketing.product.example.com."
assertNull(service.findByHost("a.b.example.test"));
assertNull(service.findByHost("example.test"));
// ...and the deeper wildcard is likewise single-level.
assertNull(service.findByHost("a.b.shop.example.test"));
}
@Test
void validatesRequiredOriginAccessControlConfiguration() {
CloudFrontService service = serviceWithDomainSuffix("cloudfront.net");
OriginAccessControl missingName = originAccessControl();
missingName.setName(null);
assertInvalidOriginAccessControl(service, missingName);
OriginAccessControl longName = originAccessControl();
longName.setName("x".repeat(65));
assertInvalidOriginAccessControl(service, longName);
OriginAccessControl invalidProtocol = originAccessControl();
invalidProtocol.setSigningProtocol("sigv2");
assertInvalidOriginAccessControl(service, invalidProtocol);
OriginAccessControl invalidBehavior = originAccessControl();
invalidBehavior.setSigningBehavior("sometimes");
assertInvalidOriginAccessControl(service, invalidBehavior);
OriginAccessControl invalidOriginType = originAccessControl();
invalidOriginType.setOriginAccessControlOriginType("custom");
assertInvalidOriginAccessControl(service, invalidOriginType);
}
@Test
void validatesOriginAccessControlConfigurationOnUpdate() {
CloudFrontService service = serviceWithDomainSuffix("cloudfront.net");
OriginAccessControl existing =
service.createOriginAccessControl(originAccessControl());
OriginAccessControl invalid = originAccessControl();
invalid.setSigningBehavior(null);
AwsException error = assertThrows(AwsException.class,
() -> service.updateOriginAccessControl(
existing.getId(), existing.getEtag(), invalid));
assertEquals("InvalidArgument", error.getErrorCode());
assertEquals("test-oac", service.getOriginAccessControl(existing.getId()).getName());
}
@Test
void rejectsDeletingOriginAccessControlUsedByDistribution() {
CloudFrontService service = serviceWithDomainSuffix("cloudfront.net");
OriginAccessControl oac = service.createOriginAccessControl(originAccessControl());
Origin origin = new Origin();
origin.setOriginAccessControlId(oac.getId());
Distribution distribution = distribution(false, List.of());
distribution.getConfig().setOrigins(List.of(origin));
service.createDistribution(distribution, Map.of());
AwsException error = assertThrows(AwsException.class,
() -> service.deleteOriginAccessControl(oac.getId(), oac.getEtag()));
assertEquals("OriginAccessControlInUse", error.getErrorCode());
assertEquals(409, error.getHttpStatus());
assertEquals(oac.getId(), service.getOriginAccessControl(oac.getId()).getId());
}
@Test
void rejectsDeletingOriginAccessIdentityUsedByDistribution() {
CloudFrontService service = serviceWithDomainSuffix("cloudfront.net");
CloudFrontOriginAccessIdentity oai = originAccessIdentity(service);
Origin origin = new Origin();
origin.setS3OriginConfig(Map.of(
"OriginAccessIdentity",
"origin-access-identity/cloudfront/" + oai.getId()));
Distribution distribution = distribution(false, List.of());
distribution.getConfig().setOrigins(List.of(origin));
service.createDistribution(distribution, Map.of());
AwsException error = assertThrows(AwsException.class,
() -> service.deleteCloudFrontOriginAccessIdentity(
oai.getId(), oai.getEtag()));
assertEquals("CloudFrontOriginAccessIdentityInUse", error.getErrorCode());
assertEquals(409, error.getHttpStatus());
assertEquals(oai.getId(),
service.getCloudFrontOriginAccessIdentity(oai.getId()).getId());
}
@Test
void rejectsDeletingOriginAccessIdentityUsedByStreamingDistribution() {
CloudFrontService service = serviceWithDomainSuffix("cloudfront.net");
CloudFrontOriginAccessIdentity oai = originAccessIdentity(service);
StreamingDistribution distribution = new StreamingDistribution();
distribution.setS3OriginAccessIdentity(
"/origin-access-identity/cloudfront/" + oai.getId());
service.createStreamingDistribution(distribution);
AwsException error = assertThrows(AwsException.class,
() -> service.deleteCloudFrontOriginAccessIdentity(
oai.getId(), oai.getEtag()));
assertEquals("CloudFrontOriginAccessIdentityInUse", error.getErrorCode());
assertEquals(409, error.getHttpStatus());
}
private static Distribution distribution(boolean enabled, List<String> aliases) {
DistributionConfig config = new DistributionConfig();
config.setEnabled(enabled);
config.setAliases(aliases);
Distribution distribution = new Distribution();
distribution.setConfig(config);
return distribution;
}
private static OriginAccessControl originAccessControl() {
OriginAccessControl oac = new OriginAccessControl();
oac.setName("test-oac");
oac.setSigningProtocol("sigv4");
oac.setSigningBehavior("always");
oac.setOriginAccessControlOriginType("s3");
return oac;
}
private static CloudFrontOriginAccessIdentity originAccessIdentity(
CloudFrontService service) {
CloudFrontOriginAccessIdentity oai = new CloudFrontOriginAccessIdentity();
oai.setCallerReference("test-reference");
return service.createCloudFrontOriginAccessIdentity(oai);
}
private static void assertInvalidOriginAccessControl(
CloudFrontService service, OriginAccessControl oac) {
AwsException error = assertThrows(AwsException.class,
() -> service.createOriginAccessControl(oac));
assertEquals("InvalidArgument", error.getErrorCode());
assertEquals(400, error.getHttpStatus());
}
}
@@ -35,6 +35,23 @@ class S3AclPolicyTest {
assertTrue(policy.grants().getFirst().allowsPublicRead());
}
@Test
void parsesCanonicalUserReadGrant() {
S3AclPolicy policy = parse(acl("""
<Grant>
<Grantee xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:type="CanonicalUser">
<ID>cloudfront-canonical-id</ID>
</Grantee>
<Permission>READ</Permission>
</Grant>
"""));
S3AclPolicy.Grant grant = policy.grants().getFirst();
assertEquals("cloudfront-canonical-id", grant.grantee().id());
assertTrue(grant.allowsCanonicalUserRead("cloudfront-canonical-id"));
}
@Test
void ignoresGrantOutsideAccessControlList() {
String grant = groupGrant(S3AclPolicy.ALL_USERS_GROUP_URI, "READ");
@@ -3,6 +3,9 @@ package io.github.hectorvent.floci.services.s3;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.jupiter.api.Test;
import java.util.Map;
import static io.github.hectorvent.floci.services.s3.S3PublicAccessEvaluator.PublicAccessDecision.ALLOW;
import static io.github.hectorvent.floci.services.s3.S3PublicAccessEvaluator.PublicAccessDecision.DENY;
import static io.github.hectorvent.floci.services.s3.S3PublicAccessEvaluator.PublicAccessDecision.NEUTRAL;
import static org.junit.jupiter.api.Assertions.assertEquals;
@@ -99,6 +102,78 @@ class S3PublicAccessEvaluatorTest {
OBJECT_MAPPER, policy, "s3:GetObject", OBJECT_ARN));
}
@Test
void cloudFrontServicePrincipalRequiresMatchingSourceArn() {
String distributionArn =
"arn:aws:cloudfront::000000000000:distribution/EDISTRIBUTION";
String policy = """
{"Version":"2012-10-17","Statement":{
"Effect":"Allow",
"Principal":{"Service":"cloudfront.amazonaws.com"},
"Action":"s3:GetObject",
"Resource":"arn:aws:s3:::public-bucket/*",
"Condition":{"StringEquals":{"AWS:SourceArn":"%s"}}
}}""".formatted(distributionArn);
assertEquals(ALLOW, S3PublicAccessEvaluator.principalPolicyDecision(
OBJECT_MAPPER, policy, "Service", "cloudfront.amazonaws.com",
"s3:GetObject", OBJECT_ARN, Map.of("aws:sourcearn", distributionArn)));
assertEquals(NEUTRAL, S3PublicAccessEvaluator.principalPolicyDecision(
OBJECT_MAPPER, policy, "Service", "cloudfront.amazonaws.com",
"s3:GetObject", OBJECT_ARN,
Map.of("AWS:SourceArn",
"arn:aws:cloudfront::000000000000:distribution/EOTHER")));
}
@Test
void cloudFrontOaiPrincipalMatchesAwsPrincipal() {
String oaiArn =
"arn:aws:iam::cloudfront:user/CloudFront Origin Access Identity EIDENTITY";
String policy = """
{"Version":"2012-10-17","Statement":{
"Effect":"Allow",
"Principal":{"AWS":"%s"},
"Action":"s3:GetObject",
"Resource":"arn:aws:s3:::public-bucket/*"
}}""".formatted(oaiArn);
assertEquals(ALLOW, S3PublicAccessEvaluator.principalPolicyDecision(
OBJECT_MAPPER, policy, "AWS", oaiArn,
"s3:GetObject", OBJECT_ARN, Map.of()));
}
@Test
void principalConditionalDenyOnlyAppliesWhenConditionMatches() {
String policy = """
{"Version":"2012-10-17","Statement":[
{
"Effect":"Allow",
"Principal":{"Service":"cloudfront.amazonaws.com"},
"Action":"s3:GetObject",
"Resource":"arn:aws:s3:::public-bucket/*"
},
{
"Effect":"Deny",
"Principal":{"Service":"cloudfront.amazonaws.com"},
"Action":"s3:GetObject",
"Resource":"arn:aws:s3:::public-bucket/*",
"Condition":{"StringEquals":{"AWS:SourceArn":
"arn:aws:cloudfront::000000000000:distribution/EBLOCKED"}}
}
]}""";
assertEquals(ALLOW, S3PublicAccessEvaluator.principalPolicyDecision(
OBJECT_MAPPER, policy, "Service", "cloudfront.amazonaws.com",
"s3:GetObject", OBJECT_ARN,
Map.of("AWS:SourceArn",
"arn:aws:cloudfront::000000000000:distribution/EALLOWED")));
assertEquals(DENY, S3PublicAccessEvaluator.principalPolicyDecision(
OBJECT_MAPPER, policy, "Service", "cloudfront.amazonaws.com",
"s3:GetObject", OBJECT_ARN,
Map.of("AWS:SourceArn",
"arn:aws:cloudfront::000000000000:distribution/EBLOCKED")));
}
@Test
void missingEffectDoesNotAllowAnonymousRead() {
String policy = """
@@ -273,6 +273,30 @@ class S3VirtualHostIntegrationTest {
.body(containsString(BUCKET));
}
@Test
@Order(19)
void objectKeyStartingWithCloudFrontPrefixRemainsReachable() {
given()
.header("Host", HOST)
.contentType("text/plain")
.body("ordinary s3 object")
.when()
.put("/_cloudfront/file.txt")
.then()
.statusCode(200);
given()
.header("Host", HOST)
.when()
.get("/_cloudfront/file.txt")
.then()
.statusCode(200)
.body(equalTo("ordinary s3 object"));
given().header("Host", HOST).delete("/_cloudfront/file.txt")
.then().statusCode(204);
}
@Test
@Order(20)
void cleanupAndDeleteBucket() {