mirror of
https://github.com/floci-io/floci.git
synced 2026-11-22 21:50:46 -05:00
fix(elbv2): tunnel WebSocket upgrades to instance and ip targets (#4517)
* fix(elbv2): tunnel WebSocket upgrades to instance and ip targets The ALB data plane stripped Connection and Upgrade as hop-by-hop headers and proxied a WebSocket handshake as a plain request, so the target answered it as a non-upgrade (typically 400) and socket.io clients stayed on long-polling. Forward the handshake with its upgrade headers, relay the target's 101, then tunnel bytes both ways until either side closes or the load balancer's idle_timeout.timeout_seconds passes with no data. A target that refuses the upgrade has its answer relayed unchanged. Upgrades to Lambda targets are rejected with 400, as AWS does. Closes #4516 * fix(elbv2): bracket IPv6 target literals in the proxied Host header Covers WebSocket upgrades to instance targets as well.
This commit is contained in:
1 parent
673c8838cf
commit
e1cc7439f6
4 files changed
+586
-8
No files matched your search
@@ -19,10 +19,13 @@ 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.HttpVersion;
|
||||
import io.vertx.core.http.RequestOptions;
|
||||
import io.vertx.core.net.NetSocket;
|
||||
import jakarta.annotation.PostConstruct;
|
||||
import jakarta.annotation.PreDestroy;
|
||||
import jakarta.enterprise.context.ApplicationScoped;
|
||||
@@ -40,6 +43,7 @@ import java.util.Map;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.concurrent.atomic.AtomicBoolean;
|
||||
import java.util.concurrent.atomic.AtomicInteger;
|
||||
import java.util.concurrent.atomic.AtomicLong;
|
||||
import java.util.concurrent.atomic.AtomicReference;
|
||||
import java.util.regex.Pattern;
|
||||
import java.util.stream.Collectors;
|
||||
@@ -53,6 +57,8 @@ public class ElbV2DataPlane {
|
||||
"connection", "keep-alive", "transfer-encoding", "upgrade", "te", "trailers", "proxy-authorization", "proxy-authenticate"
|
||||
);
|
||||
private static final String PRESERVE_HOST_HEADER_ATTRIBUTE = "routing.http.preserve_host_header.enabled";
|
||||
private static final String IDLE_TIMEOUT_ATTRIBUTE = "idle_timeout.timeout_seconds";
|
||||
private static final long DEFAULT_IDLE_TIMEOUT_SECONDS = 60;
|
||||
private static final int MAX_LAMBDA_BODY_BYTES = 1024 * 1024;
|
||||
|
||||
@Inject
|
||||
@@ -432,6 +438,10 @@ public class ElbV2DataPlane {
|
||||
}
|
||||
|
||||
if ("lambda".equals(tg.getTargetType())) {
|
||||
if (isWebSocketUpgrade(req)) {
|
||||
req.response().setStatusCode(400).end("WebSockets are not supported for Lambda targets");
|
||||
return;
|
||||
}
|
||||
List<TargetDescription> targets = tg.getTargets();
|
||||
if (targets.isEmpty()) {
|
||||
req.response().setStatusCode(503).end("No Lambda targets registered");
|
||||
@@ -455,19 +465,39 @@ public class ElbV2DataPlane {
|
||||
int idx = Math.abs(counter.getAndIncrement() % candidates.size());
|
||||
TargetDescription target = candidates.get(idx);
|
||||
int targetPort = ElbV2HealthChecker.effectivePort(target, tg);
|
||||
proxyRequest(req, ElbV2TargetResolver.resolveHost(ec2Service, tg, target), targetPort,
|
||||
preserveHostHeader(listenerArn, region));
|
||||
String host = ElbV2TargetResolver.resolveHost(ec2Service, tg, target);
|
||||
boolean preserveHostHeader = Boolean.parseBoolean(
|
||||
loadBalancerAttribute(listenerArn, region, PRESERVE_HOST_HEADER_ATTRIBUTE));
|
||||
if (isWebSocketUpgrade(req)) {
|
||||
proxyUpgrade(req, host, targetPort, preserveHostHeader, idleTimeoutMillis(listenerArn, region));
|
||||
return;
|
||||
}
|
||||
proxyRequest(req, host, targetPort, preserveHostHeader);
|
||||
}
|
||||
|
||||
private boolean preserveHostHeader(String listenerArn, String region) {
|
||||
private String loadBalancerAttribute(String listenerArn, String region, String key) {
|
||||
ListenerBinding binding = listenerBindings.get(listenerArn);
|
||||
if (binding == null) {
|
||||
return false;
|
||||
return null;
|
||||
}
|
||||
LoadBalancer loadBalancer = elbV2Service.getLoadBalancer(region, binding.loadBalancerArn());
|
||||
return loadBalancer != null
|
||||
&& loadBalancer.getAttributes() != null
|
||||
&& Boolean.parseBoolean(loadBalancer.getAttributes().get(PRESERVE_HOST_HEADER_ATTRIBUTE));
|
||||
if (loadBalancer == null || loadBalancer.getAttributes() == null) {
|
||||
return null;
|
||||
}
|
||||
return loadBalancer.getAttributes().get(key);
|
||||
}
|
||||
|
||||
private long idleTimeoutMillis(String listenerArn, String region) {
|
||||
String configured = loadBalancerAttribute(listenerArn, region, IDLE_TIMEOUT_ATTRIBUTE);
|
||||
long seconds = DEFAULT_IDLE_TIMEOUT_SECONDS;
|
||||
if (configured != null) {
|
||||
try {
|
||||
seconds = Long.parseLong(configured.trim());
|
||||
} catch (NumberFormatException e) {
|
||||
LOG.debugv("Ignoring non-numeric {0} value {1}", IDLE_TIMEOUT_ATTRIBUTE, configured);
|
||||
}
|
||||
}
|
||||
return Math.max(1, seconds) * 1000;
|
||||
}
|
||||
|
||||
private void invokeLambdaTarget(io.vertx.core.http.HttpServerRequest req, String functionArn, String region) {
|
||||
@@ -698,7 +728,7 @@ public class ElbV2DataPlane {
|
||||
}
|
||||
});
|
||||
if (!preserveHostHeader) {
|
||||
clientReq.putHeader("Host", host + ":" + port);
|
||||
clientReq.putHeader("Host", ElbV2TargetResolver.hostHeader(host, port));
|
||||
}
|
||||
AtomicBoolean responseStarted = new AtomicBoolean();
|
||||
AtomicBoolean requestFailed = new AtomicBoolean();
|
||||
@@ -745,6 +775,165 @@ 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.
|
||||
*/
|
||||
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;
|
||||
}
|
||||
|
||||
private void proxyUpgrade(HttpServerRequest req, String host, int port, boolean preserveHostHeader,
|
||||
long idleTimeoutMillis) {
|
||||
req.pause();
|
||||
if (ElbV2TargetResolver.isIpLiteral(host)) {
|
||||
try {
|
||||
proxyUpgradeTo(req, ElbV2TargetResolver.resolveCheckedAddress(host), host, port,
|
||||
preserveHostHeader, idleTimeoutMillis);
|
||||
} catch (IOException e) {
|
||||
rejectTarget(req, host, e);
|
||||
}
|
||||
return;
|
||||
}
|
||||
vertx.<String>executeBlocking(() -> ElbV2TargetResolver.resolveCheckedAddress(host))
|
||||
.onSuccess(address -> proxyUpgradeTo(req, address, host, port, preserveHostHeader,
|
||||
idleTimeoutMillis))
|
||||
.onFailure(err -> rejectTarget(req, host, err));
|
||||
}
|
||||
|
||||
/**
|
||||
* Sends the handshake to the target and, once it answers {@code 101 Switching Protocols},
|
||||
* relays that answer and joins the two connections into a byte tunnel. Any other answer means
|
||||
* the target refused the upgrade and is relayed as an ordinary response.
|
||||
*/
|
||||
private void proxyUpgradeTo(HttpServerRequest req, String address, String host, int port,
|
||||
boolean preserveHostHeader, long idleTimeoutMillis) {
|
||||
RequestOptions opts = new RequestOptions()
|
||||
.setHost(address)
|
||||
.setPort(port)
|
||||
.setURI(req.uri())
|
||||
.setMethod(req.method());
|
||||
proxyClient.request(opts)
|
||||
.onSuccess(clientReq -> {
|
||||
req.headers().forEach(entry -> {
|
||||
if (!HOP_BY_HOP_HEADERS.contains(entry.getKey().toLowerCase())) {
|
||||
clientReq.putHeader(entry.getKey(), entry.getValue());
|
||||
}
|
||||
});
|
||||
clientReq.putHeader("Connection", "Upgrade");
|
||||
clientReq.putHeader("Upgrade", req.getHeader("Upgrade"));
|
||||
if (!preserveHostHeader) {
|
||||
clientReq.putHeader("Host", ElbV2TargetResolver.hostHeader(host, port));
|
||||
}
|
||||
clientReq.connect()
|
||||
.onSuccess(resp -> {
|
||||
req.response().setStatusCode(resp.statusCode());
|
||||
resp.headers().forEach(entry -> {
|
||||
if (!HOP_BY_HOP_HEADERS.contains(entry.getKey().toLowerCase())) {
|
||||
req.response().putHeader(entry.getKey(), entry.getValue());
|
||||
}
|
||||
});
|
||||
if (resp.statusCode() != 101) {
|
||||
req.resume();
|
||||
if (resp.getHeader("Content-Length") == null) {
|
||||
req.response().setChunked(true);
|
||||
}
|
||||
resp.pipeTo(req.response());
|
||||
return;
|
||||
}
|
||||
req.response().putHeader("Connection", "Upgrade");
|
||||
req.response().putHeader("Upgrade", resp.getHeader("Upgrade"));
|
||||
NetSocket targetSocket = resp.netSocket();
|
||||
req.toNetSocket()
|
||||
.onSuccess(clientSocket ->
|
||||
tunnel(clientSocket, targetSocket, idleTimeoutMillis))
|
||||
.onFailure(err -> {
|
||||
LOG.debugv("WebSocket upgrade to {0}:{1} lost the client: {2}",
|
||||
host, String.valueOf(port), err.getMessage());
|
||||
targetSocket.close();
|
||||
});
|
||||
})
|
||||
.onFailure(err -> {
|
||||
LOG.debugv("WebSocket upgrade to {0}:{1} failed: {2}",
|
||||
host, String.valueOf(port), err.getMessage());
|
||||
req.resume();
|
||||
if (req.response().headWritten()) {
|
||||
req.response().close();
|
||||
} else {
|
||||
req.response().setStatusCode(502).end("Bad gateway");
|
||||
}
|
||||
});
|
||||
})
|
||||
.onFailure(err -> {
|
||||
req.resume();
|
||||
req.response().setStatusCode(503).end("Service unavailable");
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Relays bytes both ways until either side closes or no data crosses the tunnel in either
|
||||
* direction for the load balancer's {@code idle_timeout.timeout_seconds}, as an ALB does.
|
||||
*/
|
||||
private void tunnel(NetSocket client, NetSocket target, long idleTimeoutMillis) {
|
||||
AtomicLong lastActivity = new AtomicLong(System.nanoTime());
|
||||
AtomicLong timerId = new AtomicLong(-1);
|
||||
AtomicBoolean closed = new AtomicBoolean();
|
||||
Runnable close = () -> {
|
||||
if (closed.compareAndSet(false, true)) {
|
||||
vertx.cancelTimer(timerId.get());
|
||||
client.close();
|
||||
target.close();
|
||||
}
|
||||
};
|
||||
relay(client, target, lastActivity, close);
|
||||
relay(target, client, lastActivity, close);
|
||||
scheduleIdleCheck(idleTimeoutMillis, idleTimeoutMillis, lastActivity, timerId, closed, close);
|
||||
}
|
||||
|
||||
private void scheduleIdleCheck(long delayMillis, long idleTimeoutMillis, AtomicLong lastActivity,
|
||||
AtomicLong timerId, AtomicBoolean closed, Runnable close) {
|
||||
if (closed.get()) {
|
||||
return;
|
||||
}
|
||||
timerId.set(vertx.setTimer(delayMillis, ignored -> {
|
||||
long idleMillis = (System.nanoTime() - lastActivity.get()) / 1_000_000;
|
||||
if (idleMillis >= idleTimeoutMillis) {
|
||||
close.run();
|
||||
} else {
|
||||
scheduleIdleCheck(idleTimeoutMillis - idleMillis, idleTimeoutMillis, lastActivity, timerId,
|
||||
closed, close);
|
||||
}
|
||||
}));
|
||||
}
|
||||
|
||||
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(io.vertx.core.http.HttpServerRequest req, Action action) {
|
||||
String reqHost = req.host();
|
||||
String reqPort = "";
|
||||
|
||||
@@ -47,6 +47,14 @@ final class ElbV2TargetResolver {
|
||||
return addresses[0].getHostAddress();
|
||||
}
|
||||
|
||||
/** The {@code Host} header value for a target, bracketing an IPv6 literal as RFC 3986 requires. */
|
||||
static String hostHeader(String host, int port) {
|
||||
if (host.indexOf(':') >= 0 && !host.startsWith("[")) {
|
||||
return "[" + host + "]:" + port;
|
||||
}
|
||||
return host + ":" + port;
|
||||
}
|
||||
|
||||
static boolean isIpLiteral(String host) {
|
||||
return host != null && (host.contains(":") || host.matches("[0-9.]+"));
|
||||
}
|
||||
|
||||
@@ -74,4 +74,12 @@ class ElbV2TargetResolverTest {
|
||||
assertTrue(ex.getMessage().contains("link-local or metadata address"), ex.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void hostHeaderBracketsIpv6Literals() {
|
||||
assertEquals("[2001:db8::1]:8080", ElbV2TargetResolver.hostHeader("2001:db8::1", 8080));
|
||||
assertEquals("[::1]:80", ElbV2TargetResolver.hostHeader("[::1]", 80));
|
||||
assertEquals("10.0.0.5:8080", ElbV2TargetResolver.hostHeader("10.0.0.5", 8080));
|
||||
assertEquals("backend.internal:443", ElbV2TargetResolver.hostHeader("backend.internal", 443));
|
||||
}
|
||||
}
|
||||
+373
@@ -0,0 +1,373 @@
|
||||
package io.github.hectorvent.floci.services.elbv2;
|
||||
|
||||
import io.github.hectorvent.floci.services.ec2.Ec2Service;
|
||||
import io.github.hectorvent.floci.services.ec2.model.Instance;
|
||||
import io.github.hectorvent.floci.testing.RealElbV2DataPlaneProfile;
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import io.quarkus.test.junit.TestProfile;
|
||||
import io.quarkus.test.junit.mockito.InjectSpy;
|
||||
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 java.time.Duration;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.ExecutionException;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
import static io.restassured.RestAssured.given;
|
||||
import static org.awaitility.Awaitility.await;
|
||||
import static org.hamcrest.Matchers.anyOf;
|
||||
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.ArgumentMatchers.anyString;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
import static org.mockito.Mockito.doReturn;
|
||||
|
||||
@QuarkusTest
|
||||
@TestProfile(RealElbV2DataPlaneProfile.class)
|
||||
class ElbV2WebSocketIntegrationTest {
|
||||
|
||||
private static final String AUTH =
|
||||
"AWS4-HMAC-SHA256 Credential=test/20260927/us-east-1/elasticloadbalancing/aws4_request";
|
||||
private static final int LISTENER_PORT = 7795;
|
||||
private static final String INSTANCE_ID = "i-0websocket0000001";
|
||||
|
||||
@Inject
|
||||
Vertx vertx;
|
||||
|
||||
@InjectSpy
|
||||
Ec2Service ec2Service;
|
||||
|
||||
private HttpServer backend;
|
||||
private HttpClient client;
|
||||
private String loadBalancerArn;
|
||||
private String targetGroupArn;
|
||||
private String listenerArn;
|
||||
|
||||
@BeforeEach
|
||||
void startBackend() throws Exception {
|
||||
backend = vertx.createHttpServer()
|
||||
.requestHandler(request -> {
|
||||
if (!"websocket".equalsIgnoreCase(request.getHeader("Upgrade"))) {
|
||||
request.response().setStatusCode(400).end("not an upgrade");
|
||||
} else if (!request.path().startsWith("/socket.io/")) {
|
||||
request.response().setStatusCode(404).end();
|
||||
} else {
|
||||
String query = request.query();
|
||||
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();
|
||||
targetGroupArn = createTargetGroup("websocket-tg", "ip", backend.actualPort());
|
||||
registerTarget(targetGroupArn, "127.0.0.1", backend.actualPort());
|
||||
listenerArn = createListener(loadBalancerArn, targetGroupArn);
|
||||
await().atMost(Duration.ofSeconds(3)).untilAsserted(() -> given()
|
||||
.baseUri("http://127.0.0.1")
|
||||
.port(LISTENER_PORT)
|
||||
.when()
|
||||
.get("/")
|
||||
.then()
|
||||
.statusCode(400));
|
||||
}
|
||||
|
||||
@AfterEach
|
||||
void stopBackend() 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 tunnelsWebSocketUpgradeToIpTarget() throws Exception {
|
||||
WebSocket socket = connect("/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();
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void tunnelsWebSocketUpgradeToInstanceTarget() throws Exception {
|
||||
Instance instance = new Instance();
|
||||
instance.setInstanceId(INSTANCE_ID);
|
||||
instance.setContainerBridgeIp("127.0.0.1");
|
||||
doReturn(instance).when(ec2Service).findInstanceById(anyString(), eq(INSTANCE_ID));
|
||||
String instanceTargetGroupArn = createTargetGroup("websocket-instance-tg", "instance", backend.actualPort());
|
||||
try {
|
||||
registerTarget(instanceTargetGroupArn, INSTANCE_ID, backend.actualPort());
|
||||
forwardDefaultActionTo(listenerArn, instanceTargetGroupArn);
|
||||
|
||||
WebSocket socket = connect("/socket.io/?transport=websocket");
|
||||
try {
|
||||
assertEquals("transport=websocket:hello", exchange(socket, "hello"));
|
||||
} finally {
|
||||
socket.close();
|
||||
}
|
||||
} finally {
|
||||
deleteListener(listenerArn);
|
||||
listenerArn = null;
|
||||
deleteTargetGroup(instanceTargetGroupArn);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void relaysTargetRejectionOfUpgrade() {
|
||||
ExecutionException failure = assertThrows(ExecutionException.class,
|
||||
() -> connect("/elsewhere/?transport=websocket"));
|
||||
|
||||
UpgradeRejectedException rejected = assertInstanceOf(UpgradeRejectedException.class, failure.getCause());
|
||||
assertEquals(404, rejected.getStatus());
|
||||
}
|
||||
|
||||
@Test
|
||||
void plainRequestStillReachesTargetWithoutUpgrade() {
|
||||
given()
|
||||
.baseUri("http://127.0.0.1")
|
||||
.port(LISTENER_PORT)
|
||||
.when()
|
||||
.get("/socket.io/?transport=polling")
|
||||
.then()
|
||||
.statusCode(400)
|
||||
.body(equalTo("not an upgrade"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void closesTunnelAfterLoadBalancerIdleTimeout() throws Exception {
|
||||
setIdleTimeout(loadBalancerArn, 1);
|
||||
WebSocket socket = connect("/socket.io/?transport=websocket");
|
||||
CompletableFuture<Void> closed = new CompletableFuture<>();
|
||||
socket.closeHandler(ignored -> closed.complete(null));
|
||||
|
||||
assertEquals("transport=websocket:ping", exchange(socket, "ping"));
|
||||
|
||||
closed.get(5, TimeUnit.SECONDS);
|
||||
}
|
||||
|
||||
@Test
|
||||
void rejectsUpgradeToLambdaTargetWith400() throws Exception {
|
||||
String functionArn = createFunction("alb-websocket-fn");
|
||||
String lambdaTargetGroupArn = null;
|
||||
try {
|
||||
lambdaTargetGroupArn = createLambdaTargetGroup(functionArn);
|
||||
forwardDefaultActionTo(listenerArn, lambdaTargetGroupArn);
|
||||
|
||||
ExecutionException failure = assertThrows(ExecutionException.class,
|
||||
() -> connect("/socket.io/?transport=websocket"));
|
||||
|
||||
UpgradeRejectedException rejected = assertInstanceOf(UpgradeRejectedException.class, failure.getCause());
|
||||
assertEquals(400, rejected.getStatus());
|
||||
} finally {
|
||||
deleteListener(listenerArn);
|
||||
listenerArn = null;
|
||||
deleteTargetGroup(lambdaTargetGroupArn);
|
||||
given().when().delete("/2015-03-31/functions/alb-websocket-fn").then()
|
||||
.statusCode(anyOf(equalTo(200), equalTo(204)));
|
||||
}
|
||||
}
|
||||
|
||||
private static String createFunction(String name) {
|
||||
return given()
|
||||
.contentType("application/json")
|
||||
.body("""
|
||||
{
|
||||
"FunctionName": "%s",
|
||||
"Runtime": "nodejs20.x",
|
||||
"Role": "arn:aws:iam::000000000000:role/lambda-role",
|
||||
"Handler": "index.handler"
|
||||
}
|
||||
""".formatted(name))
|
||||
.when()
|
||||
.post("/2015-03-31/functions")
|
||||
.then()
|
||||
.statusCode(201)
|
||||
.extract()
|
||||
.path("FunctionArn");
|
||||
}
|
||||
|
||||
private static String createLambdaTargetGroup(String functionArn) {
|
||||
String targetGroupArn = given()
|
||||
.formParam("Action", "CreateTargetGroup")
|
||||
.formParam("Name", "websocket-lambda-tg")
|
||||
.formParam("TargetType", "lambda")
|
||||
.header("Authorization", AUTH)
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.extract()
|
||||
.path("CreateTargetGroupResponse.CreateTargetGroupResult.TargetGroups.member.TargetGroupArn");
|
||||
given()
|
||||
.formParam("Action", "RegisterTargets")
|
||||
.formParam("TargetGroupArn", targetGroupArn)
|
||||
.formParam("Targets.member.1.Id", functionArn)
|
||||
.header("Authorization", AUTH)
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200);
|
||||
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")
|
||||
.setPort(LISTENER_PORT)
|
||||
.setURI(uri))
|
||||
.toCompletionStage()
|
||||
.toCompletableFuture()
|
||||
.get(5, TimeUnit.SECONDS);
|
||||
}
|
||||
|
||||
private static String exchange(WebSocket socket, String text) throws Exception {
|
||||
CompletableFuture<String> 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")
|
||||
.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")
|
||||
.formParam("LoadBalancerArn", loadBalancerArn)
|
||||
.formParam("Attributes.member.1.Key", "idle_timeout.timeout_seconds")
|
||||
.formParam("Attributes.member.1.Value", String.valueOf(seconds))
|
||||
.header("Authorization", AUTH)
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.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)));
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user