mirror of
https://github.com/floci-io/floci.git
synced 2026-11-22 21:50:46 -05:00
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:
1 parent
527615bdf0
commit
82f80165fb
37 files changed
+4339
-158
No files matched your search
@@ -1,6 +1,6 @@
|
||||
# CloudFront
|
||||
|
||||
CloudFront management-plane emulation. Supports distribution lifecycle, cache policies, origin request policies, response headers policies, origin access controls, origin access identities, CloudFront Functions, invalidations, and tagging. Actual content delivery is not emulated — this is a management-plane-only implementation.
|
||||
CloudFront management-plane and local content-delivery emulation. Supports distribution lifecycle, cache policies, origin request policies, response headers policies, origin access controls, origin access identities, CloudFront Functions, invalidations, tagging, and GET/HEAD delivery from S3 or custom origins.
|
||||
|
||||
**Protocol:** REST XML
|
||||
**API version:** `2020-05-31`
|
||||
@@ -115,9 +115,24 @@ CloudFront management-plane emulation. Supports distribution lifecycle, cache po
|
||||
- `DeleteDistribution` returns `DistributionNotDisabled` (409) if `Enabled` is `true` in the config.
|
||||
- All mutating operations (`PUT`, `DELETE`) require an `If-Match` header containing the current `ETag`. A missing or incorrect `ETag` returns `InvalidIfMatchVersion` (400).
|
||||
- All `GET` and `POST` (create) responses include an `ETag` response header.
|
||||
- All list-type sub-elements in XML follow CloudFront's `<Quantity>N</Quantity><Items>...</Items>` wrapper pattern.
|
||||
- List operations emit the payload root declared by the CloudFront REST XML model (for example,
|
||||
`ListDistributions` returns `<DistributionList>`), with list contents represented by
|
||||
`<Quantity>N</Quantity><Items>...</Items>`.
|
||||
- OAI `CallerReference` uniqueness is enforced — duplicate `CallerReference` values return `CloudFrontOriginAccessIdentityAlreadyExists` (409).
|
||||
- `AssociateAlias` attaches a CNAME alias to the target distribution's config.
|
||||
- CNAME aliases are globally unique. `AssociateAlias` atomically transfers an alias from its current
|
||||
owner to the target distribution. Exact aliases take precedence over the most-specific matching
|
||||
wildcard alias.
|
||||
- Viewer GET/HEAD requests addressed to an enabled distribution's generated domain or alias are
|
||||
routed to the matching S3 or custom origin. Origin forwarding preserves the raw path;
|
||||
custom-origin redirects are not followed.
|
||||
- S3-origin reads honor anonymous access, OAI bucket-policy or object-ACL grants, and OAC
|
||||
service-principal bucket-policy grants (including the distribution `AWS:SourceArn`) when strict S3
|
||||
authentication is enabled. OAC `always`, `never`, and unsigned `no-override` requests follow their
|
||||
documented signing behavior; signed `no-override` viewer requests retain their authorization.
|
||||
- Cache-policy, origin-request-policy, and legacy `ForwardedValues` data-plane evaluation is not
|
||||
implemented yet. Viewer query strings therefore follow CloudFront's default behavior and are not
|
||||
forwarded to origins.
|
||||
- Custom origins that resolve to loopback, private, link-local, carrier-grade NAT, or other non-routable addresses are rejected by default. Development-only private origins must be explicitly allowlisted by exact hostname.
|
||||
|
||||
## Configuration
|
||||
|
||||
@@ -125,6 +140,7 @@ CloudFront management-plane emulation. Supports distribution lifecycle, cache po
|
||||
|---|---|---|---|
|
||||
| `floci.services.cloudfront.enabled` | `FLOCI_SERVICES_CLOUDFRONT_ENABLED` | `true` | Enable or disable the service |
|
||||
| `floci.services.cloudfront.domain-suffix` | `FLOCI_SERVICES_CLOUDFRONT_DOMAIN_SUFFIX` | `cloudfront.net` | Domain suffix for generated distribution domain names |
|
||||
| `floci.services.cloudfront.allowed-private-origin-hosts` | `FLOCI_SERVICES_CLOUDFRONT_ALLOWED_PRIVATE_ORIGIN_HOSTS` | `[]` | Exact custom-origin hosts permitted to resolve to private/non-routable addresses (comma-separated in the environment variable) |
|
||||
|
||||
## CLI Examples
|
||||
|
||||
|
||||
@@ -151,6 +151,11 @@
|
||||
<artifactId>docker-java-transport-httpclient5</artifactId>
|
||||
<version>3.7.1</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.apache.httpcomponents.client5</groupId>
|
||||
<artifactId>httpclient5</artifactId>
|
||||
<version>5.5.1</version>
|
||||
</dependency>
|
||||
<!-- Explicit overrides for Quarkus BOM which pins these at 3.7.0;
|
||||
docker-java-core:3.7.1 requires 3.7.1 for ImageHistoryCmd and ExportContainerCmd -->
|
||||
<dependency>
|
||||
|
||||
@@ -1311,6 +1311,12 @@ public interface EmulatorConfig {
|
||||
|
||||
@WithDefault("cloudfront.net")
|
||||
String domainSuffix();
|
||||
|
||||
/**
|
||||
* Exact custom-origin hostnames allowed to resolve to private or otherwise non-routable
|
||||
* addresses. Empty by default to match CloudFront's public custom-origin boundary.
|
||||
*/
|
||||
Optional<List<String>> allowedPrivateOriginHosts();
|
||||
}
|
||||
|
||||
interface AppSyncServiceConfig {
|
||||
|
||||
@@ -18,6 +18,7 @@ import io.github.hectorvent.floci.services.lambdamicrovms.LambdaMicrovmsControll
|
||||
import io.github.hectorvent.floci.services.lambdamicrovms.LambdaNetworkConnectorsController;
|
||||
import io.github.hectorvent.floci.services.opensearch.OpenSearchController;
|
||||
import io.github.hectorvent.floci.services.cloudfront.CloudFrontController;
|
||||
import io.github.hectorvent.floci.services.cloudfront.CloudFrontServingController;
|
||||
import io.github.hectorvent.floci.services.route53.Route53Controller;
|
||||
import io.github.hectorvent.floci.services.ses.SesController;
|
||||
import io.github.hectorvent.floci.services.appsync.AppSyncController;
|
||||
@@ -400,7 +401,8 @@ public class ResolvedServiceCatalog {
|
||||
"cloudfront", storageMode(config.storage().services().cloudfront().mode(), config.storage().mode()),
|
||||
5000L, AwsNamespaces.CLOUDFRONT, ServiceProtocol.REST_XML,
|
||||
protocols(ServiceProtocol.REST_XML),
|
||||
Set.of(), Set.of("cloudfront"), Set.of(), Set.of(CloudFrontController.class)),
|
||||
Set.of(), Set.of("cloudfront"), Set.of(),
|
||||
Set.of(CloudFrontController.class, CloudFrontServingController.class)),
|
||||
descriptor("appsync", "appsync", config.services().appsync().enabled(), true,
|
||||
"appsync", storageMode(config.storage().services().appsync().mode(), config.storage().mode()),
|
||||
config.storage().services().appsync().flushIntervalMs(), null, ServiceProtocol.REST_JSON,
|
||||
|
||||
+167
@@ -4,6 +4,12 @@ import io.github.hectorvent.floci.core.common.AwsArnUtils;
|
||||
import io.github.hectorvent.floci.core.common.AwsNamespaces;
|
||||
import io.github.hectorvent.floci.core.common.XmlBuilder;
|
||||
import io.github.hectorvent.floci.services.batch.BatchService;
|
||||
import io.github.hectorvent.floci.services.cloudfront.CloudFrontService;
|
||||
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.cloudformation.model.StackResource;
|
||||
import io.github.hectorvent.floci.services.cloudformation.provisioners.CfnRollback;
|
||||
import io.github.hectorvent.floci.services.cloudformation.provisioners.CloudFormationResourceRegistry;
|
||||
@@ -182,6 +188,7 @@ public class CloudFormationResourceProvisioner {
|
||||
private final AutoScalingService autoScalingService;
|
||||
private final FirehoseService firehoseService;
|
||||
private final DocDbService docDbService;
|
||||
private final CloudFrontService cloudFrontService;
|
||||
// Item 15 decomposition: extracted per-service provisioners are consulted before the switch
|
||||
// below. As types migrate, their switch cases and provisionXxx methods are removed here; the
|
||||
// now-dead service deps above are cleared in the final cleanup once the switch is empty.
|
||||
@@ -216,6 +223,7 @@ public class CloudFormationResourceProvisioner {
|
||||
AutoScalingService autoScalingService,
|
||||
FirehoseService firehoseService,
|
||||
DocDbService docDbService,
|
||||
CloudFrontService cloudFrontService,
|
||||
CloudFormationResourceRegistry resourceRegistry) {
|
||||
this.s3Service = s3Service;
|
||||
this.sqsService = sqsService;
|
||||
@@ -249,6 +257,7 @@ public class CloudFormationResourceProvisioner {
|
||||
this.autoScalingService = autoScalingService;
|
||||
this.firehoseService = firehoseService;
|
||||
this.docDbService = docDbService;
|
||||
this.cloudFrontService = cloudFrontService;
|
||||
this.resourceRegistry = resourceRegistry;
|
||||
}
|
||||
|
||||
@@ -389,6 +398,8 @@ public class CloudFormationResourceProvisioner {
|
||||
provisionLaunchConfiguration(resource, properties, engine, region, stackName);
|
||||
case "AWS::AutoScaling::AutoScalingGroup" ->
|
||||
provisionAutoScalingGroup(resource, properties, engine, region, stackName);
|
||||
case "AWS::CloudFront::Distribution" ->
|
||||
provisionCloudFrontDistribution(resource, properties, engine);
|
||||
default -> {
|
||||
if (resourceType != null && resourceType.startsWith("Custom::")) {
|
||||
provisionCustomResource(resource, properties, engine, region, accountId, stackName);
|
||||
@@ -561,6 +572,7 @@ public class CloudFormationResourceProvisioner {
|
||||
autoScalingService.deleteLaunchConfiguration(region, physicalId);
|
||||
case "AWS::AutoScaling::AutoScalingGroup" ->
|
||||
autoScalingService.deleteAutoScalingGroup(region, physicalId, true);
|
||||
case "AWS::CloudFront::Distribution" -> cloudFrontService.removeDistribution(physicalId);
|
||||
default -> LOG.debugv("Skipping delete of unsupported resource type: {0}", resourceType);
|
||||
}
|
||||
}
|
||||
@@ -4988,6 +5000,161 @@ public class CloudFormationResourceProvisioner {
|
||||
return node != null && node.hasNonNull(field) ? node.path(field).asText() : null;
|
||||
}
|
||||
|
||||
// ── CloudFront ────────────────────────────────────────────────────────────
|
||||
|
||||
/**
|
||||
* Provisions an {@code AWS::CloudFront::Distribution} by translating its {@code DistributionConfig}
|
||||
* property tree into a {@link DistributionConfig} and creating or updating the distribution.
|
||||
* {@code Ref} returns the distribution id; {@code Fn::GetAtt} exposes {@code Id} and
|
||||
* {@code DomainName} (closes #1147, where {@code Fn::GetAtt DomainName} previously returned an
|
||||
* unresolved token).
|
||||
*/
|
||||
private void provisionCloudFrontDistribution(StackResource r, JsonNode props,
|
||||
CloudFormationTemplateEngine engine) {
|
||||
JsonNode dc = props != null ? props.path("DistributionConfig") : null;
|
||||
DistributionConfig config = new DistributionConfig();
|
||||
if (dc != null && !dc.isMissingNode() && !dc.isNull()) {
|
||||
config.setEnabled(cfnBool(dc, "Enabled", engine, true));
|
||||
config.setComment(cfnText(dc, "Comment", engine));
|
||||
config.setDefaultRootObject(cfnText(dc, "DefaultRootObject", engine));
|
||||
config.setHttpVersion(cfnTextOrDefault(dc, "HttpVersion", engine, "http2"));
|
||||
config.setPriceClass(cfnTextOrDefault(dc, "PriceClass", engine, "PriceClass_All"));
|
||||
config.setAliases(cfnStringList(dc.path("Aliases"), engine));
|
||||
config.setOrigins(cfnOrigins(dc, engine));
|
||||
config.setDefaultCacheBehavior(cfnDefaultCacheBehavior(dc.path("DefaultCacheBehavior"), engine));
|
||||
config.setCacheBehaviors(cfnCacheBehaviors(dc, engine));
|
||||
config.setCustomErrorResponses(cfnCustomErrorResponses(dc, engine));
|
||||
}
|
||||
|
||||
Distribution dist = new Distribution();
|
||||
dist.setConfig(config);
|
||||
if (r.getPhysicalId() == null || r.getPhysicalId().isBlank()) {
|
||||
dist = cloudFrontService.createDistribution(dist, Map.of());
|
||||
} else {
|
||||
Distribution existing = cloudFrontService.getDistribution(r.getPhysicalId());
|
||||
dist = cloudFrontService.updateDistribution(
|
||||
existing.getId(), existing.getEtag(), dist);
|
||||
}
|
||||
|
||||
r.setPhysicalId(dist.getId());
|
||||
r.getAttributes().put("Id", dist.getId());
|
||||
r.getAttributes().put("DomainName", dist.getDomainName());
|
||||
r.getAttributes().put("Arn", dist.getArn());
|
||||
}
|
||||
|
||||
private List<Origin> cfnOrigins(JsonNode dc, CloudFormationTemplateEngine engine) {
|
||||
List<Origin> origins = new ArrayList<>();
|
||||
JsonNode items = dc.path("Origins");
|
||||
if (items.isArray()) {
|
||||
for (JsonNode node : items) {
|
||||
Origin origin = new Origin();
|
||||
origin.setId(cfnText(node, "Id", engine));
|
||||
origin.setDomainName(cfnText(node, "DomainName", engine));
|
||||
String originPath = cfnText(node, "OriginPath", engine);
|
||||
if (!originPath.isEmpty()) {
|
||||
origin.setOriginPath(originPath);
|
||||
}
|
||||
String originAccessControlId =
|
||||
cfnText(node, "OriginAccessControlId", engine);
|
||||
if (!originAccessControlId.isEmpty()) {
|
||||
origin.setOriginAccessControlId(originAccessControlId);
|
||||
}
|
||||
JsonNode s3 = node.path("S3OriginConfig");
|
||||
JsonNode custom = node.path("CustomOriginConfig");
|
||||
if (!custom.isMissingNode() && !custom.isNull()) {
|
||||
Map<String, Object> coc = new LinkedHashMap<>();
|
||||
coc.put("HTTPPort", cfnTextOrDefault(custom, "HTTPPort", engine, "80"));
|
||||
coc.put("HTTPSPort", cfnTextOrDefault(custom, "HTTPSPort", engine, "443"));
|
||||
coc.put("OriginProtocolPolicy",
|
||||
cfnTextOrDefault(custom, "OriginProtocolPolicy", engine, "https-only"));
|
||||
origin.setCustomOriginConfig(coc);
|
||||
} else {
|
||||
// No CustomOriginConfig => S3 origin (S3OriginConfig may be present or defaulted).
|
||||
Map<String, String> s3c = new LinkedHashMap<>();
|
||||
s3c.put("OriginAccessIdentity",
|
||||
s3.isMissingNode() || s3.isNull() ? "" : cfnText(s3, "OriginAccessIdentity", engine));
|
||||
origin.setS3OriginConfig(s3c);
|
||||
}
|
||||
origins.add(origin);
|
||||
}
|
||||
}
|
||||
return origins;
|
||||
}
|
||||
|
||||
private DefaultCacheBehavior cfnDefaultCacheBehavior(JsonNode node, CloudFormationTemplateEngine engine) {
|
||||
DefaultCacheBehavior dcb = new DefaultCacheBehavior();
|
||||
if (node != null && !node.isMissingNode() && !node.isNull()) {
|
||||
dcb.setTargetOriginId(cfnText(node, "TargetOriginId", engine));
|
||||
dcb.setViewerProtocolPolicy(cfnTextOrDefault(node, "ViewerProtocolPolicy", engine, "allow-all"));
|
||||
}
|
||||
return dcb;
|
||||
}
|
||||
|
||||
private List<CacheBehavior> cfnCacheBehaviors(JsonNode dc, CloudFormationTemplateEngine engine) {
|
||||
List<CacheBehavior> behaviors = new ArrayList<>();
|
||||
JsonNode items = dc.path("CacheBehaviors");
|
||||
if (items.isArray()) {
|
||||
for (JsonNode node : items) {
|
||||
CacheBehavior cb = new CacheBehavior();
|
||||
cb.setPathPattern(cfnText(node, "PathPattern", engine));
|
||||
cb.setTargetOriginId(cfnText(node, "TargetOriginId", engine));
|
||||
cb.setViewerProtocolPolicy(cfnTextOrDefault(node, "ViewerProtocolPolicy", engine, "allow-all"));
|
||||
behaviors.add(cb);
|
||||
}
|
||||
}
|
||||
return behaviors;
|
||||
}
|
||||
|
||||
private List<Map<String, Object>> cfnCustomErrorResponses(JsonNode dc, CloudFormationTemplateEngine engine) {
|
||||
List<Map<String, Object>> result = new ArrayList<>();
|
||||
JsonNode items = dc.path("CustomErrorResponses");
|
||||
if (items.isArray()) {
|
||||
for (JsonNode node : items) {
|
||||
Map<String, Object> cer = new LinkedHashMap<>();
|
||||
cer.put("ErrorCode", cfnText(node, "ErrorCode", engine));
|
||||
putIfPresent(cer, "ResponseCode", cfnText(node, "ResponseCode", engine));
|
||||
putIfPresent(cer, "ResponsePagePath", cfnText(node, "ResponsePagePath", engine));
|
||||
putIfPresent(cer, "ErrorCachingMinTTL", cfnText(node, "ErrorCachingMinTTL", engine));
|
||||
result.add(cer);
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
private static void putIfPresent(Map<String, Object> map, String key, String value) {
|
||||
if (value != null && !value.isEmpty()) {
|
||||
map.put(key, value);
|
||||
}
|
||||
}
|
||||
|
||||
private List<String> cfnStringList(JsonNode arrayNode, CloudFormationTemplateEngine engine) {
|
||||
List<String> result = new ArrayList<>();
|
||||
if (arrayNode != null && arrayNode.isArray()) {
|
||||
for (JsonNode item : arrayNode) {
|
||||
String value = engine.resolve(item);
|
||||
if (value != null && !value.isEmpty()) {
|
||||
result.add(value);
|
||||
}
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
private String cfnText(JsonNode parent, String field, CloudFormationTemplateEngine engine) {
|
||||
return parent == null ? "" : engine.resolve(parent.path(field));
|
||||
}
|
||||
|
||||
private String cfnTextOrDefault(JsonNode parent, String field, CloudFormationTemplateEngine engine,
|
||||
String dflt) {
|
||||
String value = cfnText(parent, field, engine);
|
||||
return value.isEmpty() ? dflt : value;
|
||||
}
|
||||
|
||||
private boolean cfnBool(JsonNode parent, String field, CloudFormationTemplateEngine engine, boolean dflt) {
|
||||
String value = cfnText(parent, field, engine);
|
||||
return value.isEmpty() ? dflt : "true".equalsIgnoreCase(value);
|
||||
}
|
||||
|
||||
private String resolveOptional(JsonNode props, String name, CloudFormationTemplateEngine engine) {
|
||||
if (props == null || !props.has(name) || props.get(name).isNull()) {
|
||||
return null;
|
||||
|
||||
+239
-135
@@ -9,6 +9,7 @@ import io.github.hectorvent.floci.services.cloudfront.model.*;
|
||||
import jakarta.inject.Inject;
|
||||
import jakarta.ws.rs.*;
|
||||
import jakarta.ws.rs.core.Response;
|
||||
import org.jboss.logging.Logger;
|
||||
|
||||
import javax.xml.stream.XMLInputFactory;
|
||||
import javax.xml.stream.XMLStreamConstants;
|
||||
@@ -19,10 +20,13 @@ import java.util.ArrayList;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.function.Function;
|
||||
|
||||
@Path("/2020-05-31")
|
||||
public class CloudFrontController {
|
||||
|
||||
private static final Logger LOG = Logger.getLogger(CloudFrontController.class);
|
||||
|
||||
private static final String NS = AwsNamespaces.CLOUDFRONT;
|
||||
private static final String XML = "application/xml";
|
||||
|
||||
@@ -137,27 +141,24 @@ public class CloudFrontController {
|
||||
public Response listDistributions(@QueryParam("Marker") String marker,
|
||||
@QueryParam("MaxItems") @DefaultValue("100") int maxItems) {
|
||||
try {
|
||||
List<Distribution> dists = service.listDistributions(marker, maxItems);
|
||||
long total = service.listDistributions(null, Integer.MAX_VALUE).size();
|
||||
boolean truncated = dists.size() == maxItems && dists.size() < total;
|
||||
Page<Distribution> page = page(
|
||||
service.listDistributions(marker, paginationFetchLimit(maxItems)),
|
||||
maxItems, Distribution::getId);
|
||||
int totalDistributions =
|
||||
service.listDistributions(null, Integer.MAX_VALUE).size();
|
||||
|
||||
XmlBuilder xml = new XmlBuilder()
|
||||
.start("ListDistributionsResult", NS)
|
||||
.start("DistributionList")
|
||||
.start("DistributionList", NS)
|
||||
.elem("Marker", marker != null ? marker : "")
|
||||
.elem("NextMarker", page.nextMarker())
|
||||
.elem("MaxItems", maxItems)
|
||||
.elem("IsTruncated", truncated);
|
||||
if (truncated && !dists.isEmpty()) {
|
||||
xml.elem("NextMarker", dists.get(dists.size() - 1).getId());
|
||||
}
|
||||
xml.elem("Quantity", dists.size())
|
||||
.elem("IsTruncated", page.truncated())
|
||||
.elem("Quantity", totalDistributions)
|
||||
.start("Items");
|
||||
for (Distribution d : dists) {
|
||||
for (Distribution d : page.items()) {
|
||||
xml.raw(xmlDistributionSummary(d));
|
||||
}
|
||||
xml.end("Items")
|
||||
.end("DistributionList")
|
||||
.end("ListDistributionsResult");
|
||||
xml.end("Items").end("DistributionList");
|
||||
return Response.ok(xml.build(), XML).build();
|
||||
} catch (AwsException e) {
|
||||
return xmlErrorResponse(e);
|
||||
@@ -222,17 +223,19 @@ public class CloudFrontController {
|
||||
@QueryParam("Marker") String marker,
|
||||
@QueryParam("MaxItems") @DefaultValue("100") int maxItems) {
|
||||
try {
|
||||
List<Invalidation> invs = service.listInvalidations(id, marker, maxItems);
|
||||
boolean truncated = invs.size() == maxItems;
|
||||
Page<Invalidation> page = page(
|
||||
service.listInvalidations(id, marker, paginationFetchLimit(maxItems)),
|
||||
maxItems, Invalidation::getId);
|
||||
|
||||
XmlBuilder xml = new XmlBuilder()
|
||||
.start("InvalidationList", NS)
|
||||
.elem("Marker", marker != null ? marker : "")
|
||||
.elem("NextMarker", page.nextMarker())
|
||||
.elem("MaxItems", maxItems)
|
||||
.elem("IsTruncated", truncated)
|
||||
.elem("Quantity", invs.size())
|
||||
.elem("IsTruncated", page.truncated())
|
||||
.elem("Quantity", page.items().size())
|
||||
.start("Items");
|
||||
for (Invalidation inv : invs) {
|
||||
for (Invalidation inv : page.items()) {
|
||||
xml.start("InvalidationSummary")
|
||||
.elem("Id", inv.getId())
|
||||
.elem("Status", inv.getStatus())
|
||||
@@ -335,24 +338,23 @@ public class CloudFrontController {
|
||||
@QueryParam("MaxItems") @DefaultValue("100") int maxItems,
|
||||
@QueryParam("Type") String type) {
|
||||
try {
|
||||
List<CachePolicy> policies = service.listCachePolicies(marker, maxItems);
|
||||
boolean truncated = policies.size() == maxItems;
|
||||
Page<CachePolicy> page = page(
|
||||
service.listCachePolicies(marker, paginationFetchLimit(maxItems)),
|
||||
maxItems, CachePolicy::getId);
|
||||
|
||||
XmlBuilder xml = new XmlBuilder()
|
||||
.start("ListCachePoliciesResult", NS)
|
||||
.start("CachePolicyList")
|
||||
.elem("Marker", marker != null ? marker : "")
|
||||
.start("CachePolicyList", NS)
|
||||
.elem("NextMarker", page.nextMarker())
|
||||
.elem("MaxItems", maxItems)
|
||||
.elem("IsTruncated", truncated)
|
||||
.elem("Quantity", policies.size())
|
||||
.elem("Quantity", page.items().size())
|
||||
.start("Items");
|
||||
for (CachePolicy p : policies) {
|
||||
for (CachePolicy p : page.items()) {
|
||||
xml.start("CachePolicySummary")
|
||||
.elem("Type", "custom")
|
||||
.raw(xmlCachePolicyResponse(p))
|
||||
.end("CachePolicySummary");
|
||||
}
|
||||
xml.end("Items").end("CachePolicyList").end("ListCachePoliciesResult");
|
||||
xml.end("Items").end("CachePolicyList");
|
||||
return Response.ok(xml.build(), XML).build();
|
||||
} catch (AwsException e) {
|
||||
return xmlErrorResponse(e);
|
||||
@@ -448,24 +450,23 @@ public class CloudFrontController {
|
||||
@QueryParam("MaxItems") @DefaultValue("100") int maxItems,
|
||||
@QueryParam("Type") String type) {
|
||||
try {
|
||||
List<OriginRequestPolicy> policies = service.listOriginRequestPolicies(marker, maxItems);
|
||||
boolean truncated = policies.size() == maxItems;
|
||||
Page<OriginRequestPolicy> page = page(
|
||||
service.listOriginRequestPolicies(marker, paginationFetchLimit(maxItems)),
|
||||
maxItems, OriginRequestPolicy::getId);
|
||||
|
||||
XmlBuilder xml = new XmlBuilder()
|
||||
.start("ListOriginRequestPoliciesResult", NS)
|
||||
.start("OriginRequestPolicyList")
|
||||
.elem("Marker", marker != null ? marker : "")
|
||||
.start("OriginRequestPolicyList", NS)
|
||||
.elem("NextMarker", page.nextMarker())
|
||||
.elem("MaxItems", maxItems)
|
||||
.elem("IsTruncated", truncated)
|
||||
.elem("Quantity", policies.size())
|
||||
.elem("Quantity", page.items().size())
|
||||
.start("Items");
|
||||
for (OriginRequestPolicy p : policies) {
|
||||
for (OriginRequestPolicy p : page.items()) {
|
||||
xml.start("OriginRequestPolicySummary")
|
||||
.elem("Type", "custom")
|
||||
.raw(xmlOriginRequestPolicyResponse(p))
|
||||
.end("OriginRequestPolicySummary");
|
||||
}
|
||||
xml.end("Items").end("OriginRequestPolicyList").end("ListOriginRequestPoliciesResult");
|
||||
xml.end("Items").end("OriginRequestPolicyList");
|
||||
return Response.ok(xml.build(), XML).build();
|
||||
} catch (AwsException e) {
|
||||
return xmlErrorResponse(e);
|
||||
@@ -562,24 +563,23 @@ public class CloudFrontController {
|
||||
@QueryParam("MaxItems") @DefaultValue("100") int maxItems,
|
||||
@QueryParam("Type") String type) {
|
||||
try {
|
||||
List<ResponseHeadersPolicy> policies = service.listResponseHeadersPolicies(marker, maxItems);
|
||||
boolean truncated = policies.size() == maxItems;
|
||||
Page<ResponseHeadersPolicy> page = page(
|
||||
service.listResponseHeadersPolicies(marker, paginationFetchLimit(maxItems)),
|
||||
maxItems, ResponseHeadersPolicy::getId);
|
||||
|
||||
XmlBuilder xml = new XmlBuilder()
|
||||
.start("ListResponseHeadersPoliciesResult", NS)
|
||||
.start("ResponseHeadersPolicyList")
|
||||
.elem("Marker", marker != null ? marker : "")
|
||||
.start("ResponseHeadersPolicyList", NS)
|
||||
.elem("NextMarker", page.nextMarker())
|
||||
.elem("MaxItems", maxItems)
|
||||
.elem("IsTruncated", truncated)
|
||||
.elem("Quantity", policies.size())
|
||||
.elem("Quantity", page.items().size())
|
||||
.start("Items");
|
||||
for (ResponseHeadersPolicy p : policies) {
|
||||
for (ResponseHeadersPolicy p : page.items()) {
|
||||
xml.start("ResponseHeadersPolicySummary")
|
||||
.elem("Type", "custom")
|
||||
.raw(xmlResponseHeadersPolicyResponse(p))
|
||||
.end("ResponseHeadersPolicySummary");
|
||||
}
|
||||
xml.end("Items").end("ResponseHeadersPolicyList").end("ListResponseHeadersPoliciesResult");
|
||||
xml.end("Items").end("ResponseHeadersPolicyList");
|
||||
return Response.ok(xml.build(), XML).build();
|
||||
} catch (AwsException e) {
|
||||
return xmlErrorResponse(e);
|
||||
@@ -677,21 +677,22 @@ public class CloudFrontController {
|
||||
public Response listOriginAccessControls(@QueryParam("Marker") String marker,
|
||||
@QueryParam("MaxItems") @DefaultValue("100") int maxItems) {
|
||||
try {
|
||||
List<OriginAccessControl> oacs = service.listOriginAccessControls(marker, maxItems);
|
||||
boolean truncated = oacs.size() == maxItems;
|
||||
Page<OriginAccessControl> page = page(
|
||||
service.listOriginAccessControls(marker, paginationFetchLimit(maxItems)),
|
||||
maxItems, OriginAccessControl::getId);
|
||||
|
||||
XmlBuilder xml = new XmlBuilder()
|
||||
.start("ListOriginAccessControlsResult", NS)
|
||||
.start("OriginAccessControlList")
|
||||
.start("OriginAccessControlList", NS)
|
||||
.elem("Marker", marker != null ? marker : "")
|
||||
.elem("NextMarker", page.nextMarker())
|
||||
.elem("MaxItems", maxItems)
|
||||
.elem("IsTruncated", truncated)
|
||||
.elem("Quantity", oacs.size())
|
||||
.elem("IsTruncated", page.truncated())
|
||||
.elem("Quantity", page.items().size())
|
||||
.start("Items");
|
||||
for (OriginAccessControl o : oacs) {
|
||||
for (OriginAccessControl o : page.items()) {
|
||||
xml.raw(xmlOriginAccessControlSummary(o));
|
||||
}
|
||||
xml.end("Items").end("OriginAccessControlList").end("ListOriginAccessControlsResult");
|
||||
xml.end("Items").end("OriginAccessControlList");
|
||||
return Response.ok(xml.build(), XML).build();
|
||||
} catch (AwsException e) {
|
||||
return xmlErrorResponse(e);
|
||||
@@ -786,27 +787,27 @@ public class CloudFrontController {
|
||||
@QueryParam("Marker") String marker,
|
||||
@QueryParam("MaxItems") @DefaultValue("100") int maxItems) {
|
||||
try {
|
||||
List<CloudFrontOriginAccessIdentity> oais =
|
||||
service.listCloudFrontOriginAccessIdentities(marker, maxItems);
|
||||
boolean truncated = oais.size() == maxItems;
|
||||
Page<CloudFrontOriginAccessIdentity> page = page(
|
||||
service.listCloudFrontOriginAccessIdentities(
|
||||
marker, paginationFetchLimit(maxItems)),
|
||||
maxItems, CloudFrontOriginAccessIdentity::getId);
|
||||
|
||||
XmlBuilder xml = new XmlBuilder()
|
||||
.start("ListCloudFrontOriginAccessIdentitiesResult", NS)
|
||||
.start("CloudFrontOriginAccessIdentityList")
|
||||
.start("CloudFrontOriginAccessIdentityList", NS)
|
||||
.elem("Marker", marker != null ? marker : "")
|
||||
.elem("NextMarker", page.nextMarker())
|
||||
.elem("MaxItems", maxItems)
|
||||
.elem("IsTruncated", truncated)
|
||||
.elem("Quantity", oais.size())
|
||||
.elem("IsTruncated", page.truncated())
|
||||
.elem("Quantity", page.items().size())
|
||||
.start("Items");
|
||||
for (CloudFrontOriginAccessIdentity o : oais) {
|
||||
for (CloudFrontOriginAccessIdentity o : page.items()) {
|
||||
xml.start("CloudFrontOriginAccessIdentitySummary")
|
||||
.elem("Id", o.getId())
|
||||
.elem("S3CanonicalUserId", o.getS3CanonicalUserId())
|
||||
.elem("Comment", o.getComment() != null ? o.getComment() : "")
|
||||
.end("CloudFrontOriginAccessIdentitySummary");
|
||||
}
|
||||
xml.end("Items").end("CloudFrontOriginAccessIdentityList")
|
||||
.end("ListCloudFrontOriginAccessIdentitiesResult");
|
||||
xml.end("Items").end("CloudFrontOriginAccessIdentityList");
|
||||
return Response.ok(xml.build(), XML).build();
|
||||
} catch (AwsException e) {
|
||||
return xmlErrorResponse(e);
|
||||
@@ -900,14 +901,16 @@ public class CloudFrontController {
|
||||
@QueryParam("Marker") String marker,
|
||||
@QueryParam("MaxItems") @DefaultValue("100") int maxItems) {
|
||||
try {
|
||||
List<CloudFrontFunction> fns = service.listFunctions(stage);
|
||||
Page<CloudFrontFunction> page = page(
|
||||
service.listFunctions(stage, marker, paginationFetchLimit(maxItems)),
|
||||
maxItems, CloudFrontFunction::getName);
|
||||
XmlBuilder xml = new XmlBuilder()
|
||||
.start("ListFunctionsResult", NS)
|
||||
.start("FunctionList")
|
||||
.start("FunctionList", NS)
|
||||
.elem("NextMarker", page.nextMarker())
|
||||
.elem("MaxItems", maxItems)
|
||||
.elem("Quantity", fns.size())
|
||||
.elem("Quantity", page.items().size())
|
||||
.start("Items");
|
||||
for (CloudFrontFunction fn : fns) {
|
||||
for (CloudFrontFunction fn : page.items()) {
|
||||
xml.start("FunctionSummary")
|
||||
.elem("Name", fn.getName())
|
||||
.elem("Status", fn.getStatus())
|
||||
@@ -925,7 +928,7 @@ public class CloudFrontController {
|
||||
.end("FunctionMetadata")
|
||||
.end("FunctionSummary");
|
||||
}
|
||||
xml.end("Items").end("FunctionList").end("ListFunctionsResult");
|
||||
xml.end("Items").end("FunctionList");
|
||||
return Response.ok(xml.build(), XML).build();
|
||||
} catch (AwsException e) {
|
||||
return xmlErrorResponse(e);
|
||||
@@ -940,8 +943,7 @@ public class CloudFrontController {
|
||||
try {
|
||||
Map<String, String> tags = service.listTagsForResource(resource);
|
||||
XmlBuilder xml = new XmlBuilder()
|
||||
.start("ListTagsForResourceResult", NS)
|
||||
.start("Tags")
|
||||
.start("Tags", NS)
|
||||
.start("Items");
|
||||
for (Map.Entry<String, String> entry : tags.entrySet()) {
|
||||
xml.start("Tag")
|
||||
@@ -949,7 +951,7 @@ public class CloudFrontController {
|
||||
.elem("Value", entry.getValue())
|
||||
.end("Tag");
|
||||
}
|
||||
xml.end("Items").end("Tags").end("ListTagsForResourceResult");
|
||||
xml.end("Items").end("Tags");
|
||||
return Response.ok(xml.build(), XML).build();
|
||||
} catch (AwsException e) {
|
||||
return xmlErrorResponse(e);
|
||||
@@ -1048,26 +1050,26 @@ public class CloudFrontController {
|
||||
public Response listContinuousDeploymentPolicies(@QueryParam("Marker") String marker,
|
||||
@QueryParam("MaxItems") @DefaultValue("100") int maxItems) {
|
||||
try {
|
||||
List<ContinuousDeploymentPolicy> policies =
|
||||
service.listContinuousDeploymentPolicies(marker, maxItems);
|
||||
boolean truncated = policies.size() == maxItems;
|
||||
Page<ContinuousDeploymentPolicy> page = page(
|
||||
service.listContinuousDeploymentPolicies(
|
||||
marker, paginationFetchLimit(maxItems)),
|
||||
maxItems, ContinuousDeploymentPolicy::getId);
|
||||
int totalPolicies = service.listContinuousDeploymentPolicies(
|
||||
null, Integer.MAX_VALUE).size();
|
||||
|
||||
XmlBuilder xml = new XmlBuilder()
|
||||
.start("ListContinuousDeploymentPoliciesResult", NS)
|
||||
.start("ContinuousDeploymentPolicyList")
|
||||
.elem("Marker", marker != null ? marker : "")
|
||||
.start("ContinuousDeploymentPolicyList", NS)
|
||||
.elem("NextMarker", page.nextMarker())
|
||||
.elem("MaxItems", maxItems)
|
||||
.elem("IsTruncated", truncated)
|
||||
.elem("Quantity", policies.size())
|
||||
.elem("Quantity", totalPolicies)
|
||||
.start("Items");
|
||||
for (ContinuousDeploymentPolicy p : policies) {
|
||||
for (ContinuousDeploymentPolicy p : page.items()) {
|
||||
xml.start("ContinuousDeploymentPolicySummary")
|
||||
.elem("Type", "custom")
|
||||
.raw(xmlContinuousDeploymentPolicyResponse(p))
|
||||
.end("ContinuousDeploymentPolicySummary");
|
||||
}
|
||||
xml.end("Items").end("ContinuousDeploymentPolicyList")
|
||||
.end("ListContinuousDeploymentPoliciesResult");
|
||||
xml.end("Items").end("ContinuousDeploymentPolicyList");
|
||||
return Response.ok(xml.build(), XML).build();
|
||||
} catch (AwsException e) {
|
||||
return xmlErrorResponse(e);
|
||||
@@ -1183,21 +1185,20 @@ public class CloudFrontController {
|
||||
public Response listPublicKeys(@QueryParam("Marker") String marker,
|
||||
@QueryParam("MaxItems") @DefaultValue("100") int maxItems) {
|
||||
try {
|
||||
List<PublicKey> keys = service.listPublicKeys(marker, maxItems);
|
||||
boolean truncated = keys.size() == maxItems;
|
||||
Page<PublicKey> page = page(
|
||||
service.listPublicKeys(marker, paginationFetchLimit(maxItems)),
|
||||
maxItems, PublicKey::getId);
|
||||
|
||||
XmlBuilder xml = new XmlBuilder()
|
||||
.start("ListPublicKeysResult", NS)
|
||||
.start("PublicKeyList")
|
||||
.elem("Marker", marker != null ? marker : "")
|
||||
.start("PublicKeyList", NS)
|
||||
.elem("NextMarker", page.nextMarker())
|
||||
.elem("MaxItems", maxItems)
|
||||
.elem("IsTruncated", truncated)
|
||||
.elem("Quantity", keys.size())
|
||||
.elem("Quantity", page.items().size())
|
||||
.start("Items");
|
||||
for (PublicKey k : keys) {
|
||||
for (PublicKey k : page.items()) {
|
||||
xml.raw(xmlPublicKeySummary(k));
|
||||
}
|
||||
xml.end("Items").end("PublicKeyList").end("ListPublicKeysResult");
|
||||
xml.end("Items").end("PublicKeyList");
|
||||
return Response.ok(xml.build(), XML).build();
|
||||
} catch (AwsException e) {
|
||||
return xmlErrorResponse(e);
|
||||
@@ -1293,21 +1294,20 @@ public class CloudFrontController {
|
||||
public Response listKeyGroups(@QueryParam("Marker") String marker,
|
||||
@QueryParam("MaxItems") @DefaultValue("100") int maxItems) {
|
||||
try {
|
||||
List<KeyGroup> groups = service.listKeyGroups(marker, maxItems);
|
||||
boolean truncated = groups.size() == maxItems;
|
||||
Page<KeyGroup> page = page(
|
||||
service.listKeyGroups(marker, paginationFetchLimit(maxItems)),
|
||||
maxItems, KeyGroup::getId);
|
||||
|
||||
XmlBuilder xml = new XmlBuilder()
|
||||
.start("ListKeyGroupsResult", NS)
|
||||
.start("KeyGroupList")
|
||||
.elem("Marker", marker != null ? marker : "")
|
||||
.start("KeyGroupList", NS)
|
||||
.elem("NextMarker", page.nextMarker())
|
||||
.elem("MaxItems", maxItems)
|
||||
.elem("IsTruncated", truncated)
|
||||
.elem("Quantity", groups.size())
|
||||
.elem("Quantity", page.items().size())
|
||||
.start("Items");
|
||||
for (KeyGroup g : groups) {
|
||||
for (KeyGroup g : page.items()) {
|
||||
xml.start("KeyGroupSummary").raw(xmlKeyGroupResponse(g)).end("KeyGroupSummary");
|
||||
}
|
||||
xml.end("Items").end("KeyGroupList").end("ListKeyGroupsResult");
|
||||
xml.end("Items").end("KeyGroupList");
|
||||
return Response.ok(xml.build(), XML).build();
|
||||
} catch (AwsException e) {
|
||||
return xmlErrorResponse(e);
|
||||
@@ -1389,20 +1389,22 @@ public class CloudFrontController {
|
||||
public Response listRealtimeLogConfigs(@QueryParam("Marker") String marker,
|
||||
@QueryParam("MaxItems") @DefaultValue("100") int maxItems) {
|
||||
try {
|
||||
List<RealtimeLogConfig> configs = service.listRealtimeLogConfigs(marker, maxItems);
|
||||
boolean truncated = configs.size() == maxItems;
|
||||
Page<RealtimeLogConfig> page = page(
|
||||
service.listRealtimeLogConfigs(marker, paginationFetchLimit(maxItems)),
|
||||
maxItems, RealtimeLogConfig::getName);
|
||||
|
||||
XmlBuilder xml = new XmlBuilder()
|
||||
.start("ListRealtimeLogConfigsResult", NS)
|
||||
.start("RealtimeLogConfigs")
|
||||
.start("RealtimeLogConfigs", NS)
|
||||
.elem("MaxItems", maxItems)
|
||||
.elem("IsTruncated", truncated)
|
||||
.elem("Quantity", configs.size())
|
||||
.start("Items");
|
||||
for (RealtimeLogConfig c : configs) {
|
||||
for (RealtimeLogConfig c : page.items()) {
|
||||
xml.raw(xmlRealtimeLogConfigBody(c));
|
||||
}
|
||||
xml.end("Items").end("RealtimeLogConfigs").end("ListRealtimeLogConfigsResult");
|
||||
xml.end("Items")
|
||||
.elem("IsTruncated", page.truncated())
|
||||
.elem("Marker", marker != null ? marker : "")
|
||||
.elem("NextMarker", page.nextMarker())
|
||||
.end("RealtimeLogConfigs");
|
||||
return Response.ok(xml.build(), XML).build();
|
||||
} catch (AwsException e) {
|
||||
return xmlErrorResponse(e);
|
||||
@@ -1558,22 +1560,21 @@ public class CloudFrontController {
|
||||
public Response listFieldLevelEncryptionConfigs(@QueryParam("Marker") String marker,
|
||||
@QueryParam("MaxItems") @DefaultValue("100") int maxItems) {
|
||||
try {
|
||||
List<FieldLevelEncryptionConfig> configs =
|
||||
service.listFieldLevelEncryptionConfigs(marker, maxItems);
|
||||
boolean truncated = configs.size() == maxItems;
|
||||
Page<FieldLevelEncryptionConfig> page = page(
|
||||
service.listFieldLevelEncryptionConfigs(
|
||||
marker, paginationFetchLimit(maxItems)),
|
||||
maxItems, FieldLevelEncryptionConfig::getId);
|
||||
|
||||
XmlBuilder xml = new XmlBuilder()
|
||||
.start("ListFieldLevelEncryptionConfigsResult", NS)
|
||||
.start("FieldLevelEncryptionList")
|
||||
.elem("Marker", marker != null ? marker : "")
|
||||
.start("FieldLevelEncryptionList", NS)
|
||||
.elem("NextMarker", page.nextMarker())
|
||||
.elem("MaxItems", maxItems)
|
||||
.elem("IsTruncated", truncated)
|
||||
.elem("Quantity", configs.size())
|
||||
.elem("Quantity", page.items().size())
|
||||
.start("Items");
|
||||
for (FieldLevelEncryptionConfig c : configs) {
|
||||
for (FieldLevelEncryptionConfig c : page.items()) {
|
||||
xml.raw(xmlFieldLevelEncryptionConfigResponse(c));
|
||||
}
|
||||
xml.end("Items").end("FieldLevelEncryptionList").end("ListFieldLevelEncryptionConfigsResult");
|
||||
xml.end("Items").end("FieldLevelEncryptionList");
|
||||
return Response.ok(xml.build(), XML).build();
|
||||
} catch (AwsException e) {
|
||||
return xmlErrorResponse(e);
|
||||
@@ -1652,23 +1653,21 @@ public class CloudFrontController {
|
||||
public Response listFieldLevelEncryptionProfiles(@QueryParam("Marker") String marker,
|
||||
@QueryParam("MaxItems") @DefaultValue("100") int maxItems) {
|
||||
try {
|
||||
List<FieldLevelEncryptionProfile> profiles =
|
||||
service.listFieldLevelEncryptionProfiles(marker, maxItems);
|
||||
boolean truncated = profiles.size() == maxItems;
|
||||
Page<FieldLevelEncryptionProfile> page = page(
|
||||
service.listFieldLevelEncryptionProfiles(
|
||||
marker, paginationFetchLimit(maxItems)),
|
||||
maxItems, FieldLevelEncryptionProfile::getId);
|
||||
|
||||
XmlBuilder xml = new XmlBuilder()
|
||||
.start("ListFieldLevelEncryptionProfilesResult", NS)
|
||||
.start("FieldLevelEncryptionProfileList")
|
||||
.elem("Marker", marker != null ? marker : "")
|
||||
.start("FieldLevelEncryptionProfileList", NS)
|
||||
.elem("NextMarker", page.nextMarker())
|
||||
.elem("MaxItems", maxItems)
|
||||
.elem("IsTruncated", truncated)
|
||||
.elem("Quantity", profiles.size())
|
||||
.elem("Quantity", page.items().size())
|
||||
.start("Items");
|
||||
for (FieldLevelEncryptionProfile p : profiles) {
|
||||
for (FieldLevelEncryptionProfile p : page.items()) {
|
||||
xml.raw(xmlFieldLevelEncryptionProfileResponse(p));
|
||||
}
|
||||
xml.end("Items").end("FieldLevelEncryptionProfileList")
|
||||
.end("ListFieldLevelEncryptionProfilesResult");
|
||||
xml.end("Items").end("FieldLevelEncryptionProfileList");
|
||||
return Response.ok(xml.build(), XML).build();
|
||||
} catch (AwsException e) {
|
||||
return xmlErrorResponse(e);
|
||||
@@ -1765,7 +1764,30 @@ public class CloudFrontController {
|
||||
}
|
||||
xml.end("CacheBehaviors");
|
||||
|
||||
xml.start("CustomErrorResponses").elem("Quantity", 0).end("CustomErrorResponses");
|
||||
List<Map<String, Object>> customErrors = cfg.getCustomErrorResponses();
|
||||
int cerCount = customErrors != null ? customErrors.size() : 0;
|
||||
xml.start("CustomErrorResponses").elem("Quantity", cerCount);
|
||||
if (cerCount > 0) {
|
||||
xml.start("Items");
|
||||
for (Map<String, Object> cer : customErrors) {
|
||||
xml.start("CustomErrorResponse").elem("ErrorCode", str(cer.get("ErrorCode")));
|
||||
// ResponsePagePath and ResponseCode are optional; CloudFront omits them when unset
|
||||
// rather than returning empty elements.
|
||||
String pagePath = str(cer.get("ResponsePagePath"));
|
||||
if (!pagePath.isEmpty()) {
|
||||
xml.elem("ResponsePagePath", pagePath);
|
||||
}
|
||||
String responseCode = str(cer.get("ResponseCode"));
|
||||
if (!responseCode.isEmpty()) {
|
||||
xml.elem("ResponseCode", responseCode);
|
||||
}
|
||||
xml.elem("ErrorCachingMinTTL", cer.get("ErrorCachingMinTTL") != null
|
||||
? str(cer.get("ErrorCachingMinTTL")) : "0")
|
||||
.end("CustomErrorResponse");
|
||||
}
|
||||
xml.end("Items");
|
||||
}
|
||||
xml.end("CustomErrorResponses");
|
||||
|
||||
List<String> aliases = cfg.getAliases();
|
||||
int aliasCount = aliases != null ? aliases.size() : 0;
|
||||
@@ -2059,6 +2081,11 @@ public class CloudFrontController {
|
||||
.build();
|
||||
}
|
||||
|
||||
/** Renders a possibly-null value as a string, using the empty string for {@code null}. */
|
||||
private static String str(Object value) {
|
||||
return value != null ? value.toString() : "";
|
||||
}
|
||||
|
||||
private String xmlQuantityItems(String wrapper, String itemTag, int count, List<String> items) {
|
||||
XmlBuilder xml = new XmlBuilder().start(wrapper).elem("Quantity", count);
|
||||
if (count > 0 && items != null && !items.isEmpty()) {
|
||||
@@ -2072,6 +2099,21 @@ public class CloudFrontController {
|
||||
return xml.build();
|
||||
}
|
||||
|
||||
private static int paginationFetchLimit(int maxItems) {
|
||||
return maxItems > 0 && maxItems < Integer.MAX_VALUE ? maxItems + 1 : maxItems;
|
||||
}
|
||||
|
||||
private static <T> Page<T> page(List<T> candidates, int maxItems,
|
||||
Function<T, String> markerFunction) {
|
||||
boolean truncated = maxItems > 0 && candidates.size() > maxItems;
|
||||
List<T> items = truncated ? candidates.subList(0, maxItems) : candidates;
|
||||
String nextMarker = truncated && !items.isEmpty()
|
||||
? markerFunction.apply(items.get(items.size() - 1)) : null;
|
||||
return new Page<>(items, truncated, nextMarker);
|
||||
}
|
||||
|
||||
private record Page<T>(List<T> items, boolean truncated, String nextMarker) {}
|
||||
|
||||
private Response xmlErrorResponse(AwsException e) {
|
||||
String xml = new XmlBuilder()
|
||||
.start("ErrorResponse", NS)
|
||||
@@ -2106,10 +2148,71 @@ public class CloudFrontController {
|
||||
cfg.setCacheBehaviors(parseCacheBehaviors(body));
|
||||
cfg.setAliases(parseAliases(body));
|
||||
cfg.setViewerCertificate(parseViewerCertificate(body));
|
||||
cfg.setCustomErrorResponses(parseCustomErrorResponses(body));
|
||||
|
||||
return cfg;
|
||||
}
|
||||
|
||||
/**
|
||||
* Parses the {@code CustomErrorResponses} block into a list of maps keyed by
|
||||
* {@code ErrorCode}, {@code ResponsePagePath}, {@code ResponseCode} and {@code ErrorCachingMinTTL}
|
||||
* (values kept as strings). CloudFront uses these to override an origin error with a custom
|
||||
* page/status — most notably the SPA fallback that turns a 403/404 into 200 {@code /index.html}.
|
||||
*/
|
||||
private List<Map<String, Object>> parseCustomErrorResponses(String body) {
|
||||
List<Map<String, Object>> result = new ArrayList<>();
|
||||
if (body == null || body.isEmpty()) {
|
||||
return result;
|
||||
}
|
||||
try {
|
||||
XMLStreamReader r = XML_FACTORY.createXMLStreamReader(new StringReader(body));
|
||||
boolean inBlock = false;
|
||||
boolean inItem = false;
|
||||
Map<String, Object> current = null;
|
||||
while (r.hasNext()) {
|
||||
int event = r.next();
|
||||
if (event == XMLStreamConstants.START_ELEMENT) {
|
||||
String local = r.getLocalName();
|
||||
switch (local) {
|
||||
case "CustomErrorResponses" -> inBlock = true;
|
||||
case "CustomErrorResponse" -> {
|
||||
if (inBlock) {
|
||||
inItem = true;
|
||||
current = new LinkedHashMap<>();
|
||||
}
|
||||
}
|
||||
case "ErrorCode", "ResponsePagePath", "ResponseCode", "ErrorCachingMinTTL" -> {
|
||||
if (inItem && current != null) {
|
||||
current.put(local, r.getElementText());
|
||||
}
|
||||
}
|
||||
default -> {
|
||||
}
|
||||
}
|
||||
} else if (event == XMLStreamConstants.END_ELEMENT) {
|
||||
switch (r.getLocalName()) {
|
||||
case "CustomErrorResponse" -> {
|
||||
if (inItem && current != null) {
|
||||
result.add(current);
|
||||
}
|
||||
inItem = false;
|
||||
current = null;
|
||||
}
|
||||
case "CustomErrorResponses" -> inBlock = false;
|
||||
default -> {
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
r.close();
|
||||
} catch (Exception e) {
|
||||
// A malformed CustomErrorResponses block yields the entries parsed so far rather than
|
||||
// failing the whole distribution create/update; log it so the cause is diagnosable.
|
||||
LOG.debugv("Ignoring malformed CustomErrorResponses during parse: {0}", e.getMessage());
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
private List<Origin> parseOrigins(String body) {
|
||||
List<Origin> result = new ArrayList<>();
|
||||
if (body == null || body.isEmpty()) {
|
||||
@@ -2487,9 +2590,10 @@ public class CloudFrontController {
|
||||
OriginAccessControl oac = new OriginAccessControl();
|
||||
oac.setName(XmlParser.extractFirst(body, "Name", null));
|
||||
oac.setDescription(XmlParser.extractFirst(body, "Description", null));
|
||||
oac.setSigningProtocol(XmlParser.extractFirst(body, "SigningProtocol", "sigv4"));
|
||||
oac.setSigningBehavior(XmlParser.extractFirst(body, "SigningBehavior", "always"));
|
||||
oac.setOriginAccessControlOriginType(XmlParser.extractFirst(body, "OriginAccessControlOriginType", "s3"));
|
||||
oac.setSigningProtocol(XmlParser.extractFirst(body, "SigningProtocol", null));
|
||||
oac.setSigningBehavior(XmlParser.extractFirst(body, "SigningBehavior", null));
|
||||
oac.setOriginAccessControlOriginType(
|
||||
XmlParser.extractFirst(body, "OriginAccessControlOriginType", null));
|
||||
return oac;
|
||||
}
|
||||
|
||||
|
||||
+90
@@ -0,0 +1,90 @@
|
||||
package io.github.hectorvent.floci.services.cloudfront;
|
||||
|
||||
import io.github.hectorvent.floci.services.cloudfront.model.Distribution;
|
||||
import jakarta.annotation.Priority;
|
||||
import jakarta.enterprise.inject.Instance;
|
||||
import jakarta.inject.Inject;
|
||||
import jakarta.ws.rs.container.ContainerRequestContext;
|
||||
import jakarta.ws.rs.container.ContainerRequestFilter;
|
||||
import jakarta.ws.rs.container.PreMatching;
|
||||
import jakarta.ws.rs.core.Response;
|
||||
import jakarta.ws.rs.ext.Provider;
|
||||
import org.jboss.logging.Logger;
|
||||
|
||||
import java.net.URI;
|
||||
|
||||
/**
|
||||
* Routes viewer requests addressed to a CloudFront distribution's domain to the distribution
|
||||
* request-serving controller.
|
||||
*
|
||||
* <p>When a request arrives with a {@code Host} header matching a distribution's assigned
|
||||
* CloudFront domain name ({@code <id>.cloudfront.net}) or one of its alternate domain names
|
||||
* (CNAME aliases), this filter rewrites the request URI to
|
||||
* {@code /_cloudfront/{distributionId}{rawPath}} so {@link CloudFrontServingController} can resolve
|
||||
* the matching origin and return the content — mirroring how CloudFront fronts an S3 or custom
|
||||
* origin.
|
||||
*
|
||||
* <p>Runs at priority 15: after the Lambda function URL (5) and API Gateway custom domain (10)
|
||||
* filters, but before the S3 virtual-host filter (default 5000), so a distribution or alias host
|
||||
* is not mistaken for an S3 virtual-hosted bucket.
|
||||
*/
|
||||
@Provider
|
||||
@PreMatching
|
||||
@Priority(15)
|
||||
public class CloudFrontDistributionFilter implements ContainerRequestFilter {
|
||||
|
||||
public static final String ROUTED_PROPERTY = CloudFrontDistributionFilter.class.getName() + ".routed";
|
||||
private static final Logger LOG = Logger.getLogger(CloudFrontDistributionFilter.class);
|
||||
|
||||
// A @PreMatching filter is wired into the request pipeline at build time, so holding the
|
||||
// CloudFrontService proxy directly would place it in the native-image build heap — illegal because
|
||||
// CloudFrontService is initialized at image run time (it uses SecureRandom). Inject a lazy Instance
|
||||
// and resolve the bean per request instead.
|
||||
private final Instance<CloudFrontService> service;
|
||||
|
||||
@Inject
|
||||
public CloudFrontDistributionFilter(Instance<CloudFrontService> service) {
|
||||
this.service = service;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void filter(ContainerRequestContext requestContext) {
|
||||
String host = requestContext.getHeaderString("Host");
|
||||
if (host == null) {
|
||||
return;
|
||||
}
|
||||
|
||||
Distribution dist = service.get().findByHost(host);
|
||||
if (dist == null) {
|
||||
return;
|
||||
}
|
||||
if (dist.getConfig() == null || !dist.getConfig().isEnabled()) {
|
||||
requestContext.abortWith(Response.status(404).build());
|
||||
return;
|
||||
}
|
||||
|
||||
URI originalUri = requestContext.getUriInfo().getRequestUri();
|
||||
String rawPath = originalUri.getRawPath();
|
||||
if (rawPath == null || rawPath.isEmpty()) {
|
||||
rawPath = "/";
|
||||
}
|
||||
|
||||
// The serving controller lives at /_cloudfront/{distId}/{proxy:.*}; the leading slash from
|
||||
// rawPath supplies the separator (root "/" becomes /_cloudfront/{id}/).
|
||||
String newPath = "/_cloudfront/" + dist.getId() + rawPath;
|
||||
|
||||
StringBuilder rewritten = new StringBuilder();
|
||||
if (originalUri.getScheme() != null) {
|
||||
rewritten.append(originalUri.getScheme()).append("://").append(originalUri.getRawAuthority());
|
||||
}
|
||||
rewritten.append(newPath);
|
||||
if (originalUri.getRawQuery() != null) {
|
||||
rewritten.append('?').append(originalUri.getRawQuery());
|
||||
}
|
||||
URI newUri = URI.create(rewritten.toString());
|
||||
|
||||
LOG.debugv("CloudFront distribution routing: {0}{1} -> {2}", host, rawPath, newUri.getPath());
|
||||
requestContext.setProperty(ROUTED_PROPERTY, Boolean.TRUE);
|
||||
requestContext.setRequestUri(newUri);
|
||||
}
|
||||
}
|
||||
+215
@@ -0,0 +1,215 @@
|
||||
package io.github.hectorvent.floci.services.cloudfront;
|
||||
|
||||
import org.apache.hc.client5.http.DnsResolver;
|
||||
import org.apache.hc.client5.http.SystemDefaultDnsResolver;
|
||||
import org.apache.hc.client5.http.config.ConnectionConfig;
|
||||
import org.apache.hc.client5.http.config.RequestConfig;
|
||||
import org.apache.hc.client5.http.config.TlsConfig;
|
||||
import org.apache.hc.client5.http.impl.DefaultSchemePortResolver;
|
||||
import org.apache.hc.client5.http.impl.classic.CloseableHttpClient;
|
||||
import org.apache.hc.client5.http.impl.classic.HttpClients;
|
||||
import org.apache.hc.client5.http.impl.io.PoolingHttpClientConnectionManager;
|
||||
import org.apache.hc.client5.http.impl.io.PoolingHttpClientConnectionManagerBuilder;
|
||||
import org.apache.hc.client5.http.impl.routing.DefaultRoutePlanner;
|
||||
import org.apache.hc.client5.http.protocol.HttpClientContext;
|
||||
import org.apache.hc.client5.http.ssl.ClientTlsStrategyBuilder;
|
||||
import org.apache.hc.core5.http.Header;
|
||||
import org.apache.hc.core5.http.HttpVersion;
|
||||
import org.apache.hc.core5.http.io.entity.EntityUtils;
|
||||
import org.apache.hc.core5.http.io.support.ClassicRequestBuilder;
|
||||
import org.apache.hc.core5.http2.HttpVersionPolicy;
|
||||
import org.apache.hc.core5.util.Timeout;
|
||||
|
||||
import javax.net.ssl.SSLContext;
|
||||
import javax.net.ssl.SSLSession;
|
||||
import java.io.IOException;
|
||||
import java.io.InterruptedIOException;
|
||||
import java.net.InetAddress;
|
||||
import java.net.URI;
|
||||
import java.net.UnknownHostException;
|
||||
import java.net.http.HttpClient;
|
||||
import java.net.http.HttpHeaders;
|
||||
import java.net.http.HttpRequest;
|
||||
import java.net.http.HttpResponse;
|
||||
import java.time.Duration;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collection;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.Set;
|
||||
import java.util.TreeMap;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
/**
|
||||
* HTTP/1.1 transport for CloudFront custom origins that validates and pins each DNS resolution to
|
||||
* the addresses used by the connection. Keeping the logical hostname in the request URI preserves
|
||||
* the origin Host header, TLS SNI, and certificate hostname verification.
|
||||
*/
|
||||
final class CloudFrontOriginHttpClient implements AutoCloseable {
|
||||
|
||||
private static final Duration CONNECT_TIMEOUT = Duration.ofSeconds(10);
|
||||
private static final Duration RESPONSE_TIMEOUT = Duration.ofSeconds(30);
|
||||
|
||||
private final CloseableHttpClient client;
|
||||
|
||||
CloudFrontOriginHttpClient(Collection<String> allowedPrivateOriginHosts) {
|
||||
this(SystemDefaultDnsResolver.INSTANCE, allowedPrivateOriginHosts, null);
|
||||
}
|
||||
|
||||
CloudFrontOriginHttpClient(DnsResolver delegate, Collection<String> allowedPrivateOriginHosts) {
|
||||
this(delegate, allowedPrivateOriginHosts, null);
|
||||
}
|
||||
|
||||
CloudFrontOriginHttpClient(
|
||||
DnsResolver delegate,
|
||||
Collection<String> allowedPrivateOriginHosts,
|
||||
SSLContext sslContext) {
|
||||
Set<String> allowedHosts = allowedPrivateOriginHosts.stream()
|
||||
.map(CloudFrontServingController::normalizeHost)
|
||||
.collect(Collectors.toUnmodifiableSet());
|
||||
DnsResolver validatingResolver = new ValidatingDnsResolver(delegate, allowedHosts);
|
||||
|
||||
ConnectionConfig connectionConfig = ConnectionConfig.custom()
|
||||
.setConnectTimeout(Timeout.of(CONNECT_TIMEOUT))
|
||||
.setSocketTimeout(Timeout.of(RESPONSE_TIMEOUT))
|
||||
.build();
|
||||
TlsConfig tlsConfig = TlsConfig.custom()
|
||||
.setHandshakeTimeout(Timeout.of(CONNECT_TIMEOUT))
|
||||
.setVersionPolicy(HttpVersionPolicy.FORCE_HTTP_1)
|
||||
.build();
|
||||
PoolingHttpClientConnectionManagerBuilder connectionManagerBuilder =
|
||||
PoolingHttpClientConnectionManagerBuilder.create()
|
||||
.setDnsResolver(validatingResolver)
|
||||
.setDefaultConnectionConfig(connectionConfig)
|
||||
.setDefaultTlsConfig(tlsConfig)
|
||||
.setMaxConnTotal(100)
|
||||
.setMaxConnPerRoute(20);
|
||||
if (sslContext != null) {
|
||||
connectionManagerBuilder.setTlsSocketStrategy(ClientTlsStrategyBuilder.create()
|
||||
.setSslContext(sslContext)
|
||||
.buildClassic());
|
||||
}
|
||||
PoolingHttpClientConnectionManager connectionManager = connectionManagerBuilder.build();
|
||||
RequestConfig requestConfig = RequestConfig.custom()
|
||||
.setConnectionRequestTimeout(Timeout.of(CONNECT_TIMEOUT))
|
||||
.setResponseTimeout(Timeout.of(RESPONSE_TIMEOUT))
|
||||
.setRedirectsEnabled(false)
|
||||
.setContentCompressionEnabled(false)
|
||||
.setProtocolUpgradeEnabled(false)
|
||||
.build();
|
||||
|
||||
this.client = HttpClients.custom()
|
||||
.setConnectionManager(connectionManager)
|
||||
.setDefaultRequestConfig(requestConfig)
|
||||
.disableAutomaticRetries()
|
||||
.disableRedirectHandling()
|
||||
.disableContentCompression()
|
||||
.disableCookieManagement()
|
||||
.setRoutePlanner(new DefaultRoutePlanner(DefaultSchemePortResolver.INSTANCE))
|
||||
.build();
|
||||
}
|
||||
|
||||
HttpResponse<byte[]> send(HttpRequest request, HttpResponse.BodyHandler<byte[]> bodyHandler)
|
||||
throws IOException, InterruptedException {
|
||||
if (Thread.currentThread().isInterrupted()) {
|
||||
throw new InterruptedException("CloudFront origin request interrupted");
|
||||
}
|
||||
if (request.bodyPublisher().filter(publisher -> publisher.contentLength() != 0).isPresent()) {
|
||||
throw new IOException("CloudFront origin request bodies are not supported");
|
||||
}
|
||||
|
||||
ClassicRequestBuilder builder = ClassicRequestBuilder.create(request.method())
|
||||
.setUri(request.uri())
|
||||
.setVersion(HttpVersion.HTTP_1_1);
|
||||
request.headers().map().forEach((name, values) ->
|
||||
values.forEach(value -> builder.addHeader(name, value)));
|
||||
|
||||
HttpClientContext context = HttpClientContext.create();
|
||||
Duration responseTimeout = request.timeout().orElse(RESPONSE_TIMEOUT);
|
||||
context.setRequestConfig(RequestConfig.custom()
|
||||
.setConnectionRequestTimeout(Timeout.of(CONNECT_TIMEOUT))
|
||||
.setResponseTimeout(Timeout.of(responseTimeout))
|
||||
.setRedirectsEnabled(false)
|
||||
.setContentCompressionEnabled(false)
|
||||
.setProtocolUpgradeEnabled(false)
|
||||
.build());
|
||||
|
||||
try {
|
||||
return client.execute(builder.build(), context, response -> {
|
||||
Map<String, List<String>> responseHeaders = new TreeMap<>(String.CASE_INSENSITIVE_ORDER);
|
||||
for (Header header : response.getHeaders()) {
|
||||
responseHeaders.computeIfAbsent(header.getName(), ignored -> new ArrayList<>())
|
||||
.add(header.getValue());
|
||||
}
|
||||
byte[] body = response.getEntity() != null
|
||||
? EntityUtils.toByteArray(response.getEntity())
|
||||
: new byte[0];
|
||||
return new PinnedHttpResponse(
|
||||
response.getCode(), request,
|
||||
HttpHeaders.of(responseHeaders, (name, value) -> true),
|
||||
body, request.uri());
|
||||
});
|
||||
} catch (InterruptedIOException e) {
|
||||
if (Thread.currentThread().isInterrupted()) {
|
||||
throw new InterruptedException("CloudFront origin request interrupted");
|
||||
}
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void close() throws IOException {
|
||||
client.close();
|
||||
}
|
||||
|
||||
private record PinnedHttpResponse(
|
||||
int statusCode,
|
||||
HttpRequest request,
|
||||
HttpHeaders headers,
|
||||
byte[] body,
|
||||
URI uri) implements HttpResponse<byte[]> {
|
||||
|
||||
@Override
|
||||
public Optional<HttpResponse<byte[]>> previousResponse() {
|
||||
return Optional.empty();
|
||||
}
|
||||
|
||||
@Override
|
||||
public Optional<SSLSession> sslSession() {
|
||||
return Optional.empty();
|
||||
}
|
||||
|
||||
@Override
|
||||
public HttpClient.Version version() {
|
||||
return HttpClient.Version.HTTP_1_1;
|
||||
}
|
||||
}
|
||||
|
||||
private record ValidatingDnsResolver(DnsResolver delegate, Set<String> allowedHosts)
|
||||
implements DnsResolver {
|
||||
|
||||
@Override
|
||||
public InetAddress[] resolve(String host) throws UnknownHostException {
|
||||
InetAddress[] addresses = delegate.resolve(host);
|
||||
String normalizedHost = CloudFrontServingController.normalizeHost(host);
|
||||
if (addresses == null || addresses.length == 0) {
|
||||
throw new UnknownHostException("CloudFront origin host has no addresses: " + normalizedHost);
|
||||
}
|
||||
if (!allowedHosts.contains(normalizedHost)) {
|
||||
for (InetAddress address : addresses) {
|
||||
if (CloudFrontServingController.isBlockedOriginAddress(address)) {
|
||||
throw new UnknownHostException(
|
||||
"CloudFront origin host resolves to a blocked address: " + normalizedHost);
|
||||
}
|
||||
}
|
||||
}
|
||||
return addresses.clone();
|
||||
}
|
||||
|
||||
@Override
|
||||
public String resolveCanonicalHostname(String host) {
|
||||
return CloudFrontServingController.normalizeHost(host);
|
||||
}
|
||||
}
|
||||
}
|
||||
+255
@@ -0,0 +1,255 @@
|
||||
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 java.util.ArrayDeque;
|
||||
import java.util.Deque;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
/**
|
||||
* Pure request-routing logic for CloudFront distribution serving, implemented to the AWS data-plane
|
||||
* spec (verified against the CloudFront Developer Guide):
|
||||
*
|
||||
* <ul>
|
||||
* <li>The requested path is normalized per RFC 3986 (collapse {@code //}, resolve {@code .}/{@code ..})
|
||||
* before behavior matching; the raw path is what gets forwarded to the origin.</li>
|
||||
* <li>Cache behaviors are evaluated in the order listed; the <em>default</em> behavior is always
|
||||
* processed <em>last</em>. The first matching path pattern wins.</li>
|
||||
* <li>Path patterns use {@code *} (0+ chars) and {@code ?} (exactly 1 char), are case-sensitive, and a
|
||||
* leading {@code /} is optional (ignored).</li>
|
||||
* <li>The default root object is returned <em>only</em> for the distribution root ({@code /}); it is
|
||||
* never appended for subdirectory requests (this differs from S3 website index documents).</li>
|
||||
* <li>The origin path is prepended to the request URI when forwarding to the origin.</li>
|
||||
* </ul>
|
||||
*
|
||||
* This class holds no distribution state and does no I/O. It keeps only a bounded compiled-pattern
|
||||
* cache so the routing rules remain cheap and can be unit-tested in isolation.
|
||||
*/
|
||||
public final class CloudFrontRequestRouter {
|
||||
|
||||
private static final int PATTERN_CACHE_CAPACITY = 256;
|
||||
private static final String REGION_PATTERN = "[a-z0-9-]+-[0-9]+";
|
||||
private static final Pattern AWS_S3_ENDPOINT = Pattern.compile(
|
||||
"(?:s3|s3\\.(?:dualstack\\.)?" + REGION_PATTERN
|
||||
+ "|s3-" + REGION_PATTERN
|
||||
+ "|s3-website[.-]" + REGION_PATTERN
|
||||
+ "|s3-accelerate(?:\\.dualstack)?)\\.amazonaws\\.com(?:\\.cn)?");
|
||||
private static final Pattern LOCAL_S3_ENDPOINT = Pattern.compile(
|
||||
"(?:s3(?:\\." + REGION_PATTERN + ")?"
|
||||
+ "|s3-website[.-]" + REGION_PATTERN
|
||||
+ ")\\.localhost(?:\\.(?:floci\\.io|localstack\\.cloud))?");
|
||||
private static final Map<String, Pattern> PATTERN_CACHE =
|
||||
new LinkedHashMap<>(PATTERN_CACHE_CAPACITY, 0.75f, true);
|
||||
|
||||
private CloudFrontRequestRouter() {
|
||||
}
|
||||
|
||||
/**
|
||||
* Normalizes a viewer request path per RFC 3986 the way CloudFront does before behavior matching:
|
||||
* resolves {@code .} / {@code ..} segments and collapses repeated slashes. Always returns a path
|
||||
* beginning with {@code /}.
|
||||
*/
|
||||
public static String normalizePath(String rawPath) {
|
||||
String path = (rawPath == null || rawPath.isEmpty()) ? "/" : rawPath;
|
||||
if (!path.startsWith("/")) {
|
||||
path = "/" + path;
|
||||
}
|
||||
boolean trailingSlash = path.length() > 1
|
||||
&& (path.endsWith("/") || path.endsWith("/.") || path.endsWith("/.."));
|
||||
Deque<String> out = new ArrayDeque<>();
|
||||
for (String seg : path.split("/")) {
|
||||
if (seg.isEmpty() || seg.equals(".")) {
|
||||
continue; // collapses "//" and drops "."
|
||||
}
|
||||
if (seg.equals("..")) {
|
||||
if (!out.isEmpty()) {
|
||||
out.removeLast();
|
||||
}
|
||||
continue;
|
||||
}
|
||||
out.addLast(seg);
|
||||
}
|
||||
if (out.isEmpty()) {
|
||||
return "/";
|
||||
}
|
||||
String joined = "/" + String.join("/", out);
|
||||
return trailingSlash ? joined + "/" : joined;
|
||||
}
|
||||
|
||||
/** True when {@code path} is the distribution root. */
|
||||
public static boolean isRoot(String normalizedPath) {
|
||||
return normalizedPath == null || normalizedPath.isEmpty() || normalizedPath.equals("/");
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the {@code targetOriginId} for a normalized path by evaluating the ordered cache
|
||||
* behaviors first (first match wins) and falling back to the default behavior last.
|
||||
*/
|
||||
public static String matchTargetOriginId(DistributionConfig config, String normalizedPath) {
|
||||
List<CacheBehavior> behaviors = config.getCacheBehaviors();
|
||||
if (behaviors != null) {
|
||||
for (CacheBehavior behavior : behaviors) {
|
||||
if (pathPatternMatches(behavior.getPathPattern(), normalizedPath)) {
|
||||
return behavior.getTargetOriginId();
|
||||
}
|
||||
}
|
||||
}
|
||||
DefaultCacheBehavior dflt = config.getDefaultCacheBehavior();
|
||||
return dflt != null ? dflt.getTargetOriginId() : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Matches a CloudFront path pattern against a normalized path. A leading {@code /} on either side is
|
||||
* ignored, {@code *} matches zero or more characters, {@code ?} matches exactly one, and matching is
|
||||
* case-sensitive. A {@code null}/blank or {@code *} pattern matches everything (the default behavior).
|
||||
*/
|
||||
public static boolean pathPatternMatches(String pattern, String path) {
|
||||
if (pattern == null || pattern.isEmpty() || pattern.equals("*") || pattern.equals("/*")) {
|
||||
return true;
|
||||
}
|
||||
String p = pattern.startsWith("/") ? pattern.substring(1) : pattern;
|
||||
String candidate = path.startsWith("/") ? path.substring(1) : path;
|
||||
return compiledPattern(p).matcher(candidate).matches();
|
||||
}
|
||||
|
||||
private static Pattern compiledPattern(String pattern) {
|
||||
synchronized (PATTERN_CACHE) {
|
||||
Pattern compiled = PATTERN_CACHE.get(pattern);
|
||||
if (compiled != null) {
|
||||
return compiled;
|
||||
}
|
||||
if (PATTERN_CACHE.size() >= PATTERN_CACHE_CAPACITY) {
|
||||
String eldest = PATTERN_CACHE.keySet().iterator().next();
|
||||
PATTERN_CACHE.remove(eldest);
|
||||
}
|
||||
compiled = Pattern.compile(wildcardToRegex(pattern));
|
||||
PATTERN_CACHE.put(pattern, compiled);
|
||||
return compiled;
|
||||
}
|
||||
}
|
||||
|
||||
static int patternCacheSize() {
|
||||
synchronized (PATTERN_CACHE) {
|
||||
return PATTERN_CACHE.size();
|
||||
}
|
||||
}
|
||||
|
||||
static void clearPatternCache() {
|
||||
synchronized (PATTERN_CACHE) {
|
||||
PATTERN_CACHE.clear();
|
||||
}
|
||||
}
|
||||
|
||||
private static String wildcardToRegex(String pattern) {
|
||||
StringBuilder regex = new StringBuilder(pattern.length() + 8);
|
||||
for (int i = 0; i < pattern.length(); i++) {
|
||||
char c = pattern.charAt(i);
|
||||
switch (c) {
|
||||
case '*' -> regex.append(".*");
|
||||
case '?' -> regex.append('.');
|
||||
// Escape every other regex metacharacter so patterns match literally.
|
||||
case '.', '\\', '+', '(', ')', '[', ']', '{', '}', '^', '$', '|' -> regex.append('\\').append(c);
|
||||
default -> regex.append(c);
|
||||
}
|
||||
}
|
||||
return regex.toString();
|
||||
}
|
||||
|
||||
/**
|
||||
* Computes the origin object key for a request: the default root object is used only for the root
|
||||
* request; the origin path is prepended; the result never begins with {@code /} (S3-object form).
|
||||
*/
|
||||
public static String resolveOriginKey(String originPath, String normalizedPath, String defaultRootObject) {
|
||||
String combined = resolveForwardUri(originPath, normalizedPath, defaultRootObject);
|
||||
return combined.startsWith("/") ? combined.substring(1) : combined;
|
||||
}
|
||||
|
||||
/**
|
||||
* Computes the URI to forward to the origin: the default root object replaces the path only for the
|
||||
* root request (applies to custom origins as well as S3), then the origin path is prepended. The
|
||||
* result keeps its leading {@code /} (custom-origin URI form).
|
||||
*/
|
||||
public static String resolveForwardUri(String originPath, String normalizedPath, String defaultRootObject) {
|
||||
String object;
|
||||
if (isRoot(normalizedPath) && defaultRootObject != null && !defaultRootObject.isBlank()) {
|
||||
object = defaultRootObject;
|
||||
} else {
|
||||
object = normalizedPath;
|
||||
}
|
||||
return joinPath(originPath, object);
|
||||
}
|
||||
|
||||
/** Joins an optional origin path with the object path, normalizing the slash between them. */
|
||||
public static String joinPath(String originPath, String object) {
|
||||
String base = (originPath == null) ? "" : originPath.trim();
|
||||
if (base.endsWith("/")) {
|
||||
base = base.substring(0, base.length() - 1);
|
||||
}
|
||||
String obj = (object == null) ? "" : object;
|
||||
if (!obj.startsWith("/")) {
|
||||
obj = "/" + obj;
|
||||
}
|
||||
return base + obj;
|
||||
}
|
||||
|
||||
/** Finds the origin with the given id, or {@code null}. */
|
||||
public static Origin findOrigin(DistributionConfig config, String originId) {
|
||||
if (config.getOrigins() == null || originId == null) {
|
||||
return null;
|
||||
}
|
||||
for (Origin origin : config.getOrigins()) {
|
||||
if (originId.equals(origin.getId())) {
|
||||
return origin;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/** True when the origin is an S3 (non-website) origin — modeled by the presence of {@code S3OriginConfig}. */
|
||||
public static boolean isS3Origin(Origin origin) {
|
||||
return origin != null && origin.getS3OriginConfig() != null && origin.getCustomOriginConfig() == null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Extracts the bucket name from an S3 origin domain name. Handles the regional/global REST endpoints
|
||||
* ({@code bucket.s3.us-east-1.amazonaws.com}, {@code bucket.s3.amazonaws.com}) and the website
|
||||
* endpoint ({@code bucket.s3-website-us-east-1.amazonaws.com}) — the bucket is the leading label(s)
|
||||
* before the {@code .s3} / {@code .s3-website} marker.
|
||||
*/
|
||||
public static String bucketFromS3Domain(String domainName) {
|
||||
if (domainName == null || domainName.isBlank()) {
|
||||
return null;
|
||||
}
|
||||
String host = domainName;
|
||||
int colon = host.lastIndexOf(':');
|
||||
if (colon > 0) {
|
||||
String port = host.substring(colon + 1);
|
||||
if (port.isEmpty() || !port.chars().allMatch(Character::isDigit)) {
|
||||
return null;
|
||||
}
|
||||
host = host.substring(0, colon);
|
||||
}
|
||||
String lowerHost = host.toLowerCase(java.util.Locale.ROOT);
|
||||
int endpointMarker = -1;
|
||||
for (String marker : new String[] {".s3-website-", ".s3-website.", ".s3.", ".s3-"}) {
|
||||
endpointMarker = Math.max(endpointMarker, lowerHost.lastIndexOf(marker));
|
||||
}
|
||||
if (endpointMarker > 0 && supportedS3Endpoint(lowerHost.substring(endpointMarker + 1))) {
|
||||
return host.substring(0, endpointMarker);
|
||||
}
|
||||
// A bare bucket name is accepted for local configuration. An unrecognized dotted host is
|
||||
// not an S3 endpoint and must not be truncated into a different local bucket name.
|
||||
return host.indexOf('.') < 0 ? host : null;
|
||||
}
|
||||
|
||||
private static boolean supportedS3Endpoint(String endpoint) {
|
||||
return AWS_S3_ENDPOINT.matcher(endpoint).matches()
|
||||
|| LOCAL_S3_ENDPOINT.matcher(endpoint).matches();
|
||||
}
|
||||
}
|
||||
+233
-9
@@ -11,11 +11,13 @@ import io.github.hectorvent.floci.services.cloudfront.model.CloudFrontFunction;
|
||||
import io.github.hectorvent.floci.services.cloudfront.model.CloudFrontOriginAccessIdentity;
|
||||
import io.github.hectorvent.floci.services.cloudfront.model.ContinuousDeploymentPolicy;
|
||||
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.FieldLevelEncryptionConfig;
|
||||
import io.github.hectorvent.floci.services.cloudfront.model.FieldLevelEncryptionProfile;
|
||||
import io.github.hectorvent.floci.services.cloudfront.model.Invalidation;
|
||||
import io.github.hectorvent.floci.services.cloudfront.model.KeyGroup;
|
||||
import io.github.hectorvent.floci.services.cloudfront.model.MonitoringSubscription;
|
||||
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.OriginRequestPolicy;
|
||||
import io.github.hectorvent.floci.services.cloudfront.model.PublicKey;
|
||||
@@ -31,6 +33,7 @@ import java.util.ArrayList;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.UUID;
|
||||
import java.util.function.Function;
|
||||
|
||||
@@ -39,6 +42,10 @@ public class CloudFrontService {
|
||||
|
||||
private static final String CHARS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
|
||||
private static final SecureRandom RANDOM = new SecureRandom();
|
||||
private static final Set<String> OAC_ORIGIN_TYPES =
|
||||
Set.of("s3", "mediastore", "mediapackagev2", "lambda");
|
||||
private static final Set<String> OAC_SIGNING_BEHAVIORS =
|
||||
Set.of("always", "never", "no-override");
|
||||
|
||||
private final StorageBackend<String, Distribution> distStore;
|
||||
private final StorageBackend<String, List<Invalidation>> invalidationStore;
|
||||
@@ -103,6 +110,7 @@ public class CloudFrontService {
|
||||
// ── Distributions ─────────────────────────────────────────────────────────
|
||||
|
||||
public synchronized Distribution createDistribution(Distribution dist, Map<String, String> tags) {
|
||||
ensureAliasesAvailable(dist.getConfig(), null);
|
||||
String id = generateDistributionId();
|
||||
dist.setId(id);
|
||||
dist.setArn(AwsArnUtils.Arn.of("cloudfront", "", accountId, "distribution/" + id).toString());
|
||||
@@ -129,6 +137,7 @@ public class CloudFrontService {
|
||||
throw new AwsException("InvalidIfMatchVersion",
|
||||
"The If-Match version is missing or not valid for the resource.", 400);
|
||||
}
|
||||
ensureAliasesAvailable(updated.getConfig(), id);
|
||||
updated.setId(id);
|
||||
updated.setArn(existing.getArn());
|
||||
updated.setDomainName(existing.getDomainName());
|
||||
@@ -155,6 +164,17 @@ public class CloudFrontService {
|
||||
tagStore.delete("distribution/" + id);
|
||||
}
|
||||
|
||||
/**
|
||||
* Removes a distribution and its associated invalidations/tags without the disable/If-Match guards
|
||||
* enforced by {@link #deleteDistribution(String, String)}. Used by CloudFormation stack deletion,
|
||||
* which owns the resource lifecycle at the stack level.
|
||||
*/
|
||||
public synchronized void removeDistribution(String id) {
|
||||
distStore.delete(id);
|
||||
invalidationStore.delete(id);
|
||||
tagStore.delete("distribution/" + id);
|
||||
}
|
||||
|
||||
public List<Distribution> listDistributions(String marker, int maxItems) {
|
||||
List<Distribution> all = new ArrayList<>(distStore.scan(k -> true));
|
||||
all.sort((a, b) -> a.getId().compareTo(b.getId()));
|
||||
@@ -175,23 +195,138 @@ public class CloudFrontService {
|
||||
}
|
||||
|
||||
public synchronized void associateAlias(String targetDistributionId, String alias) {
|
||||
if (alias == null || alias.isBlank()) {
|
||||
throw new AwsException("InvalidArgument", "The alias must not be empty.", 400);
|
||||
}
|
||||
Distribution dist = getDistribution(targetDistributionId);
|
||||
List<String> aliases = dist.getConfig() != null ? dist.getConfig().getAliases() : null;
|
||||
if (dist.getConfig() == null) {
|
||||
throw new AwsException("InvalidArgument", "The target distribution has no configuration.", 400);
|
||||
}
|
||||
for (Distribution candidate : distStore.scan(k -> true)) {
|
||||
if (targetDistributionId.equals(candidate.getId()) || candidate.getConfig() == null
|
||||
|| candidate.getConfig().getAliases() == null) {
|
||||
continue;
|
||||
}
|
||||
List<String> previousAliases = candidate.getConfig().getAliases();
|
||||
List<String> remaining = new ArrayList<>(previousAliases);
|
||||
remaining.removeIf(existing -> alias.equalsIgnoreCase(existing));
|
||||
if (remaining.size() != previousAliases.size()) {
|
||||
candidate.getConfig().setAliases(remaining);
|
||||
candidate.setEtag(UUID.randomUUID().toString());
|
||||
candidate.setLastModifiedTime(Instant.now());
|
||||
distStore.put(candidate.getId(), candidate);
|
||||
}
|
||||
}
|
||||
|
||||
List<String> aliases = dist.getConfig().getAliases();
|
||||
if (aliases == null) {
|
||||
aliases = new ArrayList<>();
|
||||
} else {
|
||||
aliases = new ArrayList<>(aliases);
|
||||
}
|
||||
if (!aliases.contains(alias)) {
|
||||
aliases.add(alias);
|
||||
}
|
||||
if (dist.getConfig() != null) {
|
||||
dist.getConfig().setAliases(aliases);
|
||||
}
|
||||
aliases.removeIf(existing -> alias.equalsIgnoreCase(existing));
|
||||
aliases.add(alias);
|
||||
dist.getConfig().setAliases(aliases);
|
||||
dist.setEtag(UUID.randomUUID().toString());
|
||||
dist.setLastModifiedTime(Instant.now());
|
||||
distStore.put(targetDistributionId, dist);
|
||||
}
|
||||
|
||||
/**
|
||||
* Finds the distribution whose data-plane requests should be served for the given {@code Host}
|
||||
* header. A distribution matches when the host equals its assigned CloudFront domain name
|
||||
* ({@code <id>.cloudfront.net}) or one of its alternate domain names (CNAME aliases). Any port
|
||||
* suffix is ignored and matching is case-insensitive. Returns {@code null} when nothing matches.
|
||||
*/
|
||||
public Distribution findByHost(String host) {
|
||||
if (host == null || host.isBlank()) {
|
||||
return null;
|
||||
}
|
||||
String hostname = stripPort(host);
|
||||
List<Distribution> distributions = new ArrayList<>(distStore.scan(k -> true));
|
||||
for (Distribution dist : distributions) {
|
||||
if (hostname.equalsIgnoreCase(dist.getDomainName())) {
|
||||
return dist;
|
||||
}
|
||||
}
|
||||
for (Distribution dist : distributions) {
|
||||
DistributionConfig cfg = dist.getConfig();
|
||||
if (cfg != null && cfg.getAliases() != null) {
|
||||
for (String alias : cfg.getAliases()) {
|
||||
if (hostname.equalsIgnoreCase(alias)) {
|
||||
return dist;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Distribution best = null;
|
||||
int bestSpecificity = -1;
|
||||
for (Distribution dist : distributions) {
|
||||
DistributionConfig cfg = dist.getConfig();
|
||||
if (cfg == null || cfg.getAliases() == null) {
|
||||
continue;
|
||||
}
|
||||
for (String alias : cfg.getAliases()) {
|
||||
if (wildcardAliasMatches(alias, hostname) && alias.length() > bestSpecificity) {
|
||||
best = dist;
|
||||
bestSpecificity = alias.length();
|
||||
}
|
||||
}
|
||||
}
|
||||
return best;
|
||||
}
|
||||
|
||||
private void ensureAliasesAvailable(DistributionConfig config, String currentDistributionId) {
|
||||
if (config == null || config.getAliases() == null) {
|
||||
return;
|
||||
}
|
||||
for (String requested : config.getAliases()) {
|
||||
if (requested == null || requested.isBlank()) {
|
||||
continue;
|
||||
}
|
||||
for (Distribution existing : distStore.scan(k -> true)) {
|
||||
if (existing.getId().equals(currentDistributionId) || existing.getConfig() == null
|
||||
|| existing.getConfig().getAliases() == null) {
|
||||
continue;
|
||||
}
|
||||
for (String assigned : existing.getConfig().getAliases()) {
|
||||
if (requested.equalsIgnoreCase(assigned)) {
|
||||
throw new AwsException("CNAMEAlreadyExists",
|
||||
"The CNAME you provided is already associated with a different resource.", 409);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static boolean wildcardAliasMatches(String alias, String hostname) {
|
||||
if (alias == null || !alias.startsWith("*.") || hostname == null) {
|
||||
return false;
|
||||
}
|
||||
String suffix = alias.substring(1); // ".example.com"
|
||||
if (hostname.length() <= suffix.length()
|
||||
|| !hostname.regionMatches(true, hostname.length() - suffix.length(),
|
||||
suffix, 0, suffix.length())) {
|
||||
return false;
|
||||
}
|
||||
// A CloudFront wildcard replaces exactly one label, so the part standing in for the "*"
|
||||
// must not itself contain a dot: "*.example.com" covers marketing.example.com but not
|
||||
// marketing.product.example.com. AWS is explicit that names at a level higher or lower
|
||||
// than the wildcard are not covered.
|
||||
return hostname.lastIndexOf('.', hostname.length() - suffix.length() - 1) < 0;
|
||||
}
|
||||
|
||||
private static String stripPort(String host) {
|
||||
int colon = host.lastIndexOf(':');
|
||||
if (colon > 0) {
|
||||
String maybePort = host.substring(colon + 1);
|
||||
if (!maybePort.isEmpty() && maybePort.chars().allMatch(Character::isDigit)) {
|
||||
return host.substring(0, colon);
|
||||
}
|
||||
}
|
||||
return host;
|
||||
}
|
||||
|
||||
// ── Invalidations ─────────────────────────────────────────────────────────
|
||||
|
||||
public synchronized Invalidation createInvalidation(String distributionId, Invalidation inv) {
|
||||
@@ -414,6 +549,7 @@ public class CloudFrontService {
|
||||
// ── Origin Access Control ─────────────────────────────────────────────────
|
||||
|
||||
public synchronized OriginAccessControl createOriginAccessControl(OriginAccessControl oac) {
|
||||
validateOriginAccessControl(oac);
|
||||
oac.setId(UUID.randomUUID().toString());
|
||||
oac.setEtag(UUID.randomUUID().toString());
|
||||
oac.setLastModifiedTime(Instant.now());
|
||||
@@ -434,6 +570,7 @@ public class CloudFrontService {
|
||||
throw new AwsException("InvalidIfMatchVersion",
|
||||
"The If-Match version is missing or not valid for the resource.", 400);
|
||||
}
|
||||
validateOriginAccessControl(updated);
|
||||
updated.setId(id);
|
||||
updated.setEtag(UUID.randomUUID().toString());
|
||||
updated.setLastModifiedTime(Instant.now());
|
||||
@@ -447,6 +584,11 @@ public class CloudFrontService {
|
||||
throw new AwsException("InvalidIfMatchVersion",
|
||||
"The If-Match version is missing or not valid for the resource.", 400);
|
||||
}
|
||||
if (originAccessControlInUse(id)) {
|
||||
throw new AwsException("OriginAccessControlInUse",
|
||||
"Cannot delete the origin access control because it's in use by one or more distributions.",
|
||||
409);
|
||||
}
|
||||
oacStore.delete(id);
|
||||
}
|
||||
|
||||
@@ -514,6 +656,10 @@ public class CloudFrontService {
|
||||
throw new AwsException("InvalidIfMatchVersion",
|
||||
"The If-Match version is missing or not valid for the resource.", 400);
|
||||
}
|
||||
if (originAccessIdentityInUse(id)) {
|
||||
throw new AwsException("CloudFrontOriginAccessIdentityInUse",
|
||||
"The Origin Access Identity specified is already in use.", 409);
|
||||
}
|
||||
oaiStore.delete(id);
|
||||
}
|
||||
|
||||
@@ -536,6 +682,84 @@ public class CloudFrontService {
|
||||
return all;
|
||||
}
|
||||
|
||||
private static void validateOriginAccessControl(OriginAccessControl oac) {
|
||||
if (oac == null) {
|
||||
throw new AwsException("InvalidArgument",
|
||||
"The origin access control configuration is required.", 400);
|
||||
}
|
||||
if (oac.getName() == null || oac.getName().isBlank()) {
|
||||
throw new AwsException("InvalidArgument", "The parameter Name is required.", 400);
|
||||
}
|
||||
if (oac.getName().length() > 64) {
|
||||
throw new AwsException("InvalidArgument",
|
||||
"The parameter Name must be 64 characters or fewer.", 400);
|
||||
}
|
||||
if (!"sigv4".equals(oac.getSigningProtocol())) {
|
||||
throw new AwsException("InvalidArgument",
|
||||
"The parameter SigningProtocol must be sigv4.", 400);
|
||||
}
|
||||
if (oac.getSigningBehavior() == null
|
||||
|| !OAC_SIGNING_BEHAVIORS.contains(oac.getSigningBehavior())) {
|
||||
throw new AwsException("InvalidArgument",
|
||||
"The parameter SigningBehavior must be one of always, never, or no-override.",
|
||||
400);
|
||||
}
|
||||
if (oac.getOriginAccessControlOriginType() == null
|
||||
|| !OAC_ORIGIN_TYPES.contains(oac.getOriginAccessControlOriginType())) {
|
||||
throw new AwsException("InvalidArgument",
|
||||
"The parameter OriginAccessControlOriginType must be one of s3, mediastore, "
|
||||
+ "mediapackagev2, or lambda.",
|
||||
400);
|
||||
}
|
||||
}
|
||||
|
||||
private boolean originAccessControlInUse(String id) {
|
||||
for (Distribution distribution : distStore.scan(k -> true)) {
|
||||
DistributionConfig config = distribution.getConfig();
|
||||
if (config == null || config.getOrigins() == null) {
|
||||
continue;
|
||||
}
|
||||
for (Origin origin : config.getOrigins()) {
|
||||
if (origin != null && id.equals(origin.getOriginAccessControlId())) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
private boolean originAccessIdentityInUse(String id) {
|
||||
for (Distribution distribution : distStore.scan(k -> true)) {
|
||||
DistributionConfig config = distribution.getConfig();
|
||||
if (config == null || config.getOrigins() == null) {
|
||||
continue;
|
||||
}
|
||||
for (Origin origin : config.getOrigins()) {
|
||||
if (origin != null && originAccessIdentityMatches(
|
||||
origin.getS3OriginConfig() != null
|
||||
? origin.getS3OriginConfig().get("OriginAccessIdentity")
|
||||
: null,
|
||||
id)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
for (StreamingDistribution distribution : streamingDistStore.scan(k -> true)) {
|
||||
if (originAccessIdentityMatches(distribution.getS3OriginAccessIdentity(), id)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
private static boolean originAccessIdentityMatches(String reference, String id) {
|
||||
if (reference == null || reference.isBlank()) {
|
||||
return false;
|
||||
}
|
||||
String normalized = reference.startsWith("/") ? reference.substring(1) : reference;
|
||||
return normalized.equals("origin-access-identity/cloudfront/" + id);
|
||||
}
|
||||
|
||||
// ── CloudFront Functions ──────────────────────────────────────────────────
|
||||
|
||||
public synchronized CloudFrontFunction createFunction(CloudFrontFunction fn) {
|
||||
@@ -599,14 +823,14 @@ public class CloudFrontService {
|
||||
functionStore.delete(name);
|
||||
}
|
||||
|
||||
public List<CloudFrontFunction> listFunctions(String stage) {
|
||||
public List<CloudFrontFunction> listFunctions(String stage, String marker, int maxItems) {
|
||||
List<CloudFrontFunction> all = new ArrayList<>(functionStore.scan(k -> true));
|
||||
if (stage != null && !stage.isEmpty()) {
|
||||
all = all.stream().filter(f -> stage.equals(f.getStage())).toList();
|
||||
all = new ArrayList<>(all);
|
||||
}
|
||||
all.sort((a, b) -> a.getName().compareTo(b.getName()));
|
||||
return all;
|
||||
return paginate(all, marker, maxItems, CloudFrontFunction::getName);
|
||||
}
|
||||
|
||||
// ── Tags ──────────────────────────────────────────────────────────────────
|
||||
|
||||
+603
@@ -0,0 +1,603 @@
|
||||
package io.github.hectorvent.floci.services.cloudfront;
|
||||
|
||||
import io.github.hectorvent.floci.config.EmulatorConfig;
|
||||
import io.github.hectorvent.floci.core.common.AwsException;
|
||||
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.github.hectorvent.floci.services.s3.model.S3Object;
|
||||
import io.quarkus.vertx.http.runtime.CurrentVertxRequest;
|
||||
import jakarta.annotation.PreDestroy;
|
||||
import jakarta.inject.Inject;
|
||||
import jakarta.ws.rs.GET;
|
||||
import jakarta.ws.rs.HEAD;
|
||||
import jakarta.ws.rs.Path;
|
||||
import jakarta.ws.rs.PathParam;
|
||||
import jakarta.ws.rs.core.Context;
|
||||
import jakarta.ws.rs.core.HttpHeaders;
|
||||
import jakarta.ws.rs.core.MediaType;
|
||||
import jakarta.ws.rs.core.Response;
|
||||
import jakarta.ws.rs.core.UriInfo;
|
||||
import org.jboss.logging.Logger;
|
||||
|
||||
import java.net.IDN;
|
||||
import java.net.InetAddress;
|
||||
import java.net.URI;
|
||||
import java.net.http.HttpRequest;
|
||||
import java.net.http.HttpResponse;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.time.Duration;
|
||||
import java.time.ZoneOffset;
|
||||
import java.time.format.DateTimeFormatter;
|
||||
import java.util.HashSet;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
|
||||
/**
|
||||
* Serves viewer requests routed to a CloudFront distribution (via {@link CloudFrontDistributionFilter})
|
||||
* by resolving the matching cache behavior + origin and returning the origin content, implemented to
|
||||
* the AWS CloudFront data-plane spec.
|
||||
*
|
||||
* <p>The internal path is {@code /_cloudfront/{distId}/{proxy:.*}}; {@code proxy} is the viewer's path
|
||||
* relative to the distribution. Routing (behavior/path-pattern matching, default-root-object, origin
|
||||
* path) is delegated to {@link CloudFrontRequestRouter}. This controller performs the origin I/O:
|
||||
*
|
||||
* <ul>
|
||||
* <li>S3 origins are read in-process through {@link S3Service} (the bucket is derived from the
|
||||
* origin domain name).</li>
|
||||
* <li>Custom origins are fetched over HTTP(S) with {@link java.net.http.HttpClient}.</li>
|
||||
* <li>When an origin returns an error status, a matching {@code CustomErrorResponse} is applied —
|
||||
* most importantly the single-page-app fallback that rewrites 403/404 to 200 {@code /index.html}.
|
||||
* If the configured error page is itself missing, the received status is returned (no loop).</li>
|
||||
* </ul>
|
||||
*
|
||||
* <p>Viewer-protocol-policy and allowed-method enforcement are intentionally out of scope for this
|
||||
* layer: the emulator is HTTP-first and serves GET/HEAD regardless of scheme.
|
||||
*/
|
||||
@Path("/_cloudfront/{distId}")
|
||||
public class CloudFrontServingController {
|
||||
|
||||
private static final Logger LOG = Logger.getLogger(CloudFrontServingController.class);
|
||||
private static final String DEFAULT_CONTENT_TYPE = "application/octet-stream";
|
||||
private static final DateTimeFormatter HTTP_DATE = DateTimeFormatter.RFC_1123_DATE_TIME
|
||||
.withZone(ZoneOffset.UTC);
|
||||
private static final Set<String> NON_FORWARDED_RESPONSE_HEADERS = Set.of(
|
||||
"connection", "keep-alive", "proxy-authenticate", "proxy-authorization",
|
||||
"proxy-connection", "te", "trailer", "transfer-encoding", "upgrade", "via",
|
||||
"content-length", "content-type");
|
||||
|
||||
private final CloudFrontService service;
|
||||
private final S3Service s3Service;
|
||||
private final CurrentVertxRequest currentVertxRequest;
|
||||
private final CloudFrontOriginHttpClient httpClient;
|
||||
|
||||
@Inject
|
||||
public CloudFrontServingController(CloudFrontService service, S3Service s3Service,
|
||||
EmulatorConfig emulatorConfig,
|
||||
CurrentVertxRequest currentVertxRequest) {
|
||||
this.service = service;
|
||||
this.s3Service = s3Service;
|
||||
this.currentVertxRequest = currentVertxRequest;
|
||||
this.httpClient = new CloudFrontOriginHttpClient(
|
||||
emulatorConfig.services().cloudfront().allowedPrivateOriginHosts().orElse(List.of()));
|
||||
}
|
||||
|
||||
@PreDestroy
|
||||
void closeHttpClient() {
|
||||
try {
|
||||
httpClient.close();
|
||||
} catch (Exception e) {
|
||||
LOG.debugv("Could not close CloudFront origin HTTP client: {0}", e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
@GET
|
||||
@Path("/{proxy:.*}")
|
||||
public Response get(@PathParam("distId") String distId, @PathParam("proxy") String proxy,
|
||||
@Context HttpHeaders headers, @Context UriInfo uriInfo) {
|
||||
String rawViewerPath = rawViewerPath(currentVertxRequest.getCurrent().request().uri());
|
||||
return serve(distId, rawViewerPath, decodedViewerPath(rawViewerPath),
|
||||
uriInfo.getRequestUri().getScheme(), headers.getHeaderString("Host"),
|
||||
headers.getHeaderString(HttpHeaders.AUTHORIZATION), true);
|
||||
}
|
||||
|
||||
@HEAD
|
||||
@Path("/{proxy:.*}")
|
||||
public Response head(@PathParam("distId") String distId, @PathParam("proxy") String proxy,
|
||||
@Context HttpHeaders headers, @Context UriInfo uriInfo) {
|
||||
String rawViewerPath = rawViewerPath(currentVertxRequest.getCurrent().request().uri());
|
||||
return serve(distId, rawViewerPath, decodedViewerPath(rawViewerPath),
|
||||
uriInfo.getRequestUri().getScheme(), headers.getHeaderString("Host"),
|
||||
headers.getHeaderString(HttpHeaders.AUTHORIZATION), false);
|
||||
}
|
||||
|
||||
private Response serve(String distId, String rawViewerPath, String decodedViewerPath,
|
||||
String viewerScheme, String viewerHost, String viewerAuthorization,
|
||||
boolean includeBody) {
|
||||
Distribution dist = service.findByHost(viewerHost);
|
||||
if (dist == null || !distId.equals(dist.getId())) {
|
||||
return textError(404, "Distribution not found.");
|
||||
}
|
||||
DistributionConfig config = dist.getConfig();
|
||||
if (config == null) {
|
||||
return textError(502, "Distribution has no configuration.");
|
||||
}
|
||||
if (!config.isEnabled()) {
|
||||
return textError(404, "Distribution is disabled.");
|
||||
}
|
||||
|
||||
String normalized = CloudFrontRequestRouter.normalizePath(decodedViewerPath);
|
||||
|
||||
OriginResponse origin = route(dist, normalized, rawViewerPath, decodedViewerPath,
|
||||
viewerScheme, viewerAuthorization, includeBody);
|
||||
|
||||
if (origin.status() >= 400) {
|
||||
Response fallback = applyCustomError(
|
||||
dist, origin, viewerScheme, viewerAuthorization, includeBody);
|
||||
if (fallback != null) {
|
||||
return fallback;
|
||||
}
|
||||
}
|
||||
return toResponse(origin, includeBody);
|
||||
}
|
||||
|
||||
/** Selects an origin with the normalized path, then forwards the original viewer path. */
|
||||
private OriginResponse route(Distribution distribution, String normalized,
|
||||
String rawViewerPath, String decodedViewerPath,
|
||||
String viewerScheme, String viewerAuthorization,
|
||||
boolean includeBody) {
|
||||
DistributionConfig config = distribution.getConfig();
|
||||
String originId = CloudFrontRequestRouter.matchTargetOriginId(config, normalized);
|
||||
Origin origin = CloudFrontRequestRouter.findOrigin(config, originId);
|
||||
if (origin == null) {
|
||||
return OriginResponse.error(502, "No origin matched the request.");
|
||||
}
|
||||
if (CloudFrontRequestRouter.isS3Origin(origin)) {
|
||||
String key = CloudFrontRequestRouter.resolveOriginKey(
|
||||
origin.getOriginPath(), decodedViewerPath, config.getDefaultRootObject());
|
||||
return fetchFromS3(
|
||||
distribution, origin, key, viewerAuthorization, includeBody);
|
||||
}
|
||||
String forwardUri = CloudFrontRequestRouter.resolveForwardUri(
|
||||
origin.getOriginPath(), rawViewerPath, config.getDefaultRootObject());
|
||||
// CloudFront forwards viewer query strings only when selected by a cache policy,
|
||||
// origin request policy, or legacy ForwardedValues configuration. Those policy
|
||||
// semantics are not modeled in the data plane yet, so the AWS default is to omit them.
|
||||
return fetchFromCustomOrigin(origin, forwardUri, null, viewerScheme, includeBody);
|
||||
}
|
||||
|
||||
private OriginResponse fetchFromS3(
|
||||
Distribution distribution,
|
||||
Origin origin,
|
||||
String key,
|
||||
String viewerAuthorization,
|
||||
boolean includeBody) {
|
||||
String bucket = CloudFrontRequestRouter.bucketFromS3Domain(origin.getDomainName());
|
||||
if (bucket == null) {
|
||||
return OriginResponse.error(502, "Could not determine S3 bucket for origin.");
|
||||
}
|
||||
try {
|
||||
authorizeS3OriginRead(
|
||||
distribution, origin, bucket, key, viewerAuthorization);
|
||||
if (includeBody) {
|
||||
S3Object obj = s3Service.getObject(bucket, key);
|
||||
byte[] data = obj.getData() != null ? obj.getData() : new byte[0];
|
||||
return new OriginResponse(
|
||||
200, contentType(obj), data, data.length, s3ObjectHeaders(obj));
|
||||
}
|
||||
S3Object meta = s3Service.headObject(bucket, key);
|
||||
return new OriginResponse(
|
||||
200, contentType(meta), null, meta.getSize(), s3ObjectHeaders(meta));
|
||||
} catch (AwsException e) {
|
||||
return OriginResponse.error(e.getHttpStatus(), e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
private void authorizeS3OriginRead(
|
||||
Distribution distribution,
|
||||
Origin origin,
|
||||
String bucket,
|
||||
String key,
|
||||
String viewerAuthorization) {
|
||||
String oacId = origin.getOriginAccessControlId();
|
||||
if (oacId != null && !oacId.isBlank()) {
|
||||
OriginAccessControl oac = service.getOriginAccessControl(oacId);
|
||||
String signingBehavior = oac.getSigningBehavior();
|
||||
boolean viewerSigned = viewerAuthorization != null && !viewerAuthorization.isBlank();
|
||||
boolean cloudFrontSigns = "always".equalsIgnoreCase(signingBehavior)
|
||||
|| ("no-override".equalsIgnoreCase(signingBehavior) && !viewerSigned);
|
||||
if (cloudFrontSigns) {
|
||||
s3Service.authorizeCloudFrontOacGetObject(
|
||||
bucket, key, distribution.getArn());
|
||||
return;
|
||||
}
|
||||
if ("no-override".equalsIgnoreCase(signingBehavior) && viewerSigned) {
|
||||
s3Service.authorizeCloudFrontViewerGetObject(
|
||||
bucket, key, viewerAuthorization);
|
||||
return;
|
||||
}
|
||||
s3Service.authorizeAnonymousGetObject(bucket, key);
|
||||
return;
|
||||
}
|
||||
|
||||
String oaiId = originAccessIdentityId(origin);
|
||||
if (oaiId != null) {
|
||||
var oai = service.getCloudFrontOriginAccessIdentity(oaiId);
|
||||
s3Service.authorizeCloudFrontOaiGetObject(
|
||||
bucket, key, oaiId, oai.getS3CanonicalUserId());
|
||||
return;
|
||||
}
|
||||
s3Service.authorizeAnonymousGetObject(bucket, key);
|
||||
}
|
||||
|
||||
private static String originAccessIdentityId(Origin origin) {
|
||||
Map<String, String> config = origin.getS3OriginConfig();
|
||||
String value = config != null ? config.get("OriginAccessIdentity") : null;
|
||||
if (value == null || value.isBlank()) {
|
||||
return null;
|
||||
}
|
||||
String normalized = value.startsWith("/") ? value.substring(1) : value;
|
||||
String prefix = "origin-access-identity/cloudfront/";
|
||||
if (!normalized.startsWith(prefix)
|
||||
|| normalized.length() == prefix.length()
|
||||
|| normalized.substring(prefix.length()).contains("/")) {
|
||||
throw new AwsException(
|
||||
"InvalidArgument", "The S3 origin access identity is invalid.", 400);
|
||||
}
|
||||
return normalized.substring(prefix.length());
|
||||
}
|
||||
|
||||
/** Fetches from a custom (non-S3) origin. {@code forwardUri} already includes the origin path. */
|
||||
private OriginResponse fetchFromCustomOrigin(Origin origin, String forwardUri, String rawQuery,
|
||||
String viewerScheme, boolean includeBody) {
|
||||
try {
|
||||
URI target = buildCustomOriginUri(
|
||||
origin, viewerScheme, forwardUri, rawQuery);
|
||||
HttpRequest.Builder rb = HttpRequest.newBuilder()
|
||||
.uri(target)
|
||||
.timeout(Duration.ofSeconds(30));
|
||||
if (includeBody) {
|
||||
rb.GET();
|
||||
} else {
|
||||
rb.method("HEAD", HttpRequest.BodyPublishers.noBody());
|
||||
}
|
||||
HttpResponse<byte[]> resp = httpClient.send(rb.build(), HttpResponse.BodyHandlers.ofByteArray());
|
||||
String ct = resp.headers().firstValue("content-type").orElse(DEFAULT_CONTENT_TYPE);
|
||||
byte[] body = resp.body() != null ? resp.body() : new byte[0];
|
||||
long contentLength = includeBody ? body.length : responseContentLength(resp);
|
||||
return new OriginResponse(resp.statusCode(), ct, includeBody ? body : null,
|
||||
contentLength, resp.headers().map());
|
||||
} catch (InterruptedException e) {
|
||||
Thread.currentThread().interrupt();
|
||||
LOG.warnv("CloudFront custom origin fetch was interrupted for host {0}",
|
||||
safeOriginName(origin));
|
||||
return OriginResponse.error(502, "Bad Gateway.");
|
||||
} catch (Exception e) {
|
||||
// Do not log the target URI: forwarded query strings can contain credentials or tokens.
|
||||
LOG.warnv("CloudFront custom origin fetch failed for host {0}: {1}",
|
||||
safeOriginName(origin), e.getClass().getSimpleName());
|
||||
return OriginResponse.error(502, "Bad Gateway.");
|
||||
}
|
||||
}
|
||||
|
||||
static boolean isBlockedOriginAddress(InetAddress address) {
|
||||
if (address.isAnyLocalAddress() || address.isLoopbackAddress()
|
||||
|| address.isLinkLocalAddress() || address.isSiteLocalAddress()
|
||||
|| address.isMulticastAddress()) {
|
||||
return true;
|
||||
}
|
||||
byte[] bytes = address.getAddress();
|
||||
if (bytes.length == 4) {
|
||||
return isBlockedIpv4Address(bytes, 0);
|
||||
}
|
||||
if (bytes.length == 16) {
|
||||
if (isIpv4MappedAddress(bytes)) {
|
||||
return isBlockedIpv4Address(bytes, 12);
|
||||
}
|
||||
int first = Byte.toUnsignedInt(bytes[0]);
|
||||
boolean uniqueLocal = (first & 0xfe) == 0xfc;
|
||||
boolean documentation = first == 0x20
|
||||
&& Byte.toUnsignedInt(bytes[1]) == 0x01
|
||||
&& Byte.toUnsignedInt(bytes[2]) == 0x0d
|
||||
&& Byte.toUnsignedInt(bytes[3]) == 0xb8;
|
||||
return uniqueLocal || documentation;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
private static boolean isIpv4MappedAddress(byte[] bytes) {
|
||||
for (int i = 0; i < 10; i++) {
|
||||
if (bytes[i] != 0) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return bytes[10] == (byte) 0xff && bytes[11] == (byte) 0xff;
|
||||
}
|
||||
|
||||
private static boolean isBlockedIpv4Address(byte[] bytes, int offset) {
|
||||
int first = Byte.toUnsignedInt(bytes[offset]);
|
||||
int second = Byte.toUnsignedInt(bytes[offset + 1]);
|
||||
int third = Byte.toUnsignedInt(bytes[offset + 2]);
|
||||
return first == 0
|
||||
|| first == 10
|
||||
|| first == 127
|
||||
|| (first == 100 && second >= 64 && second <= 127)
|
||||
|| (first == 169 && second == 254)
|
||||
|| (first == 172 && second >= 16 && second <= 31)
|
||||
|| (first == 192 && second == 168)
|
||||
|| (first == 192 && second == 0 && third == 0)
|
||||
|| (first == 192 && second == 0 && third == 2)
|
||||
|| (first == 198 && (second == 18 || second == 19))
|
||||
|| (first == 198 && second == 51 && third == 100)
|
||||
|| (first == 203 && second == 0 && third == 113)
|
||||
|| first >= 224;
|
||||
}
|
||||
|
||||
static URI buildCustomOriginUri(String protocol, String domainName, int port,
|
||||
String forwardUri, String rawQuery) {
|
||||
if (port < 1 || port > 65535) {
|
||||
throw new IllegalArgumentException("Custom origin port is outside the valid range");
|
||||
}
|
||||
String host = normalizeOriginHost(domainName);
|
||||
String path = forwardUri == null || forwardUri.isBlank() ? "/" : forwardUri;
|
||||
if (!path.startsWith("/") || path.indexOf('?') >= 0 || path.indexOf('#') >= 0) {
|
||||
throw new IllegalArgumentException("Custom origin path is invalid");
|
||||
}
|
||||
String authorityHost = host.indexOf(':') >= 0 ? "[" + host + "]" : host;
|
||||
return URI.create(protocol + "://" + authorityHost + ":" + port + path
|
||||
+ (rawQuery == null || rawQuery.isEmpty() ? "" : "?" + rawQuery));
|
||||
}
|
||||
|
||||
static URI buildCustomOriginUri(Origin origin, String viewerScheme,
|
||||
String forwardUri, String rawQuery) {
|
||||
Map<String, Object> config = origin.getCustomOriginConfig();
|
||||
String policy = config != null ? str(config.get("OriginProtocolPolicy")) : "";
|
||||
boolean useHttps = "https-only".equalsIgnoreCase(policy)
|
||||
|| ("match-viewer".equalsIgnoreCase(policy)
|
||||
&& "https".equalsIgnoreCase(viewerScheme));
|
||||
String protocol = useHttps ? "https" : "http";
|
||||
int port = useHttps
|
||||
? intOrDefault(config, "HTTPSPort", 443)
|
||||
: intOrDefault(config, "HTTPPort", 80);
|
||||
return buildCustomOriginUri(
|
||||
protocol, origin.getDomainName(), port, forwardUri, rawQuery);
|
||||
}
|
||||
|
||||
static String rawViewerPath(String requestUri) {
|
||||
if (requestUri == null || requestUri.isBlank()) {
|
||||
return "/";
|
||||
}
|
||||
int query = requestUri.indexOf('?');
|
||||
String path = query >= 0 ? requestUri.substring(0, query) : requestUri;
|
||||
if (path.startsWith("http://") || path.startsWith("https://")) {
|
||||
path = URI.create(path).getRawPath();
|
||||
}
|
||||
if (path == null || path.isEmpty()) {
|
||||
return "/";
|
||||
}
|
||||
return path.startsWith("/") ? path : "/" + path;
|
||||
}
|
||||
|
||||
static String decodedViewerPath(String rawViewerPath) {
|
||||
return URI.create("http://viewer.invalid" + rawViewerPath).getPath();
|
||||
}
|
||||
|
||||
static String normalizeOriginHost(String domainName) {
|
||||
if (domainName == null || domainName.isBlank()) {
|
||||
throw new IllegalArgumentException("Custom origin domain name is empty");
|
||||
}
|
||||
URI authority = URI.create("//" + domainName.trim());
|
||||
if (authority.getRawUserInfo() != null
|
||||
|| (authority.getRawPath() != null && !authority.getRawPath().isEmpty())
|
||||
|| authority.getRawQuery() != null || authority.getRawFragment() != null
|
||||
|| authority.getHost() == null) {
|
||||
throw new IllegalArgumentException("Custom origin domain name is not a valid authority");
|
||||
}
|
||||
return normalizeHost(authority.getHost());
|
||||
}
|
||||
|
||||
static String normalizeHost(String host) {
|
||||
String normalized = host.trim();
|
||||
if (normalized.startsWith("[") && normalized.endsWith("]")) {
|
||||
normalized = normalized.substring(1, normalized.length() - 1);
|
||||
}
|
||||
while (normalized.endsWith(".")) {
|
||||
normalized = normalized.substring(0, normalized.length() - 1);
|
||||
}
|
||||
if (normalized.isEmpty()) {
|
||||
throw new IllegalArgumentException("Custom origin host is empty");
|
||||
}
|
||||
if (normalized.indexOf(':') < 0) {
|
||||
normalized = IDN.toASCII(normalized);
|
||||
}
|
||||
return normalized.toLowerCase(Locale.ROOT);
|
||||
}
|
||||
|
||||
private static long responseContentLength(HttpResponse<?> response) {
|
||||
try {
|
||||
return response.headers().firstValueAsLong("content-length").orElse(-1L);
|
||||
} catch (NumberFormatException e) {
|
||||
LOG.debugv("Ignoring invalid custom-origin Content-Length: {0}", e.getMessage());
|
||||
return -1L;
|
||||
}
|
||||
}
|
||||
|
||||
private static String safeOriginName(Origin origin) {
|
||||
try {
|
||||
return normalizeOriginHost(origin.getDomainName());
|
||||
} catch (RuntimeException e) {
|
||||
return "<invalid>";
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Applies a matching {@code CustomErrorResponse} to an origin error, per the AWS CloudFront spec.
|
||||
* Returns {@code null} when no custom handling applies, so the caller returns the original origin
|
||||
* response unchanged. Otherwise:
|
||||
*
|
||||
* <ul>
|
||||
* <li>with no {@code ResponsePagePath}, the origin body is kept but the status is overridden by
|
||||
* {@code ResponseCode};</li>
|
||||
* <li>with a {@code ResponsePagePath}, the page is fetched through behavior/origin routing and,
|
||||
* on success, returned with {@code ResponseCode} (the single-page-app 403/404 -> 200
|
||||
* {@code /index.html} fallback);</li>
|
||||
* <li>if the custom error page is itself unavailable, CloudFront returns the status code it
|
||||
* received from the origin that holds the error pages — not the original status — and does
|
||||
* not recurse (no loop).</li>
|
||||
* </ul>
|
||||
*/
|
||||
private Response applyCustomError(
|
||||
Distribution distribution,
|
||||
OriginResponse origin,
|
||||
String viewerScheme,
|
||||
String viewerAuthorization,
|
||||
boolean includeBody) {
|
||||
DistributionConfig config = distribution.getConfig();
|
||||
Map<String, Object> cer = matchCustomError(config, origin.status());
|
||||
if (cer == null) {
|
||||
return null;
|
||||
}
|
||||
int responseCode = parseIntOr(cer.get("ResponseCode"), origin.status());
|
||||
String pagePath = str(cer.get("ResponsePagePath"));
|
||||
if (pagePath.isBlank()) {
|
||||
// ResponseCode override with no custom page: keep the origin body, change the status.
|
||||
return toResponse(new OriginResponse(responseCode, origin.contentType(), origin.body(),
|
||||
origin.contentLength(), origin.headers()), includeBody);
|
||||
}
|
||||
|
||||
String errNormalized = CloudFrontRequestRouter.normalizePath(pagePath);
|
||||
String errOriginId = CloudFrontRequestRouter.matchTargetOriginId(config, errNormalized);
|
||||
Origin errOrigin = CloudFrontRequestRouter.findOrigin(config, errOriginId);
|
||||
if (errOrigin == null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
OriginResponse page;
|
||||
if (CloudFrontRequestRouter.isS3Origin(errOrigin)) {
|
||||
String key = CloudFrontRequestRouter.resolveOriginKey(errOrigin.getOriginPath(), errNormalized, null);
|
||||
page = fetchFromS3(
|
||||
distribution, errOrigin, key, viewerAuthorization, includeBody);
|
||||
} else {
|
||||
String forwardUri = CloudFrontRequestRouter.resolveForwardUri(errOrigin.getOriginPath(), errNormalized, null);
|
||||
page = fetchFromCustomOrigin(
|
||||
errOrigin, forwardUri, null, viewerScheme, includeBody);
|
||||
}
|
||||
if (page.status() >= 400) {
|
||||
// Custom error page unavailable → return the status received from the error-page origin
|
||||
// (AWS behavior), without recursively applying custom error handling.
|
||||
return toResponse(page, includeBody);
|
||||
}
|
||||
return toResponse(new OriginResponse(responseCode, page.contentType(), page.body(),
|
||||
page.contentLength(), page.headers()), includeBody);
|
||||
}
|
||||
|
||||
private Map<String, Object> matchCustomError(DistributionConfig config, int status) {
|
||||
List<Map<String, Object>> list = config.getCustomErrorResponses();
|
||||
if (list == null) {
|
||||
return null;
|
||||
}
|
||||
for (Map<String, Object> cer : list) {
|
||||
if (parseIntOr(cer.get("ErrorCode"), -1) == status) {
|
||||
return cer;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
private Response toResponse(OriginResponse origin, boolean includeBody) {
|
||||
Response.ResponseBuilder rb = Response.status(origin.status());
|
||||
Set<String> excludedHeaders = new HashSet<>(NON_FORWARDED_RESPONSE_HEADERS);
|
||||
origin.headers().forEach((name, values) -> {
|
||||
if ("connection".equalsIgnoreCase(name)) {
|
||||
values.forEach(value -> {
|
||||
for (String token : value.split(",")) {
|
||||
excludedHeaders.add(token.trim().toLowerCase(Locale.ROOT));
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
origin.headers().forEach((name, values) -> {
|
||||
if (!excludedHeaders.contains(name.toLowerCase(Locale.ROOT))) {
|
||||
values.forEach(value -> rb.header(name, value));
|
||||
}
|
||||
});
|
||||
if (origin.contentType() != null) {
|
||||
rb.type(origin.contentType());
|
||||
}
|
||||
if (includeBody && origin.body() != null) {
|
||||
rb.entity(origin.body());
|
||||
} else if (origin.contentLength() >= 0) {
|
||||
rb.header("Content-Length", origin.contentLength());
|
||||
}
|
||||
return rb.build();
|
||||
}
|
||||
|
||||
private Response textError(int status, String message) {
|
||||
return Response.status(status)
|
||||
.type(MediaType.TEXT_PLAIN)
|
||||
.entity(message == null ? "" : message)
|
||||
.build();
|
||||
}
|
||||
|
||||
private static String contentType(S3Object obj) {
|
||||
return obj.getContentType() != null ? obj.getContentType() : DEFAULT_CONTENT_TYPE;
|
||||
}
|
||||
|
||||
private static Map<String, List<String>> s3ObjectHeaders(S3Object object) {
|
||||
Map<String, List<String>> headers = new LinkedHashMap<>();
|
||||
putHeader(headers, "Accept-Ranges", "bytes");
|
||||
putHeader(headers, "ETag", object.getETag());
|
||||
if (object.getLastModified() != null) {
|
||||
putHeader(headers, "Last-Modified", HTTP_DATE.format(object.getLastModified()));
|
||||
}
|
||||
putHeader(headers, "Cache-Control", object.getCacheControl());
|
||||
putHeader(headers, "Content-Encoding", object.getContentEncoding());
|
||||
putHeader(headers, "Content-Disposition", object.getContentDisposition());
|
||||
putHeader(headers, "x-amz-storage-class", object.getStorageClass());
|
||||
if (object.getMetadata() != null) {
|
||||
object.getMetadata().forEach((name, value) ->
|
||||
putHeader(headers, "x-amz-meta-" + name, value));
|
||||
}
|
||||
return headers;
|
||||
}
|
||||
|
||||
private static void putHeader(Map<String, List<String>> headers, String name, String value) {
|
||||
if (value != null) {
|
||||
headers.put(name, List.of(value));
|
||||
}
|
||||
}
|
||||
|
||||
private static String str(Object value) {
|
||||
return value != null ? value.toString() : "";
|
||||
}
|
||||
|
||||
private static int intOrDefault(Map<String, Object> map, String key, int dflt) {
|
||||
return map == null ? dflt : parseIntOr(map.get(key), dflt);
|
||||
}
|
||||
|
||||
private static int parseIntOr(Object value, int dflt) {
|
||||
if (value == null) {
|
||||
return dflt;
|
||||
}
|
||||
try {
|
||||
return Integer.parseInt(value.toString().trim());
|
||||
} catch (NumberFormatException e) {
|
||||
LOG.debugv("Ignoring non-integer CloudFront configuration value {0}: {1}", value, e.getMessage());
|
||||
return dflt;
|
||||
}
|
||||
}
|
||||
|
||||
/** The result of fetching from an origin, including end-to-end response headers. */
|
||||
private record OriginResponse(int status, String contentType, byte[] body, long contentLength,
|
||||
Map<String, List<String>> headers) {
|
||||
static OriginResponse error(int status, String message) {
|
||||
byte[] b = message == null ? new byte[0] : message.getBytes(StandardCharsets.UTF_8);
|
||||
return new OriginResponse(status, MediaType.TEXT_PLAIN, b, b.length, Map.of());
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -75,8 +75,9 @@ record S3AclPolicy(List<S3AclPolicy.Grant> grants) {
|
||||
private static Grant parseGrant(Element grantElement) {
|
||||
Element granteeElement = firstChildElement(grantElement, "Grantee");
|
||||
String uri = granteeElement != null ? descendantText(granteeElement, "URI") : null;
|
||||
String id = granteeElement != null ? descendantText(granteeElement, "ID") : null;
|
||||
String permissionText = childText(grantElement, "Permission");
|
||||
return new Grant(new Grantee(uri), Permission.fromXml(permissionText));
|
||||
return new Grant(new Grantee(uri, id), Permission.fromXml(permissionText));
|
||||
}
|
||||
|
||||
private static Element firstChildElement(Element parent, String localName) {
|
||||
@@ -112,12 +113,20 @@ record S3AclPolicy(List<S3AclPolicy.Grant> grants) {
|
||||
boolean allowsPublicRead() {
|
||||
return grantee.isAllUsersGroup() && permission.allowsRead();
|
||||
}
|
||||
|
||||
boolean allowsCanonicalUserRead(String canonicalUserId) {
|
||||
return grantee.isCanonicalUser(canonicalUserId) && permission.allowsRead();
|
||||
}
|
||||
}
|
||||
|
||||
record Grantee(String uri) {
|
||||
record Grantee(String uri, String id) {
|
||||
boolean isAllUsersGroup() {
|
||||
return ALL_USERS_GROUP_URI.equals(uri);
|
||||
}
|
||||
|
||||
boolean isCanonicalUser(String canonicalUserId) {
|
||||
return canonicalUserId != null && canonicalUserId.equals(id);
|
||||
}
|
||||
}
|
||||
|
||||
enum Permission {
|
||||
|
||||
@@ -8,6 +8,7 @@ import org.jboss.logging.Logger;
|
||||
|
||||
import java.util.Iterator;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
final class S3PublicAccessEvaluator {
|
||||
|
||||
@@ -57,6 +58,46 @@ final class S3PublicAccessEvaluator {
|
||||
}
|
||||
}
|
||||
|
||||
static PublicAccessDecision principalPolicyDecision(
|
||||
ObjectMapper objectMapper,
|
||||
String policy,
|
||||
String principalType,
|
||||
String principalValue,
|
||||
String action,
|
||||
String resourceArn,
|
||||
Map<String, String> context) {
|
||||
if (policy == null || policy.isBlank()) {
|
||||
return PublicAccessDecision.NEUTRAL;
|
||||
}
|
||||
try {
|
||||
JsonNode statements = objectMapper.readTree(policy).path("Statement");
|
||||
boolean allowed = false;
|
||||
Iterable<JsonNode> iterable = statements.isArray() ? statements : List.of(statements);
|
||||
for (JsonNode statement : iterable) {
|
||||
String effect = statement.path("Effect").asText("");
|
||||
if (!"Allow".equalsIgnoreCase(effect) && !"Deny".equalsIgnoreCase(effect)) {
|
||||
continue;
|
||||
}
|
||||
if (!principalMatches(statement, principalType, principalValue)
|
||||
|| !actionMatches(statement, action)
|
||||
|| !resourceMatches(statement, resourceArn)) {
|
||||
continue;
|
||||
}
|
||||
if (!conditionsMatch(statement.path("Condition"), context)) {
|
||||
continue;
|
||||
}
|
||||
if ("Deny".equalsIgnoreCase(effect)) {
|
||||
return PublicAccessDecision.DENY;
|
||||
}
|
||||
allowed = true;
|
||||
}
|
||||
return allowed ? PublicAccessDecision.ALLOW : PublicAccessDecision.NEUTRAL;
|
||||
} catch (JsonProcessingException e) {
|
||||
LOG.debugv("Failed to evaluate S3 bucket policy for principal access: {0}", e.getMessage());
|
||||
return PublicAccessDecision.NEUTRAL;
|
||||
}
|
||||
}
|
||||
|
||||
static String bucketArn(String bucketName) {
|
||||
return "arn:aws:s3:::" + bucketName;
|
||||
}
|
||||
@@ -81,6 +122,118 @@ final class S3PublicAccessEvaluator {
|
||||
return false;
|
||||
}
|
||||
|
||||
private static boolean principalMatches(
|
||||
JsonNode statement, String principalType, String principalValue) {
|
||||
if (statement.hasNonNull("Principal")) {
|
||||
return principalNodeMatches(statement.path("Principal"), principalType, principalValue);
|
||||
}
|
||||
if (statement.hasNonNull("NotPrincipal")) {
|
||||
return !principalNodeMatches(
|
||||
statement.path("NotPrincipal"), principalType, principalValue);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
private static boolean principalNodeMatches(
|
||||
JsonNode principal, String principalType, String principalValue) {
|
||||
if (principal == null || principal.isMissingNode() || principal.isNull()) {
|
||||
return false;
|
||||
}
|
||||
if (principal.isTextual() || principal.isArray()) {
|
||||
return principalValueMatches(principal, principalValue);
|
||||
}
|
||||
if (!principal.isObject()) {
|
||||
return false;
|
||||
}
|
||||
Iterator<Map.Entry<String, JsonNode>> fields = principal.fields();
|
||||
while (fields.hasNext()) {
|
||||
Map.Entry<String, JsonNode> field = fields.next();
|
||||
if (field.getKey().equalsIgnoreCase(principalType)
|
||||
&& principalValueMatches(field.getValue(), principalValue)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
private static boolean principalValueMatches(JsonNode candidate, String principalValue) {
|
||||
if (candidate == null || candidate.isNull()) {
|
||||
return false;
|
||||
}
|
||||
if (candidate.isTextual()) {
|
||||
String value = candidate.asText();
|
||||
return "*".equals(value) || value.equals(principalValue);
|
||||
}
|
||||
if (candidate.isArray()) {
|
||||
for (JsonNode item : candidate) {
|
||||
if (principalValueMatches(item, principalValue)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
private static boolean conditionsMatch(JsonNode conditions, Map<String, String> context) {
|
||||
if (conditions == null || conditions.isMissingNode() || conditions.isNull()) {
|
||||
return true;
|
||||
}
|
||||
if (!conditions.isObject()) {
|
||||
return false;
|
||||
}
|
||||
Iterator<Map.Entry<String, JsonNode>> operators = conditions.fields();
|
||||
while (operators.hasNext()) {
|
||||
Map.Entry<String, JsonNode> operator = operators.next();
|
||||
boolean glob = "StringLike".equalsIgnoreCase(operator.getKey())
|
||||
|| "ArnLike".equalsIgnoreCase(operator.getKey());
|
||||
boolean exact = "StringEquals".equalsIgnoreCase(operator.getKey())
|
||||
|| "ArnEquals".equalsIgnoreCase(operator.getKey());
|
||||
if ((!glob && !exact) || !operator.getValue().isObject()) {
|
||||
return false;
|
||||
}
|
||||
Iterator<Map.Entry<String, JsonNode>> entries = operator.getValue().fields();
|
||||
while (entries.hasNext()) {
|
||||
Map.Entry<String, JsonNode> entry = entries.next();
|
||||
String actual = contextValue(context, entry.getKey());
|
||||
if (actual == null || !conditionValueMatches(entry.getValue(), actual, glob)) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
private static String contextValue(Map<String, String> context, String key) {
|
||||
if (context == null) {
|
||||
return null;
|
||||
}
|
||||
for (Map.Entry<String, String> entry : context.entrySet()) {
|
||||
if (entry.getKey().equalsIgnoreCase(key)) {
|
||||
return entry.getValue();
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
private static boolean conditionValueMatches(JsonNode expected, String actual, boolean glob) {
|
||||
if (expected == null || expected.isNull()) {
|
||||
return false;
|
||||
}
|
||||
if (expected.isTextual()) {
|
||||
return glob
|
||||
? IamPolicyEvaluator.globMatches(expected.asText(), actual)
|
||||
: expected.asText().equals(actual);
|
||||
}
|
||||
if (expected.isArray()) {
|
||||
for (JsonNode item : expected) {
|
||||
if (conditionValueMatches(item, actual, glob)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
private static boolean actionMatches(JsonNode statement, String action) {
|
||||
if (statement.hasNonNull("Action")) {
|
||||
return nodeMatches(statement.get("Action"), action);
|
||||
|
||||
@@ -24,6 +24,7 @@ import jakarta.enterprise.context.ApplicationScoped;
|
||||
import jakarta.enterprise.event.Event;
|
||||
import jakarta.enterprise.inject.Instance;
|
||||
import jakarta.inject.Inject;
|
||||
import jakarta.ws.rs.core.MultivaluedHashMap;
|
||||
import org.jboss.logging.Logger;
|
||||
|
||||
import java.io.ByteArrayOutputStream;
|
||||
@@ -509,6 +510,75 @@ public class S3Service implements Resettable {
|
||||
authorizeObjectRead(bucketName, key, versionId, action, authorization);
|
||||
}
|
||||
|
||||
public void authorizeAnonymousGetObject(String bucketName, String key) {
|
||||
authorizeGetObject(bucketName, key, null, RequestAuthorization.unsigned());
|
||||
}
|
||||
|
||||
public void authorizeCloudFrontOacGetObject(
|
||||
String bucketName, String key, String distributionArn) {
|
||||
authorizeCloudFrontGetObject(
|
||||
bucketName,
|
||||
key,
|
||||
"Service",
|
||||
"cloudfront.amazonaws.com",
|
||||
Map.of("AWS:SourceArn", distributionArn),
|
||||
null);
|
||||
}
|
||||
|
||||
public void authorizeCloudFrontOaiGetObject(
|
||||
String bucketName, String key, String originAccessIdentityId,
|
||||
String canonicalUserId) {
|
||||
authorizeCloudFrontGetObject(
|
||||
bucketName,
|
||||
key,
|
||||
"AWS",
|
||||
"arn:aws:iam::cloudfront:user/CloudFront Origin Access Identity "
|
||||
+ originAccessIdentityId,
|
||||
Map.of(),
|
||||
canonicalUserId);
|
||||
}
|
||||
|
||||
public void authorizeCloudFrontViewerGetObject(
|
||||
String bucketName, String key, String viewerAuthorization) {
|
||||
RequestAuthorization authorization =
|
||||
S3RequestAuthorizationParser.parseIfRequired(
|
||||
enforceAuth, viewerAuthorization, new MultivaluedHashMap<>());
|
||||
authorizeGetObject(bucketName, key, null, authorization);
|
||||
}
|
||||
|
||||
private void authorizeCloudFrontGetObject(
|
||||
String bucketName,
|
||||
String key,
|
||||
String principalType,
|
||||
String principalValue,
|
||||
Map<String, String> context,
|
||||
String canonicalUserId) {
|
||||
if (!enforceAuth) {
|
||||
return;
|
||||
}
|
||||
Bucket bucket = bucketStore.get(bucketName)
|
||||
.orElseThrow(() ->
|
||||
new AwsException("NoSuchBucket", "The specified bucket does not exist.", 404));
|
||||
String resourceArn = S3PublicAccessEvaluator.objectArn(bucketName, key);
|
||||
S3PublicAccessEvaluator.PublicAccessDecision decision =
|
||||
S3PublicAccessEvaluator.principalPolicyDecision(
|
||||
objectMapper,
|
||||
bucket.getPolicy(),
|
||||
principalType,
|
||||
principalValue,
|
||||
"s3:GetObject",
|
||||
resourceArn,
|
||||
context);
|
||||
if (decision == S3PublicAccessEvaluator.PublicAccessDecision.DENY) {
|
||||
throw new AwsException("AccessDenied", "Access Denied", 403);
|
||||
}
|
||||
if (decision == S3PublicAccessEvaluator.PublicAccessDecision.ALLOW
|
||||
|| canonicalUserObjectAclAllowsRead(bucketName, key, canonicalUserId)) {
|
||||
return;
|
||||
}
|
||||
throw new AwsException("AccessDenied", "Access Denied", 403);
|
||||
}
|
||||
|
||||
void authorizeBucketRead(String bucketName, String action, RequestAuthorization authorization) {
|
||||
String bucketArn = S3PublicAccessEvaluator.bucketArn(bucketName);
|
||||
authorizeS3Read(bucketName, null, null, action, bucketArn, authorization);
|
||||
@@ -605,6 +675,27 @@ public class S3Service implements Resettable {
|
||||
.orElse(false);
|
||||
}
|
||||
|
||||
private boolean canonicalUserObjectAclAllowsRead(
|
||||
String bucketName, String key, String canonicalUserId) {
|
||||
if (canonicalUserId == null || canonicalUserId.isBlank()) {
|
||||
return false;
|
||||
}
|
||||
return objectStore.get(objectKey(bucketName, key))
|
||||
.filter(object -> !object.isDeleteMarker())
|
||||
.map(S3Object::getAcl)
|
||||
.map(acl -> {
|
||||
try {
|
||||
return S3AclPolicy.parse(acl).grants().stream()
|
||||
.anyMatch(grant ->
|
||||
grant.allowsCanonicalUserRead(canonicalUserId));
|
||||
} catch (S3AclPolicy.AclParseException e) {
|
||||
LOG.debugv(e, "Failed to parse S3 ACL for CloudFront OAI access");
|
||||
return false;
|
||||
}
|
||||
})
|
||||
.orElse(false);
|
||||
}
|
||||
|
||||
private void applyObjectLock(S3Object object, Bucket bucket,
|
||||
String objectLockMode, Instant retainUntilDate, String legalHoldStatus) {
|
||||
if (objectLockMode != null) {
|
||||
|
||||
@@ -3,6 +3,7 @@ package io.github.hectorvent.floci.services.s3;
|
||||
import io.github.hectorvent.floci.config.EmulatorConfig;
|
||||
import io.github.hectorvent.floci.core.common.dns.EmbeddedDnsServer;
|
||||
import io.github.hectorvent.floci.core.common.docker.ContainerDetector;
|
||||
import io.github.hectorvent.floci.services.cloudfront.CloudFrontDistributionFilter;
|
||||
import jakarta.enterprise.context.ApplicationScoped;
|
||||
import jakarta.inject.Inject;
|
||||
import jakarta.ws.rs.container.ContainerRequestContext;
|
||||
@@ -69,6 +70,12 @@ public class S3VirtualHostFilter implements ContainerRequestFilter {
|
||||
return;
|
||||
}
|
||||
|
||||
// A higher-priority CloudFront distribution filter may have already routed this request.
|
||||
// Use its server-side marker rather than trusting a user-controlled path prefix.
|
||||
if (Boolean.TRUE.equals(requestContext.getProperty(CloudFrontDistributionFilter.ROUTED_PROPERTY))) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Rewrite path from /key to /bucket/key
|
||||
String newPath = "/" + bucket + (path.startsWith("/") ? "" : "/") + path;
|
||||
|
||||
|
||||
@@ -459,6 +459,7 @@ floci:
|
||||
enabled: true
|
||||
cloudfront:
|
||||
enabled: true
|
||||
allowed-private-origin-hosts: []
|
||||
appsync:
|
||||
enabled: true
|
||||
schema-worker-threads: 4
|
||||
|
||||
+206
@@ -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);
|
||||
}
|
||||
}
|
||||
+1
-1
@@ -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()));
|
||||
}
|
||||
|
||||
|
||||
+1
-1
@@ -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))));
|
||||
}
|
||||
|
||||
|
||||
+1
-1
@@ -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()));
|
||||
}
|
||||
|
||||
|
||||
+1
-1
@@ -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()));
|
||||
}
|
||||
|
||||
|
||||
+1
-1
@@ -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()));
|
||||
}
|
||||
|
||||
|
||||
+1
-1
@@ -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()));
|
||||
}
|
||||
|
||||
|
||||
+124
@@ -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;
|
||||
}
|
||||
}
|
||||
+144
@@ -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");
|
||||
}
|
||||
}
|
||||
}
|
||||
+68
@@ -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");
|
||||
}
|
||||
}
|
||||
}
|
||||
+438
@@ -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);
|
||||
}
|
||||
}
|
||||
+102
@@ -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")));
|
||||
}
|
||||
}
|
||||
+255
@@ -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;
|
||||
}
|
||||
}
|
||||
+129
@@ -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;
|
||||
}
|
||||
}
|
||||
+184
@@ -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;
|
||||
}
|
||||
}
|
||||
+235
@@ -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");
|
||||
}
|
||||
}
|
||||
}
|
||||
+233
-2
@@ -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 = """
|
||||
|
||||
+24
@@ -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() {
|
||||
|
||||
@@ -280,6 +280,7 @@ floci:
|
||||
enabled: true
|
||||
cloudfront:
|
||||
enabled: true
|
||||
allowed-private-origin-hosts: []
|
||||
appsync:
|
||||
enabled: true
|
||||
schema-worker-threads: 4
|
||||
|
||||
Reference in new issue
Block a user