fix(cloudfront): tunnel WebSocket upgrades to custom origins as AWS does (#7148)

* fix(cloudfront): tunnel WebSocket upgrades to custom origins as AWS does

CloudFront forwards WebSocket handshakes to the origin on every distribution, but
Floci's serving path is a JAX-RS resource that strips Upgrade and Connection and
fetches the origin with a blocking client, so a socket.io client behind a
distribution never left long-polling.

A Vert.x route ahead of JAX-RS now catches an HTTP/1.1 WebSocket handshake to a
distribution host, resolves the behavior and custom origin as the GET path does
(allowed methods, signed requests, origin request policy, origin custom headers,
private-address guard), sends the handshake with its upgrade fields and splices
the two connections once the origin answers 101. Any other answer is relayed as
an ordinary response, and handshakes the distribution would not tunnel fall
through to the existing GET handling. Handshake detection and the byte relay are
shared with the ALB data plane.

* fix(cloudfront): honor disabled service and origin timeouts on WebSocket refusals

The WebSocket route runs ahead of ServiceEnabledFilter, so it now checks that
CloudFront is enabled before taking a handshake and otherwise falls through to
the disabled-service answer.

An origin answer that refuses the upgrade is no longer piped without limits: its
body is streamed within the origin's response timeout between packets and its
response completion timeout in all, counting only the origin's time, and an
origin that stalls past them ends the viewer connection.

* test: share the ALB fixture between the WebSocket integration tests

CloudFrontWebSocketIntegrationTest repeated ElbV2WebSocketIntegrationTest's load
balancer, target group, listener and WebSocket exchange helpers. Both now use
AlbFixtures.

* refactor(cloudfront): have the WebSocket origin clock spend a shared CompletionBudget
This commit is contained in:
Abhigya authored and GitHub committed 2026-11-01 07:53:25 -04:00
1 parent f489a6f1f3
commit d2d9ed6ca2
9 files changed
+1000 -227

No files matched your search

@@ -0,0 +1,55 @@
package io.github.hectorvent.floci.core.common;
import io.vertx.core.http.HttpMethod;
import io.vertx.core.http.HttpServerRequest;
import io.vertx.core.http.HttpVersion;
import io.vertx.core.net.NetSocket;
/**
* The parts of proxying a WebSocket handshake that the proxies Floci emulates share. An ALB and a
* CloudFront distribution both forward a WebSocket upgrade to their origin with its upgrade headers
* intact, which an ordinary proxied request cannot do: {@code Connection} and {@code Upgrade} are
* hop-by-hop and are stripped. AWS only tunnels WebSocket upgrades, over HTTP/1.1.
*/
public final class WebSocketUpgrades {
private WebSocketUpgrades() {
}
/** Whether the request is an HTTP/1.1 GET asking to upgrade the connection to WebSocket. */
public static boolean isHandshake(HttpServerRequest req) {
if (req.version() != HttpVersion.HTTP_1_1 || req.method() != HttpMethod.GET) {
return false;
}
if (!"websocket".equalsIgnoreCase(req.getHeader("Upgrade"))) {
return false;
}
for (String connection : req.headers().getAll("Connection")) {
for (String token : connection.split(",")) {
if ("upgrade".equalsIgnoreCase(token.trim())) {
return true;
}
}
}
return false;
}
/**
* Copies everything {@code source} reads to {@code destination}, pausing the source while the
* destination's write queue is full. {@code onData} runs for each buffer, and {@code close} when
* the source ends, closes or fails.
*/
public static void relay(NetSocket source, NetSocket destination, Runnable onData, Runnable close) {
source.handler(buffer -> {
onData.run();
destination.write(buffer);
if (destination.writeQueueFull()) {
source.pause();
destination.drainHandler(ignored -> source.resume());
}
});
source.endHandler(ignored -> close.run());
source.closeHandler(ignored -> close.run());
source.exceptionHandler(err -> close.run());
}
}
@@ -84,6 +84,8 @@ final class CloudFrontOriginHttpClient implements AutoCloseable {
private static final ThreadLocal<Duration> HANDSHAKE_TIMEOUT = new ThreadLocal<>();
private final CloseableHttpClient client;
/** Resolves origin hosts, refusing a private address unless the host is allowed. */
private final DnsResolver resolver;
/** The clock the completion budget reads, {@link System#nanoTime} unless a test supplies one. */
private final LongSupplier nanoClock;
@@ -129,6 +131,7 @@ final class CloudFrontOriginHttpClient implements AutoCloseable {
private CloudFrontOriginHttpClient(
DnsResolver resolver, SSLContext sslContext, LongSupplier nanoClock) {
this.nanoClock = nanoClock;
this.resolver = resolver;
ConnectionConfig connectionConfig = ConnectionConfig.custom()
.setConnectTimeout(Timeout.of(CONNECT_TIMEOUT))
@@ -285,7 +288,7 @@ final class CloudFrontOriginHttpClient implements AutoCloseable {
* viewer that reads slowly never expires a response the origin finished on time. A budget with
* no limit is the origin's own pace.
*/
private static final class CompletionBudget {
static final class CompletionBudget {
/** The time the origin may take, in nanoseconds, or 0 when it may take as long as it wants. */
private final long limitNanos;
@@ -594,18 +597,41 @@ final class CloudFrontOriginHttpClient implements AutoCloseable {
values.forEach(value -> builder.addHeader(name, value));
}
});
for (CloudFrontOriginRequestBuilder.Header header : forwardedHeaders) {
if (!replaced.contains(header.name())) {
builder.addHeader(header.name(), header.value());
}
for (CloudFrontOriginRequestBuilder.Header header : originRequestHeaders(forwardedHeaders, originHeaders)) {
builder.addHeader(header.name(), header.value());
}
originHeaders.forEach(builder::addHeader);
if (entity != null) {
builder.setEntity(entity);
}
return builder;
}
/**
* The headers an origin request carries: the forwarded headers, then the origin headers, each of
* which replaces every same-named forwarded header.
*/
static List<CloudFrontOriginRequestBuilder.Header> originRequestHeaders(
List<CloudFrontOriginRequestBuilder.Header> forwardedHeaders, Map<String, String> originHeaders) {
Set<String> replaced = new TreeSet<>(String.CASE_INSENSITIVE_ORDER);
replaced.addAll(originHeaders.keySet());
List<CloudFrontOriginRequestBuilder.Header> headers = new ArrayList<>();
for (CloudFrontOriginRequestBuilder.Header header : forwardedHeaders) {
if (!replaced.contains(header.name())) {
headers.add(header);
}
}
originHeaders.forEach((name, value) -> headers.add(new CloudFrontOriginRequestBuilder.Header(name, value)));
return headers;
}
/**
* Resolves an origin host to the address a connection made outside this client uses, with the
* same private-address guard as the requests this client sends.
*/
InetAddress resolve(String host) throws UnknownHostException {
return resolver.resolve(CloudFrontServingController.normalizeHost(host))[0];
}
/**
* The TLS configuration of a connection: the handshake answers within {@code handshakeTimeout},
* so it cannot outlive the request that opens the connection.
@@ -48,6 +48,7 @@ import java.io.InputStream;
import java.io.OutputStream;
import java.io.PushbackInputStream;
import java.net.IDN;
import java.net.InetAddress;
import java.net.URI;
import java.net.http.HttpRequest;
import java.nio.charset.StandardCharsets;
@@ -323,8 +324,8 @@ public class CloudFrontServingController {
List<String> trustedKeyGroups =
CloudFrontRequestRouter.trustedKeyGroupsFor(config, normalized);
if (!trustedKeyGroups.isEmpty()) {
CloudFrontSignatureVerifier.Result verdict =
verifySignedRequest(dist, rawViewerPath, trustedKeyGroups);
CloudFrontSignatureVerifier.Result verdict = verifySignedRequest(
dist, currentVertxRequest.getCurrent().request(), rawViewerPath, trustedKeyGroups);
if (!verdict.allowed()) {
LOG.debugv("CloudFront denied a request for distribution {0}, path {1}: {2}",
dist.getId(), rawViewerPath, verdict.reason());
@@ -381,11 +382,9 @@ public class CloudFrontServingController {
*/
private CloudFrontSignatureVerifier.Result verifySignedRequest(
Distribution distribution,
HttpServerRequest request,
String rawViewerPath,
List<String> trustedKeyGroups) {
io.vertx.core.http.HttpServerRequest request =
currentVertxRequest.getCurrent().request();
Map<String, String> query = new LinkedHashMap<>();
for (String name : request.params().names()) {
query.put(name, request.getParam(name));
@@ -516,16 +515,16 @@ public class CloudFrontServingController {
String forwardUri = CloudFrontRequestRouter.resolveForwardUri(
origin.getOriginPath(), rawViewerPath, config.getDefaultRootObject());
CloudFrontOriginRequestBuilder.OriginRequest originRequest =
CloudFrontOriginRequestBuilder.build(viewerRequest(method, viewerScheme),
CloudFrontOriginRequestBuilder.build(
viewerRequest(currentVertxRequest.getCurrent().request(), method, viewerScheme),
forwarding(config, normalized), distribution.getDomainName());
return fetchFromCustomOrigin(
distribution, origin, forwardUri, originRequest, viewerScheme, method, viewerBody);
}
/** The live viewer request, with CloudFront's signing parameters removed from its query. */
private CloudFrontOriginRequestBuilder.ViewerRequest viewerRequest(
String method, String viewerScheme) {
HttpServerRequest request = currentVertxRequest.getCurrent().request();
private static CloudFrontOriginRequestBuilder.ViewerRequest viewerRequest(
HttpServerRequest request, String method, String viewerScheme) {
List<CloudFrontOriginRequestBuilder.Header> headers = new ArrayList<>();
for (Map.Entry<String, String> header : request.headers()) {
headers.add(new CloudFrontOriginRequestBuilder.Header(header.getKey(), header.getValue()));
@@ -789,63 +788,20 @@ public class CloudFrontServingController {
String viewerScheme, String method, ViewerBody viewerBody) {
boolean includeBody = !"HEAD".equals(method);
try {
// Floci serves its own Web Function and execute-api endpoints, whatever port and protocol the origin names.
String webEndpoint = webFunctionEndpoint(origin);
String executeApiHost = webEndpoint == null ? executeApiHost(origin) : null;
String selfHost = webEndpoint == null && executeApiHost == null ? selfHost(origin, viewerScheme) : null;
boolean inProcess = webEndpoint != null || executeApiHost != null || selfHost != null;
if (inProcess && originRequest.headers().stream()
.anyMatch(header -> "Host".equalsIgnoreCase(header.name()))) {
// CloudFront checks the endpoint's certificate against the forwarded viewer Host, which it never
// names, and a self origin would route the distribution's own Host back to the distribution.
LOG.debugv("CloudFront forwards the viewer Host to in-process origin {0}", origin.getId());
return OriginResponse.error(502, "Bad Gateway.");
CustomOriginTarget target = customOriginTarget(distribution, origin, forwardUri, originRequest,
viewerScheme, currentVertxRequest.getCurrent().request().localAddress());
if (target.refusal() != null) {
return target.refusal();
}
// Dot segments would be resolved after the host filter's check and escape the API's stage.
String originPath = executeApiHost != null ? CloudFrontRequestRouter.normalizePath(rawPath(forwardUri))
: selfHost != null ? selfOriginPath(origin, rawPath(forwardUri)) : forwardUri;
if (executeApiHost != null && !executeApiHostFilter.routes(executeApiHost, originPath)) {
byte[] notFound = ApiGatewayExecuteApiHostFilter.NOT_FOUND_BODY.getBytes(StandardCharsets.UTF_8);
return new OriginResponse(404, MediaType.APPLICATION_JSON, notFound, notFound.length, Map.of());
}
URI target = inProcess
? flociListenerUri(originPath, 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
// (overriding any same-named viewer header), which is how a distribution restricts an origin
// to CloudFront-only traffic via a shared secret header.
Map<String, String> originHeaders = new LinkedHashMap<>();
List<Map<String, String>> customHeaders = origin.getCustomHeaders();
if (customHeaders != null) {
for (Map<String, String> header : customHeaders) {
String name = header.get("HeaderName");
String value = header.get("HeaderValue");
if (name != null && value != null) {
originHeaders.put(name, value);
}
}
}
if (executeApiHost != null) {
originHeaders.put("Host", executeApiHost);
}
if (selfHost != null) {
originHeaders.put("Host", selfHost);
}
if (webEndpoint != null) {
originHeaders.put("Host", webEndpoint);
if (alwaysAmzAuth(origin)) {
originHeaders.putAll(lambdaWebIamAuth.cloudFrontSignature(distribution.getArn()));
}
}
.uri(target.uri());
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 = (inProcess ? flociClient : httpClient).open(
CloudFrontOriginHttpClient.OpenResponse resp = target.client().open(
rb.build(), originRequest.headers(),
originHeaders, requestBody != null ? requestBody.stream() : null,
target.originHeaders(), requestBody != null ? requestBody.stream() : null,
requestBody != null ? requestBody.length() : -1, originTimeouts(origin));
String ct = resp.headers().firstValue("content-type").orElse(DEFAULT_CONTENT_TYPE);
long contentLength = resp.contentLength();
@@ -875,6 +831,138 @@ public class CloudFrontServingController {
}
}
/**
* Where a request to a custom origin goes: its URI, the client that reaches it, and the origin
* headers that replace every same-named forwarded header. A non-null {@code refusal} is the
* answer the viewer gets instead, as the origin cannot be asked.
*/
private record CustomOriginTarget(URI uri, CloudFrontOriginHttpClient client,
Map<String, String> originHeaders, OriginResponse refusal) {
static CustomOriginTarget refused(OriginResponse refusal) {
return new CustomOriginTarget(null, null, Map.of(), refusal);
}
}
private CustomOriginTarget customOriginTarget(Distribution distribution, Origin origin, String forwardUri,
CloudFrontOriginRequestBuilder.OriginRequest originRequest,
String viewerScheme, SocketAddress localAddress) {
// Floci serves its own Web Function and execute-api endpoints, whatever port and protocol the origin names.
String webEndpoint = webFunctionEndpoint(origin);
String executeApiHost = webEndpoint == null ? executeApiHost(origin) : null;
String selfHost = webEndpoint == null && executeApiHost == null ? selfHost(origin, viewerScheme) : null;
boolean inProcess = webEndpoint != null || executeApiHost != null || selfHost != null;
if (inProcess && originRequest.headers().stream()
.anyMatch(header -> "Host".equalsIgnoreCase(header.name()))) {
// CloudFront checks the endpoint's certificate against the forwarded viewer Host, which it never
// names, and a self origin would route the distribution's own Host back to the distribution.
LOG.debugv("CloudFront forwards the viewer Host to in-process origin {0}", origin.getId());
return CustomOriginTarget.refused(OriginResponse.error(502, "Bad Gateway."));
}
// Dot segments would be resolved after the host filter's check and escape the API's stage.
String originPath = executeApiHost != null ? CloudFrontRequestRouter.normalizePath(rawPath(forwardUri))
: selfHost != null ? selfOriginPath(origin, rawPath(forwardUri)) : forwardUri;
if (executeApiHost != null && !executeApiHostFilter.routes(executeApiHost, originPath)) {
byte[] notFound = ApiGatewayExecuteApiHostFilter.NOT_FOUND_BODY.getBytes(StandardCharsets.UTF_8);
return CustomOriginTarget.refused(
new OriginResponse(404, MediaType.APPLICATION_JSON, notFound, notFound.length, Map.of()));
}
URI target = inProcess
? flociListenerUri(localAddress, originPath, originRequest.rawQuery())
: buildCustomOriginUri(origin, viewerScheme, forwardUri, originRequest.rawQuery());
// Origin custom headers: CloudFront adds these to every request it forwards to the origin
// (overriding any same-named viewer header), which is how a distribution restricts an origin
// to CloudFront-only traffic via a shared secret header.
Map<String, String> originHeaders = new LinkedHashMap<>();
List<Map<String, String>> customHeaders = origin.getCustomHeaders();
if (customHeaders != null) {
for (Map<String, String> header : customHeaders) {
String name = header.get("HeaderName");
String value = header.get("HeaderValue");
if (name != null && value != null) {
originHeaders.put(name, value);
}
}
}
if (executeApiHost != null) {
originHeaders.put("Host", executeApiHost);
}
if (selfHost != null) {
originHeaders.put("Host", selfHost);
}
if (webEndpoint != null) {
originHeaders.put("Host", webEndpoint);
if (alwaysAmzAuth(origin)) {
originHeaders.putAll(lambdaWebIamAuth.cloudFrontSignature(distribution.getArn()));
}
}
return new CustomOriginTarget(target, inProcess ? flociClient : httpClient, originHeaders, null);
}
/**
* A custom origin a viewer's WebSocket handshake is tunneled to: the URI and the address it
* resolved to, the headers the origin request carries before the upgrade fields, and the origin's
* connection, response and response completion timeouts for the handshake.
*/
record WebSocketOrigin(URI uri, InetAddress address,
List<CloudFrontOriginRequestBuilder.Header> headers,
Duration connectTimeout, Duration responseTimeout,
Duration responseCompletionTimeout) {
}
/**
* Resolves the origin of a viewer's WebSocket handshake as {@link #serve} resolves an ordinary GET:
* the same distribution, allowed methods, signed-request check, cache behavior, origin request
* policy and origin custom headers. It is null when the handshake is to be answered as an ordinary
* GET instead, which gives the viewer the answer CloudFront gives: an unknown or disabled
* distribution, a refused method or signature, an S3 origin, or a custom origin that cannot be
* asked. Reads the request's headers only, so it can run off the event loop.
*/
WebSocketOrigin webSocketOrigin(HttpServerRequest request) {
try {
Distribution dist = service.findByHost(RequestHost.of(request));
DistributionConfig config = dist != null ? dist.getConfig() : null;
if (config == null || !config.isEnabled()) {
return null;
}
String rawViewerPath = rawViewerPath(request.uri());
String normalized = CloudFrontRequestRouter.normalizePath(decodedViewerPath(rawViewerPath));
if (!CloudFrontRequestRouter.matchAllowedMethods(config, normalized).contains("GET")) {
return null;
}
List<String> trustedKeyGroups = CloudFrontRequestRouter.trustedKeyGroupsFor(config, normalized);
if (!trustedKeyGroups.isEmpty()
&& !verifySignedRequest(dist, request, rawViewerPath, trustedKeyGroups).allowed()) {
return null;
}
Origin origin = CloudFrontRequestRouter.findOrigin(config,
CloudFrontRequestRouter.matchTargetOriginId(config, normalized));
if (origin == null || CloudFrontRequestRouter.isS3Origin(origin)) {
return null;
}
String viewerScheme = request.scheme();
String forwardUri = CloudFrontRequestRouter.resolveForwardUri(
origin.getOriginPath(), rawViewerPath, config.getDefaultRootObject());
CloudFrontOriginRequestBuilder.OriginRequest originRequest =
CloudFrontOriginRequestBuilder.build(viewerRequest(request, "GET", viewerScheme),
forwarding(config, normalized), dist.getDomainName());
CustomOriginTarget target = customOriginTarget(dist, origin, forwardUri, originRequest,
viewerScheme, request.localAddress());
if (target.refusal() != null) {
return null;
}
InetAddress address = target.client().resolve(target.uri().getHost());
CloudFrontOriginHttpClient.OriginTimeouts timeouts = originTimeouts(origin);
return new WebSocketOrigin(target.uri(), address,
CloudFrontOriginHttpClient.originRequestHeaders(originRequest.headers(), target.originHeaders()),
timeouts.connectTimeout(), timeouts.responseTimeout(), timeouts.responseCompletionTimeout());
} catch (IOException | RuntimeException e) {
// The ordinary GET meets the same failure and answers it as CloudFront does.
LOG.debugv("CloudFront answers a WebSocket handshake as a GET: {0}", e.getClass().getSimpleName());
return null;
}
}
/** Whether the origin's access control is always-amz-auth, the one a Web Function origin is signed under. */
private boolean alwaysAmzAuth(Origin origin) {
String oacId = origin.getOriginAccessControlId();
@@ -961,8 +1049,7 @@ public class CloudFrontServingController {
* 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();
private URI flociListenerUri(SocketAddress local, String forwardUri, String rawQuery) {
String host = local.hostAddress().indexOf(':') >= 0 ? "[" + local.hostAddress() + "]" : local.hostAddress();
return buildCustomOriginUri("http", host, httpServer.getPort(), forwardUri, rawQuery);
}
@@ -0,0 +1,318 @@
package io.github.hectorvent.floci.services.cloudfront;
import io.github.hectorvent.floci.core.common.RequestHost;
import io.github.hectorvent.floci.core.common.ServiceConfigAccess;
import io.github.hectorvent.floci.core.common.WebSocketUpgrades;
import io.vertx.core.MultiMap;
import io.vertx.core.Vertx;
import io.vertx.core.http.HttpClient;
import io.vertx.core.http.HttpClientOptions;
import io.vertx.core.http.HttpClientRequest;
import io.vertx.core.http.HttpClientResponse;
import io.vertx.core.http.HttpMethod;
import io.vertx.core.http.HttpServerRequest;
import io.vertx.core.http.HttpServerResponse;
import io.vertx.core.http.RequestOptions;
import io.vertx.core.net.NetSocket;
import io.vertx.core.net.SocketAddress;
import io.vertx.ext.web.Router;
import io.vertx.ext.web.RoutingContext;
import jakarta.annotation.PreDestroy;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.enterprise.event.Observes;
import jakarta.inject.Inject;
import org.jboss.logging.Logger;
import java.net.URI;
import java.time.Duration;
import java.util.Locale;
import java.util.Set;
import java.util.concurrent.atomic.AtomicBoolean;
/**
* Tunnels a viewer's WebSocket connection through a CloudFront distribution to its custom origin, as
* CloudFront does on every distribution with no setting. The handshake is caught before JAX-RS, which
* cannot hand over the connection: {@link CloudFrontServingController#webSocketOrigin} resolves the
* behavior and origin as an ordinary GET, the handshake goes to the origin with its {@code Upgrade}
* and {@code Connection} fields, and once the origin answers {@code 101 Switching Protocols} the two
* connections are joined into a byte tunnel. Any other origin answer is relayed as an ordinary
* response. A handshake the distribution would not forward to a custom origin is left to JAX-RS,
* which answers it as the GET it also is.
*
* <p>The {@code Sec-WebSocket-*} fields reach the origin only when the behavior's origin request
* policy forwards them, as on AWS, which documents forwarding all viewer headers or at least
* {@code Sec-WebSocket-Key} and {@code Sec-WebSocket-Version}.
*/
@ApplicationScoped
public class CloudFrontWebSocketProxy {
private static final Logger LOG = Logger.getLogger(CloudFrontWebSocketProxy.class);
private static final Set<String> HOP_BY_HOP_HEADERS = Set.of(
"connection", "keep-alive", "proxy-authenticate", "proxy-authorization",
"proxy-connection", "te", "trailer", "transfer-encoding", "upgrade");
private final CloudFrontService service;
private final CloudFrontServingController servingController;
private final ServiceConfigAccess serviceConfigAccess;
private final Vertx vertx;
private final HttpClient client;
@Inject
public CloudFrontWebSocketProxy(CloudFrontService service, CloudFrontServingController servingController,
ServiceConfigAccess serviceConfigAccess, Vertx vertx) {
this.service = service;
this.servingController = servingController;
this.serviceConfigAccess = serviceConfigAccess;
this.vertx = vertx;
// Keep-alive, since a client without it sends Connection: close in place of Connection: Upgrade.
// A connection that becomes a tunnel never returns to the pool. The origin's certificate is
// checked against its own name, which goes in SNI though the connection is made to its address.
this.client = vertx.createHttpClient(new HttpClientOptions()
.setKeepAlive(true)
.setVerifyHost(true)
.setForceSni(true));
}
@PreDestroy
void close() {
client.close();
}
void register(@Observes Router router) {
router.route().handler(this::handle);
}
void handle(RoutingContext context) {
HttpServerRequest request = context.request();
// This route runs ahead of the filter that refuses a disabled service, so it checks for itself.
if (!WebSocketUpgrades.isHandshake(request) || !serviceConfigAccess.isEnabled("cloudfront")) {
context.next();
return;
}
String host = RequestHost.of(request);
if (host == null || service.findByHost(host) == null) {
context.next();
return;
}
request.pause();
// Resolving the origin reads policies and the origin's DNS, so it runs off the event loop.
vertx.<CloudFrontServingController.WebSocketOrigin>executeBlocking(
() -> servingController.webSocketOrigin(request), false)
.onComplete(result -> {
if (result.failed() || result.result() == null) {
request.resume();
context.next();
return;
}
tunnel(request, result.result());
});
}
private void tunnel(HttpServerRequest request, CloudFrontServingController.WebSocketOrigin origin) {
URI uri = origin.uri();
boolean ssl = "https".equalsIgnoreCase(uri.getScheme());
String path = uri.getRawPath() + (uri.getRawQuery() != null ? "?" + uri.getRawQuery() : "");
RequestOptions options = new RequestOptions()
.setServer(SocketAddress.inetSocketAddress(uri.getPort(), origin.address().getHostAddress()))
.setHost(CloudFrontServingController.normalizeHost(uri.getHost()))
.setPort(uri.getPort())
.setSsl(ssl)
.setURI(path)
.setMethod(HttpMethod.GET)
.setConnectTimeout(origin.connectTimeout().toMillis());
client.request(options)
.onSuccess(originRequest -> handshake(request, originRequest, origin))
.onFailure(err -> {
LOG.debugv("CloudFront could not connect a WebSocket to origin {0}: {1}",
uri.getHost(), err.getMessage());
request.resume();
request.response().setStatusCode(502).end("Bad Gateway.");
});
}
private void handshake(HttpServerRequest request, HttpClientRequest originRequest,
CloudFrontServingController.WebSocketOrigin origin) {
for (CloudFrontOriginRequestBuilder.Header header : origin.headers()) {
originRequest.headers().add(header.name(), header.value());
}
originRequest.putHeader("Connection", "Upgrade");
originRequest.putHeader("Upgrade", request.getHeader("Upgrade"));
// The origin's timeouts bound its answer to the handshake, and the body of an answer that
// refuses the upgrade. Once the tunnel is open, data flows at the pace of the two ends.
AtomicBoolean answered = new AtomicBoolean();
OriginClock clock = new OriginClock(vertx, origin.responseTimeout(),
new CloudFrontOriginHttpClient.CompletionBudget(origin.responseCompletionTimeout(), System::nanoTime));
clock.onTimeout(() -> {
if (answered.compareAndSet(false, true)) {
originRequest.reset();
request.resume();
request.response().setStatusCode(504).end(CloudFrontServingController.ORIGIN_TIMEOUT_MESSAGE);
}
});
clock.arm();
originRequest.connect()
.onSuccess(response -> {
if (!answered.compareAndSet(false, true)) {
response.netSocket().close();
return;
}
HttpServerResponse viewerResponse = request.response();
viewerResponse.setStatusCode(response.statusCode());
copyEndToEndHeaders(response.headers(), viewerResponse);
if (response.statusCode() != 101) {
request.resume();
relayRefusal(response, viewerResponse, originRequest, clock);
return;
}
clock.stop();
viewerResponse.putHeader("Connection", "Upgrade");
viewerResponse.putHeader("Upgrade", response.getHeader("Upgrade"));
NetSocket originSocket = response.netSocket();
request.toNetSocket()
.onSuccess(viewerSocket -> splice(viewerSocket, originSocket))
.onFailure(err -> {
LOG.debugv("CloudFront WebSocket tunnel lost the viewer: {0}", err.getMessage());
originSocket.close();
});
})
.onFailure(err -> {
clock.stop();
if (!answered.compareAndSet(false, true)) {
return;
}
LOG.debugv("CloudFront WebSocket handshake with the origin failed: {0}", err.getMessage());
request.resume();
if (request.response().headWritten()) {
request.response().close();
} else {
request.response().setStatusCode(502).end("Bad Gateway.");
}
});
}
/**
* Streams the body of an origin answer that refused the upgrade, within the origin's timeouts. Its
* head has already been relayed, so an origin that stalls past them ends the viewer's connection,
* as CloudFront does when the origin does not complete a response in time.
*/
private static void relayRefusal(HttpClientResponse response, HttpServerResponse viewerResponse,
HttpClientRequest originRequest, OriginClock clock) {
if (response.getHeader("Content-Length") == null) {
viewerResponse.setChunked(true);
}
clock.onTimeout(() -> {
LOG.debugv("CloudFront origin stalled while refusing a WebSocket upgrade");
originRequest.reset();
viewerResponse.reset();
});
clock.arm();
viewerResponse.closeHandler(ignored -> {
clock.stop();
originRequest.reset();
});
response.handler(buffer -> {
clock.arm();
viewerResponse.write(buffer);
if (viewerResponse.writeQueueFull()) {
// The time a slow viewer takes to receive the body is not the origin's.
clock.suspend();
response.pause();
viewerResponse.drainHandler(ignored -> {
clock.arm();
response.resume();
});
}
});
response.endHandler(ignored -> {
clock.stop();
viewerResponse.end();
});
response.exceptionHandler(err -> {
clock.stop();
LOG.debugv("CloudFront origin failed while refusing a WebSocket upgrade: {0}", err.getMessage());
viewerResponse.reset();
});
}
/**
* The time the origin takes, bounded as CloudFront bounds it: no longer than the origin's response
* timeout between one packet and the next, and no longer than its response completion timeout in
* all, when it has one. Only armed time is spent from the
* {@link CloudFrontOriginHttpClient.CompletionBudget}, so a viewer that reads slowly does not use
* up the origin's time. Every method runs on the request's event loop.
*/
static final class OriginClock {
private final Vertx vertx;
private final long readTimeoutMillis;
private final CloudFrontOriginHttpClient.CompletionBudget budget;
private Runnable onTimeout = () -> { };
private long timerId = -1;
private long armedAt;
private boolean stopped;
OriginClock(Vertx vertx, Duration readTimeout, CloudFrontOriginHttpClient.CompletionBudget budget) {
this.vertx = vertx;
this.readTimeoutMillis = Math.max(1, readTimeout.toMillis());
this.budget = budget;
}
void onTimeout(Runnable onTimeout) {
this.onTimeout = onTimeout;
}
/** Starts, or restarts after a packet, the wait for the origin's next packet. */
void arm() {
if (stopped) {
return;
}
suspend();
long delayMillis = readTimeoutMillis;
if (!budget.unlimited()) {
delayMillis = Math.min(delayMillis, Math.max(1, budget.remainingNanos() / 1_000_000));
}
armedAt = budget.now();
timerId = vertx.setTimer(delayMillis, ignored -> {
timerId = -1;
stopped = true;
onTimeout.run();
});
}
/** Stops counting until the next {@link #arm}, keeping the completion time already spent. */
void suspend() {
if (timerId < 0) {
return;
}
vertx.cancelTimer(timerId);
timerId = -1;
budget.spend(budget.now() - armedAt);
}
void stop() {
suspend();
stopped = true;
}
}
private static void copyEndToEndHeaders(MultiMap headers, HttpServerResponse response) {
for (String name : headers.names()) {
if (!HOP_BY_HOP_HEADERS.contains(name.toLowerCase(Locale.ROOT))) {
response.putHeader(name, headers.getAll(name));
}
}
}
private static void splice(NetSocket viewer, NetSocket origin) {
AtomicBoolean closed = new AtomicBoolean();
Runnable close = () -> {
if (closed.compareAndSet(false, true)) {
viewer.close();
origin.close();
}
};
Runnable onData = () -> { };
WebSocketUpgrades.relay(viewer, origin, onData, close);
WebSocketUpgrades.relay(origin, viewer, onData, close);
}
}
@@ -7,6 +7,7 @@ import io.github.hectorvent.floci.config.TlsProxyServer;
import io.github.hectorvent.floci.core.common.CertificateReferenceResolver;
import io.github.hectorvent.floci.core.common.CertificateReferenceResolver.CertificateMaterial;
import io.github.hectorvent.floci.core.common.Pem;
import io.github.hectorvent.floci.core.common.WebSocketUpgrades;
import io.github.hectorvent.floci.core.common.tls.ReloadingKeyManager;
import io.github.hectorvent.floci.services.ec2.Ec2Service;
import io.github.hectorvent.floci.services.elbv2.model.Action;
@@ -25,12 +26,10 @@ import io.vertx.core.Vertx;
import io.vertx.core.buffer.Buffer;
import io.vertx.core.http.HttpClient;
import io.vertx.core.http.HttpClientOptions;
import io.vertx.core.http.HttpMethod;
import io.vertx.core.http.HttpServer;
import io.vertx.core.http.HttpServerOptions;
import io.vertx.core.http.HttpServerRequest;
import io.vertx.core.http.HttpServerResponse;
import io.vertx.core.http.HttpVersion;
import io.vertx.core.http.RequestOptions;
import io.vertx.core.net.JdkSSLEngineOptions;
import io.vertx.core.net.KeyCertOptions;
@@ -1241,26 +1240,9 @@ public class ElbV2DataPlane {
}
}
/**
* An ALB forwards a WebSocket handshake to an instance or ip target with its upgrade headers
* intact, which an ordinary proxied request cannot do: {@code Connection} and {@code Upgrade}
* are hop-by-hop and are stripped. AWS only tunnels WebSocket upgrades, over HTTP/1.1.
*/
/** An ALB forwards a WebSocket handshake to an instance or ip target with its upgrade headers intact. */
static boolean isWebSocketUpgrade(HttpServerRequest req) {
if (req.version() != HttpVersion.HTTP_1_1 || req.method() != HttpMethod.GET) {
return false;
}
if (!"websocket".equalsIgnoreCase(req.getHeader("Upgrade"))) {
return false;
}
for (String connection : req.headers().getAll("Connection")) {
for (String token : connection.split(",")) {
if ("upgrade".equalsIgnoreCase(token.trim())) {
return true;
}
}
}
return false;
return WebSocketUpgrades.isHandshake(req);
}
private void proxyUpgrade(HttpServerRequest req, String host, int port, boolean preserveHostHeader,
@@ -1362,8 +1344,9 @@ public class ElbV2DataPlane {
target.close();
}
};
relay(client, target, lastActivity, close);
relay(target, client, lastActivity, close);
Runnable onData = () -> lastActivity.set(System.nanoTime());
WebSocketUpgrades.relay(client, target, onData, close);
WebSocketUpgrades.relay(target, client, onData, close);
scheduleIdleCheck(idleTimeoutMillis, idleTimeoutMillis, lastActivity, timerId, closed, close);
}
@@ -1383,20 +1366,6 @@ public class ElbV2DataPlane {
}));
}
private static void relay(NetSocket source, NetSocket destination, AtomicLong lastActivity, Runnable close) {
source.handler(buffer -> {
lastActivity.set(System.nanoTime());
destination.write(buffer);
if (destination.writeQueueFull()) {
source.pause();
destination.drainHandler(ignored -> source.resume());
}
});
source.endHandler(ignored -> close.run());
source.closeHandler(ignored -> close.run());
source.exceptionHandler(err -> close.run());
}
private void executeRedirect(HttpServerRequest req, Action action) {
String reqHost = req.host();
String reqPort = "";