fix(cloudfront): serve a Lambda Web Function endpoint origin from Floci itself (#6022)

* fix(cloudfront): serve a Lambda Web Function endpoint origin from Floci itself

A custom origin whose domain is an endpoint this Floci minted now goes to
the listener the viewer reached, with the endpoint domain as Host. Before,
the endpoint host did not resolve, and loopback failed the private address
check.

As on AWS, a forwarded viewer Host is a 502, because the endpoint's
certificate does not name it.

* fix(cloudfront): fetch the endpoint origin over plain HTTP for TLS viewers

A viewer over TLS reached the HTTPS port, and Floci sent plain HTTP to it.
The request now goes to the plain HTTP port at the same address.

The endpoint domains are also indexed by the host a CloudFront origin
names, so a base URL host with upper case or a trailing dot still matches.
This commit is contained in:
TATSUNO “Taz” Yasuhiro authored and GitHub committed 2026-10-19 21:06:57 -04:00
1 parent 2fd6f43836
commit 7fb649715c
9 files changed
+349 -19

No files matched your search

+6
View File
@@ -247,6 +247,12 @@ PUT, PATCH and DELETE).
- Origin `Set-Cookie` headers always reach the viewer. With legacy `Forward=none`, AWS strips them
from the response; Floci does not.
- 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.
- A custom origin whose domain is a [Lambda Web Function](lambda-web-functions.md) endpoint of this Floci is
served by Floci itself, at the address the viewer reached. The origin names the endpoint's
`domainName` with or without its port, and its protocol and ports do not matter, so neither DNS nor
the private address check applies. A forwarded viewer `Host` is a 502, as on AWS, where the endpoint's
certificate does not name it. Origin access control does not sign these requests yet, so an
`IamAuth` endpoint answers them with its 403 page.
- Response headers policies validate the AWS configuration shape and are applied after the origin
response, including CORS preflight fields, origin override behavior, custom headers, security
headers, allowed header removals, and sampled `Server-Timing` metrics. `Pragma: server-timing`
+3 -1
View File
@@ -41,7 +41,7 @@ The `Lambda Web` service model (apiVersion 2025-03-07, `aws lambda-web` in the A
- **ARNs** given as identifiers must name the request's region and the caller's account, as on AWS. A revision or endpoint ARN resolves by its id or name only.
- **Page tokens** are base64 cursors that carry the request and the position of the page, not the UUIDs AWS issues. A token reused with other parameters gets the AWS "does not match the request" error, and any other token the "invalid or has expired" error.
- **Domain names** take the form `<id>.001.lambda-web.<region>.<floci host>` and `<id>.lambda-web.global.<floci host>`, with the host and port of `floci.base-url`. A `PerRegion` endpoint gets one domain per region in `regionalEndpoints`.
- **Not implemented yet:** SigV4a on `MultiRegion` endpoints, the check that a policy's principal exists, the automatic deletion of revisions past 50, the metadata API, and serving a `MultiRegion` or `PerRegion` endpoint in its other regions.
- **Not implemented yet:** SigV4a on `MultiRegion` endpoints, the check that a policy's principal exists, the automatic deletion of revisions past 50, the metadata API, CloudFront origin access control, and serving a `MultiRegion` or `PerRegion` endpoint in its other regions.
### `aws lambda-web deploy`
@@ -64,6 +64,8 @@ curl -H "Host: <domainName>" http://localhost:4566/
The `Host` must match the domain exactly, as on AWS: another case or another port is `404` with `lambda-web-error-type: Platform.InvalidEndpoint`.
A CloudFront distribution of this Floci can use the endpoint as a custom origin, named by its `domainName` without the port as on AWS. See [CloudFront](cloudfront.md).
An execution environment is a `public.ecr.aws/lambda/nodejs:24` container that a request starts when every environment of the endpoint is full. The code is the revision's S3 object unpacked into `/var/task`. Node starts `/var/runtime/index.js` with the flags AWS uses, as on AWS, and that runtime imports `index.js` or the file `AWS_LAMBDA_NODEJS_ENTRYPOINT` names. So `require.main` is not the app's module, as on AWS. The app sees `AWS_LAMBDA_HTTP_ENDPOINT=0.0.0.0:3000`, `AWS_LAMBDA_INITIALIZATION_TYPE=native-http`, `AWS_EXECUTION_ENV`, `AWS_LAMBDA_FUNCTION_MEMORY_SIZE=2048`, `AWS_LAMBDA_LOG_LEVEL`, `AWS_ACCOUNT_ID`, `AWS_REGION`, credentials and `AWS_ENDPOINT_URL` for Floci, `NODE_PATH`, and its own variables. The server has 9 seconds to listen. An environment that sees no request for `floci.services.lambda.container-idle-timeout-seconds` is stopped with `SIGTERM` and one second, as on scale to zero. Node runs under Docker's init, so a server without a `SIGTERM` handler stops at once, as on AWS. A process that exits between requests is replaced by a fresh environment on the next request.
Each endpoint scales on its own, as on AWS. An environment takes up to the revision's `maxConcurrencyPerEnvironment` requests at once, the least busy one first, so requests rotate over the environments. A request that finds every environment full starts another one, or waits for one that is starting and has room. When the endpoint already runs `maxEnvironments`, an idle environment of another revision makes room, and without one the request is refused with `429` and `Platform.EndpointMaxEnvThrottle`. A `rateLimit` admits a burst of up to `rateLimit` requests that refills at `rateLimit` per second, and refuses the rest with `429` and `Platform.EndpointRequestThrottle`. AWS adjusts the concurrency of each environment under `maxConcurrencyPerEnvironment` from the measured load, so a burst there can spread over more environments than in Floci, and the account quotas are not applied.
@@ -76,15 +76,21 @@ final class CloudFrontOriginHttpClient implements AutoCloseable {
this(delegate, allowedPrivateOriginHosts, null);
}
/** Reaches Floci's own listener, whose address the private address check refuses. */
static CloudFrontOriginHttpClient toFloci() {
return new CloudFrontOriginHttpClient(SystemDefaultDnsResolver.INSTANCE, (SSLContext) null);
}
CloudFrontOriginHttpClient(
DnsResolver delegate,
Collection<String> allowedPrivateOriginHosts,
SSLContext sslContext) {
Set<String> allowedHosts = allowedPrivateOriginHosts.stream()
this(new ValidatingDnsResolver(delegate, allowedPrivateOriginHosts.stream()
.map(CloudFrontServingController::normalizeHost)
.collect(Collectors.toUnmodifiableSet());
DnsResolver validatingResolver = new ValidatingDnsResolver(delegate, allowedHosts);
.collect(Collectors.toUnmodifiableSet())), sslContext);
}
private CloudFrontOriginHttpClient(DnsResolver resolver, SSLContext sslContext) {
ConnectionConfig connectionConfig = ConnectionConfig.custom()
.setConnectTimeout(Timeout.of(CONNECT_TIMEOUT))
.setSocketTimeout(Timeout.of(RESPONSE_TIMEOUT))
@@ -95,7 +101,7 @@ final class CloudFrontOriginHttpClient implements AutoCloseable {
.build();
PoolingHttpClientConnectionManagerBuilder connectionManagerBuilder =
PoolingHttpClientConnectionManagerBuilder.create()
.setDnsResolver(validatingResolver)
.setDnsResolver(resolver)
.setDefaultConnectionConfig(connectionConfig)
.setDefaultTlsConfig(tlsConfig)
// CloudFront has no per-origin connection limit, and a streamed response holds its
@@ -8,9 +8,11 @@ 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.lambdaweb.LambdaWebService;
import io.github.hectorvent.floci.services.s3.ByteRange;
import io.github.hectorvent.floci.services.s3.S3Service;
import io.github.hectorvent.floci.services.s3.model.S3Object;
import io.quarkus.vertx.http.HttpServer;
import io.quarkus.vertx.http.runtime.CurrentVertxRequest;
import io.vertx.core.http.HttpServerRequest;
import io.vertx.core.http.HttpVersion;
@@ -106,26 +108,33 @@ public class CloudFrontServingController {
private final CloudFrontService service;
private final S3Service s3Service;
private final LambdaWebService lambdaWebService;
private final CurrentVertxRequest currentVertxRequest;
private final HttpServer httpServer;
private final CloudFrontOriginHttpClient httpClient;
private final CloudFrontOriginHttpClient flociClient = CloudFrontOriginHttpClient.toFloci();
@Inject
public CloudFrontServingController(CloudFrontService service, S3Service s3Service,
EmulatorConfig emulatorConfig,
CurrentVertxRequest currentVertxRequest) {
LambdaWebService lambdaWebService, EmulatorConfig emulatorConfig,
CurrentVertxRequest currentVertxRequest, HttpServer httpServer) {
this.service = service;
this.s3Service = s3Service;
this.lambdaWebService = lambdaWebService;
this.currentVertxRequest = currentVertxRequest;
this.httpServer = httpServer;
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());
for (CloudFrontOriginHttpClient client : List.of(httpClient, flociClient)) {
try {
client.close();
} catch (Exception e) {
LOG.debugv("Could not close CloudFront origin HTTP client: {0}", e.getMessage());
}
}
}
@@ -759,8 +768,17 @@ public class CloudFrontServingController {
String viewerScheme, String method, ViewerBody viewerBody) {
boolean includeBody = !"HEAD".equals(method);
try {
URI target = buildCustomOriginUri(
origin, viewerScheme, forwardUri, originRequest.rawQuery());
// Floci serves its own Web Function endpoints, whatever port and protocol the origin names.
String webEndpoint = webFunctionEndpoint(origin);
if (webEndpoint != null && originRequest.headers().stream()
.anyMatch(header -> "Host".equalsIgnoreCase(header.name()))) {
// CloudFront checks the endpoint's certificate against the forwarded viewer Host, which it never names.
LOG.debugv("CloudFront forwards the viewer Host to Web Function origin {0}", origin.getId());
return OriginResponse.error(502, "Bad Gateway.");
}
URI target = webEndpoint != null
? flociListenerUri(forwardUri, originRequest.rawQuery())
: buildCustomOriginUri(origin, viewerScheme, forwardUri, originRequest.rawQuery());
HttpRequest.Builder rb = HttpRequest.newBuilder()
.uri(target);
// Origin custom headers: CloudFront adds these to every request it forwards to the origin
@@ -777,11 +795,15 @@ public class CloudFrontServingController {
}
}
}
if (webEndpoint != null) {
originHeaders.put("Host", webEndpoint);
}
rb.method(method, HttpRequest.BodyPublishers.noBody());
// Both bodies are streamed, so neither has to fit in memory: the viewer's goes out with its
// own Content-Length, or chunked as it came, and the origin's comes back as it arrives.
ViewerBody requestBody = originRequestBody(method, viewerBody);
CloudFrontOriginHttpClient.OpenResponse resp = httpClient.open(rb.build(), originRequest.headers(),
CloudFrontOriginHttpClient.OpenResponse resp = (webEndpoint != null ? flociClient : httpClient).open(
rb.build(), originRequest.headers(),
originHeaders, requestBody != null ? requestBody.stream() : null,
requestBody != null ? requestBody.length() : -1, originTimeouts(origin));
String ct = resp.headers().firstValue("content-type").orElse(DEFAULT_CONTENT_TYPE);
@@ -807,6 +829,24 @@ public class CloudFrontServingController {
}
}
private String webFunctionEndpoint(Origin origin) {
try {
return lambdaWebService.endpointDomain(normalizeOriginHost(origin.getDomainName())).orElse(null);
} catch (IllegalArgumentException e) {
return null;
}
}
/**
* The plain HTTP port at the address the viewer reached Floci at, which also serves the Web
* Function endpoints. A viewer over TLS reached the HTTPS port instead.
*/
private URI flociListenerUri(String forwardUri, String rawQuery) {
SocketAddress local = currentVertxRequest.getCurrent().request().localAddress();
String host = local.hostAddress().indexOf(':') >= 0 ? "[" + local.hostAddress() + "]" : local.hostAddress();
return buildCustomOriginUri("http", host, httpServer.getPort(), forwardUri, rawQuery);
}
/**
* The origin's connection settings for one request: {@code Origin.ConnectionTimeout},
* {@code CustomOriginConfig.OriginReadTimeout} and {@code Origin.ConnectionAttempts}. A value
@@ -143,6 +143,8 @@ public class LambdaWebService implements Resettable {
private final ConcurrentHashMap<String, Object> locks = new ConcurrentHashMap<>();
/** Every endpoint domain, filled from storage at start and kept by the create and delete paths. */
private final ConcurrentHashMap<String, EndpointLocator> domains = new ConcurrentHashMap<>();
/** Each endpoint domain keyed by its host as a CloudFront origin names it. */
private final ConcurrentHashMap<String, String> originHosts = new ConcurrentHashMap<>();
@Inject
public LambdaWebService(RegionResolver regionResolver, StorageFactory storageFactory, EmulatorConfig config,
@@ -164,6 +166,7 @@ public class LambdaWebService implements Resettable {
this.functions = storageFactory.create("lambda", "lambda-web-functions.json",
new TypeReference<Map<String, WebFunction>>() {});
domains.clear();
originHosts.clear();
List<WebFunction> all = functions instanceof AccountAwareStorageBackend<WebFunction> aware
? aware.scanAllAccounts()
: functions.scan(key -> true);
@@ -176,6 +179,7 @@ public class LambdaWebService implements Resettable {
public void clear() {
functions.clear();
domains.clear();
originHosts.clear();
}
/** Where a request to an endpoint domain goes. Domains are unique across accounts and regions. */
@@ -195,6 +199,7 @@ public class LambdaWebService implements Resettable {
Optional<WebFunction> stored = functions.get(key(locator.region(), locator.functionName()));
if (stored.isEmpty() || !stored.get().endpoints.containsKey(locator.endpointName())) {
domains.remove(host, locator);
originHosts.remove(originHost(host), host);
return Optional.empty();
}
WebFunction fn = copy(stored.get(), WebFunction.class);
@@ -204,16 +209,38 @@ public class LambdaWebService implements Resettable {
});
}
/**
* The endpoint domain that a CloudFront origin names by {@code host}, which is lowercase with no
* trailing dot or port. The domain Floci mints keeps the authority of its base URL.
*/
public Optional<String> endpointDomain(String host) {
return Optional.ofNullable(originHosts.get(host));
}
private void indexDomains(WebFunction fn, WebFunctionEndpoint endpoint) {
AwsArnUtils.Arn arn = AwsArnUtils.parse(fn.functionArn);
EndpointLocator locator = new EndpointLocator(arn.accountId(), arn.region(), fn.functionName, endpoint.endpointName);
domains.put(endpoint.domainName, locator);
endpoint.regionalDomainNames.values().forEach(domain -> domains.put(domain, locator));
index(endpoint.domainName, locator);
endpoint.regionalDomainNames.values().forEach(domain -> index(domain, locator));
}
private void index(String domain, EndpointLocator locator) {
domains.put(domain, locator);
originHosts.put(originHost(domain), domain);
}
private void unindexDomains(WebFunctionEndpoint endpoint) {
domains.remove(endpoint.domainName);
endpoint.regionalDomainNames.values().forEach(domains::remove);
unindex(endpoint.domainName);
endpoint.regionalDomainNames.values().forEach(this::unindex);
}
private void unindex(String domain) {
domains.remove(domain);
originHosts.remove(originHost(domain), domain);
}
private static String originHost(String domain) {
return domain.replaceFirst("\\.*(:\\d+)?$", "").toLowerCase(Locale.ROOT);
}
/** The revision a request goes to, drawn by the endpoint's weights. */
@@ -0,0 +1,130 @@
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.github.hectorvent.floci.testing.PartitionCleanup;
import io.quarkus.test.junit.QuarkusTest;
import jakarta.inject.Inject;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;
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;
import static org.hamcrest.Matchers.matchesPattern;
/**
* Distributions whose origin is a Web Function endpoint of this Floci, answered by the platform
* without an execution environment, so no Docker. No private origin host is allowed here.
*/
@QuarkusTest
class CloudFrontWebFunctionOriginServingTest {
private static final String BASE = "/2025-03-07";
private static final String BUCKET = "web-code-cloudfront";
private static final String ROLE = "arn:aws:iam::000000000000:role/web";
private static final String CACHING_DISABLED = "4135ea2d-6df8-44a3-9df3-4b5a84be39ad";
@Inject
CloudFrontService cloudFrontService;
@Inject
S3Service s3Service;
@RegisterExtension
final PartitionCleanup cleanup = new PartitionCleanup();
@Test
void anEndpointOriginIsReachedWhateverPortAndProtocolTheOriginNames() {
String functionName = "cf-disabled-" + Long.toString(System.nanoTime(), 36);
String domain = createFunction(s3Service, cleanup, functionName, "ApplicationManaged");
given().contentType("application/json").body("{\"throttleConfig\": {\"rateLimit\": 0}}")
.when().patch(BASE + "/web-functions/" + functionName + "/endpoints/dev")
.then().statusCode(202);
Distribution created = createDistribution(cloudFrontService, cleanup, domain,
CloudFrontService.MANAGED_ALL_VIEWER_EXCEPT_HOST_HEADER_ORIGIN_REQUEST_POLICY_ID);
given().header("Host", created.getDomainName()).when().get("/")
.then().statusCode(503)
.header("lambda-web-error-type", "Platform.EndpointDisabled")
.header("lambda-web-request-id", matchesPattern("[A-Z2-7]{26}"));
}
@Test
void anIamAuthEndpointRefusesTheUnsignedRequestOfADistributionWithoutOriginAccessControl() {
String domain = createFunction(s3Service, cleanup, "cf-iam-" + Long.toString(System.nanoTime(), 36), "IamAuth");
Distribution created = createDistribution(cloudFrontService, cleanup, domain,
CloudFrontService.MANAGED_ALL_VIEWER_EXCEPT_HOST_HEADER_ORIGIN_REQUEST_POLICY_ID);
given().header("Host", created.getDomainName()).when().get("/")
.then().statusCode(403)
.header("content-type", "text/html")
.header("lambda-web-request-id", matchesPattern("[A-Z2-7]{26}"))
.body(containsString("You are not authorized to access this endpoint."));
}
@Test
void forwardingTheViewerHostToAnEndpointIsABadGateway() {
String domain = createFunction(s3Service, cleanup, "cf-host-" + Long.toString(System.nanoTime(), 36),
"ApplicationManaged");
Distribution created = createDistribution(cloudFrontService, cleanup, domain,
CloudFrontService.MANAGED_ALL_VIEWER_ORIGIN_REQUEST_POLICY_ID);
given().header("Host", created.getDomainName()).when().get("/")
.then().statusCode(502);
}
static String createFunction(S3Service s3Service, PartitionCleanup cleanup, String functionName, String authType) {
s3Service.createBucket(BUCKET, "us-east-1");
s3Service.putObject(BUCKET, "app.zip", "zip".getBytes(StandardCharsets.UTF_8), "application/zip", Map.of());
String domain = given().contentType("application/json")
.body("""
{"functionName": "%s",
"revisionConfig": {
"buildConfig": {"codeConfig": {"s3Object": {"bucket": "%s", "key": "app.zip"}},
"runtimeConfig": {"runtime": "nodejs24.x"}},
"serviceConfig": {"executionRoleArn": "%s"}},
"endpointConfig": {"endpointName": "dev", "endpointType": "HomeRegion",
"authType": "%s", "autoDeploymentMode": "LatestRevision"}}
""".formatted(functionName, BUCKET, ROLE, authType))
.when().put(BASE + "/web-functions")
.then().statusCode(202)
.extract().path("endpoint.domainName");
cleanup.register(() -> given().when().delete(BASE + "/web-functions/" + functionName));
return domain;
}
/** The origin names the endpoint as on AWS: its host without a port, over HTTPS on 443. */
static Distribution createDistribution(CloudFrontService cloudFrontService, PartitionCleanup cleanup,
String endpointDomain, String originRequestPolicyId) {
Origin origin = new Origin();
origin.setId("web");
origin.setDomainName(endpointDomain.substring(0, endpointDomain.lastIndexOf(':')));
Map<String, Object> customOriginConfig = new LinkedHashMap<>();
customOriginConfig.put("HTTPPort", "80");
customOriginConfig.put("HTTPSPort", "443");
customOriginConfig.put("OriginProtocolPolicy", "https-only");
origin.setCustomOriginConfig(customOriginConfig);
DefaultCacheBehavior behavior = new DefaultCacheBehavior();
behavior.setTargetOriginId("web");
behavior.setViewerProtocolPolicy("allow-all");
behavior.setCachePolicyId(CACHING_DISABLED);
behavior.setOriginRequestPolicyId(originRequestPolicyId);
DistributionConfig config = new DistributionConfig();
config.setEnabled(true);
config.setOrigins(List.of(origin));
config.setDefaultCacheBehavior(behavior);
Distribution distribution = new Distribution();
distribution.setConfig(config);
Distribution created = cloudFrontService.createDistribution(distribution, Map.of());
cleanup.register(() -> cloudFrontService.removeDistribution(created.getId()));
return created;
}
}
@@ -0,0 +1,50 @@
package io.github.hectorvent.floci.services.cloudfront;
import io.github.hectorvent.floci.config.SelfSignedTlsProfile;
import io.github.hectorvent.floci.services.cloudfront.model.Distribution;
import io.github.hectorvent.floci.services.s3.S3Service;
import io.github.hectorvent.floci.testing.PartitionCleanup;
import io.quarkus.test.junit.QuarkusTest;
import io.quarkus.test.junit.TestProfile;
import jakarta.inject.Inject;
import org.eclipse.microprofile.config.inject.ConfigProperty;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;
import static io.github.hectorvent.floci.services.cloudfront.CloudFrontWebFunctionOriginServingTest.createDistribution;
import static io.github.hectorvent.floci.services.cloudfront.CloudFrontWebFunctionOriginServingTest.createFunction;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.matchesPattern;
/** A viewer over TLS reaches the HTTPS port, while Floci fetches its own endpoint origin over plain HTTP. */
@QuarkusTest
@TestProfile(SelfSignedTlsProfile.class)
class CloudFrontWebFunctionOriginTlsIntegrationTest {
@ConfigProperty(name = "quarkus.http.test-ssl-port", defaultValue = "0")
int sslPort;
@Inject
CloudFrontService cloudFrontService;
@Inject
S3Service s3Service;
@RegisterExtension
final PartitionCleanup cleanup = new PartitionCleanup();
@Test
void aViewerOverTlsReachesAnEndpointOrigin() {
String domain = createFunction(s3Service, cleanup, "cf-tls-" + Long.toString(System.nanoTime(), 36), "IamAuth");
Distribution created = createDistribution(cloudFrontService, cleanup, domain,
CloudFrontService.MANAGED_ALL_VIEWER_EXCEPT_HOST_HEADER_ORIGIN_REQUEST_POLICY_ID);
given().relaxedHTTPSValidation().baseUri("https://localhost").port(sslPort)
.header("Host", created.getDomainName())
.when().get("/")
.then().statusCode(403)
.header("lambda-web-request-id", matchesPattern("[A-Z2-7]{26}"))
.body(containsString("You are not authorized to access this endpoint."));
}
}
@@ -1,6 +1,11 @@
package io.github.hectorvent.floci.services.lambdaweb;
import com.github.dockerjava.api.DockerClient;
import io.github.hectorvent.floci.services.cloudfront.CloudFrontService;
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.lambdaweb.LambdaWebEnvironmentManager.Environment;
import io.github.hectorvent.floci.services.s3.S3Service;
import io.github.hectorvent.floci.testing.RestAssuredJsonUtils;
@@ -25,6 +30,7 @@ import java.nio.charset.StandardCharsets;
import java.time.Duration;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
@@ -39,9 +45,11 @@ import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.endsWith;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.matchesPattern;
import static org.hamcrest.Matchers.not;
import static org.hamcrest.Matchers.notNullValue;
import static org.hamcrest.Matchers.nullValue;
import static org.hamcrest.Matchers.startsWith;
import static org.junit.jupiter.api.Assertions.assertEquals;
@@ -119,6 +127,9 @@ class LambdaWebDataPlaneDockerIntegrationTest {
@Inject
LambdaWebMetrics metrics;
@Inject
CloudFrontService cloudFrontService;
private String functionName;
@BeforeAll
@@ -207,6 +218,46 @@ class LambdaWebDataPlaneDockerIntegrationTest {
.body("headers.x-amz-date", equalTo("20260101T000000Z"));
}
@Test
@Timeout(180)
void aCloudFrontDistributionReachesTheEndpointAsItsOrigin() throws Exception {
String domain = createFunction(30);
Origin origin = new Origin();
origin.setId("web");
origin.setDomainName(domain.substring(0, domain.lastIndexOf(':')));
Map<String, Object> customOriginConfig = new LinkedHashMap<>();
customOriginConfig.put("HTTPPort", "80");
customOriginConfig.put("HTTPSPort", "443");
customOriginConfig.put("OriginProtocolPolicy", "https-only");
origin.setCustomOriginConfig(customOriginConfig);
DefaultCacheBehavior behavior = new DefaultCacheBehavior();
behavior.setTargetOriginId("web");
behavior.setViewerProtocolPolicy("allow-all");
behavior.setCachePolicyId("4135ea2d-6df8-44a3-9df3-4b5a84be39ad");
behavior.setOriginRequestPolicyId("b689b0a8-53d0-40ab-baf2-68738e2966ac");
DistributionConfig config = new DistributionConfig();
config.setEnabled(true);
config.setOrigins(List.of(origin));
config.setDefaultCacheBehavior(behavior);
Distribution distribution = new Distribution();
distribution.setConfig(config);
Distribution created = cloudFrontService.createDistribution(distribution, Map.of());
try {
given().header("Host", created.getDomainName()).header("x-custom", "1").when().get("/a/b?x=1")
.then().statusCode(200)
.header("lambda-web-request-id", matchesPattern(REQUEST_ID))
.header("lambda-web-logstream", notNullValue())
.body("url", equalTo("/a/b?x=1"))
.body("headers.host", equalTo(domain))
.body("headers.x-custom", equalTo("1"))
.body("headers.via", endsWith(" (CloudFront)"))
.body("headers.x-amz-cf-id", notNullValue())
.body("headers.lambda-web-endpoint-name", equalTo("dev"));
} finally {
cloudFrontService.removeDistribution(created.getId());
}
}
@Test
@Timeout(180)
void theOutputGoesToTheLocalAndTheCentralizedLogGroupAsJsonEvents() throws Exception {
@@ -50,8 +50,12 @@ class LambdaWebServiceTest {
}
private LambdaWebService service(StorageFactory storage) {
return service(storage, "http://localhost:4566");
}
private LambdaWebService service(StorageFactory storage, String baseUrl) {
EmulatorConfig config = mock(EmulatorConfig.class);
when(config.effectiveBaseUrl()).thenReturn("http://localhost:4566");
when(config.effectiveBaseUrl()).thenReturn(baseUrl);
LambdaWebService service = new LambdaWebService(new RegionResolver(REGION, ACCOUNT_ID), storage, config, null,
mapper, null);
service.initializeStorage();
@@ -569,6 +573,20 @@ class LambdaWebServiceTest {
assertTrue(second.locate(domain).isEmpty(), "a deleted endpoint's domain is gone");
}
@Test
void aCloudFrontOriginNamesAnEndpointDomainWithoutCaseTrailingDotOrPort() {
LambdaWebService service = service(new MemoryStorageFactory(), "http://Floci.Example.:4566");
service.createFunction(REGION, createRequest("app"));
String domain = service.getEndpoint(REGION, "app", "dev").domainName;
assertTrue(domain.endsWith(".001.lambda-web.us-east-1.Floci.Example.:4566"), domain);
String host = domain.substring(0, domain.indexOf('.')) + ".001.lambda-web.us-east-1.floci.example";
assertEquals(domain, service.endpointDomain(host).orElseThrow());
assertTrue(service.endpointDomain("nope.001.lambda-web.us-east-1.floci.example").isEmpty());
service.deleteEndpoint(REGION, "app", "dev");
assertTrue(service.endpointDomain(host).isEmpty(), "a deleted endpoint's domain is gone");
}
private static final class MemoryStorageFactory extends StorageFactory {
private final Map<String, StorageBackend<String, ?>> stores = new HashMap<>();