From d2d9ed6ca264740a0422ebbc895d7603c1d0434c Mon Sep 17 00:00:00 2001 From: Abhigya Date: Sun, 1 Nov 2026 17:23:25 +0530 Subject: [PATCH] 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 --- docs/services/cloudfront.md | 10 + .../floci/core/common/WebSocketUpgrades.java | 55 +++ .../CloudFrontOriginHttpClient.java | 38 ++- .../CloudFrontServingController.java | 209 ++++++++---- .../cloudfront/CloudFrontWebSocketProxy.java | 318 ++++++++++++++++++ .../floci/services/elbv2/ElbV2DataPlane.java | 43 +-- .../CloudFrontWebSocketIntegrationTest.java | 284 ++++++++++++++++ .../elbv2/ElbV2WebSocketIntegrationTest.java | 134 +------- .../hectorvent/floci/testing/AlbFixtures.java | 136 ++++++++ 9 files changed, 1000 insertions(+), 227 deletions(-) create mode 100644 src/main/java/io/github/hectorvent/floci/core/common/WebSocketUpgrades.java create mode 100644 src/main/java/io/github/hectorvent/floci/services/cloudfront/CloudFrontWebSocketProxy.java create mode 100644 src/test/java/io/github/hectorvent/floci/services/cloudfront/CloudFrontWebSocketIntegrationTest.java create mode 100644 src/test/java/io/github/hectorvent/floci/testing/AlbFixtures.java diff --git a/docs/services/cloudfront.md b/docs/services/cloudfront.md index 096a223e13..faad04f087 100644 --- a/docs/services/cloudfront.md +++ b/docs/services/cloudfront.md @@ -238,6 +238,16 @@ PUT, PATCH and DELETE). so a large object is never held in memory. A custom origin's `Content-Length` is passed on, and a response it sends chunked stays chunked. Floci does not cache, so it serves objects larger than 50 GB the way CloudFront does with caching disabled; with caching enabled, CloudFront refuses them. +- WebSocket connections to custom origins are tunneled on every distribution, with no setting, as on + AWS. An HTTP/1.1 GET with `Upgrade: websocket` and `Connection: Upgrade` goes to the origin the + matched behavior selects with its `Upgrade` and `Connection` fields, and once the origin answers + `101 Switching Protocols` the viewer and origin connections are joined. Any other origin answer is + relayed as an ordinary response, without custom error responses or a response headers policy, + within the origin's response and response completion timeouts. The + `Sec-WebSocket-*` fields follow the behavior's forwarding settings as any other header does, so the + behavior must forward all viewer headers (the `AllViewer` origin request policy, or legacy cache + settings) or at least `Sec-WebSocket-Key` and `Sec-WebSocket-Version`. A WebSocket handshake to an + S3 origin is served as an ordinary GET. - Range GETs: an S3 origin serves the one byte range a viewer's `Range` asks for as 206 with its `Content-Range`, and answers 416 when the range starts past the end of the object. Any other `Range` gets the whole object: one CloudFront does not accept (ranges out of order or overlapping, diff --git a/src/main/java/io/github/hectorvent/floci/core/common/WebSocketUpgrades.java b/src/main/java/io/github/hectorvent/floci/core/common/WebSocketUpgrades.java new file mode 100644 index 0000000000..26d19a3512 --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/core/common/WebSocketUpgrades.java @@ -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()); + } +} diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudfront/CloudFrontOriginHttpClient.java b/src/main/java/io/github/hectorvent/floci/services/cloudfront/CloudFrontOriginHttpClient.java index 78d0133505..edc0bdf997 100644 --- a/src/main/java/io/github/hectorvent/floci/services/cloudfront/CloudFrontOriginHttpClient.java +++ b/src/main/java/io/github/hectorvent/floci/services/cloudfront/CloudFrontOriginHttpClient.java @@ -84,6 +84,8 @@ final class CloudFrontOriginHttpClient implements AutoCloseable { private static final ThreadLocal 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 originRequestHeaders( + List forwardedHeaders, Map originHeaders) { + Set replaced = new TreeSet<>(String.CASE_INSENSITIVE_ORDER); + replaced.addAll(originHeaders.keySet()); + List 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. diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudfront/CloudFrontServingController.java b/src/main/java/io/github/hectorvent/floci/services/cloudfront/CloudFrontServingController.java index 8660161582..2245dd61db 100644 --- a/src/main/java/io/github/hectorvent/floci/services/cloudfront/CloudFrontServingController.java +++ b/src/main/java/io/github/hectorvent/floci/services/cloudfront/CloudFrontServingController.java @@ -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 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 trustedKeyGroups) { - io.vertx.core.http.HttpServerRequest request = - currentVertxRequest.getCurrent().request(); - Map 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 headers = new ArrayList<>(); for (Map.Entry 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 originHeaders = new LinkedHashMap<>(); - List> customHeaders = origin.getCustomHeaders(); - if (customHeaders != null) { - for (Map 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 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 originHeaders = new LinkedHashMap<>(); + List> customHeaders = origin.getCustomHeaders(); + if (customHeaders != null) { + for (Map 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 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 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); } diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudfront/CloudFrontWebSocketProxy.java b/src/main/java/io/github/hectorvent/floci/services/cloudfront/CloudFrontWebSocketProxy.java new file mode 100644 index 0000000000..9d47c0b3bc --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/cloudfront/CloudFrontWebSocketProxy.java @@ -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. + * + *

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 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.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); + } +} diff --git a/src/main/java/io/github/hectorvent/floci/services/elbv2/ElbV2DataPlane.java b/src/main/java/io/github/hectorvent/floci/services/elbv2/ElbV2DataPlane.java index 5e9a69049e..81d781cfbe 100644 --- a/src/main/java/io/github/hectorvent/floci/services/elbv2/ElbV2DataPlane.java +++ b/src/main/java/io/github/hectorvent/floci/services/elbv2/ElbV2DataPlane.java @@ -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 = ""; diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudfront/CloudFrontWebSocketIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudfront/CloudFrontWebSocketIntegrationTest.java new file mode 100644 index 0000000000..f5bed8b144 --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/cloudfront/CloudFrontWebSocketIntegrationTest.java @@ -0,0 +1,284 @@ +package io.github.hectorvent.floci.services.cloudfront; + +import io.github.hectorvent.floci.core.common.ServiceConfigAccess; +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.testing.PartitionCleanup; +import io.quarkus.test.junit.QuarkusTest; +import io.quarkus.test.junit.QuarkusTestProfile; +import io.quarkus.test.junit.TestProfile; +import io.quarkus.test.junit.mockito.InjectSpy; +import io.restassured.RestAssured; +import io.vertx.core.Vertx; +import io.vertx.core.http.HttpClient; +import io.vertx.core.http.HttpServer; +import io.vertx.core.http.UpgradeRejectedException; +import io.vertx.core.http.WebSocket; +import io.vertx.core.http.WebSocketConnectOptions; +import jakarta.inject.Inject; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.RegisterExtension; + +import java.time.Duration; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.AtomicReference; + +import static io.github.hectorvent.floci.testing.AlbFixtures.createListener; +import static io.github.hectorvent.floci.testing.AlbFixtures.createLoadBalancer; +import static io.github.hectorvent.floci.testing.AlbFixtures.createTargetGroup; +import static io.github.hectorvent.floci.testing.AlbFixtures.deleteListener; +import static io.github.hectorvent.floci.testing.AlbFixtures.deleteLoadBalancer; +import static io.github.hectorvent.floci.testing.AlbFixtures.deleteTargetGroup; +import static io.github.hectorvent.floci.testing.AlbFixtures.exchange; +import static io.github.hectorvent.floci.testing.AlbFixtures.registerTarget; +import static io.restassured.RestAssured.given; +import static org.awaitility.Awaitility.await; +import static org.hamcrest.Matchers.equalTo; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertInstanceOf; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.mockito.Mockito.doReturn; + +/** + * Tunnels WebSocket connections through a distribution whose custom origin is an ALB listener, as + * CloudFront does on every distribution: viewer, distribution, load balancer and an echo target. + */ +@QuarkusTest +@TestProfile(CloudFrontWebSocketIntegrationTest.AlbOriginProfile.class) +class CloudFrontWebSocketIntegrationTest { + + /** The real ELBv2 data plane, and an origin at 127.0.0.1 that CloudFront would otherwise refuse. */ + public static class AlbOriginProfile implements QuarkusTestProfile { + @Override + public Map getConfigOverrides() { + return Map.of( + "floci.services.elbv2.mock", "false", + "floci.services.cloudfront.allowed-private-origin-hosts", "127.0.0.1"); + } + } + + private static final int LISTENER_PORT = 7797; + private static final String CACHING_DISABLED = "4135ea2d-6df8-44a3-9df3-4b5a84be39ad"; + private static final String ALL_VIEWER = "216adef6-5c7f-47e4-b989-5492eafa07d3"; + + @Inject + Vertx vertx; + + @Inject + CloudFrontService cloudFrontService; + + @InjectSpy + ServiceConfigAccess serviceConfigAccess; + + @RegisterExtension + final PartitionCleanup cleanup = new PartitionCleanup(); + + private final AtomicReference originCustomHeader = new AtomicReference<>(); + private final AtomicInteger originUpgrades = new AtomicInteger(); + private HttpServer backend; + private HttpClient client; + private String loadBalancerArn; + private String targetGroupArn; + private String listenerArn; + + @BeforeEach + void startAlbOrigin() throws Exception { + backend = vertx.createHttpServer() + .requestHandler(request -> { + originCustomHeader.set(request.getHeader("X-Origin-Verify")); + if (!"websocket".equalsIgnoreCase(request.getHeader("Upgrade"))) { + request.response().setStatusCode(400).end("not an upgrade"); + return; + } + originUpgrades.incrementAndGet(); + if (request.path().startsWith("/stall/")) { + // Refuses the upgrade, then never finishes the body. + request.response().setChunked(true).setStatusCode(503).write("partial"); + } else if (!request.path().startsWith("/socket.io/")) { + request.response().headers().add("X-Multi", "one").add("X-Multi", "two"); + request.response().setStatusCode(404).end("upgrade refused"); + } else { + String query = request.query(); + // A handshake without Sec-WebSocket-Key is answered 400 by Vert.x itself. + request.toWebSocket().onSuccess(socket -> socket.textMessageHandler( + text -> socket.writeTextMessage(query + ":" + text))); + } + }) + .listen(0, "127.0.0.1") + .toCompletionStage() + .toCompletableFuture() + .get(2, TimeUnit.SECONDS); + client = vertx.createHttpClient(); + loadBalancerArn = createLoadBalancer("cloudfront-websocket-lb"); + targetGroupArn = createTargetGroup("cloudfront-websocket-tg", "ip", backend.actualPort()); + registerTarget(targetGroupArn, "127.0.0.1", backend.actualPort()); + listenerArn = createListener(loadBalancerArn, targetGroupArn, LISTENER_PORT); + await().atMost(Duration.ofSeconds(3)).untilAsserted(() -> given() + .baseUri("http://127.0.0.1") + .port(LISTENER_PORT) + .when() + .get("/") + .then() + .statusCode(400)); + } + + @AfterEach + void stopAlbOrigin() throws Exception { + deleteListener(listenerArn); + deleteTargetGroup(targetGroupArn); + deleteLoadBalancer(loadBalancerArn); + client.close().toCompletionStage().toCompletableFuture().get(2, TimeUnit.SECONDS); + backend.close().toCompletionStage().toCompletableFuture().get(2, TimeUnit.SECONDS); + } + + @Test + void tunnelsWebSocketThroughDistributionToAlbOrigin() throws Exception { + Distribution distribution = createDistribution(policyBehavior(ALL_VIEWER)); + + WebSocket socket = connect(distribution, "/socket.io/?EIO=4&transport=websocket"); + try { + assertEquals("EIO=4&transport=websocket:hello", exchange(socket, "hello")); + assertEquals("EIO=4&transport=websocket:again", exchange(socket, "again")); + } finally { + socket.close(); + } + assertEquals("shared-secret", originCustomHeader.get()); + } + + @Test + void tunnelsWebSocketWithLegacyCacheSettings() throws Exception { + Distribution distribution = createDistribution(legacyBehavior()); + + WebSocket socket = connect(distribution, "/socket.io/?transport=websocket"); + try { + // Legacy cache settings forward no query string unless ForwardedValues asks for it. + assertEquals("null:hello", exchange(socket, "hello")); + } finally { + socket.close(); + } + } + + @Test + void handshakeFailsWhenPolicyDoesNotForwardWebSocketKey() { + // AWS requires the origin request policy to forward Sec-WebSocket-Key and -Version. + Distribution distribution = createDistribution(policyBehavior(null)); + + ExecutionException failure = assertThrows(ExecutionException.class, + () -> connect(distribution, "/socket.io/?transport=websocket")); + + UpgradeRejectedException rejected = assertInstanceOf(UpgradeRejectedException.class, failure.getCause()); + assertEquals(400, rejected.getStatus()); + } + + @Test + void relaysOriginRefusalOfUpgrade() { + Distribution distribution = createDistribution(policyBehavior(ALL_VIEWER)); + + ExecutionException failure = assertThrows(ExecutionException.class, + () -> connect(distribution, "/elsewhere/?transport=websocket")); + + UpgradeRejectedException rejected = assertInstanceOf(UpgradeRejectedException.class, failure.getCause()); + assertEquals(404, rejected.getStatus()); + assertEquals(List.of("one", "two"), rejected.getHeaders().getAll("X-Multi")); + assertEquals("upgrade refused", rejected.getBody().toString()); + } + + @Test + void plainRequestThroughDistributionCarriesNoUpgrade() { + Distribution distribution = createDistribution(policyBehavior(ALL_VIEWER)); + + given() + .header("Host", distribution.getDomainName()) + .when() + .get("/socket.io/?transport=polling") + .then() + .statusCode(400) + .body(equalTo("not an upgrade")); + } + + @Test + void endsRefusalWhoseBodyStallsPastOriginReadTimeout() { + Distribution distribution = createDistribution(policyBehavior(ALL_VIEWER), 1); + + // A refusal that never ends would leave connect() waiting past its 5 s limit (a TimeoutException). + assertThrows(ExecutionException.class, () -> connect(distribution, "/stall/?transport=websocket")); + assertEquals(1, originUpgrades.get()); + } + + @Test + void disabledCloudFrontDoesNotTunnel() { + Distribution distribution = createDistribution(policyBehavior(ALL_VIEWER)); + doReturn(false).when(serviceConfigAccess).isEnabled("cloudfront"); + + ExecutionException failure = assertThrows(ExecutionException.class, + () -> connect(distribution, "/socket.io/?transport=websocket")); + + assertInstanceOf(UpgradeRejectedException.class, failure.getCause()); + assertEquals(0, originUpgrades.get()); + } + + private Distribution createDistribution(DefaultCacheBehavior behavior) { + return createDistribution(behavior, null); + } + + private Distribution createDistribution(DefaultCacheBehavior behavior, Integer originReadTimeoutSeconds) { + Origin origin = new Origin(); + origin.setId("alb"); + origin.setDomainName("127.0.0.1"); + Map customOriginConfig = new LinkedHashMap<>(); + customOriginConfig.put("HTTPPort", String.valueOf(LISTENER_PORT)); + customOriginConfig.put("HTTPSPort", "443"); + customOriginConfig.put("OriginProtocolPolicy", "http-only"); + if (originReadTimeoutSeconds != null) { + customOriginConfig.put("OriginReadTimeout", String.valueOf(originReadTimeoutSeconds)); + } + origin.setCustomOriginConfig(customOriginConfig); + origin.setCustomHeaders(List.of(new LinkedHashMap<>(Map.of( + "HeaderName", "X-Origin-Verify", "HeaderValue", "shared-secret")))); + + 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; + } + + private static DefaultCacheBehavior legacyBehavior() { + DefaultCacheBehavior behavior = new DefaultCacheBehavior(); + behavior.setTargetOriginId("alb"); + behavior.setViewerProtocolPolicy("allow-all"); + return behavior; + } + + private static DefaultCacheBehavior policyBehavior(String originRequestPolicyId) { + DefaultCacheBehavior behavior = legacyBehavior(); + behavior.setCachePolicyId(CACHING_DISABLED); + behavior.setOriginRequestPolicyId(originRequestPolicyId); + return behavior; + } + + private WebSocket connect(Distribution distribution, String uri) throws Exception { + return client.webSocket(new WebSocketConnectOptions() + .setHost("127.0.0.1") + .setPort(RestAssured.port) + .setURI(uri) + .putHeader("Host", distribution.getDomainName())) + .toCompletionStage() + .toCompletableFuture() + .get(5, TimeUnit.SECONDS); + } + +} diff --git a/src/test/java/io/github/hectorvent/floci/services/elbv2/ElbV2WebSocketIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/elbv2/ElbV2WebSocketIntegrationTest.java index 11cffe29e0..d36064f82a 100644 --- a/src/test/java/io/github/hectorvent/floci/services/elbv2/ElbV2WebSocketIntegrationTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/elbv2/ElbV2WebSocketIntegrationTest.java @@ -23,6 +23,15 @@ import java.util.concurrent.CompletableFuture; import java.util.concurrent.ExecutionException; import java.util.concurrent.TimeUnit; +import static io.github.hectorvent.floci.testing.AlbFixtures.createListener; +import static io.github.hectorvent.floci.testing.AlbFixtures.createLoadBalancer; +import static io.github.hectorvent.floci.testing.AlbFixtures.createTargetGroup; +import static io.github.hectorvent.floci.testing.AlbFixtures.deleteListener; +import static io.github.hectorvent.floci.testing.AlbFixtures.deleteLoadBalancer; +import static io.github.hectorvent.floci.testing.AlbFixtures.deleteTargetGroup; +import static io.github.hectorvent.floci.testing.AlbFixtures.exchange; +import static io.github.hectorvent.floci.testing.AlbFixtures.forwardDefaultActionTo; +import static io.github.hectorvent.floci.testing.AlbFixtures.registerTarget; import static io.restassured.RestAssured.given; import static org.awaitility.Awaitility.await; import static org.hamcrest.Matchers.anyOf; @@ -81,10 +90,10 @@ class ElbV2WebSocketIntegrationTest { .toCompletableFuture() .get(2, TimeUnit.SECONDS); client = vertx.createHttpClient(); - loadBalancerArn = createLoadBalancer(); + loadBalancerArn = createLoadBalancer("websocket-lb"); targetGroupArn = createTargetGroup("websocket-tg", "ip", backend.actualPort()); registerTarget(targetGroupArn, "127.0.0.1", backend.actualPort()); - listenerArn = createListener(loadBalancerArn, targetGroupArn); + listenerArn = createListener(loadBalancerArn, targetGroupArn, LISTENER_PORT); await().atMost(Duration.ofSeconds(3)).untilAsserted(() -> given() .baseUri("http://127.0.0.1") .port(LISTENER_PORT) @@ -241,19 +250,6 @@ class ElbV2WebSocketIntegrationTest { return targetGroupArn; } - private static void forwardDefaultActionTo(String listenerArn, String targetGroupArn) { - given() - .formParam("Action", "ModifyListener") - .formParam("ListenerArn", listenerArn) - .formParam("DefaultActions.member.1.Type", "forward") - .formParam("DefaultActions.member.1.TargetGroupArn", targetGroupArn) - .header("Authorization", AUTH) - .when() - .post("/") - .then() - .statusCode(200); - } - private WebSocket connect(String uri) throws Exception { return client.webSocket(new WebSocketConnectOptions() .setHost("127.0.0.1") @@ -264,76 +260,6 @@ class ElbV2WebSocketIntegrationTest { .get(5, TimeUnit.SECONDS); } - private static String exchange(WebSocket socket, String text) throws Exception { - CompletableFuture reply = new CompletableFuture<>(); - socket.textMessageHandler(reply::complete); - socket.writeTextMessage(text); - return reply.get(5, TimeUnit.SECONDS); - } - - private static String createLoadBalancer() { - return given() - .formParam("Action", "CreateLoadBalancer") - .formParam("Name", "websocket-lb") - .formParam("Type", "application") - .formParam("Subnets.member.1", Ec2Service.defaultSubnetId("us-east-1", "a")) - .formParam("Subnets.member.2", Ec2Service.defaultSubnetId("us-east-1", "b")) - .header("Authorization", AUTH) - .when() - .post("/") - .then() - .statusCode(200) - .extract() - .path("CreateLoadBalancerResponse.CreateLoadBalancerResult.LoadBalancers.member.LoadBalancerArn"); - } - - private static String createTargetGroup(String name, String targetType, int backendPort) { - return given() - .formParam("Action", "CreateTargetGroup") - .formParam("Name", name) - .formParam("Protocol", "HTTP") - .formParam("Port", backendPort) - .formParam("TargetType", targetType) - .formParam("HealthCheckEnabled", "false") - .header("Authorization", AUTH) - .when() - .post("/") - .then() - .statusCode(200) - .extract() - .path("CreateTargetGroupResponse.CreateTargetGroupResult.TargetGroups.member.TargetGroupArn"); - } - - private static void registerTarget(String targetGroupArn, String targetId, int backendPort) { - given() - .formParam("Action", "RegisterTargets") - .formParam("TargetGroupArn", targetGroupArn) - .formParam("Targets.member.1.Id", targetId) - .formParam("Targets.member.1.Port", backendPort) - .header("Authorization", AUTH) - .when() - .post("/") - .then() - .statusCode(200); - } - - private static String createListener(String loadBalancerArn, String targetGroupArn) { - return given() - .formParam("Action", "CreateListener") - .formParam("LoadBalancerArn", loadBalancerArn) - .formParam("Protocol", "HTTP") - .formParam("Port", LISTENER_PORT) - .formParam("DefaultActions.member.1.Type", "forward") - .formParam("DefaultActions.member.1.TargetGroupArn", targetGroupArn) - .header("Authorization", AUTH) - .when() - .post("/") - .then() - .statusCode(200) - .extract() - .path("CreateListenerResponse.CreateListenerResult.Listeners.member.ListenerArn"); - } - private static void setIdleTimeout(String loadBalancerArn, int seconds) { given() .formParam("Action", "ModifyLoadBalancerAttributes") @@ -347,42 +273,4 @@ class ElbV2WebSocketIntegrationTest { .statusCode(200); } - private static void deleteListener(String listenerArn) { - if (listenerArn != null) { - given() - .formParam("Action", "DeleteListener") - .formParam("ListenerArn", listenerArn) - .header("Authorization", AUTH) - .when() - .post("/") - .then() - .statusCode(anyOf(equalTo(200), equalTo(204))); - } - } - - private static void deleteTargetGroup(String targetGroupArn) { - if (targetGroupArn != null) { - given() - .formParam("Action", "DeleteTargetGroup") - .formParam("TargetGroupArn", targetGroupArn) - .header("Authorization", AUTH) - .when() - .post("/") - .then() - .statusCode(anyOf(equalTo(200), equalTo(204))); - } - } - - private static void deleteLoadBalancer(String loadBalancerArn) { - if (loadBalancerArn != null) { - given() - .formParam("Action", "DeleteLoadBalancer") - .formParam("LoadBalancerArn", loadBalancerArn) - .header("Authorization", AUTH) - .when() - .post("/") - .then() - .statusCode(anyOf(equalTo(200), equalTo(204))); - } - } } diff --git a/src/test/java/io/github/hectorvent/floci/testing/AlbFixtures.java b/src/test/java/io/github/hectorvent/floci/testing/AlbFixtures.java new file mode 100644 index 0000000000..f0427966d4 --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/testing/AlbFixtures.java @@ -0,0 +1,136 @@ +package io.github.hectorvent.floci.testing; + +import io.github.hectorvent.floci.services.ec2.Ec2Service; +import io.vertx.core.http.WebSocket; + +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.TimeUnit; + +import static io.restassured.RestAssured.given; +import static org.hamcrest.Matchers.anyOf; +import static org.hamcrest.Matchers.equalTo; + +/** + * An application load balancer in front of a test's own target, for the classes that send traffic + * through the real ELBv2 data plane, and the WebSocket exchange they check it with. + */ +public final class AlbFixtures { + + private static final String AUTH = + "AWS4-HMAC-SHA256 Credential=test/20261101/us-east-1/elasticloadbalancing/aws4_request"; + + private AlbFixtures() { + } + + public static String createLoadBalancer(String name) { + return given() + .formParam("Action", "CreateLoadBalancer") + .formParam("Name", name) + .formParam("Type", "application") + .formParam("Subnets.member.1", Ec2Service.defaultSubnetId("us-east-1", "a")) + .formParam("Subnets.member.2", Ec2Service.defaultSubnetId("us-east-1", "b")) + .header("Authorization", AUTH) + .when() + .post("/") + .then() + .statusCode(200) + .extract() + .path("CreateLoadBalancerResponse.CreateLoadBalancerResult.LoadBalancers.member.LoadBalancerArn"); + } + + /** An HTTP target group with health checks off, so a target serves as soon as it is registered. */ + public static String createTargetGroup(String name, String targetType, int targetPort) { + return given() + .formParam("Action", "CreateTargetGroup") + .formParam("Name", name) + .formParam("Protocol", "HTTP") + .formParam("Port", targetPort) + .formParam("TargetType", targetType) + .formParam("HealthCheckEnabled", "false") + .header("Authorization", AUTH) + .when() + .post("/") + .then() + .statusCode(200) + .extract() + .path("CreateTargetGroupResponse.CreateTargetGroupResult.TargetGroups.member.TargetGroupArn"); + } + + public static void registerTarget(String targetGroupArn, String targetId, int targetPort) { + given() + .formParam("Action", "RegisterTargets") + .formParam("TargetGroupArn", targetGroupArn) + .formParam("Targets.member.1.Id", targetId) + .formParam("Targets.member.1.Port", targetPort) + .header("Authorization", AUTH) + .when() + .post("/") + .then() + .statusCode(200); + } + + /** An HTTP listener on {@code port} that forwards every request to {@code targetGroupArn}. */ + public static String createListener(String loadBalancerArn, String targetGroupArn, int port) { + return given() + .formParam("Action", "CreateListener") + .formParam("LoadBalancerArn", loadBalancerArn) + .formParam("Protocol", "HTTP") + .formParam("Port", port) + .formParam("DefaultActions.member.1.Type", "forward") + .formParam("DefaultActions.member.1.TargetGroupArn", targetGroupArn) + .header("Authorization", AUTH) + .when() + .post("/") + .then() + .statusCode(200) + .extract() + .path("CreateListenerResponse.CreateListenerResult.Listeners.member.ListenerArn"); + } + + public static void forwardDefaultActionTo(String listenerArn, String targetGroupArn) { + given() + .formParam("Action", "ModifyListener") + .formParam("ListenerArn", listenerArn) + .formParam("DefaultActions.member.1.Type", "forward") + .formParam("DefaultActions.member.1.TargetGroupArn", targetGroupArn) + .header("Authorization", AUTH) + .when() + .post("/") + .then() + .statusCode(200); + } + + public static void deleteListener(String listenerArn) { + delete("DeleteListener", "ListenerArn", listenerArn); + } + + public static void deleteTargetGroup(String targetGroupArn) { + delete("DeleteTargetGroup", "TargetGroupArn", targetGroupArn); + } + + public static void deleteLoadBalancer(String loadBalancerArn) { + delete("DeleteLoadBalancer", "LoadBalancerArn", loadBalancerArn); + } + + /** Sends {@code text} on the socket and returns the next text message it receives. */ + public static String exchange(WebSocket socket, String text) throws Exception { + CompletableFuture reply = new CompletableFuture<>(); + socket.textMessageHandler(reply::complete); + socket.writeTextMessage(text); + return reply.get(5, TimeUnit.SECONDS); + } + + private static void delete(String action, String arnParameter, String arn) { + if (arn == null) { + return; + } + given() + .formParam("Action", action) + .formParam(arnParameter, arn) + .header("Authorization", AUTH) + .when() + .post("/") + .then() + .statusCode(anyOf(equalTo(200), equalTo(204))); + } +}