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

@@ -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. */