diff --git a/compatibility-tests/sdk-test-java/pom.xml b/compatibility-tests/sdk-test-java/pom.xml
index 087f7378fe..fab2edc598 100644
--- a/compatibility-tests/sdk-test-java/pom.xml
+++ b/compatibility-tests/sdk-test-java/pom.xml
@@ -90,6 +90,10 @@
software.amazon.awssdk
apigatewayv2
+
+ software.amazon.awssdk
+ apigatewaymanagementapi
+
software.amazon.awssdk
kms
diff --git a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/ApiGatewayV2WebSocketDataPlaneTest.java b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/ApiGatewayV2WebSocketDataPlaneTest.java
new file mode 100644
index 0000000000..39247838ba
--- /dev/null
+++ b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/ApiGatewayV2WebSocketDataPlaneTest.java
@@ -0,0 +1,787 @@
+package com.floci.test;
+
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import org.junit.jupiter.api.AfterAll;
+import org.junit.jupiter.api.Assumptions;
+import org.junit.jupiter.api.BeforeAll;
+import org.junit.jupiter.api.DisplayName;
+import org.junit.jupiter.api.MethodOrderer;
+import org.junit.jupiter.api.Nested;
+import org.junit.jupiter.api.Order;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.TestMethodOrder;
+import software.amazon.awssdk.core.SdkBytes;
+import software.amazon.awssdk.services.apigatewaymanagementapi.ApiGatewayManagementApiClient;
+import software.amazon.awssdk.services.apigatewaymanagementapi.model.GetConnectionRequest;
+import software.amazon.awssdk.services.apigatewaymanagementapi.model.GetConnectionResponse;
+import software.amazon.awssdk.services.apigatewaymanagementapi.model.GoneException;
+import software.amazon.awssdk.services.apigatewaymanagementapi.model.PostToConnectionRequest;
+import software.amazon.awssdk.services.apigatewaymanagementapi.model.DeleteConnectionRequest;
+import software.amazon.awssdk.services.apigatewayv2.ApiGatewayV2Client;
+import software.amazon.awssdk.services.apigatewayv2.model.*;
+import software.amazon.awssdk.services.lambda.LambdaClient;
+import software.amazon.awssdk.services.lambda.model.CreateFunctionRequest;
+import software.amazon.awssdk.services.lambda.model.DeleteFunctionRequest;
+import software.amazon.awssdk.services.lambda.model.FunctionCode;
+import software.amazon.awssdk.services.lambda.model.Runtime;
+
+import java.io.ByteArrayOutputStream;
+import java.net.URI;
+import java.net.http.HttpClient;
+import java.net.http.WebSocket;
+import java.nio.charset.StandardCharsets;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Map;
+import java.util.concurrent.CompletableFuture;
+import java.util.concurrent.CompletionStage;
+import java.util.concurrent.LinkedBlockingQueue;
+import java.util.concurrent.TimeUnit;
+import java.util.zip.ZipEntry;
+import java.util.zip.ZipOutputStream;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThatThrownBy;
+
+/**
+ * WebSocket data-plane end-to-end compatibility tests using the AWS SDK v2 Java client.
+ *
+ * Mirrors the Node.js compatibility tests in
+ * {@code compatibility-tests/sdk-test-node/tests/apigatewayv2-websocket-dataplane.test.ts}.
+ *
+ * Covers 8 test suites:
+ * 1. Basic WebSocket flow — connect, send, receive, disconnect
+ * 2. Chat-style broadcast — two clients, Lambda uses @connections API to broadcast
+ * 3. $connect authorization — Lambda authorizer allows/denies based on query string token
+ * 4. Route selection — multiple routes dispatched correctly
+ * 5. @connections API — POST sends message, GET returns info, DELETE disconnects
+ * 6. Stage variables — integration URI with ${stageVariables.functionName} resolves
+ * 7. Mock integration — $connect with MOCK integration, no Lambda needed
+ * 8. Disconnect cleanup — after disconnect, @connections POST returns 410
+ */
+@DisplayName("API Gateway v2 — WebSocket data-plane")
+@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
+class ApiGatewayV2WebSocketDataPlaneTest {
+
+ private static final ObjectMapper JSON = new ObjectMapper();
+ private static final String ROLE = "arn:aws:iam::000000000000:role/lambda-role";
+ private static final String STAGE = "test";
+
+ private static ApiGatewayV2Client gw;
+ private static LambdaClient lambda;
+ private static HttpClient http;
+
+ private static final List createdApis = new ArrayList<>();
+ private static final List createdFunctions = new ArrayList<>();
+
+ private static boolean lambdaAvailable;
+
+ // ── Lambda handler source code ───────────────────────────────────────────
+
+ private static final String ECHO_HANDLER = """
+ exports.handler = async (event) => {
+ const body = event.body || '';
+ try {
+ const parsed = JSON.parse(body);
+ if (parsed.action === 'getConnectionId') {
+ return { statusCode: 200, body: JSON.stringify({ connectionId: event.requestContext.connectionId }) };
+ }
+ } catch (e) {}
+ return { statusCode: 200, body: body || 'echo' };
+ };
+ """;
+
+ private static final String BROADCAST_HANDLER = """
+ const http = require('http');
+ exports.handler = async (event) => {
+ const body = JSON.parse(event.body);
+ const apiId = event.requestContext.apiId;
+ const stage = event.requestContext.stage;
+ const endpoint = new URL(process.env.FLOCI_ENDPOINT || 'http://host.docker.internal:4566');
+ const promises = body.targets.map(connId => {
+ return new Promise((resolve, reject) => {
+ const postData = body.message;
+ const options = {
+ hostname: endpoint.hostname,
+ port: endpoint.port || 80,
+ path: '/execute-api/' + apiId + '/' + stage + '/@connections/' + encodeURIComponent(connId),
+ method: 'POST',
+ headers: { 'Content-Type': 'application/octet-stream', 'Content-Length': Buffer.byteLength(postData) },
+ };
+ const req = http.request(options, (res) => {
+ let data = '';
+ res.on('data', chunk => data += chunk);
+ res.on('end', () => resolve({ statusCode: res.statusCode, body: data }));
+ });
+ req.on('error', reject);
+ req.write(postData);
+ req.end();
+ });
+ });
+ await Promise.all(promises);
+ return { statusCode: 200 };
+ };
+ """;
+
+ private static final String AUTHORIZER_HANDLER = """
+ exports.handler = async (event) => {
+ const token = event.queryStringParameters && event.queryStringParameters.token;
+ const effect = token === 'allow' ? 'Allow' : 'Deny';
+ return {
+ principalId: 'user',
+ policyDocument: {
+ Version: '2012-10-17',
+ Statement: [{ Action: 'execute-api:Invoke', Effect: effect, Resource: event.methodArn || '*' }],
+ },
+ };
+ };
+ """;
+
+ private static final String PING_HANDLER = """
+ exports.handler = async (event) => {
+ return { statusCode: 200, body: 'pong' };
+ };
+ """;
+
+ private static final String SEND_MESSAGE_HANDLER = """
+ exports.handler = async (event) => {
+ const body = JSON.parse(event.body);
+ return { statusCode: 200, body: 'received: ' + body.data };
+ };
+ """;
+
+ private static final String DEFAULT_HANDLER = """
+ exports.handler = async (event) => {
+ return { statusCode: 200, body: 'default-route' };
+ };
+ """;
+
+ // ── Setup / Teardown ─────────────────────────────────────────────────────
+
+ @BeforeAll
+ static void setup() {
+ gw = TestFixtures.apiGatewayV2Client();
+ lambda = TestFixtures.lambdaClient();
+ http = HttpClient.newHttpClient();
+ lambdaAvailable = TestFixtures.isLambdaDispatchAvailable();
+ }
+
+ @AfterAll
+ static void cleanup() {
+ for (String apiId : createdApis) {
+ try { gw.deleteApi(DeleteApiRequest.builder().apiId(apiId).build()); } catch (Exception ignored) {}
+ }
+ for (String fn : createdFunctions) {
+ try { lambda.deleteFunction(DeleteFunctionRequest.builder().functionName(fn).build()); } catch (Exception ignored) {}
+ }
+ if (gw != null) gw.close();
+ if (lambda != null) lambda.close();
+ }
+
+ // ── Helpers ──────────────────────────────────────────────────────────────
+
+ private static String createLambda(String prefix, String code) {
+ return createLambda(prefix, code, null);
+ }
+
+ private static String createLambda(String prefix, String code, Map environment) {
+ String fnName = TestFixtures.uniqueName(prefix);
+ var builder = CreateFunctionRequest.builder()
+ .functionName(fnName)
+ .runtime(Runtime.NODEJS20_X)
+ .role(ROLE)
+ .handler("index.handler")
+ .timeout(30)
+ .code(FunctionCode.builder()
+ .zipFile(SdkBytes.fromByteArray(createZip(code)))
+ .build());
+ if (environment != null && !environment.isEmpty()) {
+ builder.environment(e -> e.variables(environment));
+ }
+ lambda.createFunction(builder.build());
+ createdFunctions.add(fnName);
+ return fnName;
+ }
+
+ private static String createWsApi(String prefix) {
+ var res = gw.createApi(CreateApiRequest.builder()
+ .name(TestFixtures.uniqueName(prefix))
+ .protocolType(ProtocolType.WEBSOCKET)
+ .routeSelectionExpression("$request.body.action")
+ .build());
+ createdApis.add(res.apiId());
+ return res.apiId();
+ }
+
+ private static String createLambdaIntegration(String apiId, String fnName) {
+ var res = gw.createIntegration(CreateIntegrationRequest.builder()
+ .apiId(apiId)
+ .integrationType(IntegrationType.AWS_PROXY)
+ .integrationUri("arn:aws:lambda:us-east-1:000000000000:function:" + fnName)
+ .build());
+ return res.integrationId();
+ }
+
+ private static void setupStage(String apiId, Map stageVariables) {
+ var deploy = gw.createDeployment(CreateDeploymentRequest.builder().apiId(apiId).build());
+ var req = CreateStageRequest.builder()
+ .apiId(apiId)
+ .stageName(STAGE)
+ .deploymentId(deploy.deploymentId());
+ if (stageVariables != null && !stageVariables.isEmpty()) {
+ req.stageVariables(stageVariables);
+ }
+ gw.createStage(req.build());
+ }
+
+ private static void setupStage(String apiId) {
+ setupStage(apiId, null);
+ }
+
+ private static String wsUrl(String apiId) {
+ URI endpoint = TestFixtures.endpoint();
+ String host = endpoint.getHost();
+ int port = endpoint.getPort();
+ return "ws://" + host + ":" + port + "/ws/" + apiId + "/" + STAGE;
+ }
+
+ private static ApiGatewayManagementApiClient managementClient(String apiId) {
+ URI mgmtEndpoint = URI.create(TestFixtures.endpoint() + "/execute-api/" + apiId + "/" + STAGE);
+ return ApiGatewayManagementApiClient.builder()
+ .endpointOverride(mgmtEndpoint)
+ .region(software.amazon.awssdk.regions.Region.US_EAST_1)
+ .credentialsProvider(software.amazon.awssdk.auth.credentials.StaticCredentialsProvider.create(
+ software.amazon.awssdk.auth.credentials.AwsBasicCredentials.create("test", "test")))
+ .build();
+ }
+
+ private static WebSocket connectWebSocket(String url, MultiMessageCapture capture) throws Exception {
+ return http.newWebSocketBuilder()
+ .buildAsync(URI.create(url), capture)
+ .get(60, TimeUnit.SECONDS);
+ }
+
+ private static String getConnectionId(WebSocket ws, MultiMessageCapture capture) throws Exception {
+ ws.sendText("{\"action\":\"getConnectionId\"}", true).join();
+ String response = capture.getNextMessage(15, TimeUnit.SECONDS);
+ if (response == null) return null;
+ JsonNode node = JSON.readTree(response);
+ return node.has("connectionId") ? node.get("connectionId").asText() : null;
+ }
+
+ private static byte[] createZip(String code) {
+ try {
+ ByteArrayOutputStream baos = new ByteArrayOutputStream();
+ try (ZipOutputStream zos = new ZipOutputStream(baos)) {
+ zos.putNextEntry(new ZipEntry("index.js"));
+ zos.write(code.getBytes(StandardCharsets.UTF_8));
+ zos.closeEntry();
+ }
+ return baos.toByteArray();
+ } catch (Exception e) {
+ throw new RuntimeException("Failed to build ZIP", e);
+ }
+ }
+
+ // ──────────────────────────── 1. Basic WebSocket flow ────────────────────────────
+
+ @Test @Order(1)
+ @DisplayName("1. Basic WebSocket flow — connect, send, receive, disconnect")
+ void basicWebSocketFlow() throws Exception {
+ Assumptions.assumeTrue(lambdaAvailable, "Lambda dispatch required");
+
+ String echoFn = createLambda("basic-echo", ECHO_HANDLER);
+ String apiId = createWsApi("basic-flow");
+ String integId = createLambdaIntegration(apiId, echoFn);
+
+ gw.createRoute(CreateRouteRequest.builder()
+ .apiId(apiId).routeKey("$connect")
+ .target("integrations/" + integId).build());
+ gw.createRoute(CreateRouteRequest.builder()
+ .apiId(apiId).routeKey("$default")
+ .target("integrations/" + integId)
+ .routeResponseSelectionExpression("$default").build());
+ setupStage(apiId);
+
+ MultiMessageCapture capture = new MultiMessageCapture();
+ WebSocket ws = connectWebSocket(wsUrl(apiId), capture);
+ assertThat(ws).isNotNull();
+
+ ws.sendText("{\"action\":\"test\",\"body\":\"hello\"}", true).join();
+ String response = capture.getNextMessage(15, TimeUnit.SECONDS);
+ assertThat(response).isNotNull();
+
+ ws.sendClose(WebSocket.NORMAL_CLOSURE, "done").join();
+ Thread.sleep(500);
+ }
+
+ // ──────────────────────────── 2. Chat-style broadcast ────────────────────────────
+
+ @Test @Order(2)
+ @DisplayName("2. Chat-style broadcast — Lambda uses @connections to broadcast to multiple clients")
+ void chatStyleBroadcast() throws Exception {
+ Assumptions.assumeTrue(lambdaAvailable, "Lambda dispatch required");
+
+ String broadcastFn = createLambda("broadcast", BROADCAST_HANDLER,
+ Map.of("FLOCI_ENDPOINT", "http://host.docker.internal:4566"));
+ String echoFn = createLambda("bc-echo", ECHO_HANDLER);
+ String apiId = createWsApi("broadcast");
+
+ String broadcastIntegId = createLambdaIntegration(apiId, broadcastFn);
+ String echoIntegId = createLambdaIntegration(apiId, echoFn);
+
+ gw.createRoute(CreateRouteRequest.builder()
+ .apiId(apiId).routeKey("$connect")
+ .target("integrations/" + echoIntegId).build());
+ gw.createRoute(CreateRouteRequest.builder()
+ .apiId(apiId).routeKey("$default")
+ .target("integrations/" + echoIntegId)
+ .routeResponseSelectionExpression("$default").build());
+ gw.createRoute(CreateRouteRequest.builder()
+ .apiId(apiId).routeKey("broadcast")
+ .target("integrations/" + broadcastIntegId)
+ .routeResponseSelectionExpression("$default").build());
+ setupStage(apiId);
+
+ MultiMessageCapture capture1 = new MultiMessageCapture();
+ MultiMessageCapture capture2 = new MultiMessageCapture();
+ WebSocket ws1 = connectWebSocket(wsUrl(apiId), capture1);
+ WebSocket ws2 = connectWebSocket(wsUrl(apiId), capture2);
+ Thread.sleep(300);
+
+ String connId1 = getConnectionId(ws1, capture1);
+ String connId2 = getConnectionId(ws2, capture2);
+ assertThat(connId1).isNotNull();
+ assertThat(connId2).isNotNull();
+
+ // Send broadcast action
+ ws1.sendText("{\"action\":\"broadcast\",\"targets\":[\"%s\",\"%s\"],\"message\":\"hello-all\"}"
+ .formatted(connId1, connId2), true).join();
+
+ String msg1 = capture1.getNextMessage(15, TimeUnit.SECONDS);
+ String msg2 = capture2.getNextMessage(15, TimeUnit.SECONDS);
+ assertThat(msg1).isEqualTo("hello-all");
+ assertThat(msg2).isEqualTo("hello-all");
+
+ ws1.sendClose(WebSocket.NORMAL_CLOSURE, "done").join();
+ ws2.sendClose(WebSocket.NORMAL_CLOSURE, "done").join();
+ Thread.sleep(500);
+ }
+
+ // ──────────────────────────── 3. $connect authorization ────────────────────────────
+
+ @Test @Order(3)
+ @DisplayName("3. $connect authorization — allows with valid token, denies with invalid")
+ void connectAuthorization() throws Exception {
+ Assumptions.assumeTrue(lambdaAvailable, "Lambda dispatch required");
+
+ String authFn = createLambda("authorizer", AUTHORIZER_HANDLER);
+ String echoFn = createLambda("auth-echo", ECHO_HANDLER);
+ String apiId = createWsApi("auth-test");
+
+ String echoIntegId = createLambdaIntegration(apiId, echoFn);
+
+ var authRes = gw.createAuthorizer(CreateAuthorizerRequest.builder()
+ .apiId(apiId)
+ .authorizerType(AuthorizerType.REQUEST)
+ .name("ws-auth")
+ .authorizerUri("arn:aws:lambda:us-east-1:000000000000:function:" + authFn)
+ .identitySource("route.request.querystring.token")
+ .build());
+
+ gw.createRoute(CreateRouteRequest.builder()
+ .apiId(apiId).routeKey("$connect")
+ .target("integrations/" + echoIntegId)
+ .authorizationType("CUSTOM")
+ .authorizerId(authRes.authorizerId()).build());
+ gw.createRoute(CreateRouteRequest.builder()
+ .apiId(apiId).routeKey("$default")
+ .target("integrations/" + echoIntegId).build());
+ setupStage(apiId);
+
+ // Should allow with valid token
+ MultiMessageCapture allowCapture = new MultiMessageCapture();
+ WebSocket wsAllow = connectWebSocket(wsUrl(apiId) + "?token=allow", allowCapture);
+ assertThat(wsAllow).isNotNull();
+ wsAllow.sendClose(WebSocket.NORMAL_CLOSURE, "done").join();
+
+ // Should deny with invalid token
+ MultiMessageCapture denyCapture = new MultiMessageCapture();
+ CompletableFuture denyFuture = http.newWebSocketBuilder()
+ .buildAsync(URI.create(wsUrl(apiId) + "?token=deny"), denyCapture);
+ assertThatThrownBy(() -> denyFuture.get(15, TimeUnit.SECONDS))
+ .hasMessageContaining("WebSocket");
+
+ Thread.sleep(500);
+ }
+
+ // ──────────────────────────── 4. Route selection ────────────────────────────
+
+ @Test @Order(4)
+ @DisplayName("4. Route selection — ping, sendMessage, $default dispatched correctly")
+ void routeSelection() throws Exception {
+ Assumptions.assumeTrue(lambdaAvailable, "Lambda dispatch required");
+
+ String pingFn = createLambda("ping", PING_HANDLER);
+ String sendMsgFn = createLambda("sendmsg", SEND_MESSAGE_HANDLER);
+ String defaultFn = createLambda("default", DEFAULT_HANDLER);
+ String echoFn = createLambda("rs-echo", ECHO_HANDLER);
+ String apiId = createWsApi("route-sel");
+
+ String pingIntegId = createLambdaIntegration(apiId, pingFn);
+ String sendMsgIntegId = createLambdaIntegration(apiId, sendMsgFn);
+ String defaultIntegId = createLambdaIntegration(apiId, defaultFn);
+ String echoIntegId = createLambdaIntegration(apiId, echoFn);
+
+ gw.createRoute(CreateRouteRequest.builder()
+ .apiId(apiId).routeKey("$connect")
+ .target("integrations/" + echoIntegId).build());
+ gw.createRoute(CreateRouteRequest.builder()
+ .apiId(apiId).routeKey("ping")
+ .target("integrations/" + pingIntegId)
+ .routeResponseSelectionExpression("$default").build());
+ gw.createRoute(CreateRouteRequest.builder()
+ .apiId(apiId).routeKey("sendMessage")
+ .target("integrations/" + sendMsgIntegId)
+ .routeResponseSelectionExpression("$default").build());
+ gw.createRoute(CreateRouteRequest.builder()
+ .apiId(apiId).routeKey("$default")
+ .target("integrations/" + defaultIntegId)
+ .routeResponseSelectionExpression("$default").build());
+ setupStage(apiId);
+
+ // Test ping route
+ MultiMessageCapture pingCapture = new MultiMessageCapture();
+ WebSocket wsPing = connectWebSocket(wsUrl(apiId), pingCapture);
+ wsPing.sendText("{\"action\":\"ping\"}", true).join();
+ assertThat(pingCapture.getNextMessage(15, TimeUnit.SECONDS)).isEqualTo("pong");
+
+ // Test sendMessage route
+ wsPing.sendText("{\"action\":\"sendMessage\",\"data\":\"test-data\"}", true).join();
+ assertThat(pingCapture.getNextMessage(15, TimeUnit.SECONDS)).isEqualTo("received: test-data");
+
+ // Test $default route (unknown action)
+ wsPing.sendText("{\"action\":\"unknownAction\"}", true).join();
+ assertThat(pingCapture.getNextMessage(15, TimeUnit.SECONDS)).isEqualTo("default-route");
+
+ wsPing.sendClose(WebSocket.NORMAL_CLOSURE, "done").join();
+ Thread.sleep(500);
+ }
+
+ // ──────────────────────────── 5. @connections API ────────────────────────────
+
+ @Test @Order(5)
+ @DisplayName("5. @connections API — POST sends message, GET returns info, DELETE disconnects")
+ void connectionsApi() throws Exception {
+ Assumptions.assumeTrue(lambdaAvailable, "Lambda dispatch required");
+
+ String echoFn = createLambda("conn-echo", ECHO_HANDLER);
+ String apiId = createWsApi("connections-api");
+ String integId = createLambdaIntegration(apiId, echoFn);
+
+ gw.createRoute(CreateRouteRequest.builder()
+ .apiId(apiId).routeKey("$connect")
+ .target("integrations/" + integId).build());
+ gw.createRoute(CreateRouteRequest.builder()
+ .apiId(apiId).routeKey("$default")
+ .target("integrations/" + integId)
+ .routeResponseSelectionExpression("$default").build());
+ setupStage(apiId);
+
+ ApiGatewayManagementApiClient mgmt = managementClient(apiId);
+
+ // POST sends message to connection
+ MultiMessageCapture capture = new MultiMessageCapture();
+ WebSocket ws = connectWebSocket(wsUrl(apiId), capture);
+ Thread.sleep(300);
+ String connId = getConnectionId(ws, capture);
+ assertThat(connId).isNotNull();
+
+ MultiMessageCapture pushCapture = new MultiMessageCapture();
+ WebSocket ws2 = connectWebSocket(wsUrl(apiId), pushCapture);
+ Thread.sleep(300);
+ String connId2 = getConnectionId(ws2, pushCapture);
+ assertThat(connId2).isNotNull();
+
+ mgmt.postToConnection(PostToConnectionRequest.builder()
+ .connectionId(connId2)
+ .data(SdkBytes.fromUtf8String("server-push"))
+ .build());
+ String pushed = pushCapture.getNextMessage(15, TimeUnit.SECONDS);
+ assertThat(pushed).isEqualTo("server-push");
+
+ // GET returns connection info
+ GetConnectionResponse info = mgmt.getConnection(GetConnectionRequest.builder()
+ .connectionId(connId2).build());
+ assertThat(info.connectedAt()).isNotNull();
+
+ // DELETE disconnects the client
+ CompletableFuture closeFuture = new CompletableFuture<>();
+ pushCapture.setCloseFuture(closeFuture);
+ mgmt.deleteConnection(DeleteConnectionRequest.builder()
+ .connectionId(connId2).build());
+ Integer closeCode = closeFuture.get(15, TimeUnit.SECONDS);
+ assertThat(closeCode).isNotNull();
+
+ ws.sendClose(WebSocket.NORMAL_CLOSURE, "done").join();
+ Thread.sleep(500);
+ mgmt.close();
+ }
+
+ // ──────────────────────────── 6. Stage variables ────────────────────────────
+
+ @Test @Order(6)
+ @DisplayName("6. Stage variables — integration URI with ${stageVariables.functionName} resolves")
+ void stageVariables() throws Exception {
+ Assumptions.assumeTrue(lambdaAvailable, "Lambda dispatch required");
+
+ String echoFn = createLambda("sv-echo", ECHO_HANDLER);
+ String apiId = createWsApi("stage-vars");
+
+ // Integration with stage variable reference in URI
+ var integRes = gw.createIntegration(CreateIntegrationRequest.builder()
+ .apiId(apiId)
+ .integrationType(IntegrationType.AWS_PROXY)
+ .integrationUri("arn:aws:lambda:us-east-1:000000000000:function:${stageVariables.functionName}")
+ .build());
+ String integId = integRes.integrationId();
+
+ gw.createRoute(CreateRouteRequest.builder()
+ .apiId(apiId).routeKey("$connect")
+ .target("integrations/" + integId).build());
+ gw.createRoute(CreateRouteRequest.builder()
+ .apiId(apiId).routeKey("$default")
+ .target("integrations/" + integId)
+ .routeResponseSelectionExpression("$default").build());
+ setupStage(apiId, Map.of("functionName", echoFn));
+
+ MultiMessageCapture capture = new MultiMessageCapture();
+ WebSocket ws = connectWebSocket(wsUrl(apiId), capture);
+ assertThat(ws).isNotNull();
+
+ ws.sendText("{\"action\":\"test\",\"body\":\"stage-var-test\"}", true).join();
+ String response = capture.getNextMessage(15, TimeUnit.SECONDS);
+ assertThat(response).isNotNull();
+
+ ws.sendClose(WebSocket.NORMAL_CLOSURE, "done").join();
+ Thread.sleep(500);
+ }
+
+ // ──────────────────────────── 7. Mock integration ────────────────────────────
+
+ @Test @Order(7)
+ @DisplayName("7. Mock integration — $connect with MOCK integration, no Lambda needed")
+ void mockIntegration() throws Exception {
+ Assumptions.assumeTrue(lambdaAvailable, "Lambda dispatch required for $default route");
+
+ String apiId = createWsApi("mock-integ");
+
+ // MOCK integration for $connect — no Lambda needed
+ var mockIntegRes = gw.createIntegration(CreateIntegrationRequest.builder()
+ .apiId(apiId)
+ .integrationType(IntegrationType.MOCK)
+ .build());
+ String mockIntegId = mockIntegRes.integrationId();
+
+ gw.createRoute(CreateRouteRequest.builder()
+ .apiId(apiId).routeKey("$connect")
+ .target("integrations/" + mockIntegId).build());
+
+ // $default still needs a Lambda for message handling
+ String echoFn = createLambda("mock-echo", ECHO_HANDLER);
+ String echoIntegId = createLambdaIntegration(apiId, echoFn);
+ gw.createRoute(CreateRouteRequest.builder()
+ .apiId(apiId).routeKey("$default")
+ .target("integrations/" + echoIntegId)
+ .routeResponseSelectionExpression("$default").build());
+ setupStage(apiId);
+
+ MultiMessageCapture capture = new MultiMessageCapture();
+ WebSocket ws = connectWebSocket(wsUrl(apiId), capture);
+ assertThat(ws).isNotNull();
+
+ ws.sendText("{\"action\":\"test\"}", true).join();
+ String response = capture.getNextMessage(15, TimeUnit.SECONDS);
+ assertThat(response).isNotNull();
+
+ ws.sendClose(WebSocket.NORMAL_CLOSURE, "done").join();
+ Thread.sleep(500);
+ }
+
+ // ──────────────────────────── 8. Disconnect cleanup ────────────────────────────
+
+ @Test @Order(8)
+ @DisplayName("8. Disconnect cleanup — after disconnect, @connections POST returns 410")
+ void disconnectCleanup() throws Exception {
+ Assumptions.assumeTrue(lambdaAvailable, "Lambda dispatch required");
+
+ String echoFn = createLambda("dc-echo", ECHO_HANDLER);
+ String apiId = createWsApi("disconnect");
+ String integId = createLambdaIntegration(apiId, echoFn);
+
+ gw.createRoute(CreateRouteRequest.builder()
+ .apiId(apiId).routeKey("$connect")
+ .target("integrations/" + integId).build());
+ gw.createRoute(CreateRouteRequest.builder()
+ .apiId(apiId).routeKey("$default")
+ .target("integrations/" + integId)
+ .routeResponseSelectionExpression("$default").build());
+ setupStage(apiId);
+
+ MultiMessageCapture capture = new MultiMessageCapture();
+ WebSocket ws = connectWebSocket(wsUrl(apiId), capture);
+ Thread.sleep(300);
+ String connId = getConnectionId(ws, capture);
+ assertThat(connId).isNotNull();
+
+ // Disconnect
+ ws.sendClose(WebSocket.NORMAL_CLOSURE, "done").join();
+ Thread.sleep(500);
+
+ // POST to disconnected connection should return 410
+ ApiGatewayManagementApiClient mgmt = managementClient(apiId);
+ assertThatThrownBy(() -> mgmt.postToConnection(PostToConnectionRequest.builder()
+ .connectionId(connId)
+ .data(SdkBytes.fromUtf8String("should-fail"))
+ .build()))
+ .isInstanceOf(GoneException.class);
+
+ mgmt.close();
+ }
+
+ // ──────────────────────────── 9. Payload size limit ────────────────────────────
+
+ @Test @Order(9)
+ @DisplayName("9. Payload size limit — messages exceeding 128 KB receive error frame")
+ void payloadSizeLimit() throws Exception {
+ Assumptions.assumeTrue(lambdaAvailable, "Lambda dispatch required");
+
+ String echoFn = createLambda("pl-echo", ECHO_HANDLER);
+ String apiId = createWsApi("payload-limit");
+ String integId = createLambdaIntegration(apiId, echoFn);
+
+ gw.createRoute(CreateRouteRequest.builder()
+ .apiId(apiId).routeKey("$connect")
+ .target("integrations/" + integId).build());
+ gw.createRoute(CreateRouteRequest.builder()
+ .apiId(apiId).routeKey("$default")
+ .target("integrations/" + integId)
+ .routeResponseSelectionExpression("$default").build());
+ setupStage(apiId);
+
+ MultiMessageCapture capture = new MultiMessageCapture();
+ WebSocket ws = connectWebSocket(wsUrl(apiId), capture);
+ assertThat(ws).isNotNull();
+
+ // Send a message larger than 128 KB
+ String oversizeMessage = "x".repeat(128 * 1024 + 1);
+ ws.sendText(oversizeMessage, true).join();
+ String response = capture.getNextMessage(15, TimeUnit.SECONDS);
+ assertThat(response).isNotNull();
+ assertThat(response).contains("Message too long");
+
+ // Verify connection is still alive after rejection
+ ws.sendText("{\"action\":\"test\",\"body\":\"after-oversize\"}", true).join();
+ String normalResponse = capture.getNextMessage(15, TimeUnit.SECONDS);
+ assertThat(normalResponse).isNotNull();
+
+ ws.sendClose(WebSocket.NORMAL_CLOSURE, "done").join();
+ Thread.sleep(500);
+ }
+
+ // ──────────────────────────── 10. Server-initiated close via @connections DELETE ────────────────────────────
+
+ @Test @Order(10)
+ @DisplayName("10. Server-initiated close — DELETE disconnects and subsequent POST returns 410")
+ void serverInitiatedClose() throws Exception {
+ Assumptions.assumeTrue(lambdaAvailable, "Lambda dispatch required");
+
+ String echoFn = createLambda("sc-echo", ECHO_HANDLER);
+ String apiId = createWsApi("server-close");
+ String integId = createLambdaIntegration(apiId, echoFn);
+
+ gw.createRoute(CreateRouteRequest.builder()
+ .apiId(apiId).routeKey("$connect")
+ .target("integrations/" + integId).build());
+ gw.createRoute(CreateRouteRequest.builder()
+ .apiId(apiId).routeKey("$default")
+ .target("integrations/" + integId)
+ .routeResponseSelectionExpression("$default").build());
+ setupStage(apiId);
+
+ MultiMessageCapture capture = new MultiMessageCapture();
+ CompletableFuture closeFuture = new CompletableFuture<>();
+ capture.setCloseFuture(closeFuture);
+ WebSocket ws = connectWebSocket(wsUrl(apiId), capture);
+ Thread.sleep(300);
+ String connId = getConnectionId(ws, capture);
+ assertThat(connId).isNotNull();
+
+ // DELETE the connection via @connections API
+ ApiGatewayManagementApiClient mgmt = managementClient(apiId);
+ mgmt.deleteConnection(DeleteConnectionRequest.builder()
+ .connectionId(connId).build());
+
+ // Wait for the WebSocket to close
+ Integer closeCode = closeFuture.get(15, TimeUnit.SECONDS);
+ assertThat(closeCode).isNotNull();
+ Thread.sleep(500);
+
+ // POST to the deleted connection should return 410
+ assertThatThrownBy(() -> mgmt.postToConnection(PostToConnectionRequest.builder()
+ .connectionId(connId)
+ .data(SdkBytes.fromUtf8String("should-fail"))
+ .build()))
+ .isInstanceOf(GoneException.class);
+
+ mgmt.close();
+ }
+
+ // ── WebSocket message capture listener ───────────────────────────────────
+
+ private static class MultiMessageCapture implements WebSocket.Listener {
+ private final LinkedBlockingQueue messages = new LinkedBlockingQueue<>();
+ private final StringBuilder buffer = new StringBuilder();
+ private volatile CompletableFuture closeFuture;
+
+ @Override
+ public void onOpen(WebSocket webSocket) {
+ webSocket.request(10);
+ }
+
+ @Override
+ public CompletionStage> onText(WebSocket webSocket, CharSequence data, boolean last) {
+ buffer.append(data);
+ if (last) {
+ messages.offer(buffer.toString());
+ buffer.setLength(0);
+ }
+ webSocket.request(1);
+ return null;
+ }
+
+ @Override
+ public CompletionStage> onClose(WebSocket webSocket, int statusCode, String reason) {
+ if (closeFuture != null) {
+ closeFuture.complete(statusCode);
+ }
+ return null;
+ }
+
+ @Override
+ public void onError(WebSocket webSocket, Throwable error) {
+ if (closeFuture != null) {
+ closeFuture.completeExceptionally(error);
+ }
+ }
+
+ public void setCloseFuture(CompletableFuture future) {
+ this.closeFuture = future;
+ }
+
+ public String getNextMessage(long timeout, TimeUnit unit) throws Exception {
+ return messages.poll(timeout, unit);
+ }
+ }
+}
diff --git a/compatibility-tests/sdk-test-node/package.json b/compatibility-tests/sdk-test-node/package.json
index 7ea4465b95..132258d9d7 100644
--- a/compatibility-tests/sdk-test-node/package.json
+++ b/compatibility-tests/sdk-test-node/package.json
@@ -25,11 +25,15 @@
"@aws-sdk/client-sns": "^3.500.0",
"@aws-sdk/client-sqs": "^3.500.0",
"@aws-sdk/client-ssm": "^3.500.0",
+ "@aws-sdk/client-apigatewaymanagementapi": "^3.500.0",
"@aws-sdk/client-sts": "^3.500.0",
- "selfsigned": "^5.5.0"
+ "selfsigned": "^5.5.0",
+ "ws": "^8.0.0"
},
"devDependencies": {
"@types/node": "^20.0.0",
+ "@types/ws": "^8.0.0",
+ "esbuild": "^0.21.0",
"typescript": "^5.4.0",
"vitest": "^2.0.0"
}
diff --git a/compatibility-tests/sdk-test-node/tests/apigatewayv2-websocket-dataplane.test.ts b/compatibility-tests/sdk-test-node/tests/apigatewayv2-websocket-dataplane.test.ts
new file mode 100644
index 0000000000..abe01748d6
--- /dev/null
+++ b/compatibility-tests/sdk-test-node/tests/apigatewayv2-websocket-dataplane.test.ts
@@ -0,0 +1,1049 @@
+/**
+ * API Gateway v2 WebSocket data-plane compatibility tests.
+ *
+ * Validates end-to-end WebSocket functionality: connect, send, receive, disconnect,
+ * route selection, Lambda authorizer, @connections API, stage variables, mock
+ * integration, and disconnect cleanup — using the AWS SDK v3 and the `ws` client.
+ */
+
+import { describe, it, expect, beforeAll, afterAll } from 'vitest';
+import {
+ ApiGatewayV2Client,
+ CreateApiCommand,
+ DeleteApiCommand,
+ CreateRouteCommand,
+ CreateIntegrationCommand,
+ CreateStageCommand,
+ CreateRouteResponseCommand,
+ CreateAuthorizerCommand,
+ CreateDeploymentCommand,
+} from '@aws-sdk/client-apigatewayv2';
+import {
+ ApiGatewayManagementApiClient,
+ PostToConnectionCommand,
+ GetConnectionCommand,
+ DeleteConnectionCommand,
+} from '@aws-sdk/client-apigatewaymanagementapi';
+import {
+ LambdaClient,
+ CreateFunctionCommand,
+ DeleteFunctionCommand,
+} from '@aws-sdk/client-lambda';
+import WebSocket from 'ws';
+import { makeClient, uniqueName, ENDPOINT, REGION, ACCOUNT, buildMinimalZip, buildBundledZip, sleep } from './setup';
+
+// ── Helpers ──────────────────────────────────────────────────────────────────
+
+function wsUrl(apiId: string, stage: string): string {
+ const endpoint = process.env.FLOCI_ENDPOINT || 'http://localhost:4566';
+ // Convert http/https to ws/wss and strip any trailing slashes
+ const wsEndpoint = endpoint.replace(/^https?:\/\//, '').replace(/\/$/, '');
+ return `ws://${wsEndpoint}/ws/${apiId}/${stage}`;
+}
+
+function managementClient(apiId: string, stage: string): ApiGatewayManagementApiClient {
+ return makeClient(ApiGatewayManagementApiClient, {
+ endpoint: `${ENDPOINT}/execute-api/${apiId}/${stage}`,
+ });
+}
+
+function connectWs(url: string): Promise {
+ return new Promise((resolve, reject) => {
+ const ws = new WebSocket(url);
+ ws.on('open', () => resolve(ws));
+ ws.on('error', (err) => reject(err));
+ });
+}
+
+function waitForMessage(ws: WebSocket, timeoutMs = 5000): Promise {
+ return new Promise((resolve, reject) => {
+ const timer = setTimeout(() => reject(new Error('Timeout waiting for message')), timeoutMs);
+ ws.once('message', (data) => {
+ clearTimeout(timer);
+ resolve(data.toString());
+ });
+ });
+}
+
+function waitForClose(ws: WebSocket, timeoutMs = 5000): Promise {
+ return new Promise((resolve, reject) => {
+ if (ws.readyState === WebSocket.CLOSED) { resolve(); return; }
+ const timer = setTimeout(() => reject(new Error('Timeout waiting for close')), timeoutMs);
+ ws.once('close', () => { clearTimeout(timer); resolve(); });
+ });
+}
+
+const ROLE_ARN = `arn:aws:iam::${ACCOUNT}:role/lambda-role`;
+
+// ── Lambda handler source code ───────────────────────────────────────────────
+
+const ECHO_HANDLER = `
+exports.handler = async (event) => {
+ const body = event.body || '';
+ try {
+ const parsed = JSON.parse(body);
+ if (parsed.action === 'getConnectionId') {
+ return { statusCode: 200, body: JSON.stringify({ connectionId: event.requestContext.connectionId }) };
+ }
+ } catch (e) {}
+ return { statusCode: 200, body: body || 'echo' };
+};
+`;
+
+const BROADCAST_HANDLER = `
+const { ApiGatewayManagementApiClient, PostToConnectionCommand } = require('@aws-sdk/client-apigatewaymanagementapi');
+exports.handler = async (event) => {
+ const apiId = event.requestContext.apiId;
+ const stage = event.requestContext.stage;
+ const endpoint = process.env.FLOCI_ENDPOINT + '/execute-api/' + apiId + '/' + stage;
+ const client = new ApiGatewayManagementApiClient({ endpoint, region: 'us-east-1' });
+ const body = JSON.parse(event.body);
+ for (const connId of body.targets) {
+ await client.send(new PostToConnectionCommand({
+ ConnectionId: connId,
+ Data: Buffer.from(body.message),
+ }));
+ }
+ return { statusCode: 200 };
+};
+`;
+
+const AUTHORIZER_HANDLER = `
+exports.handler = async (event) => {
+ const token = event.queryStringParameters && event.queryStringParameters.token;
+ const effect = token === 'allow' ? 'Allow' : 'Deny';
+ return {
+ principalId: 'user',
+ policyDocument: {
+ Version: '2012-10-17',
+ Statement: [{ Action: 'execute-api:Invoke', Effect: effect, Resource: event.methodArn || '*' }],
+ },
+ };
+};
+`;
+
+const PING_HANDLER = `
+exports.handler = async (event) => {
+ return { statusCode: 200, body: 'pong' };
+};
+`;
+
+const SEND_MESSAGE_HANDLER = `
+exports.handler = async (event) => {
+ const body = JSON.parse(event.body);
+ return { statusCode: 200, body: 'received: ' + body.data };
+};
+`;
+
+const DEFAULT_HANDLER = `
+exports.handler = async (event) => {
+ return { statusCode: 200, body: 'default-route' };
+};
+`;
+
+// ── Test suites ──────────────────────────────────────────────────────────────
+
+describe('WebSocket Data-Plane', () => {
+ let gw: ApiGatewayV2Client;
+ let lambda: LambdaClient;
+
+ // Track all created resources for cleanup
+ const createdFunctions: string[] = [];
+ const createdApis: string[] = [];
+
+ beforeAll(() => {
+ gw = makeClient(ApiGatewayV2Client);
+ lambda = makeClient(LambdaClient);
+ });
+
+ afterAll(async () => {
+ for (const fnName of createdFunctions) {
+ try { await lambda.send(new DeleteFunctionCommand({ FunctionName: fnName })); } catch { /* ignore */ }
+ }
+ for (const apiId of createdApis) {
+ try { await gw.send(new DeleteApiCommand({ ApiId: apiId })); } catch { /* ignore */ }
+ }
+ });
+
+ /**
+ * Create a Lambda function with/without dependencies bundled via esbuild.
+ * bundledZip should be set as true for handlers that require npm packages (e.g. @aws-sdk/client-apigatewaymanagementapi).
+ */
+ async function createLambda(name: string, code: string, environment?: Record, bundledZip?: boolean): Promise {
+ const fnName = uniqueName(name);
+ const zipBuffer = bundledZip ? buildBundledZip(code) : buildMinimalZip('index.js', Buffer.from(code));
+ await lambda.send(new CreateFunctionCommand({
+ FunctionName: fnName,
+ Runtime: 'nodejs22.x',
+ Role: ROLE_ARN,
+ Handler: 'index.handler',
+ Code: { ZipFile: zipBuffer },
+ ...(environment && { Environment: { Variables: environment } }),
+ }));
+ createdFunctions.push(fnName);
+ return fnName;
+ }
+
+ async function createWsApi(name: string): Promise {
+ const res = await gw.send(new CreateApiCommand({
+ Name: uniqueName(name),
+ ProtocolType: 'WEBSOCKET',
+ RouteSelectionExpression: '$request.body.action',
+ }));
+ createdApis.push(res.ApiId!);
+ return res.ApiId!;
+ }
+
+ async function createLambdaIntegration(apiId: string, fnName: string): Promise {
+ const res = await gw.send(new CreateIntegrationCommand({
+ ApiId: apiId,
+ IntegrationType: 'AWS_PROXY',
+ IntegrationUri: `arn:aws:lambda:${REGION}:${ACCOUNT}:function:${fnName}`,
+ }));
+ return res.IntegrationId!;
+ }
+
+ async function setupStage(apiId: string, stageName: string, stageVariables?: Record): Promise {
+ const deploy = await gw.send(new CreateDeploymentCommand({ ApiId: apiId }));
+ await gw.send(new CreateStageCommand({
+ ApiId: apiId,
+ StageName: stageName,
+ DeploymentId: deploy.DeploymentId!,
+ StageVariables: stageVariables,
+ }));
+ }
+
+ // ──────────────────────────── Basic WebSocket flow ────────────────────────────
+
+ describe('Basic WebSocket flow', () => {
+ let apiId: string;
+
+ beforeAll(async () => {
+ const echoFn = await createLambda('echo', ECHO_HANDLER);
+ apiId = await createWsApi('basic-flow');
+
+ const integId = await createLambdaIntegration(apiId, echoFn);
+
+ await gw.send(new CreateRouteCommand({
+ ApiId: apiId,
+ RouteKey: '$default',
+ Target: `integrations/${integId}`,
+ RouteResponseSelectionExpression: '$default',
+ }));
+
+ await gw.send(new CreateRouteResponseCommand({
+ ApiId: apiId,
+ RouteId: (await gw.send(new CreateRouteCommand({
+ ApiId: apiId,
+ RouteKey: '$connect',
+ Target: `integrations/${integId}`,
+ }))).RouteId!,
+ RouteResponseKey: '$default',
+ })).catch(() => { /* route response optional */ });
+
+ await setupStage(apiId, 'test');
+ });
+
+ it('should connect, send message, receive response, and disconnect', async () => {
+ const ws = await connectWs(wsUrl(apiId, 'test'));
+ try {
+ ws.send(JSON.stringify({ action: 'test', body: 'hello' }));
+ const response = await waitForMessage(ws);
+ expect(response).toBeTruthy();
+ ws.close();
+ await waitForClose(ws);
+ } finally {
+ if (ws.readyState !== WebSocket.CLOSED) ws.close();
+ }
+ });
+ });
+
+ // ──────────────────────────── Chat-style broadcast ────────────────────────────
+
+ describe('Chat-style broadcast', () => {
+ let apiId: string;
+
+ beforeAll(async () => {
+ const broadcastFn = await createLambda('broadcast', BROADCAST_HANDLER, {
+ FLOCI_ENDPOINT: 'http://host.docker.internal:4566',
+ }, true);
+ const echoFn = await createLambda('bc-echo', ECHO_HANDLER);
+ apiId = await createWsApi('broadcast');
+
+ const broadcastIntegId = await createLambdaIntegration(apiId, broadcastFn);
+ const echoIntegId = await createLambdaIntegration(apiId, echoFn);
+
+ await gw.send(new CreateRouteCommand({
+ ApiId: apiId,
+ RouteKey: '$connect',
+ Target: `integrations/${echoIntegId}`,
+ }));
+
+ await gw.send(new CreateRouteCommand({
+ ApiId: apiId,
+ RouteKey: '$default',
+ Target: `integrations/${echoIntegId}`,
+ RouteResponseSelectionExpression: '$default',
+ }));
+
+ await gw.send(new CreateRouteCommand({
+ ApiId: apiId,
+ RouteKey: 'broadcast',
+ Target: `integrations/${broadcastIntegId}`,
+ RouteResponseSelectionExpression: '$default',
+ }));
+
+ await setupStage(apiId, 'test');
+ });
+
+ it('should broadcast message to multiple connected clients', async () => {
+ const ws1 = await connectWs(wsUrl(apiId, 'test'));
+ const ws2 = await connectWs(wsUrl(apiId, 'test'));
+ try {
+ await sleep(200); // allow connections to register
+
+ // Get connection IDs for both clients
+ const connId1 = await getConnectionIdFromServer(ws1, apiId, 'test');
+ const connId2 = await getConnectionIdFromServer(ws2, apiId, 'test');
+
+ expect(connId1).toBeTruthy();
+ expect(connId2).toBeTruthy();
+
+ // Set up message listeners before sending broadcast
+ const msg1Promise = waitForMessage(ws1);
+ const msg2Promise = waitForMessage(ws2);
+
+ // Send broadcast action — Lambda will POST to both connections
+ ws1.send(JSON.stringify({
+ action: 'broadcast',
+ targets: [connId1, connId2],
+ message: 'hello-all',
+ }));
+
+ const [r1, r2] = await Promise.all([msg1Promise, msg2Promise]);
+ expect(r1).toBe('hello-all');
+ expect(r2).toBe('hello-all');
+ } finally {
+ ws1.close();
+ ws2.close();
+ }
+ });
+ });
+
+ // ──────────────────────────── $connect authorization ────────────────────────────
+
+ describe('$connect authorization', () => {
+ let apiId: string;
+
+ beforeAll(async () => {
+ const authFn = await createLambda('authorizer', AUTHORIZER_HANDLER);
+ const echoFn = await createLambda('auth-echo', ECHO_HANDLER);
+ apiId = await createWsApi('auth-test');
+
+ const echoIntegId = await createLambdaIntegration(apiId, echoFn);
+
+ const authRes = await gw.send(new CreateAuthorizerCommand({
+ ApiId: apiId,
+ AuthorizerType: 'REQUEST',
+ Name: 'ws-auth',
+ AuthorizerUri: `arn:aws:lambda:${REGION}:${ACCOUNT}:function:${authFn}`,
+ IdentitySource: ['route.request.querystring.token'],
+ }));
+
+ await gw.send(new CreateRouteCommand({
+ ApiId: apiId,
+ RouteKey: '$connect',
+ Target: `integrations/${echoIntegId}`,
+ AuthorizationType: 'CUSTOM',
+ AuthorizerId: authRes.AuthorizerId!,
+ }));
+
+ await gw.send(new CreateRouteCommand({
+ ApiId: apiId,
+ RouteKey: '$default',
+ Target: `integrations/${echoIntegId}`,
+ }));
+
+ await setupStage(apiId, 'test');
+ });
+
+ it('should allow connection with valid token', async () => {
+ const ws = await connectWs(wsUrl(apiId, 'test') + '?token=allow');
+ try {
+ expect(ws.readyState).toBe(WebSocket.OPEN);
+ } finally {
+ ws.close();
+ }
+ });
+
+ it('should deny connection with invalid token', async () => {
+ await expect(connectWs(wsUrl(apiId, 'test') + '?token=deny')).rejects.toThrow();
+ });
+ });
+
+ // ──────────────────────────── Route selection ────────────────────────────
+
+ describe('Route selection', () => {
+ let apiId: string;
+
+ beforeAll(async () => {
+ const pingFn = await createLambda('ping', PING_HANDLER);
+ const sendMsgFn = await createLambda('sendmsg', SEND_MESSAGE_HANDLER);
+ const defaultFn = await createLambda('default', DEFAULT_HANDLER);
+ const echoFn = await createLambda('rs-echo', ECHO_HANDLER);
+ apiId = await createWsApi('route-sel');
+
+ const pingIntegId = await createLambdaIntegration(apiId, pingFn);
+ const sendMsgIntegId = await createLambdaIntegration(apiId, sendMsgFn);
+ const defaultIntegId = await createLambdaIntegration(apiId, defaultFn);
+ const echoIntegId = await createLambdaIntegration(apiId, echoFn);
+
+ await gw.send(new CreateRouteCommand({
+ ApiId: apiId,
+ RouteKey: '$connect',
+ Target: `integrations/${echoIntegId}`,
+ }));
+
+ await gw.send(new CreateRouteCommand({
+ ApiId: apiId,
+ RouteKey: 'ping',
+ Target: `integrations/${pingIntegId}`,
+ RouteResponseSelectionExpression: '$default',
+ }));
+
+ await gw.send(new CreateRouteCommand({
+ ApiId: apiId,
+ RouteKey: 'sendMessage',
+ Target: `integrations/${sendMsgIntegId}`,
+ RouteResponseSelectionExpression: '$default',
+ }));
+
+ await gw.send(new CreateRouteCommand({
+ ApiId: apiId,
+ RouteKey: '$default',
+ Target: `integrations/${defaultIntegId}`,
+ RouteResponseSelectionExpression: '$default',
+ }));
+
+ await setupStage(apiId, 'test');
+ });
+
+ it('should route "ping" action to ping handler', async () => {
+ const ws = await connectWs(wsUrl(apiId, 'test'));
+ try {
+ ws.send(JSON.stringify({ action: 'ping' }));
+ const response = await waitForMessage(ws);
+ expect(response).toBe('pong');
+ } finally {
+ ws.close();
+ }
+ });
+
+ it('should route "sendMessage" action to sendMessage handler', async () => {
+ const ws = await connectWs(wsUrl(apiId, 'test'));
+ try {
+ ws.send(JSON.stringify({ action: 'sendMessage', data: 'test-data' }));
+ const response = await waitForMessage(ws);
+ expect(response).toBe('received: test-data');
+ } finally {
+ ws.close();
+ }
+ });
+
+ it('should route unknown action to $default handler', async () => {
+ const ws = await connectWs(wsUrl(apiId, 'test'));
+ try {
+ ws.send(JSON.stringify({ action: 'unknownAction' }));
+ const response = await waitForMessage(ws);
+ expect(response).toBe('default-route');
+ } finally {
+ ws.close();
+ }
+ });
+ });
+
+ // ──────────────────────────── @connections API ────────────────────────────
+
+ describe('@connections API', () => {
+ let apiId: string;
+
+ beforeAll(async () => {
+ const echoFn = await createLambda('conn-echo', ECHO_HANDLER);
+ apiId = await createWsApi('connections-api');
+
+ const integId = await createLambdaIntegration(apiId, echoFn);
+
+ await gw.send(new CreateRouteCommand({
+ ApiId: apiId,
+ RouteKey: '$connect',
+ Target: `integrations/${integId}`,
+ }));
+
+ await gw.send(new CreateRouteCommand({
+ ApiId: apiId,
+ RouteKey: '$default',
+ Target: `integrations/${integId}`,
+ RouteResponseSelectionExpression: '$default',
+ }));
+
+ await setupStage(apiId, 'test');
+ });
+
+ it('should POST message to a connection', async () => {
+ const ws = await connectWs(wsUrl(apiId, 'test'));
+ try {
+ await sleep(200);
+ const connId = await getConnectionIdFromServer(ws, apiId, 'test');
+ expect(connId).toBeTruthy();
+
+ const mgmt = managementClient(apiId, 'test');
+ const msgPromise = waitForMessage(ws);
+
+ await mgmt.send(new PostToConnectionCommand({
+ ConnectionId: connId!,
+ Data: Buffer.from('server-push'),
+ }));
+
+ const received = await msgPromise;
+ expect(received).toBe('server-push');
+ } finally {
+ ws.close();
+ }
+ });
+
+ it('should GET connection info', async () => {
+ const ws = await connectWs(wsUrl(apiId, 'test'));
+ try {
+ await sleep(200);
+ const connId = await getConnectionIdFromServer(ws, apiId, 'test');
+ expect(connId).toBeTruthy();
+
+ const mgmt = managementClient(apiId, 'test');
+ const info = await mgmt.send(new GetConnectionCommand({
+ ConnectionId: connId!,
+ }));
+
+ expect(info.ConnectedAt).toBeDefined();
+ } finally {
+ ws.close();
+ }
+ });
+
+ it('should DELETE (disconnect) a connection', async () => {
+ const ws = await connectWs(wsUrl(apiId, 'test'));
+ try {
+ await sleep(200);
+ const connId = await getConnectionIdFromServer(ws, apiId, 'test');
+ expect(connId).toBeTruthy();
+
+ const mgmt = managementClient(apiId, 'test');
+ await mgmt.send(new DeleteConnectionCommand({
+ ConnectionId: connId!,
+ }));
+
+ await waitForClose(ws);
+ expect(ws.readyState).toBe(WebSocket.CLOSED);
+ } finally {
+ if (ws.readyState !== WebSocket.CLOSED) ws.close();
+ }
+ });
+ });
+
+ // ──────────────────────────── Stage variables ────────────────────────────
+
+ describe('Stage variables', () => {
+ let apiId: string;
+
+ beforeAll(async () => {
+ const echoFn = await createLambda('sv-echo', ECHO_HANDLER);
+ apiId = await createWsApi('stage-vars');
+
+ // Create integration with stage variable reference in URI
+ const integRes = await gw.send(new CreateIntegrationCommand({
+ ApiId: apiId,
+ IntegrationType: 'AWS_PROXY',
+ IntegrationUri: `arn:aws:lambda:${REGION}:${ACCOUNT}:function:\${stageVariables.functionName}`,
+ }));
+ const integId = integRes.IntegrationId!;
+
+ await gw.send(new CreateRouteCommand({
+ ApiId: apiId,
+ RouteKey: '$connect',
+ Target: `integrations/${integId}`,
+ }));
+
+ await gw.send(new CreateRouteCommand({
+ ApiId: apiId,
+ RouteKey: '$default',
+ Target: `integrations/${integId}`,
+ RouteResponseSelectionExpression: '$default',
+ }));
+
+ await setupStage(apiId, 'test', { functionName: echoFn });
+ });
+
+ it('should resolve stage variable in integration URI', async () => {
+ const ws = await connectWs(wsUrl(apiId, 'test'));
+ try {
+ ws.send(JSON.stringify({ action: 'test', body: 'stage-var-test' }));
+ const response = await waitForMessage(ws);
+ expect(response).toBeTruthy();
+ } finally {
+ ws.close();
+ }
+ });
+ });
+
+ // ──────────────────────────── Mock integration ────────────────────────────
+
+ describe('Mock integration', () => {
+ let apiId: string;
+
+ beforeAll(async () => {
+ apiId = await createWsApi('mock-integ');
+
+ // Create MOCK integration for $connect — no Lambda needed
+ const mockIntegRes = await gw.send(new CreateIntegrationCommand({
+ ApiId: apiId,
+ IntegrationType: 'MOCK',
+ }));
+ const mockIntegId = mockIntegRes.IntegrationId!;
+
+ await gw.send(new CreateRouteCommand({
+ ApiId: apiId,
+ RouteKey: '$connect',
+ Target: `integrations/${mockIntegId}`,
+ }));
+
+ const echoFn = await createLambda('mock-echo', ECHO_HANDLER);
+ const echoIntegId = await createLambdaIntegration(apiId, echoFn);
+
+ await gw.send(new CreateRouteCommand({
+ ApiId: apiId,
+ RouteKey: '$default',
+ Target: `integrations/${echoIntegId}`,
+ RouteResponseSelectionExpression: '$default',
+ }));
+
+ await setupStage(apiId, 'test');
+ });
+
+ it('should connect successfully with MOCK integration on $connect', async () => {
+ const ws = await connectWs(wsUrl(apiId, 'test'));
+ try {
+ expect(ws.readyState).toBe(WebSocket.OPEN);
+ ws.send(JSON.stringify({ action: 'test' }));
+ const response = await waitForMessage(ws);
+ expect(response).toBeTruthy();
+ } finally {
+ ws.close();
+ }
+ });
+ });
+
+ // ──────────────────────────── Disconnect cleanup ────────────────────────────
+
+ describe('Disconnect cleanup', () => {
+ let apiId: string;
+
+ beforeAll(async () => {
+ const echoFn = await createLambda('dc-echo', ECHO_HANDLER);
+ apiId = await createWsApi('disconnect');
+
+ const integId = await createLambdaIntegration(apiId, echoFn);
+
+ await gw.send(new CreateRouteCommand({
+ ApiId: apiId,
+ RouteKey: '$connect',
+ Target: `integrations/${integId}`,
+ }));
+
+ await gw.send(new CreateRouteCommand({
+ ApiId: apiId,
+ RouteKey: '$default',
+ Target: `integrations/${integId}`,
+ RouteResponseSelectionExpression: '$default',
+ }));
+
+ await setupStage(apiId, 'test');
+ });
+
+ it('should return 410 when posting to a disconnected connection', async () => {
+ const ws = await connectWs(wsUrl(apiId, 'test'));
+ await sleep(200);
+ const connId = await getConnectionIdFromServer(ws, apiId, 'test');
+ expect(connId).toBeTruthy();
+
+ // Disconnect the client
+ ws.close();
+ await waitForClose(ws);
+ await sleep(300); // allow server to process disconnect
+
+ // Attempt to post to the disconnected connection
+ const mgmt = managementClient(apiId, 'test');
+ await expect(
+ mgmt.send(new PostToConnectionCommand({
+ ConnectionId: connId!,
+ Data: Buffer.from('should-fail'),
+ }))
+ ).rejects.toThrow(/410|Gone/);
+ });
+ });
+
+ // ──────────────────────────── Payload size limit ────────────────────────────
+
+ describe('Payload size limit', () => {
+ let apiId: string;
+
+ beforeAll(async () => {
+ const echoFn = await createLambda('pl-echo', ECHO_HANDLER);
+ apiId = await createWsApi('payload-limit');
+
+ const integId = await createLambdaIntegration(apiId, echoFn);
+
+ await gw.send(new CreateRouteCommand({
+ ApiId: apiId,
+ RouteKey: '$connect',
+ Target: `integrations/${integId}`,
+ }));
+
+ await gw.send(new CreateRouteCommand({
+ ApiId: apiId,
+ RouteKey: '$default',
+ Target: `integrations/${integId}`,
+ RouteResponseSelectionExpression: '$default',
+ }));
+
+ await setupStage(apiId, 'test');
+ });
+
+ it('should reject messages exceeding 128 KB with error frame', async () => {
+ const ws = await connectWs(wsUrl(apiId, 'test'));
+ try {
+ // Create a message larger than 128 KB
+ const oversizeMessage = 'x'.repeat(128 * 1024 + 1);
+ ws.send(oversizeMessage);
+ const response = await waitForMessage(ws);
+ expect(response).toContain('Message too long');
+ } finally {
+ ws.close();
+ }
+ });
+
+ it('should accept messages at exactly 128 KB', async () => {
+ const ws = await connectWs(wsUrl(apiId, 'test'));
+ try {
+ // Create a message at exactly 128 KB (should be accepted)
+ const maxMessage = JSON.stringify({ action: 'test', data: 'x'.repeat(128 * 1024 - 50) });
+ if (maxMessage.length <= 128 * 1024) {
+ ws.send(maxMessage);
+ const response = await waitForMessage(ws);
+ expect(response).toBeTruthy();
+ expect(response).not.toContain('Message too long');
+ }
+ } finally {
+ ws.close();
+ }
+ });
+ });
+
+ // ──────────────────────────── Server-initiated close via @connections DELETE ────────────────────────────
+
+ describe('Server-initiated close via DELETE', () => {
+ let apiId: string;
+
+ beforeAll(async () => {
+ const echoFn = await createLambda('del-echo', ECHO_HANDLER);
+ apiId = await createWsApi('server-close');
+
+ const integId = await createLambdaIntegration(apiId, echoFn);
+
+ await gw.send(new CreateRouteCommand({
+ ApiId: apiId,
+ RouteKey: '$connect',
+ Target: `integrations/${integId}`,
+ }));
+
+ await gw.send(new CreateRouteCommand({
+ ApiId: apiId,
+ RouteKey: '$default',
+ Target: `integrations/${integId}`,
+ RouteResponseSelectionExpression: '$default',
+ }));
+
+ await setupStage(apiId, 'test');
+ });
+
+ it('should disconnect client and return 410 on subsequent POST', async () => {
+ const ws = await connectWs(wsUrl(apiId, 'test'));
+ await sleep(200);
+ const connId = await getConnectionIdFromServer(ws, apiId, 'test');
+ expect(connId).toBeTruthy();
+
+ // DELETE the connection via @connections API
+ const mgmt = managementClient(apiId, 'test');
+ await mgmt.send(new DeleteConnectionCommand({
+ ConnectionId: connId!,
+ }));
+
+ // Wait for the WebSocket to close
+ await waitForClose(ws);
+ await sleep(300);
+
+ // POST to the deleted connection should return 410
+ await expect(
+ mgmt.send(new PostToConnectionCommand({
+ ConnectionId: connId!,
+ Data: Buffer.from('should-fail'),
+ }))
+ ).rejects.toThrow(/410|Gone/);
+ });
+ });
+
+ // ──────────────────────────── Binary frame support ────────────────────────────
+
+ describe('Binary frame support', () => {
+ let apiId: string;
+
+ beforeAll(async () => {
+ const echoFn = await createLambda('bin-echo', ECHO_HANDLER);
+ apiId = await createWsApi('binary-frames');
+
+ const integId = await createLambdaIntegration(apiId, echoFn);
+
+ await gw.send(new CreateRouteCommand({
+ ApiId: apiId,
+ RouteKey: '$connect',
+ Target: `integrations/${integId}`,
+ }));
+
+ await gw.send(new CreateRouteCommand({
+ ApiId: apiId,
+ RouteKey: '$default',
+ Target: `integrations/${integId}`,
+ RouteResponseSelectionExpression: '$default',
+ }));
+
+ await setupStage(apiId, 'test');
+ });
+
+ it('should handle binary frames and route to $default', async () => {
+ const ws = await connectWs(wsUrl(apiId, 'test'));
+ try {
+ // Send a binary frame (Buffer)
+ const binaryData = Buffer.from([0x01, 0x02, 0x03, 0x04, 0x05]);
+ ws.send(binaryData);
+
+ // Binary messages route to $default since they can't match JSON route selection.
+ // The Lambda receives the base64-encoded body with isBase64Encoded=true.
+ const response = await waitForMessage(ws);
+ expect(response).toBeTruthy();
+ } finally {
+ ws.close();
+ }
+ });
+
+ it('should reject binary frames exceeding 128 KB', async () => {
+ const ws = await connectWs(wsUrl(apiId, 'test'));
+ try {
+ // Create a binary payload larger than 128 KB
+ const oversizeBinary = Buffer.alloc(128 * 1024 + 1, 0x42);
+ ws.send(oversizeBinary);
+
+ const response = await waitForMessage(ws);
+ expect(response).toContain('Message too long');
+ } finally {
+ ws.close();
+ }
+ });
+ });
+
+ // ──────────────────────────── $disconnect Lambda invocation ────────────────────────────
+
+ describe('$disconnect Lambda invocation', () => {
+ let apiId: string;
+ let disconnectFnName: string;
+
+ const DISCONNECT_HANDLER = `
+const { ApiGatewayManagementApiClient, PostToConnectionCommand } = require('@aws-sdk/client-apigatewaymanagementapi');
+exports.handler = async (event) => {
+ // The $disconnect handler is invoked when a client disconnects.
+ // We verify invocation by checking the eventType in requestContext.
+ // Since the client is already disconnected, we can't send a message back.
+ // Instead, we just return successfully — the test verifies invocation happened
+ // by checking that the function was called (no error in logs).
+ if (event.requestContext.eventType === 'DISCONNECT') {
+ return { statusCode: 200 };
+ }
+ return { statusCode: 200 };
+};
+`;
+
+ beforeAll(async () => {
+ disconnectFnName = await createLambda('disconnect-fn', DISCONNECT_HANDLER, {
+ FLOCI_ENDPOINT: 'http://host.docker.internal:4566',
+ }, true);
+ const echoFn = await createLambda('dc-inv-echo', ECHO_HANDLER);
+ apiId = await createWsApi('disconnect-invoke');
+
+ const echoIntegId = await createLambdaIntegration(apiId, echoFn);
+ const disconnectIntegId = await createLambdaIntegration(apiId, disconnectFnName);
+
+ await gw.send(new CreateRouteCommand({
+ ApiId: apiId,
+ RouteKey: '$connect',
+ Target: `integrations/${echoIntegId}`,
+ }));
+
+ await gw.send(new CreateRouteCommand({
+ ApiId: apiId,
+ RouteKey: '$default',
+ Target: `integrations/${echoIntegId}`,
+ RouteResponseSelectionExpression: '$default',
+ }));
+
+ await gw.send(new CreateRouteCommand({
+ ApiId: apiId,
+ RouteKey: '$disconnect',
+ Target: `integrations/${disconnectIntegId}`,
+ }));
+
+ await setupStage(apiId, 'test');
+ });
+
+ it('should invoke $disconnect Lambda on client-initiated close', async () => {
+ const ws = await connectWs(wsUrl(apiId, 'test'));
+ await sleep(200);
+ const connId = await getConnectionIdFromServer(ws, apiId, 'test');
+ expect(connId).toBeTruthy();
+
+ // Close the connection (client-initiated)
+ ws.close();
+ await waitForClose(ws);
+ await sleep(500); // allow time for $disconnect Lambda invocation
+
+ // Verify the connection is fully cleaned up — POST should return 410
+ const mgmt = managementClient(apiId, 'test');
+ await expect(
+ mgmt.send(new PostToConnectionCommand({
+ ConnectionId: connId!,
+ Data: Buffer.from('should-fail'),
+ }))
+ ).rejects.toThrow(/410|Gone/);
+ });
+
+ it('should NOT invoke $disconnect Lambda on server-initiated close via @connections DELETE', async () => {
+ const ws = await connectWs(wsUrl(apiId, 'test'));
+ await sleep(200);
+ const connId = await getConnectionIdFromServer(ws, apiId, 'test');
+ expect(connId).toBeTruthy();
+
+ // Server-initiated close via @connections DELETE API
+ const mgmt = managementClient(apiId, 'test');
+ await mgmt.send(new DeleteConnectionCommand({
+ ConnectionId: connId!,
+ }));
+
+ await waitForClose(ws);
+ await sleep(500);
+
+ // Connection should be cleaned up — POST should return 410
+ await expect(
+ mgmt.send(new PostToConnectionCommand({
+ ConnectionId: connId!,
+ Data: Buffer.from('should-fail'),
+ }))
+ ).rejects.toThrow(/410|Gone/);
+ });
+ });
+
+ // ──────────────────────────── @connections POST payload size limit ────────────────────────────
+
+ describe('@connections POST payload size limit', () => {
+ let apiId: string;
+
+ beforeAll(async () => {
+ const echoFn = await createLambda('pl-post-echo', ECHO_HANDLER);
+ apiId = await createWsApi('post-payload-limit');
+
+ const integId = await createLambdaIntegration(apiId, echoFn);
+
+ await gw.send(new CreateRouteCommand({
+ ApiId: apiId,
+ RouteKey: '$connect',
+ Target: `integrations/${integId}`,
+ }));
+
+ await gw.send(new CreateRouteCommand({
+ ApiId: apiId,
+ RouteKey: '$default',
+ Target: `integrations/${integId}`,
+ RouteResponseSelectionExpression: '$default',
+ }));
+
+ await setupStage(apiId, 'test');
+ });
+
+ it('should reject @connections POST exceeding 128 KB with 413', async () => {
+ const ws = await connectWs(wsUrl(apiId, 'test'));
+ try {
+ await sleep(200);
+ const connId = await getConnectionIdFromServer(ws, apiId, 'test');
+ expect(connId).toBeTruthy();
+
+ const mgmt = managementClient(apiId, 'test');
+ const oversizePayload = Buffer.alloc(128 * 1024 + 1, 0x41); // 'A' repeated
+
+ await expect(
+ mgmt.send(new PostToConnectionCommand({
+ ConnectionId: connId!,
+ Data: oversizePayload,
+ }))
+ ).rejects.toThrow(/413|PayloadTooLarge|too large/i);
+ } finally {
+ ws.close();
+ }
+ });
+
+ it('should accept @connections POST at exactly 128 KB', async () => {
+ const ws = await connectWs(wsUrl(apiId, 'test'));
+ try {
+ await sleep(200);
+ const connId = await getConnectionIdFromServer(ws, apiId, 'test');
+ expect(connId).toBeTruthy();
+
+ const mgmt = managementClient(apiId, 'test');
+ const maxPayload = Buffer.alloc(128 * 1024, 0x41); // exactly 128 KB
+
+ const msgPromise = waitForMessage(ws);
+ await mgmt.send(new PostToConnectionCommand({
+ ConnectionId: connId!,
+ Data: maxPayload,
+ }));
+
+ const received = await msgPromise;
+ expect(received.length).toBe(128 * 1024);
+ } finally {
+ ws.close();
+ }
+ });
+ });
+});
+
+// ── Helper to get connection ID ──────────────────────────────────────────────
+
+/**
+ * Gets the connection ID for a WebSocket client by sending a `getConnectionId`
+ * action message. The echo handler is designed to return the connectionId from
+ * the Lambda event's requestContext when it receives this action.
+ */
+async function getConnectionIdFromServer(ws: WebSocket, _apiId: string, _stage: string): Promise {
+ ws.send(JSON.stringify({ action: 'getConnectionId' }));
+ try {
+ const response = await waitForMessage(ws, 3000);
+ const parsed = JSON.parse(response);
+ return parsed.connectionId || null;
+ } catch {
+ return null;
+ }
+}
diff --git a/compatibility-tests/sdk-test-node/tests/setup.ts b/compatibility-tests/sdk-test-node/tests/setup.ts
index f027fee380..74cb636a7e 100644
--- a/compatibility-tests/sdk-test-node/tests/setup.ts
+++ b/compatibility-tests/sdk-test-node/tests/setup.ts
@@ -3,6 +3,10 @@
*/
import { randomUUID } from 'node:crypto';
+import { writeFileSync, readFileSync, mkdtempSync, rmSync } from 'node:fs';
+import { join } from 'node:path';
+import { tmpdir } from 'node:os';
+import { buildSync } from 'esbuild';
export const ENDPOINT = process.env.FLOCI_ENDPOINT || 'http://localhost:4566';
export const REGION = process.env.AWS_DEFAULT_REGION || 'us-east-1';
@@ -109,3 +113,42 @@ function crc32(buf: Buffer): number {
}
return (crc ^ 0xffffffff) >>> 0;
}
+
+/**
+ * Build a Lambda ZIP with all dependencies bundled via esbuild.
+ *
+ * Use this when the handler code requires npm packages (e.g. @aws-sdk/client-apigatewaymanagementapi).
+ * esbuild resolves imports from the test project's node_modules and inlines everything into a single
+ * CommonJS file, which is then zipped using buildMinimalZip.
+ *
+ * This avoids maintaining a separate folder with its own package.json/node_modules.
+ */
+export function buildBundledZip(handlerCode: string): Buffer {
+ const tmpDir = mkdtempSync(join(tmpdir(), 'lambda-bundle-'));
+ const entryFile = join(tmpDir, 'index.js');
+ const outFile = join(tmpDir, 'bundle.js');
+
+ // Resolve node_modules from the test project root (where this file lives)
+ const projectRoot = join(import.meta.dirname, '..');
+ const nodeModulesPath = join(projectRoot, 'node_modules');
+
+ try {
+ writeFileSync(entryFile, handlerCode);
+
+ buildSync({
+ entryPoints: [entryFile],
+ bundle: true,
+ platform: 'node',
+ target: 'node22',
+ outfile: outFile,
+ format: 'cjs',
+ minify: false,
+ nodePaths: [nodeModulesPath],
+ });
+
+ const bundled = readFileSync(outFile);
+ return buildMinimalZip('index.js', bundled);
+ } finally {
+ rmSync(tmpDir, { recursive: true, force: true });
+ }
+}
diff --git a/docs/services/api-gateway.md b/docs/services/api-gateway.md
index f473739fd5..c67ec334a2 100644
--- a/docs/services/api-gateway.md
+++ b/docs/services/api-gateway.md
@@ -107,7 +107,7 @@ curl http://localhost:4566/restapis/$API_ID/dev/_user_request_/users
**Protocol:** REST JSON
**Endpoint:** `http://localhost:4566/v2/apis/...`
-Both HTTP and WebSocket protocol types are supported for the management plane. WebSocket data-plane (actual connection handling) is not yet implemented.
+Both HTTP and WebSocket protocol types are fully supported, including the WebSocket data-plane (real connection handling, message routing, and the `@connections` management API).
### Supported Operations
@@ -124,9 +124,60 @@ Both HTTP and WebSocket protocol types are supported for the management plane. W
| **Models** | CreateModel, GetModel, GetModels, UpdateModel, DeleteModel |
| **Tags** | TagResource, UntagResource, GetTags |
+### WebSocket Data-Plane {#websocket-data-plane}
+
+Floci supports real WebSocket connections for API Gateway v2 WebSocket APIs. Clients connect via:
+
+```
+ws://localhost:4566/ws/{apiId}/{stageName}
+```
+
+#### Supported Features
+
+| Feature | Status |
+|---------|--------|
+| `$connect` route with Lambda integration | ✅ |
+| `$disconnect` route with Lambda integration | ✅ |
+| `$default` route (fallback) | ✅ |
+| Custom routes via `routeSelectionExpression` | ✅ |
+| Route response selection expression | ✅ |
+| Lambda REQUEST authorizer on `$connect` | ✅ |
+| Identity source validation (header/querystring) | ✅ |
+| `@connections` POST (send message to client) | ✅ |
+| `@connections` GET (get connection info) | ✅ |
+| `@connections` DELETE (disconnect client) | ✅ |
+| Stage variable substitution in integration URIs | ✅ |
+| AWS_PROXY integration (Lambda) | ✅ |
+| AWS integration (Lambda with VTL templates) | ✅ |
+| HTTP_PROXY integration | ✅ |
+| HTTP integration (with VTL templates) | ✅ |
+| MOCK integration | ✅ |
+| GoneException (410) for disconnected connections | ✅ |
+| Binary frame support (`isBase64Encoded: true`) | ✅ |
+| `$connect` response headers propagation | ✅ |
+| 128 KB payload size limit enforcement | ✅ |
+| 10-minute idle timeout | ✅ |
+| 2-hour max connection duration | ✅ |
+
+#### @connections Management API
+
+The `@connections` API allows server-side code (e.g., Lambda functions) to send messages to connected clients, retrieve connection metadata, or disconnect clients:
+
+```
+POST /execute-api/{apiId}/{stageName}/@connections/{connectionId} — Send message
+GET /execute-api/{apiId}/{stageName}/@connections/{connectionId} — Get connection info
+DELETE /execute-api/{apiId}/{stageName}/@connections/{connectionId} — Disconnect client
+```
+
+#### Behavior Notes
+
+- **Connection URL**: Floci uses `ws://localhost:4566/ws/{apiId}/{stage}` instead of AWS's `wss://{api-id}.execute-api.{region}.amazonaws.com/{stage}`.
+- **Idle timeout**: 10 minutes (matching AWS default). Not configurable per-API.
+- **Max connection duration**: 2 hours (matching AWS). Connections are closed automatically.
+- **Payload size limit**: 128 KB per frame (matching AWS). Oversized messages receive an error frame.
+
### Not Implemented
-- WebSocket data-plane: actual WebSocket connection handling, `@connections` management API
- `ReimportApi`, `ExportApi`, `GetApiMapping`, `CreateApiMapping`, `DeleteApiMapping`
- `GetDomainName`, `CreateDomainName`, `DeleteDomainName`
- `CreateVpcLink`, `GetVpcLink`, `GetVpcLinks`, `UpdateVpcLink`, `DeleteVpcLink`
@@ -213,4 +264,17 @@ aws apigatewayv2 create-stage \
--api-id $WS_API_ID \
--stage-name prod \
--endpoint-url $AWS_ENDPOINT_URL
+
+# Connect via WebSocket (using wscat or any WebSocket client)
+# wscat -c ws://localhost:4566/ws/$WS_API_ID/prod
+
+# Send a message to a connected client via @connections API
+# curl -X POST http://localhost:4566/execute-api/$WS_API_ID/prod/@connections/$CONNECTION_ID \
+# -d "Hello from server"
+
+# Get connection info
+# curl http://localhost:4566/execute-api/$WS_API_ID/prod/@connections/$CONNECTION_ID
+
+# Disconnect a client
+# curl -X DELETE http://localhost:4566/execute-api/$WS_API_ID/prod/@connections/$CONNECTION_ID
```
diff --git a/docs/services/index.md b/docs/services/index.md
index 2d531e0075..3ea1360e8a 100644
--- a/docs/services/index.md
+++ b/docs/services/index.md
@@ -18,7 +18,7 @@ Operation counts are exact. For dispatch-table services (Query and JSON 1.1) eac
| [DynamoDB Streams](dynamodb.md#streams) | `POST /` + `X-Amz-Target: DynamoDBStreams_20120810.*` | JSON 1.1 | 4 |
| [Lambda](lambda.md) | `/2015-03-31/functions/...` | REST JSON | 30 |
| [API Gateway v1](api-gateway.md) | `/restapis/...` | REST JSON | 62 |
-| [API Gateway v2](api-gateway.md#v2) | `/v2/apis/...` | REST JSON | 48 |
+| [API Gateway v2](api-gateway.md#v2) | `/v2/apis/...` | REST JSON | 48 + data-plane |
| [IAM](iam.md) | `POST /` with `Action=` param | Query | 68 |
| [STS](sts.md) | `POST /` with `Action=` param | Query | 7 |
| [Cognito](cognito.md) | `POST /` + `X-Amz-Target: AWSCognitoIdentityProviderService.*` | JSON 1.1 | 43 |
diff --git a/src/main/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayController.java b/src/main/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayController.java
index c27ff237ee..ac3bb9172d 100644
--- a/src/main/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayController.java
+++ b/src/main/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayController.java
@@ -1578,6 +1578,23 @@ public class ApiGatewayController {
node.put("integrationType", i.getIntegrationType());
node.put("payloadFormatVersion", i.getPayloadFormatVersion());
if (i.getIntegrationUri() != null) node.put("integrationUri", i.getIntegrationUri());
+ if (i.getRequestTemplates() != null) {
+ ObjectNode requestTemplates = node.putObject("requestTemplates");
+ i.getRequestTemplates().forEach(requestTemplates::put);
+ }
+ if (i.getResponseTemplates() != null) {
+ ObjectNode responseTemplates = node.putObject("responseTemplates");
+ i.getResponseTemplates().forEach(responseTemplates::put);
+ }
+ if (i.getTemplateSelectionExpression() != null) {
+ node.put("templateSelectionExpression", i.getTemplateSelectionExpression());
+ }
+ if (i.getIntegrationMethod() != null) {
+ node.put("integrationMethod", i.getIntegrationMethod());
+ }
+ if (i.getTimeoutInMillis() != 0) {
+ node.put("timeoutInMillis", i.getTimeoutInMillis());
+ }
return node;
}
@@ -1588,6 +1605,10 @@ public class ApiGatewayController {
node.put("autoDeploy", s.isAutoDeploy());
node.put("createdDate", java.time.Instant.ofEpochMilli(s.getCreatedDate()).toString());
node.put("lastUpdatedDate", java.time.Instant.ofEpochMilli(s.getLastUpdatedDate()).toString());
+ if (s.getStageVariables() != null) {
+ ObjectNode stageVariables = node.putObject("stageVariables");
+ s.getStageVariables().forEach(stageVariables::put);
+ }
return node;
}
@@ -1619,6 +1640,15 @@ public class ApiGatewayController {
jwt.put("issuer", a.getJwtConfiguration().issuer());
}
}
+ if (a.getAuthorizerUri() != null) {
+ node.put("authorizerUri", a.getAuthorizerUri());
+ }
+ if (a.getAuthorizerPayloadFormatVersion() != null) {
+ node.put("authorizerPayloadFormatVersion", a.getAuthorizerPayloadFormatVersion());
+ }
+ if (a.getAuthorizerResultTtlInSeconds() != null) {
+ node.put("authorizerResultTtlInSeconds", a.getAuthorizerResultTtlInSeconds());
+ }
return node;
}
diff --git a/src/main/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayExecuteController.java b/src/main/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayExecuteController.java
index 826925c7ff..79e259e982 100644
--- a/src/main/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayExecuteController.java
+++ b/src/main/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayExecuteController.java
@@ -1,6 +1,7 @@
package io.github.hectorvent.floci.services.apigateway;
import io.github.hectorvent.floci.core.common.AwsArnUtils;
+import io.github.hectorvent.floci.core.common.AwsErrorResponse;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.common.RegionResolver;
import io.github.hectorvent.floci.services.apigateway.model.ApiGatewayResource;
@@ -10,6 +11,9 @@ import io.github.hectorvent.floci.services.apigateway.model.MethodConfig;
import io.github.hectorvent.floci.services.apigatewayv2.ApiGatewayV2Service;
import io.github.hectorvent.floci.services.apigatewayv2.model.Authorizer;
import io.github.hectorvent.floci.services.apigatewayv2.model.Route;
+import io.github.hectorvent.floci.services.apigatewayv2.websocket.ConnectionInfo;
+import io.github.hectorvent.floci.services.apigatewayv2.websocket.WebSocketConnectionManager;
+import io.github.hectorvent.floci.services.lambda.LambdaArnUtils;
import io.github.hectorvent.floci.services.lambda.LambdaService;
import io.github.hectorvent.floci.services.lambda.model.InvocationType;
import io.github.hectorvent.floci.services.lambda.model.InvokeResult;
@@ -23,7 +27,9 @@ import jakarta.ws.rs.*;
import jakarta.ws.rs.core.*;
import org.jboss.logging.Logger;
+import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
+import java.time.Instant;
import java.util.Base64;
import java.util.HashMap;
import java.util.List;
@@ -55,12 +61,14 @@ public class ApiGatewayExecuteController {
private final ObjectMapper objectMapper;
private final VtlTemplateEngine vtlEngine;
private final AwsServiceRouter serviceRouter;
+ private final WebSocketConnectionManager webSocketConnectionManager;
@Inject
public ApiGatewayExecuteController(ApiGatewayService apiGatewayService, ApiGatewayV2Service apiGatewayV2Service,
LambdaService lambdaService, RegionResolver regionResolver,
ObjectMapper objectMapper, VtlTemplateEngine vtlEngine,
- AwsServiceRouter serviceRouter) {
+ AwsServiceRouter serviceRouter,
+ WebSocketConnectionManager webSocketConnectionManager) {
this.apiGatewayService = apiGatewayService;
this.apiGatewayV2Service = apiGatewayV2Service;
this.lambdaService = lambdaService;
@@ -68,16 +76,80 @@ public class ApiGatewayExecuteController {
this.objectMapper = objectMapper;
this.vtlEngine = vtlEngine;
this.serviceRouter = serviceRouter;
+ this.webSocketConnectionManager = webSocketConnectionManager;
}
private record AuthorizerResult(Response errorResponse, String principalId, Map context) {}
+ // ──────────────────────────── @connections API ────────────────────────────
+
+ private static final String CONNECTIONS_PREFIX = "@connections/";
+
+ private String decodeConnectionId(String rawConnectionId) {
+ return URLDecoder.decode(rawConnectionId, StandardCharsets.UTF_8);
+ }
+
+ /** Maximum payload size for @connections POST (128 KB, matching AWS limit). */
+ private static final int MAX_CONNECTIONS_PAYLOAD_BYTES = 128 * 1024;
+
+ private Response handlePostToConnection(String connectionId, byte[] body) {
+ if (body != null && body.length > MAX_CONNECTIONS_PAYLOAD_BYTES) {
+ return Response.status(413)
+ .entity(new AwsErrorResponse("PayloadTooLargeException", "Payload too large"))
+ .type(MediaType.APPLICATION_JSON)
+ .build();
+ }
+ try {
+ webSocketConnectionManager.sendMessage(connectionId, new String(body, StandardCharsets.UTF_8));
+ return Response.ok().build();
+ } catch (IllegalStateException e) {
+ return Response.status(410)
+ .entity(new AwsErrorResponse("GoneException", "GoneException"))
+ .type(MediaType.APPLICATION_JSON)
+ .build();
+ }
+ }
+
+ private Response handleGetConnectionInfo(String connectionId) {
+ ConnectionInfo info = webSocketConnectionManager.getConnectionInfo(connectionId);
+ if (info == null) {
+ return Response.status(410)
+ .entity(new AwsErrorResponse("GoneException", "GoneException"))
+ .type(MediaType.APPLICATION_JSON)
+ .build();
+ }
+ String connectedAt = Instant.ofEpochMilli(info.getConnectedAt()).toString();
+ String lastActiveAt = Instant.ofEpochMilli(info.getLastActiveAt()).toString();
+ String sourceIp = info.getSourceIp() != null ? info.getSourceIp() : "127.0.0.1";
+ String userAgent = info.getUserAgent() != null ? info.getUserAgent() : "";
+ String responseBody = String.format(
+ "{\"connectedAt\":\"%s\",\"lastActiveAt\":\"%s\",\"identity\":{\"sourceIp\":\"%s\",\"userAgent\":\"%s\"}}",
+ connectedAt, lastActiveAt, sourceIp, userAgent);
+ return Response.ok(responseBody).type(MediaType.APPLICATION_JSON).build();
+ }
+
+ private Response handleDeleteConnection(String connectionId) {
+ try {
+ webSocketConnectionManager.closeConnection(connectionId);
+ return Response.noContent().build();
+ } catch (IllegalStateException e) {
+ return Response.status(410)
+ .entity(new AwsErrorResponse("GoneException", "GoneException"))
+ .type(MediaType.APPLICATION_JSON)
+ .build();
+ }
+ }
+
@GET
@Path("/{proxy: .*}")
public Response handleGet(@Context HttpHeaders headers, @Context UriInfo uriInfo,
@PathParam("apiId") String apiId,
@PathParam("stageName") String stageName,
@PathParam("proxy") String proxy) {
+ if (proxy != null && proxy.startsWith(CONNECTIONS_PREFIX)) {
+ String connectionId = decodeConnectionId(proxy.substring(CONNECTIONS_PREFIX.length()));
+ return handleGetConnectionInfo(connectionId);
+ }
return dispatch("GET", apiId, stageName, proxy, headers, uriInfo, null);
}
@@ -88,6 +160,10 @@ public class ApiGatewayExecuteController {
@PathParam("stageName") String stageName,
@PathParam("proxy") String proxy,
byte[] body) {
+ if (proxy != null && proxy.startsWith(CONNECTIONS_PREFIX)) {
+ String connectionId = decodeConnectionId(proxy.substring(CONNECTIONS_PREFIX.length()));
+ return handlePostToConnection(connectionId, body);
+ }
return dispatch("POST", apiId, stageName, proxy, headers, uriInfo, body);
}
@@ -107,6 +183,10 @@ public class ApiGatewayExecuteController {
@PathParam("apiId") String apiId,
@PathParam("stageName") String stageName,
@PathParam("proxy") String proxy) {
+ if (proxy != null && proxy.startsWith(CONNECTIONS_PREFIX)) {
+ String connectionId = decodeConnectionId(proxy.substring(CONNECTIONS_PREFIX.length()));
+ return handleDeleteConnection(connectionId);
+ }
return dispatch("DELETE", apiId, stageName, proxy, headers, uriInfo, null);
}
@@ -391,29 +471,10 @@ public class ApiGatewayExecuteController {
/**
* Extracts function name from integration URI like
* {@code arn:aws:apigateway:...:lambda:path/2015-03-31/functions/{fnArn}/invocations}.
+ * Delegates to {@link LambdaArnUtils#extractFunctionNameFromUri(String)}.
*/
private String functionNameFromUri(String uri) {
- if (uri == null) {
- return null;
- }
- // URI contains "function:{name}" or "function:{arn}"
- int idx = uri.indexOf("function:");
- if (idx < 0) {
- return null;
- }
- String after = uri.substring(idx + "function:".length());
- // after may be "myFn/invocations" or "arn:aws:lambda:...:function:myFn/invocations"
- // If it starts with "arn:" recurse on the remaining ARN
- if (after.startsWith("arn:")) {
- int fnIdx = after.lastIndexOf(":function:");
- if (fnIdx < 0) {
- return null;
- }
- after = after.substring(fnIdx + ":function:".length());
- }
- // Strip trailing "/invocations" or any path suffix
- int slash = after.indexOf('/');
- return slash >= 0 ? after.substring(0, slash) : after;
+ return LambdaArnUtils.extractFunctionNameFromUri(uri);
}
private String buildProxyEvent(String httpMethod, String path, String proxy,
diff --git a/src/main/java/io/github/hectorvent/floci/services/apigatewayv2/ApiGatewayV2JsonHandler.java b/src/main/java/io/github/hectorvent/floci/services/apigatewayv2/ApiGatewayV2JsonHandler.java
index f0a06c07cc..58145350a8 100644
--- a/src/main/java/io/github/hectorvent/floci/services/apigatewayv2/ApiGatewayV2JsonHandler.java
+++ b/src/main/java/io/github/hectorvent/floci/services/apigatewayv2/ApiGatewayV2JsonHandler.java
@@ -530,6 +530,15 @@ public class ApiGatewayV2JsonHandler {
auth.getJwtConfiguration().audience().forEach(aud::add);
}
}
+ if (auth.getAuthorizerUri() != null) {
+ node.put("AuthorizerUri", auth.getAuthorizerUri());
+ }
+ if (auth.getAuthorizerPayloadFormatVersion() != null) {
+ node.put("AuthorizerPayloadFormatVersion", auth.getAuthorizerPayloadFormatVersion());
+ }
+ if (auth.getAuthorizerResultTtlInSeconds() != null) {
+ node.put("AuthorizerResultTtlInSeconds", auth.getAuthorizerResultTtlInSeconds());
+ }
return node;
}
@@ -552,6 +561,23 @@ public class ApiGatewayV2JsonHandler {
node.put("IntegrationType", i.getIntegrationType());
node.put("PayloadFormatVersion", i.getPayloadFormatVersion());
if (i.getIntegrationUri() != null) node.put("IntegrationUri", i.getIntegrationUri());
+ if (i.getRequestTemplates() != null) {
+ ObjectNode requestTemplates = node.putObject("RequestTemplates");
+ i.getRequestTemplates().forEach(requestTemplates::put);
+ }
+ if (i.getResponseTemplates() != null) {
+ ObjectNode responseTemplates = node.putObject("ResponseTemplates");
+ i.getResponseTemplates().forEach(responseTemplates::put);
+ }
+ if (i.getTemplateSelectionExpression() != null) {
+ node.put("TemplateSelectionExpression", i.getTemplateSelectionExpression());
+ }
+ if (i.getIntegrationMethod() != null) {
+ node.put("IntegrationMethod", i.getIntegrationMethod());
+ }
+ if (i.getTimeoutInMillis() != 0) {
+ node.put("TimeoutInMillis", i.getTimeoutInMillis());
+ }
return node;
}
@@ -562,6 +588,10 @@ public class ApiGatewayV2JsonHandler {
node.put("CreatedDate", s.getCreatedDate() / 1000.0);
node.put("LastUpdatedDate", s.getLastUpdatedDate() / 1000.0);
if (s.getDeploymentId() != null) node.put("DeploymentId", s.getDeploymentId());
+ if (s.getStageVariables() != null) {
+ ObjectNode stageVariables = node.putObject("StageVariables");
+ s.getStageVariables().forEach(stageVariables::put);
+ }
return node;
}
diff --git a/src/main/java/io/github/hectorvent/floci/services/apigatewayv2/ApiGatewayV2Service.java b/src/main/java/io/github/hectorvent/floci/services/apigatewayv2/ApiGatewayV2Service.java
index beb4a6ecde..b2621576b4 100644
--- a/src/main/java/io/github/hectorvent/floci/services/apigatewayv2/ApiGatewayV2Service.java
+++ b/src/main/java/io/github/hectorvent/floci/services/apigatewayv2/ApiGatewayV2Service.java
@@ -170,8 +170,14 @@ public class ApiGatewayV2Service {
auth.setJwtConfiguration(new Authorizer.JwtConfiguration(audience, issuer));
}
+ auth.setAuthorizerUri((String) request.get("authorizerUri"));
+ auth.setAuthorizerPayloadFormatVersion((String) request.get("authorizerPayloadFormatVersion"));
+ if (request.get("authorizerResultTtlInSeconds") != null) {
+ auth.setAuthorizerResultTtlInSeconds(((Number) request.get("authorizerResultTtlInSeconds")).intValue());
+ }
+
authorizerStore.put(authorizerKey(region, apiId, auth.getAuthorizerId()), auth);
- LOG.infov("Created JWT authorizer: {0} ({1}) for API {2}", auth.getName(), auth.getAuthorizerId(), apiId);
+ LOG.infov("Created authorizer: {0} ({1}) for API {2}", auth.getName(), auth.getAuthorizerId(), apiId);
return auth;
}
@@ -218,6 +224,15 @@ public class ApiGatewayV2Service {
String issuer = (String) jwtConfig.get("issuer");
auth.setJwtConfiguration(new Authorizer.JwtConfiguration(audience, issuer));
}
+ if (request.containsKey("authorizerUri") && request.get("authorizerUri") != null) {
+ auth.setAuthorizerUri((String) request.get("authorizerUri"));
+ }
+ if (request.containsKey("authorizerPayloadFormatVersion") && request.get("authorizerPayloadFormatVersion") != null) {
+ auth.setAuthorizerPayloadFormatVersion((String) request.get("authorizerPayloadFormatVersion"));
+ }
+ if (request.containsKey("authorizerResultTtlInSeconds") && request.get("authorizerResultTtlInSeconds") != null) {
+ auth.setAuthorizerResultTtlInSeconds(((Number) request.get("authorizerResultTtlInSeconds")).intValue());
+ }
authorizerStore.put(authorizerKey(region, apiId, authorizerId), auth);
return auth;
@@ -304,6 +319,20 @@ public class ApiGatewayV2Service {
return null;
}
+ /**
+ * Finds a route by its exact routeKey (e.g. "$connect", "$disconnect", "$default").
+ * Returns null if no route with the given key exists on the API.
+ */
+ public Route findRouteByKey(String region, String apiId, String routeKey) {
+ List routes = getRoutes(region, apiId);
+ for (Route r : routes) {
+ if (routeKey.equals(r.getRouteKey())) {
+ return r;
+ }
+ }
+ return null;
+ }
+
private boolean routeKeyMatchesPath(String routeKey, String httpMethod, String path) {
int space = routeKey.indexOf(' ');
if (space < 0) return false;
@@ -335,6 +364,20 @@ public class ApiGatewayV2Service {
integration.setIntegrationType((String) request.get("integrationType"));
integration.setIntegrationUri((String) request.get("integrationUri"));
integration.setPayloadFormatVersion((String) request.getOrDefault("payloadFormatVersion", "2.0"));
+ integration.setIntegrationMethod((String) request.get("integrationMethod"));
+ integration.setTemplateSelectionExpression((String) request.get("templateSelectionExpression"));
+
+ if (request.get("timeoutInMillis") != null) {
+ integration.setTimeoutInMillis(((Number) request.get("timeoutInMillis")).intValue());
+ }
+
+ @SuppressWarnings("unchecked")
+ Map requestTemplates = (Map) request.get("requestTemplates");
+ integration.setRequestTemplates(requestTemplates);
+
+ @SuppressWarnings("unchecked")
+ Map responseTemplates = (Map) request.get("responseTemplates");
+ integration.setResponseTemplates(responseTemplates);
integrationStore.put(integrationKey(region, apiId, integration.getIntegrationId()), integration);
return integration;
@@ -368,6 +411,25 @@ public class ApiGatewayV2Service {
if (request.containsKey("payloadFormatVersion") && request.get("payloadFormatVersion") != null) {
integration.setPayloadFormatVersion((String) request.get("payloadFormatVersion"));
}
+ if (request.containsKey("integrationMethod") && request.get("integrationMethod") != null) {
+ integration.setIntegrationMethod((String) request.get("integrationMethod"));
+ }
+ if (request.containsKey("templateSelectionExpression") && request.get("templateSelectionExpression") != null) {
+ integration.setTemplateSelectionExpression((String) request.get("templateSelectionExpression"));
+ }
+ if (request.containsKey("timeoutInMillis") && request.get("timeoutInMillis") != null) {
+ integration.setTimeoutInMillis(((Number) request.get("timeoutInMillis")).intValue());
+ }
+ if (request.containsKey("requestTemplates") && request.get("requestTemplates") != null) {
+ @SuppressWarnings("unchecked")
+ Map requestTemplates = (Map) request.get("requestTemplates");
+ integration.setRequestTemplates(requestTemplates);
+ }
+ if (request.containsKey("responseTemplates") && request.get("responseTemplates") != null) {
+ @SuppressWarnings("unchecked")
+ Map responseTemplates = (Map) request.get("responseTemplates");
+ integration.setResponseTemplates(responseTemplates);
+ }
integrationStore.put(integrationKey(region, apiId, integrationId), integration);
return integration;
@@ -384,6 +446,10 @@ public class ApiGatewayV2Service {
stage.setCreatedDate(System.currentTimeMillis());
stage.setLastUpdatedDate(System.currentTimeMillis());
+ @SuppressWarnings("unchecked")
+ Map stageVariables = (Map) request.get("stageVariables");
+ stage.setStageVariables(stageVariables);
+
stageStore.put(stageKey(region, apiId, stage.getStageName()), stage);
LOG.infov("Created stage: {0} for API {1}", stage.getStageName(), apiId);
return stage;
@@ -414,6 +480,11 @@ public class ApiGatewayV2Service {
if (request.containsKey("autoDeploy") && request.get("autoDeploy") != null) {
stage.setAutoDeploy(Boolean.parseBoolean(String.valueOf(request.get("autoDeploy"))));
}
+ if (request.containsKey("stageVariables") && request.get("stageVariables") != null) {
+ @SuppressWarnings("unchecked")
+ Map stageVariables = (Map) request.get("stageVariables");
+ stage.setStageVariables(stageVariables);
+ }
stage.setLastUpdatedDate(System.currentTimeMillis());
stageStore.put(stageKey(region, apiId, stageName), stage);
diff --git a/src/main/java/io/github/hectorvent/floci/services/apigatewayv2/model/Authorizer.java b/src/main/java/io/github/hectorvent/floci/services/apigatewayv2/model/Authorizer.java
index e5bd8ad774..b7d17b2523 100644
--- a/src/main/java/io/github/hectorvent/floci/services/apigatewayv2/model/Authorizer.java
+++ b/src/main/java/io/github/hectorvent/floci/services/apigatewayv2/model/Authorizer.java
@@ -13,6 +13,9 @@ public class Authorizer {
private String name;
private JwtConfiguration jwtConfiguration;
private List identitySource;
+ private String authorizerUri;
+ private String authorizerPayloadFormatVersion;
+ private Integer authorizerResultTtlInSeconds;
public Authorizer() {}
@@ -31,6 +34,15 @@ public class Authorizer {
public List getIdentitySource() { return identitySource; }
public void setIdentitySource(List identitySource) { this.identitySource = identitySource; }
+ public String getAuthorizerUri() { return authorizerUri; }
+ public void setAuthorizerUri(String authorizerUri) { this.authorizerUri = authorizerUri; }
+
+ public String getAuthorizerPayloadFormatVersion() { return authorizerPayloadFormatVersion; }
+ public void setAuthorizerPayloadFormatVersion(String authorizerPayloadFormatVersion) { this.authorizerPayloadFormatVersion = authorizerPayloadFormatVersion; }
+
+ public Integer getAuthorizerResultTtlInSeconds() { return authorizerResultTtlInSeconds; }
+ public void setAuthorizerResultTtlInSeconds(Integer authorizerResultTtlInSeconds) { this.authorizerResultTtlInSeconds = authorizerResultTtlInSeconds; }
+
@RegisterForReflection
public record JwtConfiguration(List audience, String issuer) {}
}
diff --git a/src/main/java/io/github/hectorvent/floci/services/apigatewayv2/model/Integration.java b/src/main/java/io/github/hectorvent/floci/services/apigatewayv2/model/Integration.java
index ff1fb7b897..accaf1e1be 100644
--- a/src/main/java/io/github/hectorvent/floci/services/apigatewayv2/model/Integration.java
+++ b/src/main/java/io/github/hectorvent/floci/services/apigatewayv2/model/Integration.java
@@ -3,6 +3,8 @@ package io.github.hectorvent.floci.services.apigatewayv2.model;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import io.quarkus.runtime.annotations.RegisterForReflection;
+import java.util.Map;
+
@RegisterForReflection
@JsonIgnoreProperties(ignoreUnknown = true)
public class Integration {
@@ -12,6 +14,9 @@ public class Integration {
private String payloadFormatVersion; // 1.0, 2.0
private String integrationMethod;
private int timeoutInMillis;
+ private Map requestTemplates;
+ private Map responseTemplates;
+ private String templateSelectionExpression;
public Integration() {}
@@ -32,4 +37,13 @@ public class Integration {
public int getTimeoutInMillis() { return timeoutInMillis; }
public void setTimeoutInMillis(int timeoutInMillis) { this.timeoutInMillis = timeoutInMillis; }
+
+ public Map getRequestTemplates() { return requestTemplates; }
+ public void setRequestTemplates(Map requestTemplates) { this.requestTemplates = requestTemplates; }
+
+ public Map getResponseTemplates() { return responseTemplates; }
+ public void setResponseTemplates(Map responseTemplates) { this.responseTemplates = responseTemplates; }
+
+ public String getTemplateSelectionExpression() { return templateSelectionExpression; }
+ public void setTemplateSelectionExpression(String templateSelectionExpression) { this.templateSelectionExpression = templateSelectionExpression; }
}
diff --git a/src/main/java/io/github/hectorvent/floci/services/apigatewayv2/model/Stage.java b/src/main/java/io/github/hectorvent/floci/services/apigatewayv2/model/Stage.java
index ae63713400..8f5cc9fa71 100644
--- a/src/main/java/io/github/hectorvent/floci/services/apigatewayv2/model/Stage.java
+++ b/src/main/java/io/github/hectorvent/floci/services/apigatewayv2/model/Stage.java
@@ -3,6 +3,8 @@ package io.github.hectorvent.floci.services.apigatewayv2.model;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import io.quarkus.runtime.annotations.RegisterForReflection;
+import java.util.Map;
+
@RegisterForReflection
@JsonIgnoreProperties(ignoreUnknown = true)
public class Stage {
@@ -11,6 +13,7 @@ public class Stage {
private boolean autoDeploy;
private long createdDate;
private long lastUpdatedDate;
+ private Map stageVariables;
public Stage() {}
@@ -28,4 +31,7 @@ public class Stage {
public long getLastUpdatedDate() { return lastUpdatedDate; }
public void setLastUpdatedDate(long lastUpdatedDate) { this.lastUpdatedDate = lastUpdatedDate; }
+
+ public Map getStageVariables() { return stageVariables; }
+ public void setStageVariables(Map stageVariables) { this.stageVariables = stageVariables; }
}
diff --git a/src/main/java/io/github/hectorvent/floci/services/apigatewayv2/websocket/ConnectionInfo.java b/src/main/java/io/github/hectorvent/floci/services/apigatewayv2/websocket/ConnectionInfo.java
new file mode 100644
index 0000000000..6ddb3863d7
--- /dev/null
+++ b/src/main/java/io/github/hectorvent/floci/services/apigatewayv2/websocket/ConnectionInfo.java
@@ -0,0 +1,55 @@
+package io.github.hectorvent.floci.services.apigatewayv2.websocket;
+
+import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
+import io.quarkus.runtime.annotations.RegisterForReflection;
+
+@RegisterForReflection
+@JsonIgnoreProperties(ignoreUnknown = true)
+public class ConnectionInfo {
+ private String connectionId;
+ private String apiId;
+ private String stageName;
+ private String region;
+ private long connectedAt;
+ private long lastActiveAt;
+ private String sourceIp;
+ private String userAgent;
+
+ public ConnectionInfo() {}
+
+ public ConnectionInfo(String connectionId, String apiId, String stageName, String region,
+ long connectedAt, long lastActiveAt, String sourceIp, String userAgent) {
+ this.connectionId = connectionId;
+ this.apiId = apiId;
+ this.stageName = stageName;
+ this.region = region;
+ this.connectedAt = connectedAt;
+ this.lastActiveAt = lastActiveAt;
+ this.sourceIp = sourceIp;
+ this.userAgent = userAgent;
+ }
+
+ public String getConnectionId() { return connectionId; }
+ public void setConnectionId(String connectionId) { this.connectionId = connectionId; }
+
+ public String getApiId() { return apiId; }
+ public void setApiId(String apiId) { this.apiId = apiId; }
+
+ public String getStageName() { return stageName; }
+ public void setStageName(String stageName) { this.stageName = stageName; }
+
+ public String getRegion() { return region; }
+ public void setRegion(String region) { this.region = region; }
+
+ public long getConnectedAt() { return connectedAt; }
+ public void setConnectedAt(long connectedAt) { this.connectedAt = connectedAt; }
+
+ public long getLastActiveAt() { return lastActiveAt; }
+ public void setLastActiveAt(long lastActiveAt) { this.lastActiveAt = lastActiveAt; }
+
+ public String getSourceIp() { return sourceIp; }
+ public void setSourceIp(String sourceIp) { this.sourceIp = sourceIp; }
+
+ public String getUserAgent() { return userAgent; }
+ public void setUserAgent(String userAgent) { this.userAgent = userAgent; }
+}
diff --git a/src/main/java/io/github/hectorvent/floci/services/apigatewayv2/websocket/RouteSelectionEvaluator.java b/src/main/java/io/github/hectorvent/floci/services/apigatewayv2/websocket/RouteSelectionEvaluator.java
new file mode 100644
index 0000000000..ab563c7579
--- /dev/null
+++ b/src/main/java/io/github/hectorvent/floci/services/apigatewayv2/websocket/RouteSelectionEvaluator.java
@@ -0,0 +1,79 @@
+package io.github.hectorvent.floci.services.apigatewayv2.websocket;
+
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import jakarta.enterprise.context.ApplicationScoped;
+import jakarta.inject.Inject;
+import org.jboss.logging.Logger;
+
+/**
+ * Evaluates the API's routeSelectionExpression against a message payload
+ * to determine which route to invoke.
+ *
+ * Supports the $request.body.{fieldName} expression format, extracting
+ * the named top-level JSON field from the message body.
+ */
+@ApplicationScoped
+public class RouteSelectionEvaluator {
+
+ private static final Logger LOG = Logger.getLogger(RouteSelectionEvaluator.class);
+ private static final String EXPRESSION_PREFIX = "$request.body.";
+
+ @Inject
+ ObjectMapper objectMapper;
+
+ /**
+ * Extracts the route key from a message using the route selection expression.
+ *
+ * @param routeSelectionExpression the expression (e.g. "$request.body.action")
+ * @param messageBody the raw message body (expected to be JSON)
+ * @return the extracted route key, or null if extraction fails
+ */
+ public String evaluate(String routeSelectionExpression, String messageBody) {
+ if (routeSelectionExpression == null || messageBody == null) {
+ return null;
+ }
+
+ String fieldName = parseFieldName(routeSelectionExpression);
+ if (fieldName == null) {
+ return null;
+ }
+
+ try {
+ JsonNode root = objectMapper.readTree(messageBody);
+ JsonNode fieldNode = root.get(fieldName);
+ if (fieldNode == null || fieldNode.isMissingNode()) {
+ return null;
+ }
+
+ if (fieldNode.isTextual()) {
+ return fieldNode.asText();
+ }
+
+ // For non-string values (number, boolean, object, array), convert to string
+ return fieldNode.asText();
+ } catch (Exception e) {
+ LOG.debugv("Failed to parse message body as JSON: {0}", e.getMessage());
+ return null;
+ }
+ }
+
+ /**
+ * Parses a $request.body.{fieldName} expression and returns the field name.
+ *
+ * @param expression the route selection expression
+ * @return the field name, or null if the expression format is not recognized
+ */
+ String parseFieldName(String expression) {
+ if (expression == null || !expression.startsWith(EXPRESSION_PREFIX)) {
+ return null;
+ }
+
+ String fieldName = expression.substring(EXPRESSION_PREFIX.length());
+ if (fieldName.isEmpty()) {
+ return null;
+ }
+
+ return fieldName;
+ }
+}
diff --git a/src/main/java/io/github/hectorvent/floci/services/apigatewayv2/websocket/WebSocketAuthorizerService.java b/src/main/java/io/github/hectorvent/floci/services/apigatewayv2/websocket/WebSocketAuthorizerService.java
new file mode 100644
index 0000000000..ecf9ad9272
--- /dev/null
+++ b/src/main/java/io/github/hectorvent/floci/services/apigatewayv2/websocket/WebSocketAuthorizerService.java
@@ -0,0 +1,233 @@
+package io.github.hectorvent.floci.services.apigatewayv2.websocket;
+
+import com.fasterxml.jackson.core.type.TypeReference;
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import io.github.hectorvent.floci.services.apigatewayv2.ApiGatewayV2Service;
+import io.github.hectorvent.floci.services.apigatewayv2.model.Authorizer;
+import io.github.hectorvent.floci.services.lambda.LambdaArnUtils;
+import io.github.hectorvent.floci.services.lambda.LambdaService;
+import io.github.hectorvent.floci.services.lambda.model.InvocationType;
+import io.github.hectorvent.floci.services.lambda.model.InvokeResult;
+import jakarta.enterprise.context.ApplicationScoped;
+import jakarta.inject.Inject;
+import org.jboss.logging.Logger;
+
+import java.util.List;
+import java.util.Map;
+
+/**
+ * Service responsible for invoking and evaluating Lambda REQUEST authorizers
+ * for WebSocket $connect routes.
+ *
+ * Extracted from WebSocketHandler to keep the handler thin (controller responsibility)
+ * and make authorizer logic independently testable.
+ */
+@ApplicationScoped
+public class WebSocketAuthorizerService {
+
+ private static final Logger LOG = Logger.getLogger(WebSocketAuthorizerService.class);
+ private static final TypeReference