Light, fluffy, and always free - The AWS Local Emulator alternative
feat(apigatewayv2): Add WebSocket data-plane support (#712)
Dixit R Jain3ae5c7b467a4
diff --git a/compatibility-tests/sdk-test-java/pom.xml b/compatibility-tests/sdk-test-java/pom.xmlindex 087f7378fe..fab2edc598 100644--- a/compatibility-tests/sdk-test-java/pom.xml+++ b/compatibility-tests/sdk-test-java/pom.xml@@ -90,6 +90,10 @@<groupId>software.amazon.awssdk</groupId><artifactId>apigatewayv2</artifactId></dependency>+ <dependency>+ <groupId>software.amazon.awssdk</groupId>+ <artifactId>apigatewaymanagementapi</artifactId>+ </dependency><dependency><groupId>software.amazon.awssdk</groupId><artifactId>kms</artifactId>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.javanew file mode 100644index 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<String> createdApis = new ArrayList<>();+ private static final List<String> 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<String, String> 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<String, String> 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<WebSocket> 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<Integer> 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<Integer> 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<String> messages = new LinkedBlockingQueue<>();+ private final StringBuilder buffer = new StringBuilder();+ private volatile CompletableFuture<Integer> 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<Integer> 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.jsonindex 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.tsnew file mode 100644index 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<WebSocket> {+ 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<string> {+ 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<void> {+ 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<string, string>, bundledZip?: boolean): Promise<string> {+ 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<string> {+ 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<string> {+ 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<string, string>): Promise<void> {+ 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<string | null> {+ 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.tsindex 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.mdindex 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.mdindex 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.javaindex 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.javaindex 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;@Injectpublic 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<String, Object> 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.javaindex 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.javaindex 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<Route> 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<String, String> requestTemplates = (Map<String, String>) request.get("requestTemplates");+ integration.setRequestTemplates(requestTemplates);++ @SuppressWarnings("unchecked")+ Map<String, String> responseTemplates = (Map<String, String>) 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<String, String> requestTemplates = (Map<String, String>) request.get("requestTemplates");+ integration.setRequestTemplates(requestTemplates);+ }+ if (request.containsKey("responseTemplates") && request.get("responseTemplates") != null) {+ @SuppressWarnings("unchecked")+ Map<String, String> responseTemplates = (Map<String, String>) 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<String, String> stageVariables = (Map<String, String>) 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<String, String> stageVariables = (Map<String, String>) 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.javaindex 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<String> identitySource;+ private String authorizerUri;+ private String authorizerPayloadFormatVersion;+ private Integer authorizerResultTtlInSeconds;public Authorizer() {}@@ -31,6 +34,15 @@ public class Authorizer {public List<String> getIdentitySource() { return identitySource; }public void setIdentitySource(List<String> 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; }+@RegisterForReflectionpublic record JwtConfiguration(List<String> 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.javaindex 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.0private String integrationMethod;private int timeoutInMillis;+ private Map<String, String> requestTemplates;+ private Map<String, String> 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<String, String> getRequestTemplates() { return requestTemplates; }+ public void setRequestTemplates(Map<String, String> requestTemplates) { this.requestTemplates = requestTemplates; }++ public Map<String, String> getResponseTemplates() { return responseTemplates; }+ public void setResponseTemplates(Map<String, String> 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.javaindex 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<String, String> 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<String, String> getStageVariables() { return stageVariables; }+ public void setStageVariables(Map<String, String> 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.javanew file mode 100644index 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.javanew file mode 100644index 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.javanew file mode 100644index 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<Map<String, Object>> MAP_TYPE = new TypeReference<>() {};++ private final ApiGatewayV2Service apiGatewayV2Service;+ private final LambdaService lambdaService;+ private final WebSocketProxyEventBuilder proxyEventBuilder;+ private final ObjectMapper objectMapper;++ @Inject+ public WebSocketAuthorizerService(ApiGatewayV2Service apiGatewayV2Service,+ LambdaService lambdaService,+ WebSocketProxyEventBuilder proxyEventBuilder,+ ObjectMapper objectMapper) {+ this.apiGatewayV2Service = apiGatewayV2Service;+ this.lambdaService = lambdaService;+ this.proxyEventBuilder = proxyEventBuilder;+ this.objectMapper = objectMapper;+ }++ /**+ * Result of authorizer evaluation.+ *+ * @param allowed whether the connection is allowed+ * @param statusCode HTTP status code to return if denied (403 for Deny, 500 for errors, 401 for missing identity)+ * @param context authorizer context map (may be null)+ */+ public record AuthorizerResult(boolean allowed, int statusCode, Map<String, Object> context) {++ public static AuthorizerResult allow(Map<String, Object> context) {+ return new AuthorizerResult(true, 200, context);+ }++ public static AuthorizerResult deny() {+ return new AuthorizerResult(false, 403, null);+ }++ public static AuthorizerResult unauthorized() {+ return new AuthorizerResult(false, 401, null);+ }++ public static AuthorizerResult error() {+ return new AuthorizerResult(false, 500, null);+ }+ }++ /**+ * Invoke the Lambda REQUEST authorizer for a $connect route.+ * Validates identity source values, invokes the authorizer Lambda,+ * and parses the policy document to determine Allow/Deny.+ *+ * @return AuthorizerResult indicating whether the connection is allowed+ */+ public AuthorizerResult invokeAndEvaluate(String region, String apiId, String stageName,+ String authorizerId, String connectionId, long connectedAt,+ Map<String, List<String>> headers,+ Map<String, List<String>> queryParams,+ String sourceIp, String userAgent,+ Map<String, String> stageVariables) {+ // Fetch the authorizer model+ Authorizer authorizer = apiGatewayV2Service.getAuthorizer(region, apiId, authorizerId);++ if (!"REQUEST".equals(authorizer.getAuthorizerType())) {+ // Only REQUEST type authorizers are supported for WebSocket APIs+ LOG.debugv("Authorizer {0} is not REQUEST type (is {1}), allowing by default",+ authorizerId, authorizer.getAuthorizerType());+ return AuthorizerResult.allow(null);+ }++ // Validate identity source expressions+ List<String> identitySources = authorizer.getIdentitySource();+ if (identitySources != null && !identitySources.isEmpty()) {+ for (String expression : identitySources) {+ if (expression.startsWith("$request.header.")) {+ String headerName = expression.substring("$request.header.".length());+ if (!hasHeaderValue(headers, headerName)) {+ LOG.debugv("Missing required identity source header: {0}", headerName);+ return AuthorizerResult.unauthorized();+ }+ } else if (expression.startsWith("$request.querystring.")) {+ String paramName = expression.substring("$request.querystring.".length());+ if (!hasQueryParamValue(queryParams, paramName)) {+ LOG.debugv("Missing required identity source query param: {0}", paramName);+ return AuthorizerResult.unauthorized();+ }+ }+ }+ }++ // Build the authorizer event payload+ String authorizerEventJson = proxyEventBuilder.buildAuthorizerEvent(+ connectionId, apiId, stageName, region, connectedAt,+ headers, queryParams, sourceIp, userAgent, stageVariables);++ // Extract the Lambda function name from the authorizer URI+ String functionName = extractFunctionNameFromUri(authorizer.getAuthorizerUri());+ if (functionName == null) {+ LOG.warnv("Cannot extract function name from authorizer URI: {0}",+ authorizer.getAuthorizerUri());+ return AuthorizerResult.error();+ }++ // Invoke the authorizer Lambda+ InvokeResult invokeResult;+ try {+ invokeResult = lambdaService.invoke(region, functionName,+ authorizerEventJson.getBytes(), InvocationType.RequestResponse);+ } catch (Exception e) {+ LOG.warnv("Lambda authorizer invocation failed for API {0}: {1}", apiId, e.getMessage());+ return AuthorizerResult.error();+ }++ // Parse the policy document+ return parseAuthorizerResponse(invokeResult, apiId);+ }++ /**+ * Parse the authorizer Lambda response and extract the policy decision.+ */+ private AuthorizerResult parseAuthorizerResponse(InvokeResult invokeResult, String apiId) {+ // Check for function error+ if (invokeResult.getFunctionError() != null) {+ LOG.warnv("Lambda authorizer returned function error for API {0}: {1}",+ apiId, invokeResult.getFunctionError());+ return AuthorizerResult.error();+ }++ byte[] payload = invokeResult.getPayload();+ if (payload == null || payload.length == 0) {+ LOG.warnv("Lambda authorizer returned empty payload for API {0}", apiId);+ return AuthorizerResult.error();+ }++ try {+ JsonNode policy = objectMapper.readTree(payload);+ JsonNode policyDocument = policy.path("policyDocument");+ if (policyDocument.isMissingNode() || policyDocument.isNull()) {+ LOG.warnv("Authorizer response missing policyDocument for API {0}", apiId);+ return AuthorizerResult.error();+ }++ JsonNode statements = policyDocument.path("Statement");+ if (statements.isMissingNode() || statements.isNull()+ || !statements.isArray() || statements.isEmpty()) {+ LOG.warnv("Authorizer response missing or empty Statement array for API {0}", apiId);+ return AuthorizerResult.error();+ }++ String effect = statements.get(0).path("Effect").asText("Deny");+ if ("Deny".equalsIgnoreCase(effect)) {+ return AuthorizerResult.deny();+ }++ if (!"Allow".equalsIgnoreCase(effect)) {+ LOG.warnv("Authorizer response has unrecognized Effect '{0}' for API {1}",+ effect, apiId);+ return AuthorizerResult.error();+ }++ // Extract context map if present+ Map<String, Object> context = null;+ JsonNode contextNode = policy.path("context");+ if (!contextNode.isMissingNode() && !contextNode.isNull() && contextNode.isObject()) {+ context = objectMapper.convertValue(contextNode, MAP_TYPE);+ }++ return AuthorizerResult.allow(context);+ } catch (Exception e) {+ LOG.warnv("Failed to parse authorizer policy for API {0}: {1}", apiId, e.getMessage());+ return AuthorizerResult.error();+ }+ }++ /**+ * Check if a header value is present (case-insensitive header name lookup).+ */+ private boolean hasHeaderValue(Map<String, List<String>> headers, String headerName) {+ if (headers == null) return false;+ for (Map.Entry<String, List<String>> entry : headers.entrySet()) {+ if (entry.getKey().equalsIgnoreCase(headerName)) {+ List<String> values = entry.getValue();+ return values != null && !values.isEmpty()+ && values.get(0) != null && !values.get(0).isEmpty();+ }+ }+ return false;+ }++ /**+ * Check if a query parameter value is present.+ */+ private boolean hasQueryParamValue(Map<String, List<String>> queryParams, String paramName) {+ if (queryParams == null) return false;+ List<String> values = queryParams.get(paramName);+ return values != null && !values.isEmpty()+ && values.get(0) != null && !values.get(0).isEmpty();+ }++ /**+ * Extract the Lambda function name from an authorizer URI.+ * Delegates to {@link LambdaArnUtils#extractFunctionNameFromUri(String)}.+ */+ private String extractFunctionNameFromUri(String uri) {+ return LambdaArnUtils.extractFunctionNameFromUri(uri);+ }+}diff --git a/src/main/java/io/github/hectorvent/floci/services/apigatewayv2/websocket/WebSocketConnectionManager.java b/src/main/java/io/github/hectorvent/floci/services/apigatewayv2/websocket/WebSocketConnectionManager.javanew file mode 100644index 0000000000..7af07d9470--- /dev/null+++ b/src/main/java/io/github/hectorvent/floci/services/apigatewayv2/websocket/WebSocketConnectionManager.java@@ -0,0 +1,118 @@+package io.github.hectorvent.floci.services.apigatewayv2.websocket;++import io.vertx.core.http.ServerWebSocket;+import jakarta.enterprise.context.ApplicationScoped;+import org.jboss.logging.Logger;++import java.util.Set;+import java.util.concurrent.ConcurrentHashMap;++/**+ * In-memory manager for active WebSocket connections.+ * Tracks connection metadata and live socket references.+ */+@ApplicationScoped+public class WebSocketConnectionManager {++ private static final Logger LOG = Logger.getLogger(WebSocketConnectionManager.class);++ private final ConcurrentHashMap<String, ConnectionInfo> connections = new ConcurrentHashMap<>();+ private final ConcurrentHashMap<String, ServerWebSocket> sockets = new ConcurrentHashMap<>();++ /**+ * Tracks connections that were closed server-side via the @connections DELETE API.+ * When a connection is in this set, the $disconnect Lambda should NOT be invoked+ * because AWS does not invoke $disconnect for server-initiated disconnections via+ * the management API.+ */+ private final Set<String> serverInitiatedCloses = ConcurrentHashMap.newKeySet();++ /**+ * Register a new WebSocket connection.+ */+ public void register(String connectionId, ConnectionInfo info, ServerWebSocket ws) {+ connections.put(connectionId, info);+ sockets.put(connectionId, ws);+ LOG.debugv("Registered WebSocket connection {0}", connectionId);+ }++ /**+ * Unregister a WebSocket connection, removing both metadata and socket reference.+ */+ public void unregister(String connectionId) {+ connections.remove(connectionId);+ sockets.remove(connectionId);+ serverInitiatedCloses.remove(connectionId);+ LOG.debugv("Unregistered WebSocket connection {0}", connectionId);+ }++ /**+ * Send a text message to the specified connection.+ *+ * @throws IllegalStateException if the connection is not active+ */+ public void sendMessage(String connectionId, String message) {+ ServerWebSocket ws = sockets.get(connectionId);+ if (ws == null) {+ throw new IllegalStateException("Connection " + connectionId + " is not active");+ }+ try {+ ws.writeTextMessage(message);+ } catch (Exception e) {+ LOG.debugv("Failed to write message to connection {0}: {1}", connectionId, e.getMessage());+ throw new IllegalStateException("Connection " + connectionId + " is not active");+ }+ }++ /**+ * Close the specified connection via the @connections DELETE API.+ * Marks the connection as server-initiated so that the $disconnect Lambda+ * is NOT invoked when the close handler fires (matching AWS behavior).+ *+ * @throws IllegalStateException if the connection is not active+ */+ public void closeConnection(String connectionId) {+ ServerWebSocket ws = sockets.get(connectionId);+ if (ws == null) {+ throw new IllegalStateException("Connection " + connectionId + " is not active");+ }+ // Mark as server-initiated BEFORE closing so the close handler knows to skip $disconnect+ serverInitiatedCloses.add(connectionId);+ ws.close();+ // Note: unregister is called by the close handler in WebSocketHandler.onClose()+ }++ /**+ * Check whether a close was initiated by the server (via @connections DELETE API).+ * When true, the $disconnect Lambda should NOT be invoked.+ */+ public boolean isServerInitiatedClose(String connectionId) {+ return serverInitiatedCloses.contains(connectionId);+ }++ /**+ * Get connection metadata for the specified connection.+ *+ * @return the ConnectionInfo, or null if the connection is not active+ */+ public ConnectionInfo getConnectionInfo(String connectionId) {+ return connections.get(connectionId);+ }++ /**+ * Update the lastActiveAt timestamp on the connection metadata.+ */+ public void updateLastActiveAt(String connectionId) {+ ConnectionInfo info = connections.get(connectionId);+ if (info != null) {+ info.setLastActiveAt(System.currentTimeMillis());+ }+ }++ /**+ * Check whether a connection is currently active.+ */+ public boolean isConnected(String connectionId) {+ return sockets.containsKey(connectionId);+ }+}diff --git a/src/main/java/io/github/hectorvent/floci/services/apigatewayv2/websocket/WebSocketHandler.java b/src/main/java/io/github/hectorvent/floci/services/apigatewayv2/websocket/WebSocketHandler.javanew file mode 100644index 0000000000..f7cbcdd61d--- /dev/null+++ b/src/main/java/io/github/hectorvent/floci/services/apigatewayv2/websocket/WebSocketHandler.java@@ -0,0 +1,761 @@+package io.github.hectorvent.floci.services.apigatewayv2.websocket;++import com.fasterxml.jackson.databind.JsonNode;+import com.fasterxml.jackson.databind.ObjectMapper;+import io.github.hectorvent.floci.core.common.AwsException;+import io.github.hectorvent.floci.core.common.RegionResolver;+import io.github.hectorvent.floci.services.apigatewayv2.ApiGatewayV2Service;+import io.github.hectorvent.floci.services.apigatewayv2.model.Api;+import io.github.hectorvent.floci.services.apigatewayv2.model.Integration;+import io.github.hectorvent.floci.services.apigatewayv2.model.Route;+import io.github.hectorvent.floci.services.apigatewayv2.model.Stage;+import io.vertx.core.buffer.Buffer;+import io.vertx.core.http.ServerWebSocket;+import io.vertx.ext.web.Router;+import io.vertx.ext.web.RoutingContext;+import jakarta.enterprise.context.ApplicationScoped;+import jakarta.enterprise.event.Observes;+import jakarta.inject.Inject;+import org.jboss.logging.Logger;++import java.util.Collections;+import java.util.HashMap;+import java.util.List;+import java.util.Map;+import java.util.UUID;++/**+ * Vert.x-based WebSocket handler for API Gateway v2 WebSocket APIs.+ *+ * Registers a route on the Quarkus HTTP server via {@code @Observes Router} to handle+ * WebSocket upgrade requests at {@code /ws/{apiId}/{stageName}}.+ *+ * This handler validates the API and stage, generates a unique connectionId,+ * and delegates to the $connect/$disconnect/message lifecycle (implemented in Tasks 3-5).+ */+@ApplicationScoped+public class WebSocketHandler {++ private static final Logger LOG = Logger.getLogger(WebSocketHandler.class);++ private final ApiGatewayV2Service apiGatewayV2Service;+ private final WebSocketConnectionManager connectionManager;+ private final RouteSelectionEvaluator routeSelectionEvaluator;+ private final WebSocketProxyEventBuilder proxyEventBuilder;+ private final WebSocketIntegrationInvoker integrationInvoker;+ private final WebSocketAuthorizerService authorizerService;+ private final RegionResolver regionResolver;+ private final ObjectMapper objectMapper;+ private final io.vertx.core.Vertx vertx;++ @Inject+ public WebSocketHandler(ApiGatewayV2Service apiGatewayV2Service,+ WebSocketConnectionManager connectionManager,+ RouteSelectionEvaluator routeSelectionEvaluator,+ WebSocketProxyEventBuilder proxyEventBuilder,+ WebSocketIntegrationInvoker integrationInvoker,+ WebSocketAuthorizerService authorizerService,+ RegionResolver regionResolver,+ ObjectMapper objectMapper,+ io.vertx.core.Vertx vertx) {+ this.apiGatewayV2Service = apiGatewayV2Service;+ this.connectionManager = connectionManager;+ this.routeSelectionEvaluator = routeSelectionEvaluator;+ this.proxyEventBuilder = proxyEventBuilder;+ this.integrationInvoker = integrationInvoker;+ this.authorizerService = authorizerService;+ this.regionResolver = regionResolver;+ this.objectMapper = objectMapper;+ this.vertx = vertx;+ }++ /**+ * Register the WebSocket route handler on the Vert.x Router.+ * This runs before JAX-RS routing and intercepts WebSocket upgrade requests.+ */+ void init(@Observes Router router) {+ router.route("/ws/*").handler(this::handleWebSocketUpgrade);+ LOG.info("Registered WebSocket handler on /ws/*");+ }++ /**+ * Handle a WebSocket upgrade request.+ * Parses apiId and stageName from the path, validates the API and stage,+ * generates a unique connectionId, and proceeds with the $connect lifecycle.+ */+ private void handleWebSocketUpgrade(RoutingContext ctx) {+ String path = ctx.request().path();++ // Strip the /ws/ prefix and parse apiId/stageName+ String pathAfterPrefix = path.substring("/ws/".length());+ String[] segments = pathAfterPrefix.split("/", 2);++ if (segments.length < 2 || segments[0].isEmpty() || segments[1].isEmpty()) {+ ctx.response().setStatusCode(403).end();+ return;+ }++ String apiId = segments[0];+ // stageName may contain additional path segments — take only the first segment+ String stageName = segments[1].contains("/") ? segments[1].split("/")[0] : segments[1];++ // Resolve region from the request Authorization header+ String region = resolveRegionFromVertxRequest(ctx);++ // Validate the API exists and is a WEBSOCKET protocol API+ Api api;+ try {+ api = apiGatewayV2Service.getApi(region, apiId);+ } catch (AwsException e) {+ LOG.debugv("WebSocket upgrade rejected: API {0} not found in region {1}", apiId, region);+ ctx.response().setStatusCode(403).end();+ return;+ }++ if (!"WEBSOCKET".equals(api.getProtocolType())) {+ LOG.debugv("WebSocket upgrade rejected: API {0} is not WEBSOCKET protocol (is {1})",+ apiId, api.getProtocolType());+ ctx.response().setStatusCode(403).end();+ return;+ }++ // Validate the stage exists+ Stage stage;+ try {+ stage = apiGatewayV2Service.getStage(region, apiId, stageName);+ } catch (AwsException e) {+ LOG.debugv("WebSocket upgrade rejected: stage {0} not found on API {1}", stageName, apiId);+ ctx.response().setStatusCode(403).end();+ return;+ }++ // Generate a unique connectionId (AWS format: base64-encoded random bytes, ~10-14 chars)+ String connectionId = generateConnectionId();+ long connectedAt = System.currentTimeMillis();++ // Extract source IP and user agent from the upgrade request+ String sourceIp = ctx.request().remoteAddress() != null+ ? ctx.request().remoteAddress().host() : "127.0.0.1";+ String userAgent = ctx.request().getHeader("User-Agent");++ // Load stage variables (default to empty map if null)+ Map<String, String> stageVariables = stage.getStageVariables() != null+ ? stage.getStageVariables() : Collections.emptyMap();++ // Look up the $connect route+ Route connectRoute = apiGatewayV2Service.findRouteByKey(region, apiId, "$connect");++ if (connectRoute != null && connectRoute.getTarget() != null) {+ // Check if the $connect route has a Lambda REQUEST authorizer configured+ if ("CUSTOM".equals(connectRoute.getAuthorizationType())+ && connectRoute.getAuthorizerId() != null+ && !connectRoute.getAuthorizerId().isEmpty()) {++ // Build headers and query params from the upgrade request (needed for both authorizer and integration)+ Map<String, List<String>> headers = extractHeaders(ctx);+ Map<String, List<String>> queryParams = extractQueryParams(ctx);++ // Invoke the authorizer on a worker thread (blocking Lambda call)+ final Map<String, String> finalStageVariables = stageVariables;+ final String finalConnectionId = connectionId;+ final long finalConnectedAt = connectedAt;+ final String finalSourceIp = sourceIp;+ final String finalUserAgent = userAgent;++ vertx.<WebSocketAuthorizerService.AuthorizerResult>executeBlocking(() -> {+ return authorizerService.invokeAndEvaluate(region, apiId, stageName,+ connectRoute.getAuthorizerId(), finalConnectionId, finalConnectedAt,+ headers, queryParams, finalSourceIp, finalUserAgent, finalStageVariables);+ }).onSuccess(authResult -> {+ if (!authResult.allowed()) {+ ctx.response().setStatusCode(authResult.statusCode()).end();+ return;+ }+ // Authorizer allowed — proceed with $connect integration+ proceedWithConnectIntegration(ctx, connectRoute, region, apiId, stageName,+ finalConnectionId, finalConnectedAt, finalSourceIp, finalUserAgent,+ finalStageVariables, headers, queryParams, authResult.context());+ }).onFailure(e -> {+ LOG.warnv("Lambda authorizer invocation failed for API {0}: {1}",+ apiId, e.getMessage());+ ctx.response().setStatusCode(500).end();+ });+ } else {+ // No authorizer configured — proceed directly with $connect integration+ Map<String, List<String>> headers = extractHeaders(ctx);+ Map<String, List<String>> queryParams = extractQueryParams(ctx);+ proceedWithConnectIntegration(ctx, connectRoute, region, apiId, stageName,+ connectionId, connectedAt, sourceIp, userAgent,+ stageVariables, headers, queryParams, null);+ }+ } else {+ // No $connect route — complete the upgrade directly+ completeUpgrade(ctx, connectionId, apiId, stageName, region,+ connectedAt, sourceIp, userAgent);+ }+ }++ /**+ * Proceed with the $connect integration invocation after authorizer check.+ * The authorizerContext parameter holds the extracted authorizer context (may be null if no authorizer).+ */+ private void proceedWithConnectIntegration(RoutingContext ctx, Route connectRoute,+ String region, String apiId, String stageName,+ String connectionId, long connectedAt,+ String sourceIp, String userAgent,+ Map<String, String> stageVariables,+ Map<String, List<String>> headers,+ Map<String, List<String>> queryParams,+ Map<String, Object> authorizerContext) {+ // Resolve the $connect integration+ String integrationId = parseIntegrationId(connectRoute.getTarget());+ Integration integration;+ try {+ integration = apiGatewayV2Service.getIntegration(region, apiId, integrationId);+ } catch (AwsException e) {+ LOG.warnv("$connect integration {0} not found for API {1}", integrationId, apiId);+ ctx.response().setStatusCode(500).end();+ return;+ }++ // Build the CONNECT proxy event with authorizer context+ String eventJson = proxyEventBuilder.buildConnectEvent(+ connectionId, apiId, stageName, region, connectedAt,+ headers, queryParams, sourceIp, userAgent, stageVariables, authorizerContext);++ // Execute the blocking Lambda invocation on a worker thread+ final Integration finalIntegration = integration;+ final Map<String, String> finalStageVariables = stageVariables;+ vertx.<WebSocketIntegrationInvoker.IntegrationResult>executeBlocking(() -> {+ return integrationInvoker.invoke(region, finalIntegration, eventJson,+ finalStageVariables, Collections.emptyMap(), Collections.emptyMap());+ }).onSuccess(result -> {+ // Check for function error (Lambda invocation error)+ if (result.functionError() != null) {+ LOG.debugv("$connect Lambda returned function error: {0}, rejecting upgrade for API {1}",+ result.functionError(), apiId);+ ctx.response().setStatusCode(500).end();+ return;+ }+ // Check the response status code+ if (result.statusCode() >= 200 && result.statusCode() <= 299) {+ // 2xx — complete the WebSocket upgrade with response headers from Lambda+ completeUpgradeWithHeaders(ctx, connectionId, apiId, stageName, region,+ connectedAt, sourceIp, userAgent, result.headers());+ } else {+ // Non-2xx — reject the upgrade+ LOG.debugv("$connect route returned status {0}, rejecting upgrade for API {1}",+ result.statusCode(), apiId);+ ctx.response().setStatusCode(403).end();+ }+ }).onFailure(e -> {+ LOG.warnv("$connect integration invocation failed for API {0}: {1}",+ apiId, e.getMessage());+ ctx.response().setStatusCode(500).end();+ });+ }++ /** Maximum WebSocket frame payload size in bytes (128 KB, matching AWS limit). */+ private static final int MAX_FRAME_PAYLOAD_BYTES = 128 * 1024;++ /** Idle timeout in milliseconds (10 minutes, matching AWS default). */+ private static final long IDLE_TIMEOUT_MS = 10 * 60 * 1000L;++ /** Maximum connection duration in milliseconds (2 hours, matching AWS limit). */+ private static final long MAX_CONNECTION_DURATION_MS = 2 * 60 * 60 * 1000L;++ /**+ * Complete the WebSocket upgrade, register the connection, and attach message/close handlers.+ */+ private void completeUpgrade(RoutingContext ctx, String connectionId, String apiId,+ String stageName, String region, long connectedAt,+ String sourceIp, String userAgent) {+ ctx.request().toWebSocket().onSuccess(ws -> {+ // Register the connection+ ConnectionInfo connectionInfo = new ConnectionInfo(+ connectionId, apiId, stageName, region,+ connectedAt, connectedAt, sourceIp, userAgent);+ connectionManager.register(connectionId, connectionInfo, ws);++ LOG.debugv("WebSocket connection {0} established for API {1}/{2}",+ connectionId, apiId, stageName);++ // Attach text message handler+ ws.textMessageHandler(msg -> {+ // Enforce payload size limit (AWS: 128 KB for WebSocket frames)+ if (msg.length() > MAX_FRAME_PAYLOAD_BYTES) {+ LOG.debugv("Message exceeds 128 KB limit on connection {0} ({1} bytes)",+ connectionId, msg.length());+ safeWriteTextMessage(ws, "{\"message\":\"Message too long\",\"connectionId\":\""+ + connectionId + "\"}", connectionId);+ return;+ }+ onMessage(ws, connectionId, apiId, stageName, region, msg, false);+ });++ // Attach binary message handler (AWS supports binary frames with isBase64Encoded=true)+ ws.binaryMessageHandler(buffer -> {+ byte[] data = buffer.getBytes();+ // Enforce payload size limit+ if (data.length > MAX_FRAME_PAYLOAD_BYTES) {+ LOG.debugv("Binary message exceeds 128 KB limit on connection {0} ({1} bytes)",+ connectionId, data.length);+ safeWriteTextMessage(ws, "{\"message\":\"Message too long\",\"connectionId\":\""+ + connectionId + "\"}", connectionId);+ return;+ }+ onBinaryMessage(ws, connectionId, apiId, stageName, region, data);+ });++ // Attach close handler+ ws.closeHandler(v -> onClose(ws, connectionId, apiId, stageName, region));++ // Schedule idle timeout check+ scheduleIdleTimeout(connectionId, connectedAt);+ }).onFailure(err -> {+ LOG.warnv("WebSocket upgrade failed for connection {0}: {1}",+ connectionId, err.getMessage());+ });+ }++ /**+ * Complete the WebSocket upgrade with custom response headers from the $connect Lambda.+ * AWS allows the $connect Lambda to return headers that are included in the upgrade response.+ */+ private void completeUpgradeWithHeaders(RoutingContext ctx, String connectionId, String apiId,+ String stageName, String region, long connectedAt,+ String sourceIp, String userAgent,+ Map<String, String> responseHeaders) {+ // Add custom headers to the upgrade response before completing the WebSocket handshake+ if (responseHeaders != null && !responseHeaders.isEmpty()) {+ for (Map.Entry<String, String> header : responseHeaders.entrySet()) {+ // Skip hop-by-hop headers that shouldn't be propagated+ String key = header.getKey().toLowerCase();+ if (key.equals("connection") || key.equals("upgrade") || key.equals("sec-websocket-accept")+ || key.equals("sec-websocket-key") || key.equals("sec-websocket-version")) {+ continue;+ }+ ctx.response().putHeader(header.getKey(), header.getValue());+ }+ }+ completeUpgrade(ctx, connectionId, apiId, stageName, region, connectedAt, sourceIp, userAgent);+ }++ /**+ * Schedule periodic idle timeout and max duration checks for a connection.+ * AWS enforces a 10-minute idle timeout and 2-hour maximum connection duration.+ */+ private void scheduleIdleTimeout(String connectionId, long connectedAt) {+ // Check every 60 seconds+ vertx.setPeriodic(60_000L, timerId -> {+ ConnectionInfo info = connectionManager.getConnectionInfo(connectionId);+ if (info == null) {+ // Connection already closed — cancel the timer+ vertx.cancelTimer(timerId);+ return;+ }++ long now = System.currentTimeMillis();++ // Check max connection duration (2 hours)+ if (now - connectedAt > MAX_CONNECTION_DURATION_MS) {+ LOG.debugv("Connection {0} exceeded max duration (2h), closing", connectionId);+ vertx.cancelTimer(timerId);+ connectionManager.closeConnection(connectionId);+ return;+ }++ // Check idle timeout (10 minutes since last activity)+ if (now - info.getLastActiveAt() > IDLE_TIMEOUT_MS) {+ LOG.debugv("Connection {0} idle timeout (10m), closing", connectionId);+ vertx.cancelTimer(timerId);+ connectionManager.closeConnection(connectionId);+ }+ });+ }++ /**+ * Handle an incoming WebSocket binary message.+ * Encodes the binary data as base64 and routes it like a text message with isBase64Encoded=true.+ */+ private void onBinaryMessage(ServerWebSocket ws, String connectionId, String apiId,+ String stageName, String region, byte[] data) {+ LOG.debugv("Received binary message on connection {0}: {1} bytes", connectionId, data.length);++ // Update lastActiveAt timestamp+ connectionManager.updateLastActiveAt(connectionId);++ // Base64-encode the binary data for the proxy event body+ String base64Body = java.util.Base64.getEncoder().encodeToString(data);++ // Route using the base64 body (route selection won't match JSON fields in binary messages,+ // so it will fall through to $default)+ onMessage(ws, connectionId, apiId, stageName, region, base64Body, true);+ }++ /**+ * Handle an incoming WebSocket text message.+ * Routes the message to the appropriate integration based on the API's routeSelectionExpression.+ *+ * @param isBinary if true, the body is base64-encoded binary data and isBase64Encoded should be set in the event+ */+ private void onMessage(ServerWebSocket ws, String connectionId, String apiId,+ String stageName, String region, String message, boolean isBinary) {+ LOG.debugv("Received message on connection {0}: {1}", connectionId, message);++ // Update lastActiveAt timestamp (Requirement 9.1)+ connectionManager.updateLastActiveAt(connectionId);++ // Load the API to get routeSelectionExpression+ Api api;+ try {+ api = apiGatewayV2Service.getApi(region, apiId);+ } catch (AwsException e) {+ LOG.warnv("Failed to load API {0} for message routing: {1}", apiId, e.getMessage());+ return;+ }++ String routeSelectionExpression = api.getRouteSelectionExpression();++ // Evaluate routeSelectionExpression against the message+ String routeKey = routeSelectionEvaluator.evaluate(routeSelectionExpression, message);++ // Look up matching route+ Route route = null;+ if (routeKey != null) {+ route = apiGatewayV2Service.findRouteByKey(region, apiId, routeKey);+ }++ // Fall back to $default if no match+ if (route == null) {+ route = apiGatewayV2Service.findRouteByKey(region, apiId, "$default");+ }++ // If no route found (no match and no $default)+ if (route == null) {+ String requestId = UUID.randomUUID().toString();+ if (routeKey == null) {+ // Message is non-JSON or field not found, and no $default+ String errorFrame = String.format(+ "{\"message\":\"Could not route message\",\"connectionId\":\"%s\",\"requestId\":\"%s\"}",+ connectionId, requestId);+ safeWriteTextMessage(ws, errorFrame, connectionId);+ } else {+ // Route key extracted but no matching route and no $default+ String errorFrame = String.format(+ "{\"message\":\"No route found\",\"connectionId\":\"%s\",\"requestId\":\"%s\"}",+ connectionId, requestId);+ safeWriteTextMessage(ws, errorFrame, connectionId);+ }+ return;+ }++ // Determine the effective route key for the proxy event+ String effectiveRouteKey = routeKey != null ? routeKey : "$default";++ // Resolve integration+ if (route.getTarget() == null) {+ LOG.debugv("Route {0} has no target integration", route.getRouteKey());+ return;+ }++ String integrationId = parseIntegrationId(route.getTarget());+ Integration integration;+ try {+ integration = apiGatewayV2Service.getIntegration(region, apiId, integrationId);+ } catch (AwsException e) {+ LOG.warnv("Integration {0} not found for route {1}: {2}",+ integrationId, route.getRouteKey(), e.getMessage());+ String requestId = UUID.randomUUID().toString();+ String errorFrame = String.format(+ "{\"message\":\"Internal server error\",\"connectionId\":\"%s\",\"requestId\":\"%s\"}",+ connectionId, requestId);+ safeWriteTextMessage(ws, errorFrame, connectionId);+ return;+ }++ // Load stage variables+ Map<String, String> stageVariables = Collections.emptyMap();+ try {+ Stage stage = apiGatewayV2Service.getStage(region, apiId, stageName);+ if (stage.getStageVariables() != null) {+ stageVariables = stage.getStageVariables();+ }+ } catch (AwsException e) {+ LOG.debugv("Failed to load stage {0} for stage variables: {1}", stageName, e.getMessage());+ }++ // Get connection info for connectedAt, sourceIp, userAgent+ ConnectionInfo connectionInfo = connectionManager.getConnectionInfo(connectionId);+ long connectedAt = connectionInfo != null ? connectionInfo.getConnectedAt() : System.currentTimeMillis();+ String sourceIp = connectionInfo != null ? connectionInfo.getSourceIp() : "127.0.0.1";+ String userAgent = connectionInfo != null ? connectionInfo.getUserAgent() : "";++ // Build MESSAGE proxy event+ String eventJson = proxyEventBuilder.buildMessageEvent(+ connectionId, effectiveRouteKey, apiId, stageName, region,+ connectedAt, message, sourceIp, userAgent, stageVariables, isBinary);++ // Invoke integration on a worker thread to avoid blocking the event loop+ final Integration finalIntegration = integration;+ final Map<String, String> finalStageVariables = stageVariables;+ final Route finalRoute = route;+ final String finalConnectionId = connectionId;+ vertx.executeBlocking(() -> {+ return integrationInvoker.invoke(region, finalIntegration, eventJson,+ finalStageVariables, Collections.emptyMap(), Collections.emptyMap());+ }).onSuccess(result -> {+ // Route response handling (Requirements 5.1–5.3)+ if (finalRoute.getRouteResponseSelectionExpression() != null && result.body() != null) {+ try {+ JsonNode responseJson = objectMapper.readTree(result.body());+ if (responseJson.has("body")) {+ String responseBody = responseJson.get("body").asText();+ safeWriteTextMessage(ws, responseBody, finalConnectionId);+ } else {+ // If no "body" field, send the entire body as-is+ safeWriteTextMessage(ws, result.body(), finalConnectionId);+ }+ } catch (Exception e) {+ // If parsing fails, send the raw body+ LOG.debugv("Failed to parse integration response as JSON, sending raw body: {0}",+ e.getMessage());+ safeWriteTextMessage(ws, result.body(), finalConnectionId);+ }+ }+ }).onFailure(e -> {+ LOG.warnv("Integration invocation failed for route {0} on connection {1}: {2}",+ finalRoute.getRouteKey(), finalConnectionId, e.getMessage());+ String requestId = UUID.randomUUID().toString();+ String errorFrame = String.format(+ "{\"message\":\"Internal server error\",\"connectionId\":\"%s\",\"requestId\":\"%s\"}",+ finalConnectionId, requestId);+ safeWriteTextMessage(ws, errorFrame, finalConnectionId);+ });+ }++ /**+ * Handle WebSocket connection close.+ * Invokes the $disconnect route's Lambda integration (if configured) and then+ * unregisters the connection from the ConnectionManager.+ * Errors during $disconnect invocation are logged but never propagated.+ *+ * AWS behavior: $disconnect is NOT invoked when the close was initiated by the server+ * via the @connections DELETE API. Only client-initiated disconnections trigger $disconnect.+ */+ private void onClose(ServerWebSocket ws, String connectionId, String apiId,+ String stageName, String region) {+ LOG.debugv("WebSocket connection {0} closed", connectionId);++ // Check if this close was initiated by the server via @connections DELETE API.+ // In AWS, server-initiated disconnections do NOT invoke the $disconnect Lambda.+ if (connectionManager.isServerInitiatedClose(connectionId)) {+ LOG.debugv("Skipping $disconnect for server-initiated close on connection {0}", connectionId);+ connectionManager.unregister(connectionId);+ return;+ }++ // Retrieve connection info BEFORE unregistering so we have connectedAt, sourceIp, userAgent+ ConnectionInfo connectionInfo = connectionManager.getConnectionInfo(connectionId);+ long connectedAt = connectionInfo != null ? connectionInfo.getConnectedAt() : System.currentTimeMillis();+ String sourceIp = connectionInfo != null ? connectionInfo.getSourceIp() : "127.0.0.1";+ String userAgent = connectionInfo != null ? connectionInfo.getUserAgent() : "";++ // Look up the $disconnect route+ Route disconnectRoute = apiGatewayV2Service.findRouteByKey(region, apiId, "$disconnect");++ if (disconnectRoute != null && disconnectRoute.getTarget() != null) {+ // Load stage variables+ Map<String, String> stageVariables = Collections.emptyMap();+ try {+ Stage stage = apiGatewayV2Service.getStage(region, apiId, stageName);+ if (stage.getStageVariables() != null) {+ stageVariables = stage.getStageVariables();+ }+ } catch (AwsException e) {+ LOG.debugv("Failed to load stage {0} for $disconnect stage variables: {1}",+ stageName, e.getMessage());+ }++ // Resolve integration and invoke on a worker thread+ String integrationId = parseIntegrationId(disconnectRoute.getTarget());+ Integration integration;+ try {+ integration = apiGatewayV2Service.getIntegration(region, apiId, integrationId);+ } catch (AwsException e) {+ LOG.warnv("$disconnect integration {0} not found for connection {1}: {2}",+ integrationId, connectionId, e.getMessage());+ connectionManager.unregister(connectionId);+ return;+ }++ // Build DISCONNECT proxy event+ String eventJson = proxyEventBuilder.buildDisconnectEvent(+ connectionId, apiId, stageName, region, connectedAt,+ sourceIp, userAgent, stageVariables);++ // Execute the blocking Lambda invocation on a worker thread+ final Integration finalIntegration = integration;+ final Map<String, String> finalStageVariables = stageVariables;+ vertx.executeBlocking(() -> {+ integrationInvoker.invoke(region, finalIntegration, eventJson,+ finalStageVariables, Collections.emptyMap(), Collections.emptyMap());+ return null;+ }).onComplete(ar -> {+ if (ar.failed()) {+ // $disconnect errors must never prevent cleanup — log and continue+ LOG.warnv("Error invoking $disconnect route for connection {0}: {1}",+ connectionId, ar.cause().getMessage());+ }+ // Always unregister the connection regardless of $disconnect outcome+ connectionManager.unregister(connectionId);+ });+ } else {+ // No $disconnect route — just unregister+ connectionManager.unregister(connectionId);+ }+ }++ /**+ * Safely write a text message to a WebSocket, catching any exceptions that may occur+ * if the connection is in a closing or closed state.+ */+ private void safeWriteTextMessage(ServerWebSocket ws, String message, String connectionId) {+ try {+ ws.writeTextMessage(message);+ } catch (Exception e) {+ LOG.debugv("Failed to write message to connection {0}: {1}", connectionId, e.getMessage());+ }+ }++ /**+ * Generate a connection ID matching the AWS format.+ * AWS connection IDs are URL-safe base64-encoded random bytes, typically 10-14 characters+ * (e.g. "L0SM9cOFvHcCIhw", "d2ljbGVz").+ * Uses 9 random bytes → 12 base64url characters (no padding).+ */+ private static String generateConnectionId() {+ byte[] bytes = new byte[9];+ java.util.concurrent.ThreadLocalRandom.current().nextBytes(bytes);+ return java.util.Base64.getUrlEncoder().withoutPadding().encodeToString(bytes);+ }++ /**+ * Parse the integrationId from a route target string.+ * Target format: "integrations/{integrationId}"+ */+ private String parseIntegrationId(String target) {+ if (target == null) {+ return null;+ }+ if (target.startsWith("integrations/")) {+ return target.substring("integrations/".length());+ }+ return target;+ }++ /**+ * Extract headers from the Vert.x routing context as a multi-value map.+ */+ private Map<String, List<String>> extractHeaders(RoutingContext ctx) {+ Map<String, List<String>> headers = new HashMap<>();+ ctx.request().headers().forEach(entry ->+ headers.computeIfAbsent(entry.getKey(), k -> new java.util.ArrayList<>())+ .add(entry.getValue()));+ return headers;+ }++ /**+ * Extract query parameters from the Vert.x routing context as a multi-value map.+ */+ private Map<String, List<String>> extractQueryParams(RoutingContext ctx) {+ Map<String, List<String>> params = new HashMap<>();+ ctx.request().params().forEach(entry ->+ params.computeIfAbsent(entry.getKey(), k -> new java.util.ArrayList<>())+ .add(entry.getValue()));+ return params;+ }++ /**+ * Resolve the AWS region from the Vert.x request headers.+ * Extracts the Authorization header and delegates to RegionResolver's parsing logic.+ * Falls back to the default region if no Authorization header is present.+ */+ private String resolveRegionFromVertxRequest(RoutingContext ctx) {+ String authHeader = ctx.request().getHeader("Authorization");+ if (authHeader == null || authHeader.isEmpty()) {+ return regionResolver.getDefaultRegion();+ }+ // Use a simple JAX-RS HttpHeaders adapter to delegate to RegionResolver+ jakarta.ws.rs.core.HttpHeaders headers = new SimpleHttpHeaders(authHeader);+ return regionResolver.resolveRegion(headers);+ }++ /**+ * Minimal HttpHeaders implementation that provides only the Authorization header.+ * Used to bridge Vert.x request headers to the RegionResolver API.+ */+ private static class SimpleHttpHeaders implements jakarta.ws.rs.core.HttpHeaders {+ private final String authorizationHeader;++ SimpleHttpHeaders(String authorizationHeader) {+ this.authorizationHeader = authorizationHeader;+ }++ @Override+ public String getHeaderString(String name) {+ if ("Authorization".equalsIgnoreCase(name)) {+ return authorizationHeader;+ }+ return null;+ }++ @Override+ public java.util.List<String> getRequestHeader(String name) {+ if ("Authorization".equalsIgnoreCase(name) && authorizationHeader != null) {+ return java.util.List.of(authorizationHeader);+ }+ return java.util.Collections.emptyList();+ }++ @Override+ public jakarta.ws.rs.core.MultivaluedMap<String, String> getRequestHeaders() {+ return new jakarta.ws.rs.core.MultivaluedHashMap<>();+ }++ @Override+ public java.util.List<jakarta.ws.rs.core.MediaType> getAcceptableMediaTypes() {+ return java.util.Collections.emptyList();+ }++ @Override+ public java.util.List<java.util.Locale> getAcceptableLanguages() {+ return java.util.Collections.emptyList();+ }++ @Override+ public jakarta.ws.rs.core.MediaType getMediaType() {+ return null;+ }++ @Override+ public java.util.Locale getLanguage() {+ return null;+ }++ @Override+ public java.util.Map<String, jakarta.ws.rs.core.Cookie> getCookies() {+ return java.util.Collections.emptyMap();+ }++ @Override+ public java.util.Date getDate() {+ return null;+ }++ @Override+ public int getLength() {+ return -1;+ }+ }+}diff --git a/src/main/java/io/github/hectorvent/floci/services/apigatewayv2/websocket/WebSocketIntegrationInvoker.java b/src/main/java/io/github/hectorvent/floci/services/apigatewayv2/websocket/WebSocketIntegrationInvoker.javanew file mode 100644index 0000000000..923e1f1e02--- /dev/null+++ b/src/main/java/io/github/hectorvent/floci/services/apigatewayv2/websocket/WebSocketIntegrationInvoker.java@@ -0,0 +1,532 @@+package io.github.hectorvent.floci.services.apigatewayv2.websocket;++import com.fasterxml.jackson.databind.JsonNode;+import com.fasterxml.jackson.databind.ObjectMapper;+import io.github.hectorvent.floci.services.apigateway.AwsServiceRouter;+import io.github.hectorvent.floci.services.apigateway.VtlTemplateEngine;+import io.github.hectorvent.floci.services.apigatewayv2.model.Integration;+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.annotation.PreDestroy;+import jakarta.enterprise.context.ApplicationScoped;+import jakarta.inject.Inject;+import org.jboss.logging.Logger;++import java.net.URI;+import java.net.http.HttpClient;+import java.net.http.HttpRequest;+import java.net.http.HttpResponse;+import java.nio.charset.StandardCharsets;+import java.util.Collections;+import java.util.Map;+import java.util.regex.Matcher;+import java.util.regex.Pattern;++/**+ * Resolves and invokes integration targets for WebSocket routes.+ * Supports AWS_PROXY (Lambda), AWS (Lambda with VTL templates), HTTP_PROXY, HTTP (with VTL templates), and MOCK integration types.+ */+@ApplicationScoped+public class WebSocketIntegrationInvoker {++ private static final Logger LOG = Logger.getLogger(WebSocketIntegrationInvoker.class);++ /**+ * Regex pattern matching ${stageVariables.variableName} references in URIs.+ */+ private static final Pattern STAGE_VAR_PATTERN =+ Pattern.compile("\\$\\{stageVariables\\.([^}]+)}");++ private final LambdaService lambdaService;+ private final AwsServiceRouter serviceRouter;+ private final ObjectMapper objectMapper;+ private final VtlTemplateEngine vtlEngine;+ private final HttpClient httpClient;++ @Inject+ public WebSocketIntegrationInvoker(LambdaService lambdaService, AwsServiceRouter serviceRouter,+ ObjectMapper objectMapper, VtlTemplateEngine vtlEngine) {+ this.lambdaService = lambdaService;+ this.serviceRouter = serviceRouter;+ this.objectMapper = objectMapper;+ this.vtlEngine = vtlEngine;+ this.httpClient = HttpClient.newHttpClient();+ }++ @PreDestroy+ void shutdown() {+ // HttpClient does not have an explicit close in Java 11-20.+ // In Java 21+ HttpClient implements AutoCloseable. For forward compatibility,+ // we attempt to close if the method is available.+ try {+ httpClient.close();+ } catch (UnsupportedOperationException | NoSuchMethodError e) {+ // Pre-Java 21 — no-op, GC will handle cleanup+ }+ }++ /**+ * Result of an integration invocation.+ *+ * @param statusCode HTTP-like status code from the integration response+ * @param body response body (may be null)+ * @param functionError function error string if the Lambda reported an error (may be null)+ * @param headers response headers from the integration (may be null)+ */+ public record IntegrationResult(int statusCode, String body, String functionError,+ Map<String, String> headers) {+ /** Convenience constructor without headers (backwards compatible). */+ public IntegrationResult(int statusCode, String body, String functionError) {+ this(statusCode, body, functionError, null);+ }+ }++ /**+ * Invoke the integration for a route.+ *+ * @param region the AWS region+ * @param integration the Integration model+ * @param eventJson the serialized proxy event JSON+ * @param stageVariables stage variables for URI substitution+ * @param requestTemplates request templates (for MOCK integration)+ * @param responseTemplates response templates (for MOCK integration)+ * @return the integration result+ */+ public IntegrationResult invoke(String region, Integration integration, String eventJson,+ Map<String, String> stageVariables,+ Map<String, String> requestTemplates,+ Map<String, String> responseTemplates) {+ String integrationType = integration.getIntegrationType();+ if (integrationType == null) {+ integrationType = "AWS_PROXY";+ }++ return switch (integrationType) {+ case "AWS_PROXY" -> invokeAwsProxy(region, integration, eventJson, stageVariables);+ case "AWS" -> invokeAws(region, integration, eventJson, stageVariables, requestTemplates, responseTemplates);+ case "HTTP_PROXY" -> invokeHttpProxy(integration, eventJson, stageVariables);+ case "HTTP" -> invokeHttp(integration, eventJson, stageVariables, requestTemplates, responseTemplates);+ case "MOCK" -> invokeMock(integration, stageVariables, requestTemplates, responseTemplates);+ default -> {+ LOG.warnv("Unsupported integration type: {0}", integrationType);+ yield new IntegrationResult(500, null, "Unsupported integration type: " + integrationType);+ }+ };+ }++ /**+ * Invoke a Lambda function via AWS_PROXY integration.+ */+ private IntegrationResult invokeAwsProxy(String region, Integration integration,+ String eventJson, Map<String, String> stageVariables) {+ String uri = integration.getIntegrationUri();+ uri = substituteStageVariables(uri, stageVariables);++ String functionName = extractFunctionName(uri);+ if (functionName == null || functionName.isEmpty()) {+ LOG.warnv("Could not extract function name from integration URI: {0}", uri);+ return new IntegrationResult(500, null, "Invalid integration URI");+ }++ LOG.debugv("Invoking Lambda function {0} for AWS_PROXY integration", functionName);++ InvokeResult result = lambdaService.invoke(region, functionName,+ eventJson.getBytes(StandardCharsets.UTF_8), InvocationType.RequestResponse);++ int statusCode = 200;+ String body = null;+ String functionError = result.getFunctionError();+ Map<String, String> responseHeaders = null;++ byte[] payload = result.getPayload();+ if (payload != null && payload.length > 0) {+ String payloadStr = new String(payload, StandardCharsets.UTF_8);+ try {+ JsonNode responseNode = objectMapper.readTree(payloadStr);+ if (responseNode.has("statusCode")) {+ statusCode = responseNode.get("statusCode").asInt(200);+ }+ if (responseNode.has("body")) {+ body = responseNode.get("body").asText();+ }+ // Extract response headers (used by $connect to propagate to upgrade response)+ if (responseNode.has("headers") && responseNode.get("headers").isObject()) {+ responseHeaders = new java.util.HashMap<>();+ var headersNode = responseNode.get("headers");+ var fields = headersNode.fields();+ while (fields.hasNext()) {+ var field = fields.next();+ responseHeaders.put(field.getKey(), field.getValue().asText());+ }+ }+ } catch (Exception e) {+ LOG.debugv("Failed to parse Lambda response as JSON: {0}", e.getMessage());+ body = payloadStr;+ }+ }++ return new IntegrationResult(statusCode, body, functionError, responseHeaders);+ }++ /**+ * Invoke a Lambda function via AWS integration with VTL template transformation.+ * Applies requestTemplates before invocation and responseTemplates after.+ * Uses templates from the method parameters first, falling back to the integration model's templates.+ */+ private IntegrationResult invokeAws(String region, Integration integration, String eventJson,+ Map<String, String> stageVariables,+ Map<String, String> requestTemplates,+ Map<String, String> responseTemplates) {+ String uri = integration.getIntegrationUri();+ uri = substituteStageVariables(uri, stageVariables);++ String functionName = extractFunctionName(uri);+ if (functionName == null || functionName.isEmpty()) {+ LOG.warnv("Could not extract function name from integration URI: {0}", uri);+ return new IntegrationResult(500, null, "Invalid integration URI");+ }++ // Use passed templates, falling back to integration model's templates+ Map<String, String> effectiveRequestTemplates = (requestTemplates != null && !requestTemplates.isEmpty())+ ? requestTemplates+ : integration.getRequestTemplates();+ Map<String, String> effectiveResponseTemplates = (responseTemplates != null && !responseTemplates.isEmpty())+ ? responseTemplates+ : integration.getResponseTemplates();++ // Apply request template transformation+ String transformedPayload = applyRequestTemplate(eventJson, effectiveRequestTemplates,+ integration.getTemplateSelectionExpression(), stageVariables);++ LOG.debugv("Invoking Lambda function {0} for AWS integration", functionName);++ InvokeResult result = lambdaService.invoke(region, functionName,+ transformedPayload.getBytes(StandardCharsets.UTF_8), InvocationType.RequestResponse);++ int statusCode = 200;+ String body = null;+ String functionError = result.getFunctionError();++ byte[] payload = result.getPayload();+ if (payload != null && payload.length > 0) {+ body = new String(payload, StandardCharsets.UTF_8);+ }++ // Apply response template transformation+ if (body != null) {+ body = applyResponseTemplate(body, effectiveResponseTemplates,+ integration.getTemplateSelectionExpression(), stageVariables, statusCode);+ }++ return new IntegrationResult(statusCode, body, functionError);+ }++ /**+ * Invoke an HTTP endpoint via HTTP_PROXY integration (passthrough, no VTL transformation).+ * Forwards the event JSON as an HTTP POST to the resolved integration URI and returns+ * the HTTP response status code and body as the IntegrationResult.+ */+ private IntegrationResult invokeHttpProxy(Integration integration, String eventJson,+ Map<String, String> stageVariables) {+ String uri = integration.getIntegrationUri();+ uri = substituteStageVariables(uri, stageVariables);++ if (uri == null || uri.isEmpty()) {+ LOG.warnv("HTTP_PROXY integration URI is null or empty");+ return new IntegrationResult(500, null, "Invalid integration URI");+ }++ LOG.debugv("Forwarding event to HTTP_PROXY endpoint: {0}", uri);++ try {+ HttpRequest request = HttpRequest.newBuilder()+ .uri(URI.create(uri))+ .header("Content-Type", "application/json")+ .POST(HttpRequest.BodyPublishers.ofString(eventJson, StandardCharsets.UTF_8))+ .build();++ HttpResponse<String> response = httpClient.send(request, HttpResponse.BodyHandlers.ofString());++ return new IntegrationResult(response.statusCode(), response.body(), null);+ } catch (Exception e) {+ LOG.warnv("HTTP_PROXY integration call failed: {0}", e.getMessage());+ return new IntegrationResult(500, null, "HTTP_PROXY integration error: " + e.getMessage());+ }+ }++ /**+ * Invoke an HTTP endpoint via HTTP integration with VTL template transformation.+ * Applies requestTemplates to transform the event before forwarding, and+ * responseTemplates to transform the HTTP response before returning.+ * Stage variable substitution is applied to the integrationUri (Requirement 3.3).+ */+ private IntegrationResult invokeHttp(Integration integration, String eventJson,+ Map<String, String> stageVariables,+ Map<String, String> requestTemplates,+ Map<String, String> responseTemplates) {+ String uri = integration.getIntegrationUri();+ uri = substituteStageVariables(uri, stageVariables);++ if (uri == null || uri.isEmpty()) {+ LOG.warnv("HTTP integration URI is null or empty");+ return new IntegrationResult(500, null, "Invalid integration URI");+ }++ // Use passed templates, falling back to integration model's templates+ Map<String, String> effectiveRequestTemplates = (requestTemplates != null && !requestTemplates.isEmpty())+ ? requestTemplates+ : integration.getRequestTemplates();+ Map<String, String> effectiveResponseTemplates = (responseTemplates != null && !responseTemplates.isEmpty())+ ? responseTemplates+ : integration.getResponseTemplates();++ // Apply request template transformation (Requirement 3.1)+ String transformedPayload = applyRequestTemplate(eventJson, effectiveRequestTemplates,+ integration.getTemplateSelectionExpression(), stageVariables);++ LOG.debugv("Forwarding transformed event to HTTP endpoint: {0}", uri);++ try {+ HttpRequest request = HttpRequest.newBuilder()+ .uri(URI.create(uri))+ .header("Content-Type", "application/json")+ .POST(HttpRequest.BodyPublishers.ofString(transformedPayload, StandardCharsets.UTF_8))+ .build();++ HttpResponse<String> response = httpClient.send(request, HttpResponse.BodyHandlers.ofString());++ int statusCode = response.statusCode();+ String body = response.body();++ // Apply response template transformation (Requirement 3.2)+ if (body != null) {+ body = applyResponseTemplate(body, effectiveResponseTemplates,+ integration.getTemplateSelectionExpression(), stageVariables, statusCode);+ }++ return new IntegrationResult(statusCode, body, null);+ } catch (Exception e) {+ LOG.warnv("HTTP integration call failed: {0}", e.getMessage());+ return new IntegrationResult(500, null, "HTTP integration error: " + e.getMessage());+ }+ }++ /**+ * Handle a MOCK integration — no backend invocation.+ * Evaluates templateSelectionExpression against requestTemplates to determine status code,+ * then selects matching responseTemplate.+ * Stage variable substitution is applied to the integrationUri and templateSelectionExpression+ * per Requirement 8.4 (all integration types).+ *+ * If no request templates are provided but templateSelectionExpression is a numeric value,+ * it is used directly as the status code. This allows MOCK integrations to return non-200+ * status codes without requiring template configuration.+ */+ private IntegrationResult invokeMock(Integration integration,+ Map<String, String> stageVariables,+ Map<String, String> requestTemplates,+ Map<String, String> responseTemplates) {+ // Apply stage variable substitution to integrationUri (Requirement 8.4)+ String uri = integration.getIntegrationUri();+ if (uri != null) {+ substituteStageVariables(uri, stageVariables);+ }++ int statusCode = 200;+ String body = null;++ String templateSelectionExpression = integration.getTemplateSelectionExpression();+ // Apply stage variable substitution to templateSelectionExpression+ if (templateSelectionExpression != null) {+ templateSelectionExpression = substituteStageVariables(templateSelectionExpression, stageVariables);+ }++ // Evaluate request templates to determine status code+ if (templateSelectionExpression != null && requestTemplates != null && !requestTemplates.isEmpty()) {+ // The templateSelectionExpression for mock integrations typically evaluates to a status code+ // Try to find a matching request template key+ String matchedKey = null;+ for (String key : requestTemplates.keySet()) {+ if (templateSelectionExpression.contains(key) || key.equals(templateSelectionExpression)) {+ matchedKey = key;+ break;+ }+ }+ if (matchedKey != null) {+ try {+ statusCode = Integer.parseInt(matchedKey);+ } catch (NumberFormatException e) {+ // Key is not a numeric status code, keep default 200+ }+ }+ } else if (templateSelectionExpression != null && (requestTemplates == null || requestTemplates.isEmpty())) {+ // No request templates provided — try to parse templateSelectionExpression directly as a status code.+ // This supports MOCK integrations configured with a numeric templateSelectionExpression+ // to return a specific status code without requiring template maps.+ try {+ statusCode = Integer.parseInt(templateSelectionExpression);+ } catch (NumberFormatException e) {+ // Not a numeric value, keep default 200+ }+ }++ // Select matching response template+ if (responseTemplates != null && !responseTemplates.isEmpty()) {+ String statusStr = String.valueOf(statusCode);+ body = responseTemplates.get(statusStr);+ if (body == null) {+ // Try to find a default or first available template+ body = responseTemplates.values().stream().findFirst().orElse(null);+ }+ }++ return new IntegrationResult(statusCode, body, null);+ }++ /**+ * Apply a request template (VTL) to transform the event payload.+ * Uses templateSelectionExpression to select which template to apply.+ * Falls back to the first available template if no match is found.+ *+ * @param eventJson the original event JSON+ * @param requestTemplates the request templates map (keyed by content type or selection key)+ * @param templateSelectionExpression expression to select which template to use+ * @param stageVariables stage variables for VTL context+ * @return the transformed payload, or the original eventJson if no template applies+ */+ private String applyRequestTemplate(String eventJson, Map<String, String> requestTemplates,+ String templateSelectionExpression,+ Map<String, String> stageVariables) {+ if (requestTemplates == null || requestTemplates.isEmpty()) {+ return eventJson;+ }++ String template = selectTemplate(requestTemplates, templateSelectionExpression);+ if (template == null || template.isEmpty()) {+ return eventJson;+ }++ VtlTemplateEngine.VtlContext vtlCtx = new VtlTemplateEngine.VtlContext(+ eventJson, Map.of(), Map.of(), Map.of(), "", "", "", "", "000000000000",+ stageVariables != null ? stageVariables : Map.of());++ VtlTemplateEngine.EvaluateResult result = vtlEngine.evaluate(template, vtlCtx);+ return result.body();+ }++ /**+ * Apply a response template (VTL) to transform the Lambda response.+ * Uses templateSelectionExpression to select which template to apply.+ * Falls back to matching by status code, then the first available template.+ *+ * @param responseBody the Lambda response body+ * @param responseTemplates the response templates map (keyed by status code or selection key)+ * @param templateSelectionExpression expression to select which template to use+ * @param stageVariables stage variables for VTL context+ * @param statusCode the response status code+ * @return the transformed response body, or the original if no template applies+ */+ private String applyResponseTemplate(String responseBody, Map<String, String> responseTemplates,+ String templateSelectionExpression,+ Map<String, String> stageVariables, int statusCode) {+ if (responseTemplates == null || responseTemplates.isEmpty()) {+ return responseBody;+ }++ // Try to select template by templateSelectionExpression first, then by status code+ String template = selectTemplate(responseTemplates, templateSelectionExpression);+ if (template == null) {+ template = responseTemplates.get(String.valueOf(statusCode));+ }+ if (template == null) {+ // Fall back to first available template+ template = responseTemplates.values().stream().findFirst().orElse(null);+ }+ if (template == null || template.isEmpty()) {+ return responseBody;+ }++ VtlTemplateEngine.VtlContext vtlCtx = new VtlTemplateEngine.VtlContext(+ responseBody, Map.of(), Map.of(), Map.of(), "", "", "", "", "000000000000",+ stageVariables != null ? stageVariables : Map.of());++ VtlTemplateEngine.EvaluateResult result = vtlEngine.evaluate(template, vtlCtx);+ return result.body();+ }++ /**+ * Select a template from the templates map using the templateSelectionExpression.+ * The expression is matched against template keys.+ *+ * @param templates the templates map+ * @param templateSelectionExpression the selection expression+ * @return the selected template value, or null if no match+ */+ private String selectTemplate(Map<String, String> templates, String templateSelectionExpression) {+ if (templates == null || templates.isEmpty()) {+ return null;+ }++ if (templateSelectionExpression != null && !templateSelectionExpression.isEmpty()) {+ // Try exact match with the expression value+ String template = templates.get(templateSelectionExpression);+ if (template != null) {+ return template;+ }+ // Try to find a key that the expression contains or matches+ for (Map.Entry<String, String> entry : templates.entrySet()) {+ if (templateSelectionExpression.contains(entry.getKey())+ || entry.getKey().equals(templateSelectionExpression)) {+ return entry.getValue();+ }+ }+ }++ // Fall back to first available template+ return templates.values().stream().findFirst().orElse(null);+ }++ /**+ * Extract Lambda function name from an integration URI.+ * Delegates to {@link LambdaArnUtils#extractFunctionNameFromUri(String)}.+ *+ * @param uri the integration URI (Lambda ARN or function name)+ * @return the extracted function name, or null if not parseable+ */+ String extractFunctionName(String uri) {+ return LambdaArnUtils.extractFunctionNameFromUri(uri);+ }++ /**+ * Perform stage variable substitution on a URI.+ * Replaces all ${stageVariables.variableName} occurrences with the corresponding+ * value from the stageVariables map. Undefined variables are replaced with empty string.+ *+ * @param uri the URI containing stage variable references+ * @param stageVariables the stage variables map (may be null or empty)+ * @return the URI with all stage variable references substituted+ */+ String substituteStageVariables(String uri, Map<String, String> stageVariables) {+ if (uri == null) {+ return null;+ }+ if (stageVariables == null) {+ stageVariables = Collections.emptyMap();+ }++ Matcher matcher = STAGE_VAR_PATTERN.matcher(uri);+ StringBuilder result = new StringBuilder();+ Map<String, String> vars = stageVariables;++ while (matcher.find()) {+ String variableName = matcher.group(1);+ String replacement = vars.getOrDefault(variableName, "");+ matcher.appendReplacement(result, Matcher.quoteReplacement(replacement));+ }+ matcher.appendTail(result);++ return result.toString();+ }+}diff --git a/src/main/java/io/github/hectorvent/floci/services/apigatewayv2/websocket/WebSocketProxyEventBuilder.java b/src/main/java/io/github/hectorvent/floci/services/apigatewayv2/websocket/WebSocketProxyEventBuilder.javanew file mode 100644index 0000000000..c851fd0483--- /dev/null+++ b/src/main/java/io/github/hectorvent/floci/services/apigatewayv2/websocket/WebSocketProxyEventBuilder.java@@ -0,0 +1,297 @@+package io.github.hectorvent.floci.services.apigatewayv2.websocket;++import com.fasterxml.jackson.databind.ObjectMapper;+import com.fasterxml.jackson.databind.node.ArrayNode;+import com.fasterxml.jackson.databind.node.ObjectNode;+import jakarta.enterprise.context.ApplicationScoped;+import jakarta.inject.Inject;+import org.jboss.logging.Logger;++import java.time.ZoneOffset;+import java.time.ZonedDateTime;+import java.time.format.DateTimeFormatter;+import java.util.List;+import java.util.Locale;+import java.util.Map;+import java.util.UUID;++/**+ * Constructs AWS-compatible WebSocket proxy event JSON payloads for Lambda invocations.+ *+ * Produces CONNECT, MESSAGE, DISCONNECT, and Lambda REQUEST authorizer event formats+ * matching the AWS API Gateway v2 WebSocket proxy integration contract.+ */+@ApplicationScoped+public class WebSocketProxyEventBuilder {++ private static final Logger LOG = Logger.getLogger(WebSocketProxyEventBuilder.class);+ private static final DateTimeFormatter REQUEST_TIME_FORMATTER =+ DateTimeFormatter.ofPattern("dd/MMM/yyyy:HH:mm:ss +0000", Locale.ENGLISH);++ @Inject+ ObjectMapper objectMapper;++ /**+ * Build a CONNECT event from the upgrade request.+ */+ public String buildConnectEvent(String connectionId, String apiId, String stageName,+ String region, long connectedAt,+ Map<String, List<String>> headers,+ Map<String, List<String>> queryParams,+ String sourceIp, String userAgent,+ Map<String, String> stageVariables,+ Map<String, Object> authorizerContext) {+ ObjectNode event = objectMapper.createObjectNode();++ putHeaders(event, headers);+ putMultiValueHeaders(event, headers);+ putQueryStringParameters(event, queryParams);+ putMultiValueQueryStringParameters(event, queryParams);+ putStageVariables(event, stageVariables);++ ObjectNode requestContext = buildRequestContext(connectionId, "$connect", "CONNECT",+ apiId, stageName, region, connectedAt, sourceIp, userAgent);++ // Include authorizer context in requestContext if present+ if (authorizerContext != null && !authorizerContext.isEmpty()) {+ ObjectNode authorizerNode = objectMapper.valueToTree(authorizerContext);+ requestContext.set("authorizer", authorizerNode);+ }++ event.set("requestContext", requestContext);++ event.put("isBase64Encoded", false);++ try {+ return objectMapper.writeValueAsString(event);+ } catch (Exception e) {+ throw new RuntimeException("Failed to serialize CONNECT proxy event", e);+ }+ }++ /**+ * Build a MESSAGE event from an incoming WebSocket message.+ */+ public String buildMessageEvent(String connectionId, String routeKey, String apiId,+ String stageName, String region, long connectedAt,+ String body, String sourceIp, String userAgent,+ Map<String, String> stageVariables) {+ return buildMessageEvent(connectionId, routeKey, apiId, stageName, region, connectedAt,+ body, sourceIp, userAgent, stageVariables, false);+ }++ /**+ * Build a MESSAGE event from an incoming WebSocket message with explicit base64 encoding flag.+ *+ * @param isBase64Encoded true if the body is base64-encoded binary data+ */+ public String buildMessageEvent(String connectionId, String routeKey, String apiId,+ String stageName, String region, long connectedAt,+ String body, String sourceIp, String userAgent,+ Map<String, String> stageVariables, boolean isBase64Encoded) {+ ObjectNode event = objectMapper.createObjectNode();++ ObjectNode requestContext = buildRequestContext(connectionId, routeKey, "MESSAGE",+ apiId, stageName, region, connectedAt, sourceIp, userAgent);+ event.set("requestContext", requestContext);++ if (body != null) {+ event.put("body", body);+ } else {+ event.putNull("body");+ }++ putStageVariables(event, stageVariables);+ event.put("isBase64Encoded", isBase64Encoded);++ try {+ return objectMapper.writeValueAsString(event);+ } catch (Exception e) {+ throw new RuntimeException("Failed to serialize MESSAGE proxy event", e);+ }+ }++ /**+ * Build a DISCONNECT event.+ */+ public String buildDisconnectEvent(String connectionId, String apiId, String stageName,+ String region, long connectedAt,+ String sourceIp, String userAgent,+ Map<String, String> stageVariables) {+ ObjectNode event = objectMapper.createObjectNode();++ ObjectNode requestContext = buildRequestContext(connectionId, "$disconnect", "DISCONNECT",+ apiId, stageName, region, connectedAt, sourceIp, userAgent);+ event.set("requestContext", requestContext);++ event.putNull("body");+ putStageVariables(event, stageVariables);+ event.put("isBase64Encoded", false);++ try {+ return objectMapper.writeValueAsString(event);+ } catch (Exception e) {+ throw new RuntimeException("Failed to serialize DISCONNECT proxy event", e);+ }+ }++ /**+ * Build a Lambda REQUEST authorizer event for $connect.+ */+ public String buildAuthorizerEvent(String connectionId, String apiId, String stageName,+ String region, long connectedAt,+ Map<String, List<String>> headers,+ Map<String, List<String>> queryParams,+ String sourceIp, String userAgent,+ Map<String, String> stageVariables) {+ ObjectNode event = objectMapper.createObjectNode();++ event.put("type", "REQUEST");+ event.put("methodArn", buildMethodArn(region, apiId, stageName));++ putHeaders(event, headers);+ putMultiValueHeaders(event, headers);+ putQueryStringParameters(event, queryParams);+ putMultiValueQueryStringParameters(event, queryParams);+ putStageVariables(event, stageVariables);++ ObjectNode requestContext = objectMapper.createObjectNode();+ requestContext.put("apiId", apiId);+ requestContext.put("stage", stageName);+ requestContext.put("connectionId", connectionId);+ requestContext.put("domainName", buildDomainName(apiId, region));++ String requestId = UUID.randomUUID().toString();+ requestContext.put("requestId", requestId);++ long now = System.currentTimeMillis();+ requestContext.put("requestTime", formatRequestTime(now));+ requestContext.put("requestTimeEpoch", now);++ ObjectNode identity = requestContext.putObject("identity");+ identity.put("sourceIp", sourceIp != null ? sourceIp : "127.0.0.1");+ identity.put("userAgent", userAgent != null ? userAgent : "");++ requestContext.put("eventType", "CONNECT");++ event.set("requestContext", requestContext);++ try {+ return objectMapper.writeValueAsString(event);+ } catch (Exception e) {+ throw new RuntimeException("Failed to serialize authorizer event", e);+ }+ }++ private ObjectNode buildRequestContext(String connectionId, String routeKey, String eventType,+ String apiId, String stageName, String region,+ long connectedAt, String sourceIp, String userAgent) {+ ObjectNode ctx = objectMapper.createObjectNode();++ ctx.put("routeKey", routeKey);+ ctx.put("eventType", eventType);++ String extendedRequestId = UUID.randomUUID().toString();+ ctx.put("extendedRequestId", extendedRequestId);++ long now = System.currentTimeMillis();+ ctx.put("requestTime", formatRequestTime(now));+ ctx.put("messageDirection", "IN");+ ctx.put("stage", stageName);+ ctx.put("connectedAt", connectedAt);+ ctx.put("requestTimeEpoch", now);++ ObjectNode identity = ctx.putObject("identity");+ identity.put("sourceIp", sourceIp != null ? sourceIp : "127.0.0.1");+ identity.put("userAgent", userAgent != null ? userAgent : "");++ String requestId = UUID.randomUUID().toString();+ ctx.put("requestId", requestId);+ ctx.put("domainName", buildDomainName(apiId, region));+ ctx.put("connectionId", connectionId);+ ctx.put("apiId", apiId);++ return ctx;+ }++ private void putHeaders(ObjectNode event, Map<String, List<String>> headers) {+ if (headers != null && !headers.isEmpty()) {+ ObjectNode headersNode = event.putObject("headers");+ for (Map.Entry<String, List<String>> entry : headers.entrySet()) {+ if (entry.getValue() != null && !entry.getValue().isEmpty()) {+ headersNode.put(entry.getKey(), entry.getValue().get(0));+ }+ }+ } else {+ event.putNull("headers");+ }+ }++ private void putMultiValueHeaders(ObjectNode event, Map<String, List<String>> headers) {+ if (headers != null && !headers.isEmpty()) {+ ObjectNode mvHeaders = event.putObject("multiValueHeaders");+ for (Map.Entry<String, List<String>> entry : headers.entrySet()) {+ if (entry.getValue() != null && !entry.getValue().isEmpty()) {+ ArrayNode arr = mvHeaders.putArray(entry.getKey());+ for (String val : entry.getValue()) {+ arr.add(val);+ }+ }+ }+ } else {+ event.putNull("multiValueHeaders");+ }+ }++ private void putQueryStringParameters(ObjectNode event, Map<String, List<String>> queryParams) {+ if (queryParams != null && !queryParams.isEmpty()) {+ ObjectNode qsp = event.putObject("queryStringParameters");+ for (Map.Entry<String, List<String>> entry : queryParams.entrySet()) {+ if (entry.getValue() != null && !entry.getValue().isEmpty()) {+ qsp.put(entry.getKey(), entry.getValue().get(0));+ }+ }+ } else {+ event.putNull("queryStringParameters");+ }+ }++ private void putMultiValueQueryStringParameters(ObjectNode event, Map<String, List<String>> queryParams) {+ if (queryParams != null && !queryParams.isEmpty()) {+ ObjectNode mvQsp = event.putObject("multiValueQueryStringParameters");+ for (Map.Entry<String, List<String>> entry : queryParams.entrySet()) {+ if (entry.getValue() != null && !entry.getValue().isEmpty()) {+ ArrayNode arr = mvQsp.putArray(entry.getKey());+ for (String val : entry.getValue()) {+ arr.add(val);+ }+ }+ }+ } else {+ event.putNull("multiValueQueryStringParameters");+ }+ }++ private void putStageVariables(ObjectNode event, Map<String, String> stageVariables) {+ if (stageVariables != null && !stageVariables.isEmpty()) {+ ObjectNode svNode = event.putObject("stageVariables");+ stageVariables.forEach(svNode::put);+ } else {+ event.putNull("stageVariables");+ }+ }++ private String buildDomainName(String apiId, String region) {+ return apiId + ".execute-api." + region + ".amazonaws.com";+ }++ private String buildMethodArn(String region, String apiId, String stageName) {+ return "arn:aws:execute-api:" + region + ":000000000000:" + apiId + "/" + stageName + "/$connect";+ }++ private String formatRequestTime(long epochMillis) {+ ZonedDateTime time = ZonedDateTime.ofInstant(+ java.time.Instant.ofEpochMilli(epochMillis), ZoneOffset.UTC);+ return REQUEST_TIME_FORMATTER.format(time);+ }+}diff --git a/src/main/java/io/github/hectorvent/floci/services/apigatewayv2/websocket/WebSocketRouteResolver.java b/src/main/java/io/github/hectorvent/floci/services/apigatewayv2/websocket/WebSocketRouteResolver.javanew file mode 100644index 0000000000..8076449df4--- /dev/null+++ b/src/main/java/io/github/hectorvent/floci/services/apigatewayv2/websocket/WebSocketRouteResolver.java@@ -0,0 +1,101 @@+package io.github.hectorvent.floci.services.apigatewayv2.websocket;++import io.github.hectorvent.floci.core.common.AwsException;+import io.github.hectorvent.floci.services.apigatewayv2.ApiGatewayV2Service;+import io.github.hectorvent.floci.services.apigatewayv2.model.Api;+import io.github.hectorvent.floci.services.apigatewayv2.model.Route;+import jakarta.enterprise.context.ApplicationScoped;+import jakarta.inject.Inject;+import org.jboss.logging.Logger;++/**+ * Resolves the target route for an incoming WebSocket message based on the API's+ * routeSelectionExpression and configured routes.+ *+ * Extracted from WebSocketHandler for independent testability and to keep the handler thin.+ */+@ApplicationScoped+public class WebSocketRouteResolver {++ private static final Logger LOG = Logger.getLogger(WebSocketRouteResolver.class);++ private final ApiGatewayV2Service apiGatewayV2Service;+ private final RouteSelectionEvaluator routeSelectionEvaluator;++ @Inject+ public WebSocketRouteResolver(ApiGatewayV2Service apiGatewayV2Service,+ RouteSelectionEvaluator routeSelectionEvaluator) {+ this.apiGatewayV2Service = apiGatewayV2Service;+ this.routeSelectionEvaluator = routeSelectionEvaluator;+ }++ /**+ * Result of route resolution.+ *+ * @param route the matched route (null if no route found)+ * @param effectiveRouteKey the route key to use in the proxy event+ * @param errorMessage error message to send to client if no route found (null if route was found)+ */+ public record RouteResolution(Route route, String effectiveRouteKey, String errorMessage) {++ public boolean hasRoute() {+ return route != null;+ }++ public static RouteResolution matched(Route route, String effectiveRouteKey) {+ return new RouteResolution(route, effectiveRouteKey, null);+ }++ public static RouteResolution noRoute(String errorMessage) {+ return new RouteResolution(null, null, errorMessage);+ }+ }++ /**+ * Resolve the target route for a message.+ *+ * @param region the AWS region+ * @param apiId the API ID+ * @param message the raw message body+ * @return RouteResolution with the matched route or an error message+ */+ public RouteResolution resolve(String region, String apiId, String message) {+ // Load the API to get routeSelectionExpression+ Api api;+ try {+ api = apiGatewayV2Service.getApi(region, apiId);+ } catch (AwsException e) {+ LOG.warnv("Failed to load API {0} for message routing: {1}", apiId, e.getMessage());+ return RouteResolution.noRoute("Internal server error");+ }++ String routeSelectionExpression = api.getRouteSelectionExpression();++ // Evaluate routeSelectionExpression against the message+ String routeKey = routeSelectionEvaluator.evaluate(routeSelectionExpression, message);++ // Look up matching route+ Route route = null;+ if (routeKey != null) {+ route = apiGatewayV2Service.findRouteByKey(region, apiId, routeKey);+ }++ // Fall back to $default if no match+ if (route == null) {+ route = apiGatewayV2Service.findRouteByKey(region, apiId, "$default");+ }++ // If no route found (no match and no $default)+ if (route == null) {+ if (routeKey == null) {+ return RouteResolution.noRoute("Could not route message");+ } else {+ return RouteResolution.noRoute("No route found");+ }+ }++ // Determine the effective route key for the proxy event+ String effectiveRouteKey = routeKey != null ? routeKey : "$default";+ return RouteResolution.matched(route, effectiveRouteKey);+ }+}diff --git a/src/main/java/io/github/hectorvent/floci/services/lambda/LambdaArnUtils.java b/src/main/java/io/github/hectorvent/floci/services/lambda/LambdaArnUtils.javaindex a339a843f9..ce1e3eb24e 100644--- a/src/main/java/io/github/hectorvent/floci/services/lambda/LambdaArnUtils.java+++ b/src/main/java/io/github/hectorvent/floci/services/lambda/LambdaArnUtils.java@@ -161,4 +161,41 @@ public final class LambdaArnUtils {private static AwsException invalid(String message) {return new AwsException("InvalidParameterValueException", message, 400);}++ /**+ * Extracts the Lambda function name from an API Gateway integration URI.+ * Handles formats like:+ * <ul>+ * <li>{@code arn:aws:lambda:us-east-1:000000000000:function:myFn/invocations}</li>+ * <li>{@code arn:aws:lambda:us-east-1:000000000000:function:myFn}</li>+ * <li>{@code myFn} (bare function name)</li>+ * </ul>+ *+ * @param uri the integration URI (may be null)+ * @return the extracted function name, or null if the URI is null or unparseable+ */+ public static String extractFunctionNameFromUri(String uri) {+ if (uri == null) {+ return null;+ }+ try {+ // Parse as a full ARN — resource is "function:myFn" or "function:myFn/invocations"+ String resource = AwsArnUtils.parse(uri).resource();+ String[] parts = resource.split("/");+ // API Gateway v1 style: resource is "path/2015-03-31/functions/{lambdaArn}/invocations"+ // In this case recurse on the embedded Lambda ARN+ if (parts.length >= 4 && "path".equals(parts[0]) && "functions".equals(parts[2])) {+ // parts[3] onwards is the embedded Lambda ARN+ String embeddedArn = String.join("/", java.util.Arrays.copyOfRange(parts, 3, parts.length));+ return extractFunctionNameFromUri(embeddedArn);+ }+ // Standard Lambda ARN: parts[0] is "function:myFn", strip the "function:" prefix+ String functionPart = parts[0];+ int colon = functionPart.lastIndexOf(':');+ return colon >= 0 ? functionPart.substring(colon + 1) : functionPart;+ } catch (IllegalArgumentException e) {+ // Not a valid ARN — treat the entire URI as the function name+ return uri;+ }+ }}diff --git a/src/test/java/io/github/hectorvent/floci/services/apigatewayv2/WebSocketAwsHttpIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/apigatewayv2/WebSocketAwsHttpIntegrationTest.javanew file mode 100644index 0000000000..1c5ee21c07--- /dev/null+++ b/src/test/java/io/github/hectorvent/floci/services/apigatewayv2/WebSocketAwsHttpIntegrationTest.java@@ -0,0 +1,537 @@+package io.github.hectorvent.floci.services.apigatewayv2;++import com.fasterxml.jackson.databind.JsonNode;+import com.fasterxml.jackson.databind.ObjectMapper;+import io.quarkus.test.junit.QuarkusTest;+import io.restassured.http.ContentType;+import org.junit.jupiter.api.MethodOrderer;+import org.junit.jupiter.api.Order;+import org.junit.jupiter.api.Test;+import org.junit.jupiter.api.TestMethodOrder;++import java.net.URI;+import java.net.http.HttpClient;+import java.net.http.WebSocket;+import java.util.concurrent.TimeUnit;++import static io.restassured.RestAssured.given;+import static org.hamcrest.Matchers.notNullValue;+import static org.junit.jupiter.api.Assertions.*;++/**+ * Integration tests for WebSocket AWS, HTTP_PROXY, and HTTP integration types.+ *+ * <ul>+ * <li>AWS integration: Lambda invocation with VTL request/response template transformation</li>+ * <li>HTTP_PROXY integration: passthrough HTTP POST forwarding, no VTL transformation</li>+ * <li>HTTP integration: HTTP POST forwarding with VTL request/response template transformation</li>+ * </ul>+ */+@QuarkusTest+@TestMethodOrder(MethodOrderer.OrderAnnotation.class)+class WebSocketAwsHttpIntegrationTest {++ @io.quarkus.test.common.http.TestHTTPResource("/")+ URI baseUri;++ private static final ObjectMapper MAPPER = new ObjectMapper();++ // -- AWS integration type --+ private static String awsApiId;+ private static String awsFnName = "ws-aws-integ-fn";+ private static String awsConnectFnName = "ws-aws-integ-connect-fn";++ // -- HTTP_PROXY integration type --+ private static String httpProxyApiId;+ private static String httpProxyConnectFnName = "ws-http-proxy-connect-fn";++ // -- HTTP integration type --+ private static String httpApiId;+ private static String httpConnectFnName = "ws-http-integ-connect-fn";++ // -- Stage variable test --+ private static String stageVarHttpApiId;+ private static String stageVarHttpFnName = "ws-sv-http-connect-fn";++ // ──────────────────────────── Setup: Lambda Functions ────────────────────────────++ @Test+ @Order(1)+ void setupLambdaFunctions() throws Exception {+ // Lambda for AWS integration: echoes the received payload wrapped in a response+ String awsZip = WebSocketTestSupport.createLambdaZip("""+ exports.handler = async (event) => {+ // For AWS integration, the event is the VTL-transformed payload+ return { transformed: true, input: event };+ };+ """);+ given()+ .contentType(ContentType.JSON)+ .body("""+ {"FunctionName":"%s","Runtime":"nodejs20.x","Role":"arn:aws:iam::000000000000:role/lambda-role","Handler":"index.handler","Timeout":30,"Code":{"ZipFile":"%s"}}+ """.formatted(awsFnName, awsZip))+ .when().post("/2015-03-31/functions")+ .then()+ .statusCode(201);++ // Connect handler (simple allow)+ String connectZip = WebSocketTestSupport.createLambdaZip(+ "exports.handler = async (event) => ({ statusCode: 200, body: 'connected' });");+ given()+ .contentType(ContentType.JSON)+ .body("""+ {"FunctionName":"%s","Runtime":"nodejs20.x","Role":"arn:aws:iam::000000000000:role/lambda-role","Handler":"index.handler","Timeout":30,"Code":{"ZipFile":"%s"}}+ """.formatted(awsConnectFnName, connectZip))+ .when().post("/2015-03-31/functions")+ .then()+ .statusCode(201);++ given()+ .contentType(ContentType.JSON)+ .body("""+ {"FunctionName":"%s","Runtime":"nodejs20.x","Role":"arn:aws:iam::000000000000:role/lambda-role","Handler":"index.handler","Timeout":30,"Code":{"ZipFile":"%s"}}+ """.formatted(httpProxyConnectFnName, connectZip))+ .when().post("/2015-03-31/functions")+ .then()+ .statusCode(201);++ given()+ .contentType(ContentType.JSON)+ .body("""+ {"FunctionName":"%s","Runtime":"nodejs20.x","Role":"arn:aws:iam::000000000000:role/lambda-role","Handler":"index.handler","Timeout":30,"Code":{"ZipFile":"%s"}}+ """.formatted(httpConnectFnName, connectZip))+ .when().post("/2015-03-31/functions")+ .then()+ .statusCode(201);++ given()+ .contentType(ContentType.JSON)+ .body("""+ {"FunctionName":"%s","Runtime":"nodejs20.x","Role":"arn:aws:iam::000000000000:role/lambda-role","Handler":"index.handler","Timeout":30,"Code":{"ZipFile":"%s"}}+ """.formatted(stageVarHttpFnName, connectZip))+ .when().post("/2015-03-31/functions")+ .then()+ .statusCode(201);++ // Prewarm all functions+ for (String fn : new String[]{awsFnName, awsConnectFnName, httpProxyConnectFnName, httpConnectFnName, stageVarHttpFnName}) {+ given().contentType(ContentType.JSON).body("{}")+ .when().post("/2015-03-31/functions/" + fn + "/invocations")+ .then().statusCode(200);+ }+ }++ // ──────────────────────────── AWS Integration Type Tests ────────────────────────────++ @Test+ @Order(10)+ void setupAwsIntegrationApi() {+ awsApiId = given()+ .contentType(ContentType.JSON)+ .body("""+ {"name":"ws-aws-integ-test","protocolType":"WEBSOCKET","routeSelectionExpression":"$request.body.action"}+ """)+ .when().post("/v2/apis")+ .then()+ .statusCode(201)+ .body("apiId", notNullValue())+ .extract().path("apiId");++ given()+ .contentType(ContentType.JSON)+ .body("""+ {"stageName":"test"}+ """)+ .when().post("/v2/apis/" + awsApiId + "/stages")+ .then()+ .statusCode(201);++ String connectIntegId = given()+ .contentType(ContentType.JSON)+ .body("""+ {"integrationType":"AWS_PROXY","integrationUri":"arn:aws:lambda:us-east-1:000000000000:function:%s/invocations","integrationMethod":"POST"}+ """.formatted(awsConnectFnName))+ .when().post("/v2/apis/" + awsApiId + "/integrations")+ .then()+ .statusCode(201)+ .extract().path("integrationId");++ String awsIntegId = given()+ .contentType(ContentType.JSON)+ .body("""+ {"integrationType":"AWS","integrationUri":"arn:aws:lambda:us-east-1:000000000000:function:%s/invocations","integrationMethod":"POST","requestTemplates":{"$default":"{\\"wrapped\\": true, \\"originalBody\\": $input.body}"},"responseTemplates":{"$default":"{\\"result\\": $input.body}"},"templateSelectionExpression":"$default"}+ """.formatted(awsFnName))+ .when().post("/v2/apis/" + awsApiId + "/integrations")+ .then()+ .statusCode(201)+ .extract().path("integrationId");++ given()+ .contentType(ContentType.JSON)+ .body("""+ {"routeKey":"$connect","target":"integrations/%s"}+ """.formatted(connectIntegId))+ .when().post("/v2/apis/" + awsApiId + "/routes")+ .then()+ .statusCode(201);++ given()+ .contentType(ContentType.JSON)+ .body("""+ {"routeKey":"$default","target":"integrations/%s","routeResponseSelectionExpression":"$default"}+ """.formatted(awsIntegId))+ .when().post("/v2/apis/" + awsApiId + "/routes")+ .then()+ .statusCode(201);+ }++ @Test+ @Order(11)+ void awsIntegrationInvokesLambdaWithTemplateTransformation() throws Exception {+ WebSocketTestSupport.MultiMessageCapture capture = new WebSocketTestSupport.MultiMessageCapture();+ WebSocket ws = connectWebSocket(awsApiId, "test", capture);+ assertNotNull(ws, "WebSocket connection should succeed");++ ws.sendText("{\"action\":\"test\",\"data\":\"hello-aws\"}", true).join();+ String response = capture.getNextMessage(15, TimeUnit.SECONDS);+ assertNotNull(response, "Should receive response from AWS integration");++ JsonNode responseNode = MAPPER.readTree(response);+ assertTrue(responseNode.has("result"), "Response should have 'result' field from response template");++ ws.sendClose(WebSocket.NORMAL_CLOSURE, "done").join();+ Thread.sleep(500);+ }++ @Test+ @Order(12)+ void awsIntegrationWithoutTemplatesPassesThrough() throws Exception {+ WebSocketTestSupport.MultiMessageCapture capture = new WebSocketTestSupport.MultiMessageCapture();+ WebSocket ws = connectWebSocket(awsApiId, "test", capture);+ assertNotNull(ws, "WebSocket connection should succeed");++ ws.sendText("{\"action\":\"verify\",\"value\":42}", true).join();+ String response = capture.getNextMessage(15, TimeUnit.SECONDS);+ assertNotNull(response, "Should receive response");++ ws.sendClose(WebSocket.NORMAL_CLOSURE, "done").join();+ Thread.sleep(500);+ }++ // ──────────────────────────── HTTP_PROXY Integration Type Tests ────────────────────────────++ @Test+ @Order(20)+ void setupHttpProxyIntegrationApi() {+ httpProxyApiId = given()+ .contentType(ContentType.JSON)+ .body("""+ {"name":"ws-http-proxy-test","protocolType":"WEBSOCKET","routeSelectionExpression":"$request.body.action"}+ """)+ .when().post("/v2/apis")+ .then()+ .statusCode(201)+ .body("apiId", notNullValue())+ .extract().path("apiId");++ given()+ .contentType(ContentType.JSON)+ .body("""+ {"stageName":"test"}+ """)+ .when().post("/v2/apis/" + httpProxyApiId + "/stages")+ .then()+ .statusCode(201);++ String connectIntegId = given()+ .contentType(ContentType.JSON)+ .body("""+ {"integrationType":"AWS_PROXY","integrationUri":"arn:aws:lambda:us-east-1:000000000000:function:%s/invocations","integrationMethod":"POST"}+ """.formatted(httpProxyConnectFnName))+ .when().post("/v2/apis/" + httpProxyApiId + "/integrations")+ .then()+ .statusCode(201)+ .extract().path("integrationId");++ String httpTargetUrl = baseUri.toString() + "2015-03-31/functions/" + awsFnName + "/invocations";+ String httpProxyIntegId = given()+ .contentType(ContentType.JSON)+ .body("""+ {"integrationType":"HTTP_PROXY","integrationUri":"%s","integrationMethod":"POST"}+ """.formatted(httpTargetUrl))+ .when().post("/v2/apis/" + httpProxyApiId + "/integrations")+ .then()+ .statusCode(201)+ .extract().path("integrationId");++ given()+ .contentType(ContentType.JSON)+ .body("""+ {"routeKey":"$connect","target":"integrations/%s"}+ """.formatted(connectIntegId))+ .when().post("/v2/apis/" + httpProxyApiId + "/routes")+ .then()+ .statusCode(201);++ given()+ .contentType(ContentType.JSON)+ .body("""+ {"routeKey":"$default","target":"integrations/%s","routeResponseSelectionExpression":"$default"}+ """.formatted(httpProxyIntegId))+ .when().post("/v2/apis/" + httpProxyApiId + "/routes")+ .then()+ .statusCode(201);+ }++ @Test+ @Order(21)+ void httpProxyIntegrationForwardsEventAsPost() throws Exception {+ WebSocketTestSupport.MultiMessageCapture capture = new WebSocketTestSupport.MultiMessageCapture();+ WebSocket ws = connectWebSocket(httpProxyApiId, "test", capture);+ assertNotNull(ws, "WebSocket connection should succeed");++ ws.sendText("{\"action\":\"test\",\"data\":\"hello-http-proxy\"}", true).join();+ String response = capture.getNextMessage(15, TimeUnit.SECONDS);+ assertNotNull(response, "Should receive response from HTTP_PROXY integration");++ JsonNode responseNode = MAPPER.readTree(response);+ assertTrue(responseNode.has("transformed") || responseNode.has("input"),+ "Response should contain Lambda output forwarded via HTTP_PROXY");++ ws.sendClose(WebSocket.NORMAL_CLOSURE, "done").join();+ Thread.sleep(500);+ }++ @Test+ @Order(22)+ void httpProxyIntegrationNoTemplateTransformation() throws Exception {+ WebSocketTestSupport.MultiMessageCapture capture = new WebSocketTestSupport.MultiMessageCapture();+ WebSocket ws = connectWebSocket(httpProxyApiId, "test", capture);+ assertNotNull(ws, "WebSocket connection should succeed");++ ws.sendText("{\"action\":\"raw\",\"payload\":\"no-transform\"}", true).join();+ String response = capture.getNextMessage(15, TimeUnit.SECONDS);+ assertNotNull(response, "Should receive response without template transformation");++ ws.sendClose(WebSocket.NORMAL_CLOSURE, "done").join();+ Thread.sleep(500);+ }++ // ──────────────────────────── HTTP Integration Type Tests ────────────────────────────++ @Test+ @Order(30)+ void setupHttpIntegrationApi() {+ httpApiId = given()+ .contentType(ContentType.JSON)+ .body("""+ {"name":"ws-http-integ-test","protocolType":"WEBSOCKET","routeSelectionExpression":"$request.body.action"}+ """)+ .when().post("/v2/apis")+ .then()+ .statusCode(201)+ .body("apiId", notNullValue())+ .extract().path("apiId");++ given()+ .contentType(ContentType.JSON)+ .body("""+ {"stageName":"test"}+ """)+ .when().post("/v2/apis/" + httpApiId + "/stages")+ .then()+ .statusCode(201);++ String connectIntegId = given()+ .contentType(ContentType.JSON)+ .body("""+ {"integrationType":"AWS_PROXY","integrationUri":"arn:aws:lambda:us-east-1:000000000000:function:%s/invocations","integrationMethod":"POST"}+ """.formatted(httpConnectFnName))+ .when().post("/v2/apis/" + httpApiId + "/integrations")+ .then()+ .statusCode(201)+ .extract().path("integrationId");++ String httpTargetUrl = baseUri.toString() + "2015-03-31/functions/" + awsFnName + "/invocations";+ String httpIntegId = given()+ .contentType(ContentType.JSON)+ .body("""+ {"integrationType":"HTTP","integrationUri":"%s","integrationMethod":"POST","requestTemplates":{"$default":"{\\"httpWrapped\\": true, \\"body\\": $input.body}"},"responseTemplates":{"$default":"{\\"httpResult\\": $input.body}"},"templateSelectionExpression":"$default"}+ """.formatted(httpTargetUrl))+ .when().post("/v2/apis/" + httpApiId + "/integrations")+ .then()+ .statusCode(201)+ .extract().path("integrationId");++ given()+ .contentType(ContentType.JSON)+ .body("""+ {"routeKey":"$connect","target":"integrations/%s"}+ """.formatted(connectIntegId))+ .when().post("/v2/apis/" + httpApiId + "/routes")+ .then()+ .statusCode(201);++ given()+ .contentType(ContentType.JSON)+ .body("""+ {"routeKey":"$default","target":"integrations/%s","routeResponseSelectionExpression":"$default"}+ """.formatted(httpIntegId))+ .when().post("/v2/apis/" + httpApiId + "/routes")+ .then()+ .statusCode(201);+ }++ @Test+ @Order(31)+ void httpIntegrationAppliesRequestAndResponseTemplates() throws Exception {+ WebSocketTestSupport.MultiMessageCapture capture = new WebSocketTestSupport.MultiMessageCapture();+ WebSocket ws = connectWebSocket(httpApiId, "test", capture);+ assertNotNull(ws, "WebSocket connection should succeed");++ ws.sendText("{\"action\":\"test\",\"data\":\"hello-http\"}", true).join();+ String response = capture.getNextMessage(15, TimeUnit.SECONDS);+ assertNotNull(response, "Should receive response from HTTP integration");++ JsonNode responseNode = MAPPER.readTree(response);+ assertTrue(responseNode.has("httpResult"),+ "Response should have 'httpResult' field from response template");++ ws.sendClose(WebSocket.NORMAL_CLOSURE, "done").join();+ Thread.sleep(500);+ }++ @Test+ @Order(32)+ void httpIntegrationForwardsToCorrectEndpoint() throws Exception {+ WebSocketTestSupport.MultiMessageCapture capture = new WebSocketTestSupport.MultiMessageCapture();+ WebSocket ws = connectWebSocket(httpApiId, "test", capture);+ assertNotNull(ws, "WebSocket connection should succeed");++ ws.sendText("{\"action\":\"verify\",\"value\":\"http-forward\"}", true).join();+ String response = capture.getNextMessage(15, TimeUnit.SECONDS);+ assertNotNull(response, "Should receive response from HTTP endpoint");++ ws.sendClose(WebSocket.NORMAL_CLOSURE, "done").join();+ Thread.sleep(500);+ }++ // ──────────────────────────── Stage Variable Substitution in HTTP URI ────────────────────────────++ @Test+ @Order(40)+ void setupStageVariableHttpApi() {+ stageVarHttpApiId = given()+ .contentType(ContentType.JSON)+ .body("""+ {"name":"ws-sv-http-test","protocolType":"WEBSOCKET","routeSelectionExpression":"$request.body.action"}+ """)+ .when().post("/v2/apis")+ .then()+ .statusCode(201)+ .body("apiId", notNullValue())+ .extract().path("apiId");++ String httpTargetUrl = baseUri.toString() + "2015-03-31/functions/" + awsFnName + "/invocations";+ given()+ .contentType(ContentType.JSON)+ .body("""+ {"stageName":"test","stageVariables":{"httpTarget":"%s"}}+ """.formatted(httpTargetUrl))+ .when().post("/v2/apis/" + stageVarHttpApiId + "/stages")+ .then()+ .statusCode(201);++ String connectIntegId = given()+ .contentType(ContentType.JSON)+ .body("""+ {"integrationType":"AWS_PROXY","integrationUri":"arn:aws:lambda:us-east-1:000000000000:function:%s/invocations","integrationMethod":"POST"}+ """.formatted(stageVarHttpFnName))+ .when().post("/v2/apis/" + stageVarHttpApiId + "/integrations")+ .then()+ .statusCode(201)+ .extract().path("integrationId");++ String httpProxyIntegId = given()+ .contentType(ContentType.JSON)+ .body("""+ {"integrationType":"HTTP_PROXY","integrationUri":"${stageVariables.httpTarget}","integrationMethod":"POST"}+ """)+ .when().post("/v2/apis/" + stageVarHttpApiId + "/integrations")+ .then()+ .statusCode(201)+ .extract().path("integrationId");++ given()+ .contentType(ContentType.JSON)+ .body("""+ {"routeKey":"$connect","target":"integrations/%s"}+ """.formatted(connectIntegId))+ .when().post("/v2/apis/" + stageVarHttpApiId + "/routes")+ .then()+ .statusCode(201);++ given()+ .contentType(ContentType.JSON)+ .body("""+ {"routeKey":"$default","target":"integrations/%s","routeResponseSelectionExpression":"$default"}+ """.formatted(httpProxyIntegId))+ .when().post("/v2/apis/" + stageVarHttpApiId + "/routes")+ .then()+ .statusCode(201);+ }++ @Test+ @Order(41)+ void httpProxyIntegrationSubstitutesStageVariablesInUri() throws Exception {+ WebSocketTestSupport.MultiMessageCapture capture = new WebSocketTestSupport.MultiMessageCapture();+ WebSocket ws = connectWebSocket(stageVarHttpApiId, "test", capture);+ assertNotNull(ws, "WebSocket connection should succeed with stage variable URI");++ ws.sendText("{\"action\":\"test\",\"data\":\"stage-var-http\"}", true).join();+ String response = capture.getNextMessage(15, TimeUnit.SECONDS);+ assertNotNull(response, "Should receive response after stage variable substitution in HTTP URI");++ JsonNode responseNode = MAPPER.readTree(response);+ assertTrue(responseNode.has("transformed") || responseNode.has("input"),+ "Response should come from Lambda invoked via stage-variable-resolved HTTP URI");++ ws.sendClose(WebSocket.NORMAL_CLOSURE, "done").join();+ Thread.sleep(500);+ }++ // ──────────────────────────── Cleanup ────────────────────────────++ @Test+ @Order(999)+ void cleanup() {+ if (awsApiId != null) {+ given().when().delete("/v2/apis/" + awsApiId);+ }+ if (httpProxyApiId != null) {+ given().when().delete("/v2/apis/" + httpProxyApiId);+ }+ if (httpApiId != null) {+ given().when().delete("/v2/apis/" + httpApiId);+ }+ if (stageVarHttpApiId != null) {+ given().when().delete("/v2/apis/" + stageVarHttpApiId);+ }++ for (String fn : new String[]{awsFnName, awsConnectFnName, httpProxyConnectFnName,+ httpConnectFnName, stageVarHttpFnName}) {+ given().when().delete("/2015-03-31/functions/" + fn);+ }+ }++ // ──────────────────────────── Helpers ────────────────────────────++ private WebSocket connectWebSocket(String apiId, String stageName,+ WebSocketTestSupport.MultiMessageCapture capture) throws Exception {+ String wsUrl = WebSocketTestSupport.buildWsUrl(baseUri, apiId, stageName);+ HttpClient client = HttpClient.newHttpClient();+ return client.newWebSocketBuilder()+ .buildAsync(URI.create(wsUrl), capture)+ .get(60, TimeUnit.SECONDS);+ }+}diff --git a/src/test/java/io/github/hectorvent/floci/services/apigatewayv2/WebSocketConnectionLifecycleTest.java b/src/test/java/io/github/hectorvent/floci/services/apigatewayv2/WebSocketConnectionLifecycleTest.javanew file mode 100644index 0000000000..5f90d25a7e--- /dev/null+++ b/src/test/java/io/github/hectorvent/floci/services/apigatewayv2/WebSocketConnectionLifecycleTest.java@@ -0,0 +1,548 @@+package io.github.hectorvent.floci.services.apigatewayv2;++import io.quarkus.test.junit.QuarkusTest;+import io.restassured.http.ContentType;+import org.junit.jupiter.api.MethodOrderer;+import org.junit.jupiter.api.Order;+import org.junit.jupiter.api.Test;+import org.junit.jupiter.api.TestMethodOrder;++import java.net.URI;+import java.net.http.HttpClient;+import java.net.http.WebSocket;+import java.util.HashSet;+import java.util.Set;+import java.util.concurrent.CompletableFuture;+import java.util.concurrent.CompletionStage;+import java.util.concurrent.TimeUnit;++import static io.restassured.RestAssured.given;+import static org.hamcrest.Matchers.notNullValue;+import static org.junit.jupiter.api.Assertions.*;++/**+ * Integration tests for WebSocket connection lifecycle.+ */+@QuarkusTest+@TestMethodOrder(MethodOrderer.OrderAnnotation.class)+class WebSocketConnectionLifecycleTest {++ @io.quarkus.test.common.http.TestHTTPResource("/")+ URI baseUri;++ private static String wsApiId;+ private static String httpApiId;+ private static String allowFunctionName = "ws-connect-allow-fn";+ private static String denyFunctionName = "ws-connect-deny-fn";+ private static String errorFunctionName = "ws-connect-error-fn";+ private static String disconnectFunctionName = "ws-disconnect-fn";+ private static String integrationIdAllow;+ private static String integrationIdDeny;+ private static String integrationIdError;+ private static String integrationIdDisconnect;+ private static String connectRouteId;+ private static String disconnectRouteId;++ // ──────────────────────────── Setup ────────────────────────────++ @Test+ @Order(1)+ void setupWebSocketApi() {+ // Create a WEBSOCKET API+ wsApiId = given()+ .contentType(ContentType.JSON)+ .body("""+ {"name":"ws-lifecycle-test","protocolType":"WEBSOCKET","routeSelectionExpression":"$request.body.action"}+ """)+ .when().post("/v2/apis")+ .then()+ .statusCode(201)+ .body("apiId", notNullValue())+ .extract().path("apiId");++ // Create a stage+ given()+ .contentType(ContentType.JSON)+ .body("""+ {"stageName":"test"}+ """)+ .when().post("/v2/apis/" + wsApiId + "/stages")+ .then()+ .statusCode(201);+ }++ @Test+ @Order(2)+ void setupHttpApi() {+ // Create an HTTP API (non-WebSocket) for negative test+ httpApiId = given()+ .contentType(ContentType.JSON)+ .body("""+ {"name":"http-lifecycle-test","protocolType":"HTTP"}+ """)+ .when().post("/v2/apis")+ .then()+ .statusCode(201)+ .extract().path("apiId");++ // Create a stage on the HTTP API+ given()+ .contentType(ContentType.JSON)+ .body("""+ {"stageName":"test"}+ """)+ .when().post("/v2/apis/" + httpApiId + "/stages")+ .then()+ .statusCode(201);+ }++ @Test+ @Order(3)+ void setupLambdaFunctions() throws Exception {+ // Create Lambda function that returns 200 (allow connection)+ String allowZip = WebSocketTestSupport.createLambdaZip("exports.handler = async (event) => ({ statusCode: 200, body: 'connected' });");+ given()+ .contentType(ContentType.JSON)+ .body("""+ {"FunctionName":"%s","Runtime":"nodejs20.x","Role":"arn:aws:iam::000000000000:role/lambda-role","Handler":"index.handler","Timeout":30,"Code":{"ZipFile":"%s"}}+ """.formatted(allowFunctionName, allowZip))+ .when().post("/2015-03-31/functions")+ .then()+ .statusCode(201);++ // Create Lambda function that returns 403 (deny connection)+ String denyZip = WebSocketTestSupport.createLambdaZip("exports.handler = async (event) => ({ statusCode: 403, body: 'denied' });");+ given()+ .contentType(ContentType.JSON)+ .body("""+ {"FunctionName":"%s","Runtime":"nodejs20.x","Role":"arn:aws:iam::000000000000:role/lambda-role","Handler":"index.handler","Timeout":30,"Code":{"ZipFile":"%s"}}+ """.formatted(denyFunctionName, denyZip))+ .when().post("/2015-03-31/functions")+ .then()+ .statusCode(201);++ // Create Lambda function that throws an error+ String errorZip = WebSocketTestSupport.createLambdaZip("exports.handler = async (event) => { throw new Error('connection error'); };");+ given()+ .contentType(ContentType.JSON)+ .body("""+ {"FunctionName":"%s","Runtime":"nodejs20.x","Role":"arn:aws:iam::000000000000:role/lambda-role","Handler":"index.handler","Timeout":30,"Code":{"ZipFile":"%s"}}+ """.formatted(errorFunctionName, errorZip))+ .when().post("/2015-03-31/functions")+ .then()+ .statusCode(201);++ // Create Lambda function for $disconnect route+ String disconnectZip = WebSocketTestSupport.createLambdaZip("exports.handler = async (event) => ({ statusCode: 200, body: 'disconnected' });");+ given()+ .contentType(ContentType.JSON)+ .body("""+ {"FunctionName":"%s","Runtime":"nodejs20.x","Role":"arn:aws:iam::000000000000:role/lambda-role","Handler":"index.handler","Timeout":30,"Code":{"ZipFile":"%s"}}+ """.formatted(disconnectFunctionName, disconnectZip))+ .when().post("/2015-03-31/functions")+ .then()+ .statusCode(201);+ }++ @Test+ @Order(5)+ void prewarmLambdaFunctions() {+ // Pre-warm Lambda containers by invoking them directly.+ // This ensures containers are ready before WebSocket tests run.+ given()+ .contentType(ContentType.JSON)+ .body("{}")+ .when().post("/2015-03-31/functions/" + allowFunctionName + "/invocations")+ .then()+ .statusCode(200);++ given()+ .contentType(ContentType.JSON)+ .body("{}")+ .when().post("/2015-03-31/functions/" + denyFunctionName + "/invocations")+ .then()+ .statusCode(200);++ given()+ .contentType(ContentType.JSON)+ .body("{}")+ .when().post("/2015-03-31/functions/" + disconnectFunctionName + "/invocations")+ .then()+ .statusCode(200);++ // Error function will throw, but that's fine — we just want the container warm+ given()+ .contentType(ContentType.JSON)+ .body("{}")+ .when().post("/2015-03-31/functions/" + errorFunctionName + "/invocations")+ .then()+ .statusCode(200);+ }++ @Test+ @Order(4)+ void setupIntegrations() {+ // Create integration for allow function+ integrationIdAllow = given()+ .contentType(ContentType.JSON)+ .body("""+ {"integrationType":"AWS_PROXY","integrationUri":"arn:aws:lambda:us-east-1:000000000000:function:%s/invocations","integrationMethod":"POST"}+ """.formatted(allowFunctionName))+ .when().post("/v2/apis/" + wsApiId + "/integrations")+ .then()+ .statusCode(201)+ .extract().path("integrationId");++ // Create integration for deny function+ integrationIdDeny = given()+ .contentType(ContentType.JSON)+ .body("""+ {"integrationType":"AWS_PROXY","integrationUri":"arn:aws:lambda:us-east-1:000000000000:function:%s/invocations","integrationMethod":"POST"}+ """.formatted(denyFunctionName))+ .when().post("/v2/apis/" + wsApiId + "/integrations")+ .then()+ .statusCode(201)+ .extract().path("integrationId");++ // Create integration for error function+ integrationIdError = given()+ .contentType(ContentType.JSON)+ .body("""+ {"integrationType":"AWS_PROXY","integrationUri":"arn:aws:lambda:us-east-1:000000000000:function:%s/invocations","integrationMethod":"POST"}+ """.formatted(errorFunctionName))+ .when().post("/v2/apis/" + wsApiId + "/integrations")+ .then()+ .statusCode(201)+ .extract().path("integrationId");++ // Create integration for disconnect function+ integrationIdDisconnect = given()+ .contentType(ContentType.JSON)+ .body("""+ {"integrationType":"AWS_PROXY","integrationUri":"arn:aws:lambda:us-east-1:000000000000:function:%s/invocations","integrationMethod":"POST"}+ """.formatted(disconnectFunctionName))+ .when().post("/v2/apis/" + wsApiId + "/integrations")+ .then()+ .statusCode(201)+ .extract().path("integrationId");+ }++ // ──────────────────────────── Test 1: Connect with no $connect route ────────────────────────────++ @Test+ @Order(10)+ void connectWithNoConnectRoute() throws Exception {+ // No $connect route is defined yet, so connection should succeed directly+ WebSocket ws = connectWebSocket(wsApiId, "test");+ assertNotNull(ws, "WebSocket connection should succeed when no $connect route is defined");+ ws.sendClose(WebSocket.NORMAL_CLOSURE, "done").join();+ Thread.sleep(500);+ }++ // ──────────────────────────── Test 2: Connect with $connect route Lambda allow ────────────────────────────++ @Test+ @Order(20)+ void connectWithConnectRouteLambdaAllow() throws Exception {+ // Create $connect route pointing to the allow function+ connectRouteId = given()+ .contentType(ContentType.JSON)+ .body("""+ {"routeKey":"$connect","target":"integrations/%s"}+ """.formatted(integrationIdAllow))+ .when().post("/v2/apis/" + wsApiId + "/routes")+ .then()+ .statusCode(201)+ .extract().path("routeId");++ // Connection should succeed because Lambda returns 200+ WebSocket ws = connectWebSocket(wsApiId, "test");+ assertNotNull(ws, "WebSocket connection should succeed when $connect Lambda returns 200");+ ws.sendClose(WebSocket.NORMAL_CLOSURE, "done").join();+ Thread.sleep(500);+ }++ // ──────────────────────────── Test 3: Connect with $connect route Lambda deny ────────────────────────────++ @Test+ @Order(30)+ void connectWithConnectRouteLambdaDeny() throws Exception {+ // Update $connect route to point to the deny function+ given()+ .contentType(ContentType.JSON)+ .body("""+ {"target":"integrations/%s"}+ """.formatted(integrationIdDeny))+ .when().patch("/v2/apis/" + wsApiId + "/routes/" + connectRouteId)+ .then()+ .statusCode(200);++ // Connection should fail with 403 because Lambda returns non-2xx+ assertWebSocketConnectionFails(wsApiId, "test", 403);+ }++ // ──────────────────────────── Test 4: Connect with $connect route Lambda error ────────────────────────────++ @Test+ @Order(40)+ void connectWithConnectRouteLambdaError() throws Exception {+ // Update $connect route to point to the error function+ given()+ .contentType(ContentType.JSON)+ .body("""+ {"target":"integrations/%s"}+ """.formatted(integrationIdError))+ .when().patch("/v2/apis/" + wsApiId + "/routes/" + connectRouteId)+ .then()+ .statusCode(200);++ // Connection should fail with 500 because Lambda invocation throws+ assertWebSocketConnectionFails(wsApiId, "test", 500);+ }++ // ──────────────────────────── Test 5: Disconnect invokes $disconnect route ────────────────────────────++ @Test+ @Order(50)+ void disconnectInvokesDisconnectRoute() throws Exception {+ // Update $connect route back to allow function+ given()+ .contentType(ContentType.JSON)+ .body("""+ {"target":"integrations/%s"}+ """.formatted(integrationIdAllow))+ .when().patch("/v2/apis/" + wsApiId + "/routes/" + connectRouteId)+ .then()+ .statusCode(200);++ // Create $disconnect route+ disconnectRouteId = given()+ .contentType(ContentType.JSON)+ .body("""+ {"routeKey":"$disconnect","target":"integrations/%s"}+ """.formatted(integrationIdDisconnect))+ .when().post("/v2/apis/" + wsApiId + "/routes")+ .then()+ .statusCode(201)+ .extract().path("routeId");++ // Connect and then disconnect — $disconnect Lambda should be invoked+ // (We verify this doesn't throw/fail; the Lambda is invoked server-side)+ WebSocket ws = connectWebSocket(wsApiId, "test");+ assertNotNull(ws);+ ws.sendClose(WebSocket.NORMAL_CLOSURE, "done").join();+ // Give time for the $disconnect handler to execute+ Thread.sleep(2000);+ }++ // ──────────────────────────── Test 6: Disconnect cleans up connection ────────────────────────────++ @Test+ @Order(60)+ void disconnectCleansUpConnection() throws Exception {+ // Connect, then disconnect, and verify the connection is cleaned up+ WebSocket ws = connectWebSocket(wsApiId, "test");+ assertNotNull(ws);+ ws.sendClose(WebSocket.NORMAL_CLOSURE, "done").join();+ // Give time for cleanup+ Thread.sleep(2000);++ // Attempting to reconnect should work (proving old connection was cleaned up)+ WebSocket ws2 = connectWebSocket(wsApiId, "test");+ assertNotNull(ws2);+ ws2.sendClose(WebSocket.NORMAL_CLOSURE, "done").join();+ Thread.sleep(500);+ }++ // ──────────────────────────── Test 7: Disconnect error does not propagate to client ────────────────────────────++ @Test+ @Order(70)+ void disconnectErrorDoesNotPropagateToClient() throws Exception {+ // Update $disconnect route to point to the error function+ given()+ .contentType(ContentType.JSON)+ .body("""+ {"target":"integrations/%s"}+ """.formatted(integrationIdError))+ .when().patch("/v2/apis/" + wsApiId + "/routes/" + disconnectRouteId)+ .then()+ .statusCode(200);++ // Connect and disconnect — even though $disconnect Lambda throws,+ // the client should not see an error (clean close)+ WebSocket ws = connectWebSocket(wsApiId, "test");+ assertNotNull(ws);++ // The close should complete normally+ ws.sendClose(WebSocket.NORMAL_CLOSURE, "done").join();+ // Give time for the $disconnect handler to execute (and fail)+ Thread.sleep(2000);+ // If we got here without exception, the error was not propagated+ }++ // ──────────────────────────── Test 8: Connect to non-existent API ────────────────────────────++ @Test+ @Order(80)+ void connectToNonExistentApi() throws Exception {+ assertWebSocketConnectionFails("nonexistent-api-id", "test", 403);+ }++ // ──────────────────────────── Test 9: Connect to non-WebSocket API ────────────────────────────++ @Test+ @Order(90)+ void connectToNonWebSocketApi() throws Exception {+ assertWebSocketConnectionFails(httpApiId, "test", 403);+ }++ // ──────────────────────────── Test 10: Connect to non-existent stage ────────────────────────────++ @Test+ @Order(100)+ void connectToNonExistentStage() throws Exception {+ assertWebSocketConnectionFails(wsApiId, "nonexistent-stage", 403);+ }++ // ──────────────────────────── Test 11: Connection ID is unique per connection ────────────────────────────++ @Test+ @Order(110)+ void connectionIdIsUniquePerConnection() throws Exception {+ // Remove $connect route to simplify (no Lambda invocation needed)+ given()+ .when().delete("/v2/apis/" + wsApiId + "/routes/" + connectRouteId)+ .then()+ .statusCode(204);+ connectRouteId = null;++ // Also remove $disconnect route to avoid Lambda invocation on close+ given()+ .when().delete("/v2/apis/" + wsApiId + "/routes/" + disconnectRouteId)+ .then()+ .statusCode(204);+ disconnectRouteId = null;++ // Open multiple connections and verify each gets a unique connectionId+ // We can't directly observe connectionId from the client, but we can verify+ // that multiple simultaneous connections are possible (each has its own state)+ Set<WebSocket> connections = new HashSet<>();+ for (int i = 0; i < 5; i++) {+ WebSocket ws = connectWebSocket(wsApiId, "test");+ assertNotNull(ws);+ connections.add(ws);+ }++ // All connections should be distinct objects (unique connections)+ assertEquals(5, connections.size());++ // Close all connections+ for (WebSocket ws : connections) {+ ws.sendClose(WebSocket.NORMAL_CLOSURE, "done").join();+ }+ Thread.sleep(1000);+ }++ // ──────────────────────────── Cleanup ────────────────────────────++ @Test+ @Order(999)+ void cleanup() {+ // Delete routes if they still exist+ if (connectRouteId != null) {+ given().when().delete("/v2/apis/" + wsApiId + "/routes/" + connectRouteId)+ .then().statusCode(anyOf(204, 404));+ }+ if (disconnectRouteId != null) {+ given().when().delete("/v2/apis/" + wsApiId + "/routes/" + disconnectRouteId)+ .then().statusCode(anyOf(204, 404));+ }++ // Delete APIs+ if (wsApiId != null) {+ given().when().delete("/v2/apis/" + wsApiId).then().statusCode(anyOf(204, 404));+ }+ if (httpApiId != null) {+ given().when().delete("/v2/apis/" + httpApiId).then().statusCode(anyOf(204, 404));+ }++ // Delete Lambda functions+ given().when().delete("/2015-03-31/functions/" + allowFunctionName);+ given().when().delete("/2015-03-31/functions/" + denyFunctionName);+ given().when().delete("/2015-03-31/functions/" + errorFunctionName);+ given().when().delete("/2015-03-31/functions/" + disconnectFunctionName);+ }++ // ──────────────────────────── Helpers ────────────────────────────++ private WebSocket connectWebSocket(String apiId, String stageName) throws Exception {+ String wsUrl = WebSocketTestSupport.buildWsUrl(baseUri, apiId, stageName);++ HttpClient client = HttpClient.newHttpClient();+ CompletableFuture<WebSocket> wsFuture = client.newWebSocketBuilder()+ .buildAsync(URI.create(wsUrl), new WebSocket.Listener() {+ @Override+ public void onOpen(WebSocket webSocket) {+ WebSocket.Listener.super.onOpen(webSocket);+ }++ @Override+ public CompletionStage<?> onText(WebSocket webSocket, CharSequence data, boolean last) {+ return WebSocket.Listener.super.onText(webSocket, data, last);+ }++ @Override+ public CompletionStage<?> onClose(WebSocket webSocket, int statusCode, String reason) {+ return WebSocket.Listener.super.onClose(webSocket, statusCode, reason);+ }++ @Override+ public void onError(WebSocket webSocket, Throwable error) {+ WebSocket.Listener.super.onError(webSocket, error);+ }+ });++ return wsFuture.get(60, TimeUnit.SECONDS);+ }++ private void assertWebSocketConnectionFails(String apiId, String stageName, int expectedStatus) throws Exception {+ String wsUrl = WebSocketTestSupport.buildWsUrl(baseUri, apiId, stageName);++ HttpClient client = HttpClient.newHttpClient();+ CompletableFuture<WebSocket> wsFuture = client.newWebSocketBuilder()+ .buildAsync(URI.create(wsUrl), new WebSocket.Listener() {});++ try {+ wsFuture.get(60, TimeUnit.SECONDS);+ fail("Expected WebSocket connection to fail with status " + expectedStatus);+ } catch (java.util.concurrent.ExecutionException e) {+ // The java.net.http WebSocket client wraps the rejection in an ExecutionException+ // whose cause is a java.net.http.WebSocketHandshakeException (or IOException)+ Throwable cause = e.getCause();+ assertNotNull(cause, "Expected a cause for the ExecutionException");+ // The handshake exception message typically contains the HTTP status code+ String message = cause.getMessage() != null ? cause.getMessage() : "";+ // Also check the full exception chain+ if (!message.contains(String.valueOf(expectedStatus))) {+ Throwable inner = cause.getCause();+ if (inner != null && inner.getMessage() != null) {+ message = inner.getMessage();+ }+ }+ assertTrue(+ message.contains(String.valueOf(expectedStatus)),+ "Expected connection failure with status " + expectedStatus + " but got exception: " + cause);+ }+ }++ // Helper for Hamcrest anyOf with integers+ private static org.hamcrest.Matcher<Integer> anyOf(int... values) {+ @SuppressWarnings("unchecked")+ org.hamcrest.Matcher<Integer>[] matchers = new org.hamcrest.Matcher[values.length];+ for (int i = 0; i < values.length; i++) {+ matchers[i] = org.hamcrest.Matchers.equalTo(values[i]);+ }+ return org.hamcrest.Matchers.anyOf(matchers);+ }+}diff --git a/src/test/java/io/github/hectorvent/floci/services/apigatewayv2/WebSocketConnectionsApiTest.java b/src/test/java/io/github/hectorvent/floci/services/apigatewayv2/WebSocketConnectionsApiTest.javanew file mode 100644index 0000000000..4cf8a50bd3--- /dev/null+++ b/src/test/java/io/github/hectorvent/floci/services/apigatewayv2/WebSocketConnectionsApiTest.java@@ -0,0 +1,529 @@+package io.github.hectorvent.floci.services.apigatewayv2;++import com.fasterxml.jackson.databind.JsonNode;+import com.fasterxml.jackson.databind.ObjectMapper;+import io.quarkus.test.junit.QuarkusTest;+import io.restassured.http.ContentType;+import org.junit.jupiter.api.MethodOrderer;+import org.junit.jupiter.api.Order;+import org.junit.jupiter.api.Test;+import org.junit.jupiter.api.TestMethodOrder;++import java.net.URI;+import java.net.http.HttpClient;+import java.net.http.WebSocket;+import java.util.concurrent.CompletableFuture;+import java.util.concurrent.CompletionStage;+import java.util.concurrent.TimeUnit;++import static io.restassured.RestAssured.given;+import static org.hamcrest.Matchers.notNullValue;+import static org.junit.jupiter.api.Assertions.*;++/**+ * Integration tests for the @connections REST API (POST, GET, DELETE).+ */+@QuarkusTest+@TestMethodOrder(MethodOrderer.OrderAnnotation.class)+class WebSocketConnectionsApiTest {++ @io.quarkus.test.common.http.TestHTTPResource("/")+ URI baseUri;++ private static final ObjectMapper MAPPER = new ObjectMapper();++ private static String wsApiId;+ private static String connectFnName = "ws-conn-api-connect-fn";+ private static String messageFnName = "ws-conn-api-message-fn";+ private static String integrationId;+ private static String messageIntegrationId;+ private static String connectRouteId;+ private static String defaultRouteId;++ // Track the connectionId from the WebSocket connection+ private static String activeConnectionId;++ // ──────────────────────────── Setup ────────────────────────────++ @Test+ @Order(1)+ void setupWebSocketApi() {+ // Create a WEBSOCKET API+ wsApiId = given()+ .contentType(ContentType.JSON)+ .body("""+ {"name":"ws-connections-api-test","protocolType":"WEBSOCKET","routeSelectionExpression":"$request.body.action"}+ """)+ .when().post("/v2/apis")+ .then()+ .statusCode(201)+ .body("apiId", notNullValue())+ .extract().path("apiId");++ // Create a stage+ given()+ .contentType(ContentType.JSON)+ .body("""+ {"stageName":"test"}+ """)+ .when().post("/v2/apis/" + wsApiId + "/stages")+ .then()+ .statusCode(201);+ }++ @Test+ @Order(2)+ void setupLambdaFunctions() throws Exception {+ // $connect Lambda that returns 200+ String connectZip = WebSocketTestSupport.createLambdaZip(+ "exports.handler = async (event) => ({ statusCode: 200, body: 'connected' });");+ given()+ .contentType(ContentType.JSON)+ .body("""+ {"FunctionName":"%s","Runtime":"nodejs20.x","Role":"arn:aws:iam::000000000000:role/lambda-role","Handler":"index.handler","Timeout":30,"Code":{"ZipFile":"%s"}}+ """.formatted(connectFnName, connectZip))+ .when().post("/2015-03-31/functions")+ .then()+ .statusCode(201);++ // $default Lambda that echoes the event (with routeResponseSelectionExpression)+ String messageZip = WebSocketTestSupport.createLambdaZip(+ "exports.handler = async (event) => ({ statusCode: 200, body: JSON.stringify({ event: event }) });");+ given()+ .contentType(ContentType.JSON)+ .body("""+ {"FunctionName":"%s","Runtime":"nodejs20.x","Role":"arn:aws:iam::000000000000:role/lambda-role","Handler":"index.handler","Timeout":30,"Code":{"ZipFile":"%s"}}+ """.formatted(messageFnName, messageZip))+ .when().post("/2015-03-31/functions")+ .then()+ .statusCode(201);++ // Prewarm+ given().contentType(ContentType.JSON).body("{}")+ .when().post("/2015-03-31/functions/" + connectFnName + "/invocations")+ .then().statusCode(200);+ given().contentType(ContentType.JSON).body("{}")+ .when().post("/2015-03-31/functions/" + messageFnName + "/invocations")+ .then().statusCode(200);+ }++ @Test+ @Order(3)+ void setupIntegrationAndRoutes() {+ // Create integration for $connect+ integrationId = given()+ .contentType(ContentType.JSON)+ .body("""+ {"integrationType":"AWS_PROXY","integrationUri":"arn:aws:lambda:us-east-1:000000000000:function:%s/invocations","integrationMethod":"POST"}+ """.formatted(connectFnName))+ .when().post("/v2/apis/" + wsApiId + "/integrations")+ .then()+ .statusCode(201)+ .extract().path("integrationId");++ // Create integration for $default (message echo)+ messageIntegrationId = given()+ .contentType(ContentType.JSON)+ .body("""+ {"integrationType":"AWS_PROXY","integrationUri":"arn:aws:lambda:us-east-1:000000000000:function:%s/invocations","integrationMethod":"POST"}+ """.formatted(messageFnName))+ .when().post("/v2/apis/" + wsApiId + "/integrations")+ .then()+ .statusCode(201)+ .extract().path("integrationId");++ // Create $connect route+ connectRouteId = given()+ .contentType(ContentType.JSON)+ .body("""+ {"routeKey":"$connect","target":"integrations/%s"}+ """.formatted(integrationId))+ .when().post("/v2/apis/" + wsApiId + "/routes")+ .then()+ .statusCode(201)+ .extract().path("routeId");++ // Create $default route with routeResponseSelectionExpression for echo+ defaultRouteId = given()+ .contentType(ContentType.JSON)+ .body("""+ {"routeKey":"$default","target":"integrations/%s","routeResponseSelectionExpression":"$default"}+ """.formatted(messageIntegrationId))+ .when().post("/v2/apis/" + wsApiId + "/routes")+ .then()+ .statusCode(201)+ .extract().path("routeId");+ }++ // ──────────────────────────── Test 1: POST sends message to client ────────────────────────────++ @Test+ @Order(10)+ void postToConnectionSendsMessageToClient() throws Exception {+ // POST to @connections sends message and returns 200+ WebSocketTestSupport.MessageCapture capture = new WebSocketTestSupport.MessageCapture();+ WebSocket ws = connectWebSocketWithListener(wsApiId, "test", capture);+ assertNotNull(ws, "WebSocket connection should succeed");++ // We need the connectionId. Send a message to get the event echoed back which contains connectionId+ ws.sendText("{\"action\":\"getConnectionId\"}", true).join();+ String response = capture.getResponse(15, TimeUnit.SECONDS);+ assertNotNull(response, "Should receive echoed event");++ JsonNode eventWrapper = MAPPER.readTree(response);+ String connectionId = eventWrapper.get("event").get("requestContext").get("connectionId").asText();+ assertNotNull(connectionId, "Should have a connectionId");+ activeConnectionId = connectionId;++ // Now POST a message via @connections API+ WebSocketTestSupport.MessageCapture capture2 = new WebSocketTestSupport.MessageCapture();+ // We need a new listener to capture the pushed message+ // Actually, the first capture already consumed its future. Let's reconnect.+ ws.sendClose(WebSocket.NORMAL_CLOSURE, "done").join();+ Thread.sleep(500);++ // Reconnect with a fresh capture+ WebSocketTestSupport.MessageCapture pushCapture = new WebSocketTestSupport.MessageCapture();+ WebSocket ws2 = connectWebSocketWithListener(wsApiId, "test", pushCapture);+ assertNotNull(ws2, "Second WebSocket connection should succeed");++ // Get the new connectionId+ // Send a message first to get the connectionId from the echo+ WebSocketTestSupport.MessageCapture idCapture = new WebSocketTestSupport.MessageCapture();+ // We need yet another approach — let's use a multi-message capture+ ws2.sendText("{\"action\":\"getId\"}", true).join();+ // The pushCapture will get this response+ String idResponse = pushCapture.getResponse(15, TimeUnit.SECONDS);+ assertNotNull(idResponse, "Should receive echoed event for connectionId");++ JsonNode idEvent = MAPPER.readTree(idResponse);+ String connId = idEvent.get("event").get("requestContext").get("connectionId").asText();+ assertNotNull(connId, "Should have connectionId from echo");++ // Now use a fresh capture for the pushed message+ WebSocketTestSupport.MultiMessageCapture multiCapture = new WebSocketTestSupport.MultiMessageCapture();+ WebSocket ws3 = connectWebSocketWithListener2(wsApiId, "test", multiCapture);+ assertNotNull(ws3, "Third WebSocket connection should succeed");++ // Get connectionId+ ws3.sendText("{\"action\":\"getId\"}", true).join();+ String idResp = multiCapture.getNextMessage(15, TimeUnit.SECONDS);+ assertNotNull(idResp, "Should get connectionId response");+ JsonNode idNode = MAPPER.readTree(idResp);+ String ws3ConnId = idNode.get("event").get("requestContext").get("connectionId").asText();++ // POST a message to this connection via @connections API+ String pushMessage = "Hello from @connections API!";+ given()+ .body(pushMessage)+ .contentType(ContentType.TEXT)+ .when().post("/execute-api/" + wsApiId + "/test/@connections/" + ws3ConnId)+ .then()+ .statusCode(200);++ // The client should receive the pushed message+ String pushed = multiCapture.getNextMessage(15, TimeUnit.SECONDS);+ assertNotNull(pushed, "Client should receive pushed message");+ assertEquals(pushMessage, pushed, "Pushed message should match");++ ws2.sendClose(WebSocket.NORMAL_CLOSURE, "done").join();+ ws3.sendClose(WebSocket.NORMAL_CLOSURE, "done").join();+ Thread.sleep(500);+ }++ // ──────────────────────────── Test 2: POST to gone connection returns 410 ────────────────────────────++ @Test+ @Order(20)+ void postToGoneConnectionReturns410() {+ // POST to non-existent connection returns 410 GoneException+ String fakeConnectionId = "non-existent-connection-id";+ String body = given()+ .body("test message")+ .contentType(ContentType.TEXT)+ .when().post("/execute-api/" + wsApiId + "/test/@connections/" + fakeConnectionId)+ .then()+ .statusCode(410)+ .contentType(ContentType.JSON)+ .extract().body().asString();++ assertTrue(body.contains("GoneException"), "Response should contain GoneException");+ }++ // ──────────────────────────── Test 3: GET connection info returns metadata ────────────────────────────++ @Test+ @Order(30)+ void getConnectionInfoReturnsMetadata() throws Exception {+ // GET returns connectedAt, lastActiveAt, identity+ WebSocketTestSupport.MultiMessageCapture capture = new WebSocketTestSupport.MultiMessageCapture();+ WebSocket ws = connectWebSocketWithListener2(wsApiId, "test", capture);+ assertNotNull(ws, "WebSocket connection should succeed");++ // Get connectionId+ ws.sendText("{\"action\":\"getId\"}", true).join();+ String idResp = capture.getNextMessage(15, TimeUnit.SECONDS);+ assertNotNull(idResp, "Should get connectionId response");+ JsonNode idNode = MAPPER.readTree(idResp);+ String connId = idNode.get("event").get("requestContext").get("connectionId").asText();++ // GET connection info+ String infoBody = given()+ .when().get("/execute-api/" + wsApiId + "/test/@connections/" + connId)+ .then()+ .statusCode(200)+ .contentType(ContentType.JSON)+ .extract().body().asString();++ JsonNode info = MAPPER.readTree(infoBody);+ assertNotNull(info.get("connectedAt"), "Should have connectedAt");+ assertNotNull(info.get("lastActiveAt"), "Should have lastActiveAt");+ assertNotNull(info.get("identity"), "Should have identity");+ assertNotNull(info.get("identity").get("sourceIp"), "Should have sourceIp");+ assertNotNull(info.get("identity").get("userAgent"), "Should have userAgent");++ // Verify ISO 8601 format (contains 'T' and ends with 'Z')+ String connectedAt = info.get("connectedAt").asText();+ assertTrue(connectedAt.contains("T"), "connectedAt should be ISO 8601 format");++ String lastActiveAt = info.get("lastActiveAt").asText();+ assertTrue(lastActiveAt.contains("T"), "lastActiveAt should be ISO 8601 format");++ ws.sendClose(WebSocket.NORMAL_CLOSURE, "done").join();+ Thread.sleep(500);+ }++ // ──────────────────────────── Test 4: GET gone connection returns 410 ────────────────────────────++ @Test+ @Order(40)+ void getGoneConnectionReturns410() {+ // GET for non-existent connection returns 410+ String fakeConnectionId = "non-existent-get-connection";+ String body = given()+ .when().get("/execute-api/" + wsApiId + "/test/@connections/" + fakeConnectionId)+ .then()+ .statusCode(410)+ .contentType(ContentType.JSON)+ .extract().body().asString();++ assertTrue(body.contains("GoneException"), "Response should contain GoneException");+ }++ // ──────────────────────────── Test 5: DELETE disconnects client ────────────────────────────++ @Test+ @Order(50)+ void deleteConnectionDisconnectsClient() throws Exception {+ // DELETE closes the connection and returns 204+ WebSocketTestSupport.MultiMessageCapture capture = new WebSocketTestSupport.MultiMessageCapture();+ CompletableFuture<Integer> closeFuture = new CompletableFuture<>();+ WebSocket ws = connectWebSocketWithCloseListener(wsApiId, "test", capture, closeFuture);+ assertNotNull(ws, "WebSocket connection should succeed");++ // Get connectionId+ ws.sendText("{\"action\":\"getId\"}", true).join();+ String idResp = capture.getNextMessage(15, TimeUnit.SECONDS);+ assertNotNull(idResp, "Should get connectionId response");+ JsonNode idNode = MAPPER.readTree(idResp);+ String connId = idNode.get("event").get("requestContext").get("connectionId").asText();++ // DELETE the connection via @connections API+ given()+ .when().delete("/execute-api/" + wsApiId + "/test/@connections/" + connId)+ .then()+ .statusCode(204);++ // The WebSocket should be closed+ Integer closeCode = closeFuture.get(15, TimeUnit.SECONDS);+ assertNotNull(closeCode, "WebSocket should receive close frame");++ Thread.sleep(500);+ }++ // ──────────────────────────── Test 6: DELETE gone connection returns 410 ────────────────────────────++ @Test+ @Order(60)+ void deleteGoneConnectionReturns410() {+ // DELETE for non-existent connection returns 410+ String fakeConnectionId = "non-existent-delete-connection";+ String body = given()+ .when().delete("/execute-api/" + wsApiId + "/test/@connections/" + fakeConnectionId)+ .then()+ .statusCode(410)+ .contentType(ContentType.JSON)+ .extract().body().asString();++ assertTrue(body.contains("GoneException"), "Response should contain GoneException");+ }++ // ──────────────────────────── Test 7: lastActiveAt updated on message ────────────────────────────++ @Test+ @Order(70)+ void lastActiveAtUpdatedOnMessage() throws Exception {+ // lastActiveAt is updated when a message is received+ WebSocketTestSupport.MultiMessageCapture capture = new WebSocketTestSupport.MultiMessageCapture();+ WebSocket ws = connectWebSocketWithListener2(wsApiId, "test", capture);+ assertNotNull(ws, "WebSocket connection should succeed");++ // Get connectionId and initial lastActiveAt+ ws.sendText("{\"action\":\"getId\"}", true).join();+ String idResp = capture.getNextMessage(15, TimeUnit.SECONDS);+ assertNotNull(idResp, "Should get connectionId response");+ JsonNode idNode = MAPPER.readTree(idResp);+ String connId = idNode.get("event").get("requestContext").get("connectionId").asText();++ // Get initial connection info+ String info1Body = given()+ .when().get("/execute-api/" + wsApiId + "/test/@connections/" + connId)+ .then()+ .statusCode(200)+ .extract().body().asString();+ JsonNode info1 = MAPPER.readTree(info1Body);+ String lastActive1 = info1.get("lastActiveAt").asText();++ // Wait a bit and send another message+ Thread.sleep(1100);+ ws.sendText("{\"action\":\"update\"}", true).join();+ String updateResp = capture.getNextMessage(15, TimeUnit.SECONDS);+ assertNotNull(updateResp, "Should get response after second message");++ // Get updated connection info+ String info2Body = given()+ .when().get("/execute-api/" + wsApiId + "/test/@connections/" + connId)+ .then()+ .statusCode(200)+ .extract().body().asString();+ JsonNode info2 = MAPPER.readTree(info2Body);+ String lastActive2 = info2.get("lastActiveAt").asText();++ // lastActiveAt should have been updated+ assertNotEquals(lastActive1, lastActive2,+ "lastActiveAt should be updated after receiving a message");++ ws.sendClose(WebSocket.NORMAL_CLOSURE, "done").join();+ Thread.sleep(500);+ }++ // ──────────────────────────── Test 8: Server-initiated DELETE does not invoke $disconnect ────────────────────────────++ @Test+ @Order(80)+ void serverInitiatedDeleteDoesNotInvokeDisconnect() throws Exception {+ // AWS behavior: when a connection is closed via @connections DELETE,+ // the $disconnect Lambda is NOT invoked. Only client-initiated disconnections trigger $disconnect.+ // We verify this by connecting, then using DELETE to close, and confirming the connection+ // is properly cleaned up (subsequent POST returns 410).+ WebSocketTestSupport.MultiMessageCapture capture = new WebSocketTestSupport.MultiMessageCapture();+ CompletableFuture<Integer> closeFuture = new CompletableFuture<>();+ WebSocket ws = connectWebSocketWithCloseListener(wsApiId, "test", capture, closeFuture);+ assertNotNull(ws, "WebSocket connection should succeed");++ // Get connectionId+ ws.sendText("{\"action\":\"getId\"}", true).join();+ String idResp = capture.getNextMessage(15, TimeUnit.SECONDS);+ assertNotNull(idResp, "Should get connectionId response");+ JsonNode idNode = MAPPER.readTree(idResp);+ String connId = idNode.get("event").get("requestContext").get("connectionId").asText();++ // DELETE the connection via @connections API (server-initiated close)+ given()+ .when().delete("/execute-api/" + wsApiId + "/test/@connections/" + connId)+ .then()+ .statusCode(204);++ // Wait for the WebSocket to be closed+ Integer closeCode = closeFuture.get(15, TimeUnit.SECONDS);+ assertNotNull(closeCode, "WebSocket should receive close frame");++ // Wait for cleanup+ Thread.sleep(500);++ // Verify the connection is fully cleaned up (POST returns 410)+ given()+ .body("test")+ .contentType(ContentType.TEXT)+ .when().post("/execute-api/" + wsApiId + "/test/@connections/" + connId)+ .then()+ .statusCode(410);+ }++ // ──────────────────────────── Cleanup ────────────────────────────++ @Test+ @Order(999)+ void cleanup() {+ if (connectRouteId != null) {+ given().when().delete("/v2/apis/" + wsApiId + "/routes/" + connectRouteId);+ }+ if (defaultRouteId != null) {+ given().when().delete("/v2/apis/" + wsApiId + "/routes/" + defaultRouteId);+ }+ if (wsApiId != null) {+ given().when().delete("/v2/apis/" + wsApiId);+ }+ given().when().delete("/2015-03-31/functions/" + connectFnName);+ given().when().delete("/2015-03-31/functions/" + messageFnName);+ }++ // ──────────────────────────── Helpers ────────────────────────────++ private WebSocket connectWebSocketWithListener(String apiId, String stageName,+ WebSocketTestSupport.MessageCapture capture) throws Exception {+ String wsUrl = WebSocketTestSupport.buildWsUrl(baseUri, apiId, stageName);+ HttpClient client = HttpClient.newHttpClient();+ return client.newWebSocketBuilder()+ .buildAsync(URI.create(wsUrl), capture)+ .get(60, TimeUnit.SECONDS);+ }++ private WebSocket connectWebSocketWithListener2(String apiId, String stageName,+ WebSocketTestSupport.MultiMessageCapture capture) throws Exception {+ String wsUrl = WebSocketTestSupport.buildWsUrl(baseUri, apiId, stageName);+ HttpClient client = HttpClient.newHttpClient();+ return client.newWebSocketBuilder()+ .buildAsync(URI.create(wsUrl), capture)+ .get(60, TimeUnit.SECONDS);+ }++ private WebSocket connectWebSocketWithCloseListener(String apiId, String stageName,+ WebSocketTestSupport.MultiMessageCapture capture,+ CompletableFuture<Integer> closeFuture) throws Exception {+ String wsUrl = WebSocketTestSupport.buildWsUrl(baseUri, apiId, stageName);+ HttpClient client = HttpClient.newHttpClient();+ return client.newWebSocketBuilder()+ .buildAsync(URI.create(wsUrl), new WebSocket.Listener() {+ private final StringBuilder buffer = new StringBuilder();++ @Override+ public void onOpen(WebSocket webSocket) {+ webSocket.request(10);+ }++ @Override+ public CompletionStage<?> onText(WebSocket webSocket, CharSequence data, boolean last) {+ buffer.append(data);+ if (last) {+ capture.complete(buffer.toString());+ buffer.setLength(0);+ }+ webSocket.request(1);+ return null;+ }++ @Override+ public CompletionStage<?> onClose(WebSocket webSocket, int statusCode, String reason) {+ closeFuture.complete(statusCode);+ return null;+ }++ @Override+ public void onError(WebSocket webSocket, Throwable error) {+ closeFuture.completeExceptionally(error);+ }+ })+ .get(60, TimeUnit.SECONDS);+ }+}diff --git a/src/test/java/io/github/hectorvent/floci/services/apigatewayv2/WebSocketLambdaAuthorizerTest.java b/src/test/java/io/github/hectorvent/floci/services/apigatewayv2/WebSocketLambdaAuthorizerTest.javanew file mode 100644index 0000000000..b4abcbe78c--- /dev/null+++ b/src/test/java/io/github/hectorvent/floci/services/apigatewayv2/WebSocketLambdaAuthorizerTest.java@@ -0,0 +1,631 @@+package io.github.hectorvent.floci.services.apigatewayv2;++import com.fasterxml.jackson.databind.JsonNode;+import com.fasterxml.jackson.databind.ObjectMapper;+import io.quarkus.test.junit.QuarkusTest;+import io.restassured.http.ContentType;+import org.junit.jupiter.api.MethodOrderer;+import org.junit.jupiter.api.Order;+import org.junit.jupiter.api.Test;+import org.junit.jupiter.api.TestMethodOrder;++import java.net.URI;+import java.net.http.HttpClient;+import java.net.http.WebSocket;+import java.util.concurrent.CompletableFuture;+import java.util.concurrent.CompletionStage;+import java.util.concurrent.TimeUnit;++import static io.restassured.RestAssured.given;+import static org.hamcrest.Matchers.notNullValue;+import static org.junit.jupiter.api.Assertions.*;++/**+ * Integration tests for Lambda REQUEST authorizer on $connect route.+ */+@QuarkusTest+@TestMethodOrder(MethodOrderer.OrderAnnotation.class)+class WebSocketLambdaAuthorizerTest {++ @io.quarkus.test.common.http.TestHTTPResource("/")+ URI baseUri;++ private static final ObjectMapper MAPPER = new ObjectMapper();++ private static String wsApiId;+ private static String allowAuthFnName = "ws-auth-allow-fn";+ private static String denyAuthFnName = "ws-auth-deny-fn";+ private static String errorAuthFnName = "ws-auth-error-fn";+ private static String contextAuthFnName = "ws-auth-context-fn";+ private static String echoAuthFnName = "ws-auth-echo-fn";+ private static String connectFnName = "ws-auth-connect-fn";+ private static String integrationId;+ private static String connectRouteId;+ private static String allowAuthorizerId;+ private static String denyAuthorizerId;+ private static String errorAuthorizerId;+ private static String contextAuthorizerId;+ private static String echoAuthorizerId;+ private static String identitySourceAuthorizerId;++ // ──────────────────────────── Setup ────────────────────────────++ @Test+ @Order(1)+ void setupWebSocketApi() {+ // Create a WEBSOCKET API+ wsApiId = given()+ .contentType(ContentType.JSON)+ .body("""+ {"name":"ws-authorizer-test","protocolType":"WEBSOCKET","routeSelectionExpression":"$request.body.action"}+ """)+ .when().post("/v2/apis")+ .then()+ .statusCode(201)+ .body("apiId", notNullValue())+ .extract().path("apiId");++ // Create a stage with stage variables+ given()+ .contentType(ContentType.JSON)+ .body("""+ {"stageName":"test","stageVariables":{"env":"testing","version":"2.0"}}+ """)+ .when().post("/v2/apis/" + wsApiId + "/stages")+ .then()+ .statusCode(201);+ }++ @Test+ @Order(2)+ void setupLambdaFunctions() throws Exception {+ // Authorizer that returns Allow policy+ String allowZip = WebSocketTestSupport.createLambdaZip("""+ exports.handler = async (event) => ({+ principalId: "user123",+ policyDocument: {+ Version: "2012-10-17",+ Statement: [{ Action: "execute-api:Invoke", Effect: "Allow", Resource: event.methodArn }]+ }+ });+ """);+ given()+ .contentType(ContentType.JSON)+ .body("""+ {"FunctionName":"%s","Runtime":"nodejs20.x","Role":"arn:aws:iam::000000000000:role/lambda-role","Handler":"index.handler","Timeout":30,"Code":{"ZipFile":"%s"}}+ """.formatted(allowAuthFnName, allowZip))+ .when().post("/2015-03-31/functions")+ .then()+ .statusCode(201);++ // Authorizer that returns Deny policy+ String denyZip = WebSocketTestSupport.createLambdaZip("""+ exports.handler = async (event) => ({+ principalId: "user123",+ policyDocument: {+ Version: "2012-10-17",+ Statement: [{ Action: "execute-api:Invoke", Effect: "Deny", Resource: event.methodArn }]+ }+ });+ """);+ given()+ .contentType(ContentType.JSON)+ .body("""+ {"FunctionName":"%s","Runtime":"nodejs20.x","Role":"arn:aws:iam::000000000000:role/lambda-role","Handler":"index.handler","Timeout":30,"Code":{"ZipFile":"%s"}}+ """.formatted(denyAuthFnName, denyZip))+ .when().post("/2015-03-31/functions")+ .then()+ .statusCode(201);++ // Authorizer that throws an error+ String errorZip = WebSocketTestSupport.createLambdaZip("""+ exports.handler = async (event) => { throw new Error("Authorizer error"); };+ """);+ given()+ .contentType(ContentType.JSON)+ .body("""+ {"FunctionName":"%s","Runtime":"nodejs20.x","Role":"arn:aws:iam::000000000000:role/lambda-role","Handler":"index.handler","Timeout":30,"Code":{"ZipFile":"%s"}}+ """.formatted(errorAuthFnName, errorZip))+ .when().post("/2015-03-31/functions")+ .then()+ .statusCode(201);++ // Authorizer that returns Allow policy WITH context+ String contextZip = WebSocketTestSupport.createLambdaZip("""+ exports.handler = async (event) => ({+ principalId: "user456",+ policyDocument: {+ Version: "2012-10-17",+ Statement: [{ Action: "execute-api:Invoke", Effect: "Allow", Resource: event.methodArn }]+ },+ context: { userId: "user456", role: "admin", score: 42 }+ });+ """);+ given()+ .contentType(ContentType.JSON)+ .body("""+ {"FunctionName":"%s","Runtime":"nodejs20.x","Role":"arn:aws:iam::000000000000:role/lambda-role","Handler":"index.handler","Timeout":30,"Code":{"ZipFile":"%s"}}+ """.formatted(contextAuthFnName, contextZip))+ .when().post("/2015-03-31/functions")+ .then()+ .statusCode(201);++ // Authorizer that echoes the event payload (for format verification)+ String echoZip = WebSocketTestSupport.createLambdaZip("""+ exports.handler = async (event) => ({+ principalId: "user789",+ policyDocument: {+ Version: "2012-10-17",+ Statement: [{ Action: "execute-api:Invoke", Effect: "Allow", Resource: event.methodArn }]+ },+ context: { authorizerEvent: JSON.stringify(event) }+ });+ """);+ given()+ .contentType(ContentType.JSON)+ .body("""+ {"FunctionName":"%s","Runtime":"nodejs20.x","Role":"arn:aws:iam::000000000000:role/lambda-role","Handler":"index.handler","Timeout":30,"Code":{"ZipFile":"%s"}}+ """.formatted(echoAuthFnName, echoZip))+ .when().post("/2015-03-31/functions")+ .then()+ .statusCode(201);++ // $connect integration Lambda that echoes the event+ String connectZip = WebSocketTestSupport.createLambdaZip("""+ exports.handler = async (event) => ({ statusCode: 200, body: JSON.stringify({ proxyEvent: event }) });+ """);+ given()+ .contentType(ContentType.JSON)+ .body("""+ {"FunctionName":"%s","Runtime":"nodejs20.x","Role":"arn:aws:iam::000000000000:role/lambda-role","Handler":"index.handler","Timeout":30,"Code":{"ZipFile":"%s"}}+ """.formatted(connectFnName, connectZip))+ .when().post("/2015-03-31/functions")+ .then()+ .statusCode(201);+ }++ @Test+ @Order(3)+ void prewarmLambdaFunctions() {+ given().contentType(ContentType.JSON).body("{}")+ .when().post("/2015-03-31/functions/" + allowAuthFnName + "/invocations")+ .then().statusCode(200);+ given().contentType(ContentType.JSON).body("{}")+ .when().post("/2015-03-31/functions/" + denyAuthFnName + "/invocations")+ .then().statusCode(200);+ given().contentType(ContentType.JSON).body("{}")+ .when().post("/2015-03-31/functions/" + errorAuthFnName + "/invocations")+ .then().statusCode(200);+ given().contentType(ContentType.JSON).body("{}")+ .when().post("/2015-03-31/functions/" + contextAuthFnName + "/invocations")+ .then().statusCode(200);+ given().contentType(ContentType.JSON).body("{}")+ .when().post("/2015-03-31/functions/" + echoAuthFnName + "/invocations")+ .then().statusCode(200);+ given().contentType(ContentType.JSON).body("{}")+ .when().post("/2015-03-31/functions/" + connectFnName + "/invocations")+ .then().statusCode(200);+ }++ @Test+ @Order(4)+ void setupIntegrationAndRoute() {+ // Create integration for the $connect Lambda+ integrationId = given()+ .contentType(ContentType.JSON)+ .body("""+ {"integrationType":"AWS_PROXY","integrationUri":"arn:aws:lambda:us-east-1:000000000000:function:%s/invocations","integrationMethod":"POST"}+ """.formatted(connectFnName))+ .when().post("/v2/apis/" + wsApiId + "/integrations")+ .then()+ .statusCode(201)+ .extract().path("integrationId");++ // Create $connect route (no authorizer initially)+ connectRouteId = given()+ .contentType(ContentType.JSON)+ .body("""+ {"routeKey":"$connect","target":"integrations/%s"}+ """.formatted(integrationId))+ .when().post("/v2/apis/" + wsApiId + "/routes")+ .then()+ .statusCode(201)+ .extract().path("routeId");+ }++ @Test+ @Order(5)+ void setupAuthorizers() {+ // Allow authorizer+ allowAuthorizerId = given()+ .contentType(ContentType.JSON)+ .body("""+ {"name":"allow-auth","authorizerType":"REQUEST","authorizerUri":"arn:aws:lambda:us-east-1:000000000000:function:%s/invocations"}+ """.formatted(allowAuthFnName))+ .when().post("/v2/apis/" + wsApiId + "/authorizers")+ .then()+ .statusCode(201)+ .extract().path("authorizerId");++ // Deny authorizer+ denyAuthorizerId = given()+ .contentType(ContentType.JSON)+ .body("""+ {"name":"deny-auth","authorizerType":"REQUEST","authorizerUri":"arn:aws:lambda:us-east-1:000000000000:function:%s/invocations"}+ """.formatted(denyAuthFnName))+ .when().post("/v2/apis/" + wsApiId + "/authorizers")+ .then()+ .statusCode(201)+ .extract().path("authorizerId");++ // Error authorizer+ errorAuthorizerId = given()+ .contentType(ContentType.JSON)+ .body("""+ {"name":"error-auth","authorizerType":"REQUEST","authorizerUri":"arn:aws:lambda:us-east-1:000000000000:function:%s/invocations"}+ """.formatted(errorAuthFnName))+ .when().post("/v2/apis/" + wsApiId + "/authorizers")+ .then()+ .statusCode(201)+ .extract().path("authorizerId");++ // Context authorizer+ contextAuthorizerId = given()+ .contentType(ContentType.JSON)+ .body("""+ {"name":"context-auth","authorizerType":"REQUEST","authorizerUri":"arn:aws:lambda:us-east-1:000000000000:function:%s/invocations"}+ """.formatted(contextAuthFnName))+ .when().post("/v2/apis/" + wsApiId + "/authorizers")+ .then()+ .statusCode(201)+ .extract().path("authorizerId");++ // Echo authorizer+ echoAuthorizerId = given()+ .contentType(ContentType.JSON)+ .body("""+ {"name":"echo-auth","authorizerType":"REQUEST","authorizerUri":"arn:aws:lambda:us-east-1:000000000000:function:%s/invocations"}+ """.formatted(echoAuthFnName))+ .when().post("/v2/apis/" + wsApiId + "/authorizers")+ .then()+ .statusCode(201)+ .extract().path("authorizerId");++ // Identity source authorizer (requires Authorization header)+ identitySourceAuthorizerId = given()+ .contentType(ContentType.JSON)+ .body("""+ {"name":"identity-auth","authorizerType":"REQUEST","identitySource":"$request.header.Authorization","authorizerUri":"arn:aws:lambda:us-east-1:000000000000:function:%s/invocations"}+ """.formatted(allowAuthFnName))+ .when().post("/v2/apis/" + wsApiId + "/authorizers")+ .then()+ .statusCode(201)+ .extract().path("authorizerId");+ }++ // ──────────────────────────── Test 1: Authorizer allows connection ────────────────────────────++ @Test+ @Order(10)+ void authorizerAllowsConnection() throws Exception {+ given()+ .contentType(ContentType.JSON)+ .body("""+ {"authorizationType":"CUSTOM","authorizerId":"%s"}+ """.formatted(allowAuthorizerId))+ .when().patch("/v2/apis/" + wsApiId + "/routes/" + connectRouteId)+ .then()+ .statusCode(200);++ WebSocket ws = connectWebSocket(wsApiId, "test");+ assertNotNull(ws, "WebSocket connection should succeed when authorizer returns Allow");+ ws.sendClose(WebSocket.NORMAL_CLOSURE, "done").join();+ Thread.sleep(500);+ }++ // ──────────────────────────── Test 2: Authorizer denies connection ────────────────────────────++ @Test+ @Order(20)+ void authorizerDeniesConnection() throws Exception {+ given()+ .contentType(ContentType.JSON)+ .body("""+ {"authorizationType":"CUSTOM","authorizerId":"%s"}+ """.formatted(denyAuthorizerId))+ .when().patch("/v2/apis/" + wsApiId + "/routes/" + connectRouteId)+ .then()+ .statusCode(200);++ assertWebSocketConnectionFails(wsApiId, "test", 403);+ }++ // ──────────────────────────── Test 3: Authorizer invocation error ────────────────────────────++ @Test+ @Order(30)+ void authorizerInvocationError() throws Exception {+ given()+ .contentType(ContentType.JSON)+ .body("""+ {"authorizationType":"CUSTOM","authorizerId":"%s"}+ """.formatted(errorAuthorizerId))+ .when().patch("/v2/apis/" + wsApiId + "/routes/" + connectRouteId)+ .then()+ .statusCode(200);++ assertWebSocketConnectionFails(wsApiId, "test", 500);+ }++ // ──────────────────────────── Test 4: Authorizer context propagated to $connect integration ────────────────────────────++ @Test+ @Order(40)+ void authorizerContextPropagatedToConnectIntegration() throws Exception {+ given()+ .contentType(ContentType.JSON)+ .body("""+ {"authorizationType":"CUSTOM","authorizerId":"%s"}+ """.formatted(contextAuthorizerId))+ .when().patch("/v2/apis/" + wsApiId + "/routes/" + connectRouteId)+ .then()+ .statusCode(200);++ String defaultRouteId = given()+ .contentType(ContentType.JSON)+ .body("""+ {"routeKey":"$default","target":"integrations/%s","routeResponseSelectionExpression":"$default"}+ """.formatted(integrationId))+ .when().post("/v2/apis/" + wsApiId + "/routes")+ .then()+ .statusCode(201)+ .extract().path("routeId");++ try {+ WebSocketTestSupport.MessageCapture capture = new WebSocketTestSupport.MessageCapture();+ WebSocket ws = connectWebSocketWithListener(wsApiId, "test", capture);+ assertNotNull(ws, "Connection should succeed with context authorizer");++ ws.sendText("{\"action\":\"test\"}", true).join();++ String response = capture.getResponse(15, TimeUnit.SECONDS);+ assertNotNull(response, "Should receive echoed event");++ JsonNode wrapper = MAPPER.readTree(response);+ JsonNode event = wrapper.get("proxyEvent");+ assertNotNull(event, "Response should contain proxyEvent");++ JsonNode requestContext = event.get("requestContext");+ assertNotNull(requestContext, "Event should have requestContext");++ ws.sendClose(WebSocket.NORMAL_CLOSURE, "done").join();+ Thread.sleep(500);+ } finally {+ given().when().delete("/v2/apis/" + wsApiId + "/routes/" + defaultRouteId);+ }+ }++ // ──────────────────────────── Test 5: Missing identity source rejects with 401 ────────────────────────────++ @Test+ @Order(50)+ void missingIdentitySourceRejectsWithout401() throws Exception {+ given()+ .contentType(ContentType.JSON)+ .body("""+ {"authorizationType":"CUSTOM","authorizerId":"%s"}+ """.formatted(identitySourceAuthorizerId))+ .when().patch("/v2/apis/" + wsApiId + "/routes/" + connectRouteId)+ .then()+ .statusCode(200);++ // Connect WITHOUT the required Authorization header — should get 401+ assertWebSocketConnectionFails(wsApiId, "test", 401);++ // Now connect WITH the Authorization header — should succeed+ WebSocket ws = connectWebSocketWithHeader(wsApiId, "test", "Authorization", "Bearer test-token");+ assertNotNull(ws, "Connection should succeed when identity source header is present");+ ws.sendClose(WebSocket.NORMAL_CLOSURE, "done").join();+ Thread.sleep(500);+ }++ // ──────────────────────────── Test 6: Authorizer event payload matches AWS format ────────────────────────────++ @Test+ @Order(60)+ void authorizerEventPayloadMatchesAwsFormat() throws Exception {+ given()+ .contentType(ContentType.JSON)+ .body("""+ {"authorizationType":"CUSTOM","authorizerId":"%s"}+ """.formatted(echoAuthorizerId))+ .when().patch("/v2/apis/" + wsApiId + "/routes/" + connectRouteId)+ .then()+ .statusCode(200);++ String defaultRouteId = given()+ .contentType(ContentType.JSON)+ .body("""+ {"routeKey":"$default","target":"integrations/%s","routeResponseSelectionExpression":"$default"}+ """.formatted(integrationId))+ .when().post("/v2/apis/" + wsApiId + "/routes")+ .then()+ .statusCode(201)+ .extract().path("routeId");++ try {+ WebSocketTestSupport.MessageCapture capture = new WebSocketTestSupport.MessageCapture();+ WebSocket ws = connectWebSocketWithQueryAndListener(wsApiId, "test", "token=abc123", capture);+ assertNotNull(ws, "Connection should succeed with echo authorizer");++ ws.sendText("{\"action\":\"check\"}", true).join();++ String response = capture.getResponse(15, TimeUnit.SECONDS);+ assertNotNull(response, "Should receive echoed event");++ JsonNode wrapper = MAPPER.readTree(response);+ JsonNode messageEvent = wrapper.get("proxyEvent");+ assertNotNull(messageEvent, "Response should contain proxyEvent");++ ws.sendClose(WebSocket.NORMAL_CLOSURE, "done").join();+ Thread.sleep(500);++ WebSocketTestSupport.MessageCapture capture2 = new WebSocketTestSupport.MessageCapture();+ WebSocket ws2 = connectWebSocketWithQueryAndListener(wsApiId, "test", "token=verify123", capture2);+ assertNotNull(ws2, "Second connection should succeed");++ ws2.sendText("{\"action\":\"verify\"}", true).join();+ String response2 = capture2.getResponse(15, TimeUnit.SECONDS);+ assertNotNull(response2, "Should receive second echoed event");++ String testPayload = """+ {"type":"REQUEST","methodArn":"arn:aws:execute-api:us-east-1:000000000000:%s/test/$connect"}+ """.formatted(wsApiId);+ String invokeResponse = given()+ .contentType(ContentType.JSON)+ .body(testPayload)+ .when().post("/2015-03-31/functions/" + echoAuthFnName + "/invocations")+ .then()+ .statusCode(200)+ .extract().body().asString();++ JsonNode authResponse = MAPPER.readTree(invokeResponse);+ assertNotNull(authResponse.get("context"), "Authorizer should return context");+ String authEventStr = authResponse.get("context").get("authorizerEvent").asText();+ JsonNode authEvent = MAPPER.readTree(authEventStr);++ assertEquals("REQUEST", authEvent.get("type").asText(),+ "Authorizer event type should be REQUEST");+ assertNotNull(authEvent.get("methodArn"), "Authorizer event should have methodArn");+ assertTrue(authEvent.get("methodArn").asText().contains("$connect"),+ "methodArn should contain $connect");++ ws2.sendClose(WebSocket.NORMAL_CLOSURE, "done").join();+ Thread.sleep(500);+ } finally {+ given().when().delete("/v2/apis/" + wsApiId + "/routes/" + defaultRouteId);+ }+ }++ // ──────────────────────────── Cleanup ────────────────────────────++ @Test+ @Order(999)+ void cleanup() {+ if (connectRouteId != null) {+ given().when().delete("/v2/apis/" + wsApiId + "/routes/" + connectRouteId);+ }+ if (wsApiId != null) {+ given().when().delete("/v2/apis/" + wsApiId);+ }+ given().when().delete("/2015-03-31/functions/" + allowAuthFnName);+ given().when().delete("/2015-03-31/functions/" + denyAuthFnName);+ given().when().delete("/2015-03-31/functions/" + errorAuthFnName);+ given().when().delete("/2015-03-31/functions/" + contextAuthFnName);+ given().when().delete("/2015-03-31/functions/" + echoAuthFnName);+ given().when().delete("/2015-03-31/functions/" + connectFnName);+ }++ // ──────────────────────────── Helpers ────────────────────────────++ private WebSocket connectWebSocket(String apiId, String stageName) throws Exception {+ String wsUrl = WebSocketTestSupport.buildWsUrl(baseUri, apiId, stageName);+ HttpClient client = HttpClient.newHttpClient();+ CompletableFuture<WebSocket> wsFuture = client.newWebSocketBuilder()+ .buildAsync(URI.create(wsUrl), new WebSocket.Listener() {+ @Override+ public void onOpen(WebSocket webSocket) {+ WebSocket.Listener.super.onOpen(webSocket);+ }++ @Override+ public CompletionStage<?> onText(WebSocket webSocket, CharSequence data, boolean last) {+ return WebSocket.Listener.super.onText(webSocket, data, last);+ }++ @Override+ public CompletionStage<?> onClose(WebSocket webSocket, int statusCode, String reason) {+ return WebSocket.Listener.super.onClose(webSocket, statusCode, reason);+ }++ @Override+ public void onError(WebSocket webSocket, Throwable error) {+ WebSocket.Listener.super.onError(webSocket, error);+ }+ });+ return wsFuture.get(60, TimeUnit.SECONDS);+ }++ private WebSocket connectWebSocketWithHeader(String apiId, String stageName,+ String headerName, String headerValue) throws Exception {+ String wsUrl = WebSocketTestSupport.buildWsUrl(baseUri, apiId, stageName);+ HttpClient client = HttpClient.newHttpClient();+ CompletableFuture<WebSocket> wsFuture = client.newWebSocketBuilder()+ .header(headerName, headerValue)+ .buildAsync(URI.create(wsUrl), new WebSocket.Listener() {+ @Override+ public void onOpen(WebSocket webSocket) {+ WebSocket.Listener.super.onOpen(webSocket);+ }++ @Override+ public CompletionStage<?> onText(WebSocket webSocket, CharSequence data, boolean last) {+ return WebSocket.Listener.super.onText(webSocket, data, last);+ }++ @Override+ public CompletionStage<?> onClose(WebSocket webSocket, int statusCode, String reason) {+ return WebSocket.Listener.super.onClose(webSocket, statusCode, reason);+ }++ @Override+ public void onError(WebSocket webSocket, Throwable error) {+ WebSocket.Listener.super.onError(webSocket, error);+ }+ });+ return wsFuture.get(60, TimeUnit.SECONDS);+ }++ private WebSocket connectWebSocketWithListener(String apiId, String stageName,+ WebSocketTestSupport.MessageCapture capture) throws Exception {+ String wsUrl = WebSocketTestSupport.buildWsUrl(baseUri, apiId, stageName);+ HttpClient client = HttpClient.newHttpClient();+ return client.newWebSocketBuilder()+ .buildAsync(URI.create(wsUrl), capture)+ .get(60, TimeUnit.SECONDS);+ }++ private WebSocket connectWebSocketWithQueryAndListener(String apiId, String stageName,+ String queryString, WebSocketTestSupport.MessageCapture capture) throws Exception {+ String wsUrl = WebSocketTestSupport.buildWsUrl(baseUri, apiId, stageName) + "?" + queryString;+ HttpClient client = HttpClient.newHttpClient();+ return client.newWebSocketBuilder()+ .buildAsync(URI.create(wsUrl), capture)+ .get(60, TimeUnit.SECONDS);+ }++ private void assertWebSocketConnectionFails(String apiId, String stageName, int expectedStatus) throws Exception {+ String wsUrl = WebSocketTestSupport.buildWsUrl(baseUri, apiId, stageName);+ HttpClient client = HttpClient.newHttpClient();+ CompletableFuture<WebSocket> wsFuture = client.newWebSocketBuilder()+ .buildAsync(URI.create(wsUrl), new WebSocket.Listener() {});++ try {+ wsFuture.get(60, TimeUnit.SECONDS);+ fail("Expected WebSocket connection to fail with status " + expectedStatus);+ } catch (java.util.concurrent.ExecutionException e) {+ Throwable cause = e.getCause();+ assertNotNull(cause, "Expected a cause for the ExecutionException");+ String message = cause.getMessage() != null ? cause.getMessage() : "";+ if (!message.contains(String.valueOf(expectedStatus))) {+ Throwable inner = cause.getCause();+ if (inner != null && inner.getMessage() != null) {+ message = inner.getMessage();+ }+ }+ assertTrue(+ message.contains(String.valueOf(expectedStatus)),+ "Expected connection failure with status " + expectedStatus + " but got exception: " + cause);+ }+ }+}diff --git a/src/test/java/io/github/hectorvent/floci/services/apigatewayv2/WebSocketMessageRoutingTest.java b/src/test/java/io/github/hectorvent/floci/services/apigatewayv2/WebSocketMessageRoutingTest.javanew file mode 100644index 0000000000..e75d164549--- /dev/null+++ b/src/test/java/io/github/hectorvent/floci/services/apigatewayv2/WebSocketMessageRoutingTest.java@@ -0,0 +1,489 @@+package io.github.hectorvent.floci.services.apigatewayv2;++import io.quarkus.test.junit.QuarkusTest;+import io.restassured.http.ContentType;+import org.junit.jupiter.api.MethodOrderer;+import org.junit.jupiter.api.Order;+import org.junit.jupiter.api.Test;+import org.junit.jupiter.api.TestMethodOrder;++import java.net.URI;+import java.net.http.HttpClient;+import java.net.http.WebSocket;+import java.util.concurrent.TimeUnit;++import static io.restassured.RestAssured.given;+import static org.hamcrest.Matchers.notNullValue;+import static org.junit.jupiter.api.Assertions.*;++/**+ * Integration tests for WebSocket message routing.+ */+@QuarkusTest+@TestMethodOrder(MethodOrderer.OrderAnnotation.class)+class WebSocketMessageRoutingTest {++ @io.quarkus.test.common.http.TestHTTPResource("/")+ URI baseUri;++ // API with $request.body.action (default expression)+ private static String wsApiId;+ // API with $request.body.type (custom expression)+ private static String wsApiTypeId;++ private static String sendMessageFnName = "ws-route-sendmsg-fn";+ private static String defaultFnName = "ws-route-default-fn";++ private static String integrationIdSendMessage;+ private static String integrationIdDefault;++ private static String sendMessageRouteId;+ private static String defaultRouteId;+ private static String typeRouteId;+ private static String typeDefaultRouteId;++ // ──────────────────────────── Setup ────────────────────────────++ @Test+ @Order(1)+ void setupApis() {+ // Create a WEBSOCKET API with routeSelectionExpression: $request.body.action+ wsApiId = given()+ .contentType(ContentType.JSON)+ .body("""+ {"name":"ws-routing-test","protocolType":"WEBSOCKET","routeSelectionExpression":"$request.body.action"}+ """)+ .when().post("/v2/apis")+ .then()+ .statusCode(201)+ .body("apiId", notNullValue())+ .extract().path("apiId");++ // Create a stage for the action-based API+ given()+ .contentType(ContentType.JSON)+ .body("""+ {"stageName":"test"}+ """)+ .when().post("/v2/apis/" + wsApiId + "/stages")+ .then()+ .statusCode(201);++ // Create a WEBSOCKET API with routeSelectionExpression: $request.body.type+ wsApiTypeId = given()+ .contentType(ContentType.JSON)+ .body("""+ {"name":"ws-routing-type-test","protocolType":"WEBSOCKET","routeSelectionExpression":"$request.body.type"}+ """)+ .when().post("/v2/apis")+ .then()+ .statusCode(201)+ .body("apiId", notNullValue())+ .extract().path("apiId");++ // Create a stage for the type-based API+ given()+ .contentType(ContentType.JSON)+ .body("""+ {"stageName":"test"}+ """)+ .when().post("/v2/apis/" + wsApiTypeId + "/stages")+ .then()+ .statusCode(201);+ }++ @Test+ @Order(2)+ void setupLambdaFunctions() throws Exception {+ // Lambda for sendMessage route — returns a fixed identifier "sendMessage-handler"+ String sendMsgZip = WebSocketTestSupport.createLambdaZip(+ "exports.handler = async (event) => ({ statusCode: 200, body: JSON.stringify({handler:'sendMessage-handler', routeKey: (event.requestContext || {}).routeKey || 'none'}) });");+ given()+ .contentType(ContentType.JSON)+ .body("""+ {"FunctionName":"%s","Runtime":"nodejs20.x","Role":"arn:aws:iam::000000000000:role/lambda-role","Handler":"index.handler","Timeout":30,"Code":{"ZipFile":"%s"}}+ """.formatted(sendMessageFnName, sendMsgZip))+ .when().post("/2015-03-31/functions")+ .then()+ .statusCode(201);++ // Lambda for $default route — returns a fixed identifier "default-handler"+ String defaultZip = WebSocketTestSupport.createLambdaZip(+ "exports.handler = async (event) => ({ statusCode: 200, body: JSON.stringify({handler:'default-handler', routeKey: (event.requestContext || {}).routeKey || 'none'}) });");+ given()+ .contentType(ContentType.JSON)+ .body("""+ {"FunctionName":"%s","Runtime":"nodejs20.x","Role":"arn:aws:iam::000000000000:role/lambda-role","Handler":"index.handler","Timeout":30,"Code":{"ZipFile":"%s"}}+ """.formatted(defaultFnName, defaultZip))+ .when().post("/2015-03-31/functions")+ .then()+ .statusCode(201);+ }++ @Test+ @Order(3)+ void prewarmLambdaFunctions() {+ given().contentType(ContentType.JSON).body("{}")+ .when().post("/2015-03-31/functions/" + sendMessageFnName + "/invocations")+ .then().statusCode(200);+ given().contentType(ContentType.JSON).body("{}")+ .when().post("/2015-03-31/functions/" + defaultFnName + "/invocations")+ .then().statusCode(200);+ }++ @Test+ @Order(4)+ void setupIntegrationsAndRoutes() {+ // Integration for sendMessage function+ integrationIdSendMessage = given()+ .contentType(ContentType.JSON)+ .body("""+ {"integrationType":"AWS_PROXY","integrationUri":"arn:aws:lambda:us-east-1:000000000000:function:%s/invocations","integrationMethod":"POST"}+ """.formatted(sendMessageFnName))+ .when().post("/v2/apis/" + wsApiId + "/integrations")+ .then()+ .statusCode(201)+ .extract().path("integrationId");++ // Integration for default function+ integrationIdDefault = given()+ .contentType(ContentType.JSON)+ .body("""+ {"integrationType":"AWS_PROXY","integrationUri":"arn:aws:lambda:us-east-1:000000000000:function:%s/invocations","integrationMethod":"POST"}+ """.formatted(defaultFnName))+ .when().post("/v2/apis/" + wsApiId + "/integrations")+ .then()+ .statusCode(201)+ .extract().path("integrationId");++ // Create "sendMessage" route with routeResponseSelectionExpression so we get a response back+ sendMessageRouteId = given()+ .contentType(ContentType.JSON)+ .body("""+ {"routeKey":"sendMessage","target":"integrations/%s","routeResponseSelectionExpression":"$default"}+ """.formatted(integrationIdSendMessage))+ .when().post("/v2/apis/" + wsApiId + "/routes")+ .then()+ .statusCode(201)+ .extract().path("routeId");++ // Create "$default" route with routeResponseSelectionExpression+ defaultRouteId = given()+ .contentType(ContentType.JSON)+ .body("""+ {"routeKey":"$default","target":"integrations/%s","routeResponseSelectionExpression":"$default"}+ """.formatted(integrationIdDefault))+ .when().post("/v2/apis/" + wsApiId + "/routes")+ .then()+ .statusCode(201)+ .extract().path("routeId");++ // Setup for the type-based API — reuse the same Lambda functions+ String typeIntegrationId = given()+ .contentType(ContentType.JSON)+ .body("""+ {"integrationType":"AWS_PROXY","integrationUri":"arn:aws:lambda:us-east-1:000000000000:function:%s/invocations","integrationMethod":"POST"}+ """.formatted(sendMessageFnName))+ .when().post("/v2/apis/" + wsApiTypeId + "/integrations")+ .then()+ .statusCode(201)+ .extract().path("integrationId");++ // Create "chat" route on type-based API with routeResponseSelectionExpression+ typeRouteId = given()+ .contentType(ContentType.JSON)+ .body("""+ {"routeKey":"chat","target":"integrations/%s","routeResponseSelectionExpression":"$default"}+ """.formatted(typeIntegrationId))+ .when().post("/v2/apis/" + wsApiTypeId + "/routes")+ .then()+ .statusCode(201)+ .extract().path("routeId");++ // Create "$default" route on type-based API (for fallback tests)+ String typeDefaultIntegrationId = given()+ .contentType(ContentType.JSON)+ .body("""+ {"integrationType":"AWS_PROXY","integrationUri":"arn:aws:lambda:us-east-1:000000000000:function:%s/invocations","integrationMethod":"POST"}+ """.formatted(defaultFnName))+ .when().post("/v2/apis/" + wsApiTypeId + "/integrations")+ .then()+ .statusCode(201)+ .extract().path("integrationId");++ typeDefaultRouteId = given()+ .contentType(ContentType.JSON)+ .body("""+ {"routeKey":"$default","target":"integrations/%s","routeResponseSelectionExpression":"$default"}+ """.formatted(typeDefaultIntegrationId))+ .when().post("/v2/apis/" + wsApiTypeId + "/routes")+ .then()+ .statusCode(201)+ .extract().path("routeId");+ }++ // ──────────────────────────── Test 1: Route by action field ────────────────────────────++ @Test+ @Order(10)+ void routeByActionField() throws Exception {+ // Message with {"action":"sendMessage"} routes to the sendMessage route+ WebSocketTestSupport.MessageCapture capture = new WebSocketTestSupport.MessageCapture();+ WebSocket ws = connectWebSocketWithListener(wsApiId, "test", capture);+ assertNotNull(ws);++ // Send a message with action field+ ws.sendText("{\"action\":\"sendMessage\",\"data\":\"hello\"}", true).join();++ // Wait for response+ String response = capture.getResponse(15, TimeUnit.SECONDS);+ assertNotNull(response, "Should receive a response from the sendMessage route");+ assertTrue(response.contains("sendMessage-handler"),+ "Response should indicate the sendMessage route handled it, got: " + response);++ ws.sendClose(WebSocket.NORMAL_CLOSURE, "done").join();+ Thread.sleep(500);+ }++ // ──────────────────────────── Test 2: Route to $default when no match ────────────────────────────++ @Test+ @Order(20)+ void routeToDefaultWhenNoMatch() throws Exception {+ // Message with unmatched action routes to $default+ WebSocketTestSupport.MessageCapture capture = new WebSocketTestSupport.MessageCapture();+ WebSocket ws = connectWebSocketWithListener(wsApiId, "test", capture);+ assertNotNull(ws);++ // Send a message with an action that doesn't match any route+ ws.sendText("{\"action\":\"unknownAction\",\"data\":\"test\"}", true).join();++ // Wait for response from $default route+ String response = capture.getResponse(15, TimeUnit.SECONDS);+ assertNotNull(response, "Should receive a response from the $default route");+ assertTrue(response.contains("default-handler"),+ "Response should indicate the $default route handled it, got: " + response);++ ws.sendClose(WebSocket.NORMAL_CLOSURE, "done").join();+ Thread.sleep(500);+ }++ // ──────────────────────────── Test 3: Error frame when no match and no $default ────────────────────────────++ @Test+ @Order(30)+ void errorFrameWhenNoMatchAndNoDefault() throws Exception {+ // Message with unmatched action and no $default gets error frame+ // Remove the $default route temporarily+ given().when().delete("/v2/apis/" + wsApiId + "/routes/" + defaultRouteId)+ .then().statusCode(204);++ try {+ WebSocketTestSupport.MessageCapture capture = new WebSocketTestSupport.MessageCapture();+ WebSocket ws = connectWebSocketWithListener(wsApiId, "test", capture);+ assertNotNull(ws);++ // Send a message with an action that doesn't match any route+ ws.sendText("{\"action\":\"noSuchRoute\",\"data\":\"test\"}", true).join();++ // Should receive an error frame+ String response = capture.getResponse(15, TimeUnit.SECONDS);+ assertNotNull(response, "Should receive an error frame");+ assertTrue(response.contains("No route found") || response.contains("no route"),+ "Error frame should indicate no route found, got: " + response);++ ws.sendClose(WebSocket.NORMAL_CLOSURE, "done").join();+ Thread.sleep(500);+ } finally {+ // Re-create the $default route+ defaultRouteId = given()+ .contentType(ContentType.JSON)+ .body("""+ {"routeKey":"$default","target":"integrations/%s","routeResponseSelectionExpression":"$default"}+ """.formatted(integrationIdDefault))+ .when().post("/v2/apis/" + wsApiId + "/routes")+ .then()+ .statusCode(201)+ .extract().path("routeId");+ }+ }++ // ──────────────────────────── Test 4: Non-JSON message routes to $default ────────────────────────────++ @Test+ @Order(40)+ void nonJsonMessageRoutesToDefault() throws Exception {+ // Non-JSON message routes to $default+ WebSocketTestSupport.MessageCapture capture = new WebSocketTestSupport.MessageCapture();+ WebSocket ws = connectWebSocketWithListener(wsApiId, "test", capture);+ assertNotNull(ws);++ // Send a non-JSON message+ ws.sendText("this is not json", true).join();++ // Should route to $default and get a response+ String response = capture.getResponse(15, TimeUnit.SECONDS);+ assertNotNull(response, "Should receive a response from the $default route for non-JSON message");+ assertTrue(response.contains("default-handler"),+ "Response should indicate the $default route handled it, got: " + response);++ ws.sendClose(WebSocket.NORMAL_CLOSURE, "done").join();+ Thread.sleep(500);+ }++ // ──────────────────────────── Test 5: Error frame for non-JSON with no $default ────────────────────────────++ @Test+ @Order(50)+ void errorFrameForNonJsonWithNoDefault() throws Exception {+ // Non-JSON message with no $default gets error frame+ // Remove the $default route temporarily+ given().when().delete("/v2/apis/" + wsApiId + "/routes/" + defaultRouteId)+ .then().statusCode(204);++ try {+ WebSocketTestSupport.MessageCapture capture = new WebSocketTestSupport.MessageCapture();+ WebSocket ws = connectWebSocketWithListener(wsApiId, "test", capture);+ assertNotNull(ws);++ // Send a non-JSON message+ ws.sendText("not json at all", true).join();++ // Should receive an error frame+ String response = capture.getResponse(15, TimeUnit.SECONDS);+ assertNotNull(response, "Should receive an error frame for non-JSON with no $default");+ assertTrue(response.contains("Could not route message") || response.contains("could not route"),+ "Error frame should indicate message could not be routed, got: " + response);++ ws.sendClose(WebSocket.NORMAL_CLOSURE, "done").join();+ Thread.sleep(500);+ } finally {+ // Re-create the $default route+ defaultRouteId = given()+ .contentType(ContentType.JSON)+ .body("""+ {"routeKey":"$default","target":"integrations/%s","routeResponseSelectionExpression":"$default"}+ """.formatted(integrationIdDefault))+ .when().post("/v2/apis/" + wsApiId + "/routes")+ .then()+ .statusCode(201)+ .extract().path("routeId");+ }+ }++ // ──────────────────────────── Test 6: Route selection expression field extraction ────────────────────────────++ @Test+ @Order(60)+ void routeSelectionExpressionFieldExtraction() throws Exception {+ // Custom $request.body.type expression extracts the type field+ WebSocketTestSupport.MessageCapture capture = new WebSocketTestSupport.MessageCapture();+ WebSocket ws = connectWebSocketWithListener(wsApiTypeId, "test", capture);+ assertNotNull(ws);++ // Send a message with "type" field matching the "chat" route+ ws.sendText("{\"type\":\"chat\",\"message\":\"hello\"}", true).join();++ // Should route to the "chat" route+ String response = capture.getResponse(15, TimeUnit.SECONDS);+ assertNotNull(response, "Should receive a response from the chat route");+ assertTrue(response.contains("sendMessage-handler"),+ "Response should indicate the chat route's Lambda handled it, got: " + response);++ ws.sendClose(WebSocket.NORMAL_CLOSURE, "done").join();+ Thread.sleep(500);+ }++ // ──────────────────────────── Test 7: Non-string field value converted to string ────────────────────────────++ @Test+ @Order(70)+ void nonStringFieldValueConvertedToString() throws Exception {+ // Numeric field value is converted to string for route matching+ // Create a route with a numeric key on the action-based API+ String numericRouteId = given()+ .contentType(ContentType.JSON)+ .body("""+ {"routeKey":"42","target":"integrations/%s","routeResponseSelectionExpression":"$default"}+ """.formatted(integrationIdSendMessage))+ .when().post("/v2/apis/" + wsApiId + "/routes")+ .then()+ .statusCode(201)+ .extract().path("routeId");++ try {+ WebSocketTestSupport.MessageCapture capture = new WebSocketTestSupport.MessageCapture();+ WebSocket ws = connectWebSocketWithListener(wsApiId, "test", capture);+ assertNotNull(ws);++ // Send a message with a numeric action value+ ws.sendText("{\"action\":42,\"data\":\"numeric\"}", true).join();++ // Should route to the "42" route (numeric converted to string)+ String response = capture.getResponse(15, TimeUnit.SECONDS);+ assertNotNull(response, "Should receive a response when numeric field is converted to string");+ // The sendMessage Lambda handles this route, so we should get its response+ assertTrue(response.contains("42"),+ "Response should come from the route matching '42', got: " + response);++ ws.sendClose(WebSocket.NORMAL_CLOSURE, "done").join();+ Thread.sleep(500);+ } finally {+ // Clean up the numeric route+ given().when().delete("/v2/apis/" + wsApiId + "/routes/" + numericRouteId)+ .then().statusCode(204);+ }+ }++ // ──────────────────────────── Test 8: Missing field falls to $default ────────────────────────────++ @Test+ @Order(80)+ void missingFieldFallsToDefault() throws Exception {+ // Message missing the field in routeSelectionExpression falls to $default+ WebSocketTestSupport.MessageCapture capture = new WebSocketTestSupport.MessageCapture();+ WebSocket ws = connectWebSocketWithListener(wsApiId, "test", capture);+ assertNotNull(ws);++ // Send a JSON message that doesn't have the "action" field+ ws.sendText("{\"data\":\"no action field here\"}", true).join();++ // Should fall to $default+ String response = capture.getResponse(15, TimeUnit.SECONDS);+ assertNotNull(response, "Should receive a response from the $default route");+ assertTrue(response.contains("default-handler"),+ "Response should indicate the $default route handled it, got: " + response);++ ws.sendClose(WebSocket.NORMAL_CLOSURE, "done").join();+ Thread.sleep(500);+ }++ // ──────────────────────────── Cleanup ────────────────────────────++ @Test+ @Order(999)+ void cleanup() {+ // Delete APIs (cascades routes/integrations in storage)+ if (wsApiId != null) {+ given().when().delete("/v2/apis/" + wsApiId);+ }+ if (wsApiTypeId != null) {+ given().when().delete("/v2/apis/" + wsApiTypeId);+ }++ // Delete Lambda functions+ given().when().delete("/2015-03-31/functions/" + sendMessageFnName);+ given().when().delete("/2015-03-31/functions/" + defaultFnName);+ }++ // ──────────────────────────── Helpers ────────────────────────────++ private WebSocket connectWebSocketWithListener(String apiId, String stageName, WebSocketTestSupport.MessageCapture capture)+ throws Exception {+ String wsUrl = WebSocketTestSupport.buildWsUrl(baseUri, apiId, stageName);+ HttpClient client = HttpClient.newHttpClient();+ return client.newWebSocketBuilder()+ .buildAsync(URI.create(wsUrl), capture)+ .get(60, TimeUnit.SECONDS);+ }+}diff --git a/src/test/java/io/github/hectorvent/floci/services/apigatewayv2/WebSocketMockIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/apigatewayv2/WebSocketMockIntegrationTest.javanew file mode 100644index 0000000000..36deb51b1e--- /dev/null+++ b/src/test/java/io/github/hectorvent/floci/services/apigatewayv2/WebSocketMockIntegrationTest.java@@ -0,0 +1,264 @@+package io.github.hectorvent.floci.services.apigatewayv2;++import io.quarkus.test.junit.QuarkusTest;+import io.restassured.http.ContentType;+import org.junit.jupiter.api.MethodOrderer;+import org.junit.jupiter.api.Order;+import org.junit.jupiter.api.Test;+import org.junit.jupiter.api.TestMethodOrder;++import java.net.URI;+import java.net.http.HttpClient;+import java.net.http.WebSocket;+import java.util.concurrent.CompletableFuture;+import java.util.concurrent.CompletionStage;+import java.util.concurrent.TimeUnit;++import static io.restassured.RestAssured.given;+import static org.hamcrest.Matchers.notNullValue;+import static org.junit.jupiter.api.Assertions.*;++/**+ * Integration tests for WebSocket MOCK integration type.+ *+ * MOCK integration does NOT invoke any backend service or Lambda function.+ * MOCK integration with no matching response template returns default 200.+ * MOCK integration on $connect with 200 allows upgrade; non-2xx denies upgrade.+ */+@QuarkusTest+@TestMethodOrder(MethodOrderer.OrderAnnotation.class)+class WebSocketMockIntegrationTest {++ @io.quarkus.test.common.http.TestHTTPResource("/")+ URI baseUri;++ private static String wsApiId;+ private static String mockIntegrationIdDefault;+ private static String mockIntegrationIdDeny;+ private static String connectRouteId;+ private static String defaultRouteId;++ // ──────────────────────────── Setup ────────────────────────────++ @Test+ @Order(1)+ void setupWebSocketApi() {+ // Create a WEBSOCKET API+ wsApiId = given()+ .contentType(ContentType.JSON)+ .body("""+ {"name":"ws-mock-integration-test","protocolType":"WEBSOCKET","routeSelectionExpression":"$request.body.action"}+ """)+ .when().post("/v2/apis")+ .then()+ .statusCode(201)+ .body("apiId", notNullValue())+ .extract().path("apiId");++ // Create a stage+ given()+ .contentType(ContentType.JSON)+ .body("""+ {"stageName":"test"}+ """)+ .when().post("/v2/apis/" + wsApiId + "/stages")+ .then()+ .statusCode(201);+ }++ @Test+ @Order(2)+ void setupMockIntegrations() {+ // Create a MOCK integration with default behavior (no templateSelectionExpression → returns 200)+ mockIntegrationIdDefault = given()+ .contentType(ContentType.JSON)+ .body("""+ {"integrationType":"MOCK"}+ """)+ .when().post("/v2/apis/" + wsApiId + "/integrations")+ .then()+ .statusCode(201)+ .body("integrationId", notNullValue())+ .extract().path("integrationId");++ // Create a MOCK integration configured to return 403+ // templateSelectionExpression of "403" causes invokeMock to use 403 as the status code+ mockIntegrationIdDeny = given()+ .contentType(ContentType.JSON)+ .body("""+ {"integrationType":"MOCK","templateSelectionExpression":"403"}+ """)+ .when().post("/v2/apis/" + wsApiId + "/integrations")+ .then()+ .statusCode(201)+ .body("integrationId", notNullValue())+ .extract().path("integrationId");+ }++ // ──────────────────────────── Test 1: MOCK integration does not invoke backend ────────────────────────────++ @Test+ @Order(10)+ void mockIntegrationDoesNotInvokeBackend() throws Exception {+ // Create a $default route with the MOCK integration (default 200).+ // If MOCK tried to invoke a Lambda, it would fail because there's no integrationUri.+ // The fact that the connection works and messages don't cause errors proves no backend is invoked.+ defaultRouteId = given()+ .contentType(ContentType.JSON)+ .body("""+ {"routeKey":"$default","target":"integrations/%s"}+ """.formatted(mockIntegrationIdDefault))+ .when().post("/v2/apis/" + wsApiId + "/routes")+ .then()+ .statusCode(201)+ .extract().path("routeId");++ // Connect (no $connect route, so upgrade succeeds directly)+ WebSocket ws = connectWebSocket(wsApiId, "test");+ assertNotNull(ws, "WebSocket connection should succeed");++ // Send a message — it will route to $default which uses MOCK integration.+ // MOCK integration does NOT invoke any Lambda.+ // If it tried to invoke a Lambda, it would fail since there's no integrationUri.+ ws.sendText("{\"action\":\"hello\",\"data\":\"world\"}", true).join();++ // Wait a bit to ensure no errors occur server-side+ Thread.sleep(1000);++ // The connection should still be open (no error frame sent for MOCK integration success)+ // Send another message to verify the connection is still alive+ ws.sendText("{\"action\":\"ping\"}", true).join();+ Thread.sleep(500);++ ws.sendClose(WebSocket.NORMAL_CLOSURE, "done").join();+ Thread.sleep(500);+ }++ // ──────────────────────────── Test 2: MOCK integration on $connect allows upgrade ────────────────────────────++ @Test+ @Order(20)+ void mockIntegrationOnConnectAllowsUpgrade() throws Exception {+ // Remove the $default route from previous test+ if (defaultRouteId != null) {+ given().when().delete("/v2/apis/" + wsApiId + "/routes/" + defaultRouteId)+ .then().statusCode(204);+ defaultRouteId = null;+ }++ // Create $connect route with MOCK integration that returns 200 (default behavior)+ connectRouteId = given()+ .contentType(ContentType.JSON)+ .body("""+ {"routeKey":"$connect","target":"integrations/%s"}+ """.formatted(mockIntegrationIdDefault))+ .when().post("/v2/apis/" + wsApiId + "/routes")+ .then()+ .statusCode(201)+ .extract().path("routeId");++ // Connection should succeed because MOCK returns 200+ WebSocket ws = connectWebSocket(wsApiId, "test");+ assertNotNull(ws, "WebSocket connection should succeed with MOCK integration returning 200");+ ws.sendClose(WebSocket.NORMAL_CLOSURE, "done").join();+ Thread.sleep(500);+ }++ // ──────────────────────────── Test 3: MOCK integration on $connect denies upgrade ────────────────────────────++ @Test+ @Order(30)+ void mockIntegrationOnConnectDeniesUpgrade() throws Exception {+ // Update $connect route to use the MOCK integration that returns 403+ given()+ .contentType(ContentType.JSON)+ .body("""+ {"target":"integrations/%s"}+ """.formatted(mockIntegrationIdDeny))+ .when().patch("/v2/apis/" + wsApiId + "/routes/" + connectRouteId)+ .then()+ .statusCode(200);++ // Connection should fail with 403 because MOCK returns 403 (non-2xx → deny upgrade)+ assertWebSocketConnectionFails(wsApiId, "test", 403);+ }++ // ──────────────────────────── Cleanup ────────────────────────────++ @Test+ @Order(999)+ void cleanup() {+ // Delete routes+ if (connectRouteId != null) {+ given().when().delete("/v2/apis/" + wsApiId + "/routes/" + connectRouteId);+ }+ if (defaultRouteId != null) {+ given().when().delete("/v2/apis/" + wsApiId + "/routes/" + defaultRouteId);+ }++ // Delete API (cascades integrations, routes, stages)+ if (wsApiId != null) {+ given().when().delete("/v2/apis/" + wsApiId);+ }+ }++ // ──────────────────────────── Helpers ────────────────────────────++ private WebSocket connectWebSocket(String apiId, String stageName) throws Exception {+ String wsUrl = baseUri.toString().replaceFirst("^http", "ws") + "ws/" + apiId + "/" + stageName;+ wsUrl = wsUrl.replace("//ws/", "/ws/");++ HttpClient client = HttpClient.newHttpClient();+ CompletableFuture<WebSocket> wsFuture = client.newWebSocketBuilder()+ .buildAsync(URI.create(wsUrl), new WebSocket.Listener() {+ @Override+ public void onOpen(WebSocket webSocket) {+ WebSocket.Listener.super.onOpen(webSocket);+ }++ @Override+ public CompletionStage<?> onText(WebSocket webSocket, CharSequence data, boolean last) {+ return WebSocket.Listener.super.onText(webSocket, data, last);+ }++ @Override+ public CompletionStage<?> onClose(WebSocket webSocket, int statusCode, String reason) {+ return WebSocket.Listener.super.onClose(webSocket, statusCode, reason);+ }++ @Override+ public void onError(WebSocket webSocket, Throwable error) {+ WebSocket.Listener.super.onError(webSocket, error);+ }+ });++ return wsFuture.get(60, TimeUnit.SECONDS);+ }++ private void assertWebSocketConnectionFails(String apiId, String stageName, int expectedStatus) throws Exception {+ String wsUrl = baseUri.toString().replaceFirst("^http", "ws") + "ws/" + apiId + "/" + stageName;+ wsUrl = wsUrl.replace("//ws/", "/ws/");++ HttpClient client = HttpClient.newHttpClient();+ CompletableFuture<WebSocket> wsFuture = client.newWebSocketBuilder()+ .buildAsync(URI.create(wsUrl), new WebSocket.Listener() {});++ try {+ wsFuture.get(60, TimeUnit.SECONDS);+ fail("Expected WebSocket connection to fail with status " + expectedStatus);+ } catch (java.util.concurrent.ExecutionException e) {+ Throwable cause = e.getCause();+ assertNotNull(cause, "Expected a cause for the ExecutionException");+ String message = cause.getMessage() != null ? cause.getMessage() : "";+ if (!message.contains(String.valueOf(expectedStatus))) {+ Throwable inner = cause.getCause();+ if (inner != null && inner.getMessage() != null) {+ message = inner.getMessage();+ }+ }+ assertTrue(+ message.contains(String.valueOf(expectedStatus)),+ "Expected connection failure with status " + expectedStatus + " but got exception: " + cause);+ }+ }+}diff --git a/src/test/java/io/github/hectorvent/floci/services/apigatewayv2/WebSocketProxyEventFormatTest.java b/src/test/java/io/github/hectorvent/floci/services/apigatewayv2/WebSocketProxyEventFormatTest.javanew file mode 100644index 0000000000..22ba36e68d--- /dev/null+++ b/src/test/java/io/github/hectorvent/floci/services/apigatewayv2/WebSocketProxyEventFormatTest.java@@ -0,0 +1,492 @@+package io.github.hectorvent.floci.services.apigatewayv2;++import com.fasterxml.jackson.databind.JsonNode;+import com.fasterxml.jackson.databind.ObjectMapper;+import io.quarkus.test.junit.QuarkusTest;+import io.restassured.http.ContentType;+import org.junit.jupiter.api.MethodOrderer;+import org.junit.jupiter.api.Order;+import org.junit.jupiter.api.Test;+import org.junit.jupiter.api.TestMethodOrder;++import java.net.URI;+import java.net.http.HttpClient;+import java.net.http.WebSocket;+import java.util.concurrent.TimeUnit;++import static io.restassured.RestAssured.given;+import static org.hamcrest.Matchers.notNullValue;+import static org.junit.jupiter.api.Assertions.*;++/**+ * Integration tests for WebSocket proxy event format.+ *+ * Uses an echo Lambda that wraps the full event in a wrapper object to avoid+ * the handler extracting the event's own "body" field. The Lambda returns:+ * { statusCode: 200, body: JSON.stringify({ proxyEvent: event }) }+ *+ * The handler extracts the "body" field from the Lambda response, parses it,+ * finds no nested "body" at the wrapper level, and sends the raw JSON string+ * to the client. The test then parses it and accesses "proxyEvent" to inspect+ * the full event.+ */+@QuarkusTest+@TestMethodOrder(MethodOrderer.OrderAnnotation.class)+class WebSocketProxyEventFormatTest {++ @io.quarkus.test.common.http.TestHTTPResource("/")+ URI baseUri;++ private static final ObjectMapper MAPPER = new ObjectMapper();++ private static String wsApiId;+ private static String echoFnName = "ws-event-format-echo-fn";+ private static String integrationId;+ private static String defaultRouteId;+ private static String connectRouteId;++ // ──────────────────────────── Setup ────────────────────────────++ @Test+ @Order(1)+ void setupApi() {+ // Create a WEBSOCKET API+ wsApiId = given()+ .contentType(ContentType.JSON)+ .body("""+ {"name":"ws-event-format-test","protocolType":"WEBSOCKET","routeSelectionExpression":"$request.body.action"}+ """)+ .when().post("/v2/apis")+ .then()+ .statusCode(201)+ .body("apiId", notNullValue())+ .extract().path("apiId");++ // Create a stage WITH stage variables+ given()+ .contentType(ContentType.JSON)+ .body("""+ {"stageName":"test","stageVariables":{"env":"test","version":"1.0"}}+ """)+ .when().post("/v2/apis/" + wsApiId + "/stages")+ .then()+ .statusCode(201);+ }++ @Test+ @Order(2)+ void setupLambdaFunction() throws Exception {+ // Echo Lambda: wraps the event in a wrapper to avoid body field collision.+ // The handler extracts "body" from Lambda response, parses it as JSON,+ // and since the wrapper has no "body" field, sends the raw string to the client.+ // Actually, looking at the handler code: if parsed JSON has "body", it sends that.+ // If not, it sends result.body() as-is.+ // So we wrap: { proxyEvent: event } — no "body" at top level of wrapper.+ String zip = WebSocketTestSupport.createLambdaZip(+ "exports.handler = async (event) => ({ statusCode: 200, body: JSON.stringify({ proxyEvent: event }) });");+ given()+ .contentType(ContentType.JSON)+ .body("""+ {"FunctionName":"%s","Runtime":"nodejs20.x","Role":"arn:aws:iam::000000000000:role/lambda-role","Handler":"index.handler","Timeout":30,"Code":{"ZipFile":"%s"}}+ """.formatted(echoFnName, zip))+ .when().post("/2015-03-31/functions")+ .then()+ .statusCode(201);+ }++ @Test+ @Order(3)+ void prewarmLambdaFunction() {+ given().contentType(ContentType.JSON).body("{}")+ .when().post("/2015-03-31/functions/" + echoFnName + "/invocations")+ .then().statusCode(200);+ }++ @Test+ @Order(4)+ void setupIntegrationsAndRoutes() {+ // Create integration pointing to the echo Lambda+ integrationId = given()+ .contentType(ContentType.JSON)+ .body("""+ {"integrationType":"AWS_PROXY","integrationUri":"arn:aws:lambda:us-east-1:000000000000:function:%s/invocations","integrationMethod":"POST"}+ """.formatted(echoFnName))+ .when().post("/v2/apis/" + wsApiId + "/integrations")+ .then()+ .statusCode(201)+ .extract().path("integrationId");++ // Create $default route with routeResponseSelectionExpression so we get the echo back+ defaultRouteId = given()+ .contentType(ContentType.JSON)+ .body("""+ {"routeKey":"$default","target":"integrations/%s","routeResponseSelectionExpression":"$default"}+ """.formatted(integrationId))+ .when().post("/v2/apis/" + wsApiId + "/routes")+ .then()+ .statusCode(201)+ .extract().path("routeId");++ // Create $connect route pointing to the echo Lambda (allows connection — returns 200)+ connectRouteId = given()+ .contentType(ContentType.JSON)+ .body("""+ {"routeKey":"$connect","target":"integrations/%s"}+ """.formatted(integrationId))+ .when().post("/v2/apis/" + wsApiId + "/routes")+ .then()+ .statusCode(201)+ .extract().path("routeId");+ }++ // ──────────────────────────── Test 1: CONNECT event contains all required fields ────────────────────────────++ @Test+ @Order(10)+ void connectEventContainsAllRequiredFields() throws Exception {+ // requestContext has connectionId, routeKey, eventType, apiId, stage,+ // domainName, requestId, requestTime, requestTimeEpoch, connectedAt, messageDirection,+ // extendedRequestId, identity+ //+ // We verify via the MESSAGE event echo since the $connect response is not sent to client.+ // The MESSAGE event has the same requestContext structure with all required fields.+ JsonNode event = sendMessageAndGetEvent("{\"action\":\"test\",\"data\":\"hello\"}");++ JsonNode requestContext = event.get("requestContext");+ assertNotNull(requestContext, "Event should have requestContext");++ // Verify all required fields exist in requestContext+ assertNotNull(requestContext.get("connectionId"), "requestContext should have connectionId");+ assertFalse(requestContext.get("connectionId").asText().isEmpty(), "connectionId should not be empty");++ assertNotNull(requestContext.get("routeKey"), "requestContext should have routeKey");+ assertNotNull(requestContext.get("eventType"), "requestContext should have eventType");+ assertNotNull(requestContext.get("apiId"), "requestContext should have apiId");+ assertEquals(wsApiId, requestContext.get("apiId").asText());++ assertNotNull(requestContext.get("stage"), "requestContext should have stage");+ assertEquals("test", requestContext.get("stage").asText());++ assertNotNull(requestContext.get("domainName"), "requestContext should have domainName");+ assertNotNull(requestContext.get("requestId"), "requestContext should have requestId");+ assertFalse(requestContext.get("requestId").asText().isEmpty(), "requestId should not be empty");++ assertNotNull(requestContext.get("requestTime"), "requestContext should have requestTime");+ assertFalse(requestContext.get("requestTime").asText().isEmpty(), "requestTime should not be empty");++ assertNotNull(requestContext.get("requestTimeEpoch"), "requestContext should have requestTimeEpoch");+ assertTrue(requestContext.get("requestTimeEpoch").isNumber(), "requestTimeEpoch should be a number");++ assertNotNull(requestContext.get("connectedAt"), "requestContext should have connectedAt");+ assertTrue(requestContext.get("connectedAt").isNumber(), "connectedAt should be a number");++ assertNotNull(requestContext.get("messageDirection"), "requestContext should have messageDirection");+ assertNotNull(requestContext.get("extendedRequestId"), "requestContext should have extendedRequestId");++ assertNotNull(requestContext.get("identity"), "requestContext should have identity");+ assertTrue(requestContext.get("identity").isObject(), "identity should be an object");+ }++ // ──────────────────────────── Test 2: MESSAGE event contains body and isBase64Encoded ────────────────────────────++ @Test+ @Order(20)+ void messageEventContainsBodyAndIsBase64Encoded() throws Exception {+ // MESSAGE event has body field with the message text and isBase64Encoded=false+ String messageText = "{\"action\":\"greet\",\"message\":\"hello world\"}";+ JsonNode event = sendMessageAndGetEvent(messageText);++ // Verify body field contains the original message+ assertNotNull(event.get("body"), "MESSAGE event should have body field");+ assertEquals(messageText, event.get("body").asText(),+ "body should contain the original message text");++ // Verify isBase64Encoded is false+ assertNotNull(event.get("isBase64Encoded"), "MESSAGE event should have isBase64Encoded field");+ assertFalse(event.get("isBase64Encoded").asBoolean(),+ "isBase64Encoded should be false for text messages");++ // Verify eventType is MESSAGE+ JsonNode requestContext = event.get("requestContext");+ assertEquals("MESSAGE", requestContext.get("eventType").asText(),+ "eventType should be MESSAGE");+ }++ // ──────────────────────────── Test 3: DISCONNECT event has null body ────────────────────────────++ @Test+ @Order(30)+ void disconnectEventHasNullBody() throws Exception {+ // DISCONNECT event has null body.+ // We cannot directly observe the DISCONNECT event from the client side.+ // We verify indirectly: the MESSAGE event has a non-null body (proving body handling works),+ // and the builder implementation sets body to null for DISCONNECT events.+ // This test confirms MESSAGE events have body present, proving differentiation.+ JsonNode event = sendMessageAndGetEvent("{\"action\":\"test\"}");++ // For MESSAGE, body should NOT be null+ assertNotNull(event.get("body"), "MESSAGE event body should not be null");+ assertFalse(event.get("body").isNull(), "MESSAGE event body should not be JSON null");+ assertEquals("{\"action\":\"test\"}", event.get("body").asText(),+ "MESSAGE body should contain the sent message");++ // The DISCONNECT event format is verified by the builder implementation:+ // buildDisconnectEvent() calls event.putNull("body")+ }++ // ──────────────────────────── Test 4: requestContext.identity contains sourceIp and userAgent ────────────────────────────++ @Test+ @Order(40)+ void requestContextIdentityContainsSourceIp() throws Exception {+ // requestContext.identity has sourceIp and userAgent+ JsonNode event = sendMessageAndGetEvent("{\"action\":\"identity-test\"}");+ JsonNode identity = event.get("requestContext").get("identity");++ assertNotNull(identity, "requestContext should have identity object");+ assertNotNull(identity.get("sourceIp"), "identity should have sourceIp");+ assertFalse(identity.get("sourceIp").asText().isEmpty(), "sourceIp should not be empty");++ assertNotNull(identity.get("userAgent"), "identity should have userAgent");+ // userAgent may be empty string but the field should exist+ }++ // ──────────────────────────── Test 5: domainName matches apiId and region ────────────────────────────++ @Test+ @Order(50)+ void domainNameMatchesApiIdAndRegion() throws Exception {+ // domainName is {apiId}.execute-api.{region}.amazonaws.com+ JsonNode event = sendMessageAndGetEvent("{\"action\":\"domain-test\"}");+ String domainName = event.get("requestContext").get("domainName").asText();++ // domainName should follow the pattern {apiId}.execute-api.{region}.amazonaws.com+ assertTrue(domainName.startsWith(wsApiId + ".execute-api."),+ "domainName should start with apiId.execute-api., got: " + domainName);+ assertTrue(domainName.endsWith(".amazonaws.com"),+ "domainName should end with .amazonaws.com, got: " + domainName);++ // Verify the full format: {apiId}.execute-api.{region}.amazonaws.com+ String[] parts = domainName.split("\\.");+ // Expected: [apiId, execute-api, region, amazonaws, com]+ assertTrue(parts.length >= 5, "domainName should have at least 5 dot-separated parts, got: " + domainName);+ assertEquals(wsApiId, parts[0], "First part should be apiId");+ assertEquals("execute-api", parts[1], "Second part should be execute-api");+ // parts[2] is the region+ assertFalse(parts[2].isEmpty(), "Region part should not be empty");+ }++ // ──────────────────────────── Test 6: connectedAt is epoch millis ────────────────────────────++ @Test+ @Order(60)+ void connectedAtIsEpochMillis() throws Exception {+ // connectedAt is a valid epoch millisecond timestamp+ long beforeConnect = System.currentTimeMillis();++ WebSocketTestSupport.MessageCapture capture = new WebSocketTestSupport.MessageCapture();+ WebSocket ws = connectWebSocketWithListener(wsApiId, "test", capture);+ assertNotNull(ws);++ long afterConnect = System.currentTimeMillis();++ ws.sendText("{\"action\":\"timestamp-test\"}", true).join();++ String response = capture.getResponse(15, TimeUnit.SECONDS);+ assertNotNull(response, "Should receive echoed event");+ JsonNode wrapper = MAPPER.readTree(response);+ JsonNode event = wrapper.get("proxyEvent");+ assertNotNull(event, "Wrapper should contain proxyEvent");++ long connectedAt = event.get("requestContext").get("connectedAt").asLong();++ // connectedAt should be a reasonable epoch millis timestamp+ assertTrue(connectedAt >= beforeConnect - 5000,+ "connectedAt should be >= beforeConnect (with 5s tolerance), got: " + connectedAt);+ assertTrue(connectedAt <= afterConnect + 5000,+ "connectedAt should be <= afterConnect (with 5s tolerance), got: " + connectedAt);++ // Verify it's in milliseconds (not seconds) — should be > 1_000_000_000_000+ assertTrue(connectedAt > 1_000_000_000_000L,+ "connectedAt should be in epoch milliseconds (> 1 trillion), got: " + connectedAt);++ ws.sendClose(WebSocket.NORMAL_CLOSURE, "done").join();+ Thread.sleep(500);+ }++ // ──────────────────────────── Test 7: messageDirection is always IN ────────────────────────────++ @Test+ @Order(70)+ void messageDirectionIsAlwaysIn() throws Exception {+ // messageDirection is always "IN"+ JsonNode event = sendMessageAndGetEvent("{\"action\":\"direction-test\"}");+ String messageDirection = event.get("requestContext").get("messageDirection").asText();++ assertEquals("IN", messageDirection, "messageDirection should always be 'IN'");+ }++ // ──────────────────────────── Test 8: extendedRequestId distinct from requestId ────────────────────────────++ @Test+ @Order(80)+ void extendedRequestIdDistinctFromRequestId() throws Exception {+ // extendedRequestId is different from requestId+ JsonNode event = sendMessageAndGetEvent("{\"action\":\"requestid-test\"}");+ JsonNode requestContext = event.get("requestContext");++ String requestId = requestContext.get("requestId").asText();+ String extendedRequestId = requestContext.get("extendedRequestId").asText();++ assertNotNull(requestId, "requestId should not be null");+ assertNotNull(extendedRequestId, "extendedRequestId should not be null");+ assertFalse(requestId.isEmpty(), "requestId should not be empty");+ assertFalse(extendedRequestId.isEmpty(), "extendedRequestId should not be empty");+ assertNotEquals(requestId, extendedRequestId,+ "extendedRequestId should be distinct from requestId");+ }++ // ──────────────────────────── Test 9: stageVariables included in event ────────────────────────────++ @Test+ @Order(90)+ void stageVariablesIncludedInEvent() throws Exception {+ // stageVariables field contains the stage's configured variables+ JsonNode event = sendMessageAndGetEvent("{\"action\":\"stagevars-test\"}");++ JsonNode stageVariables = event.get("stageVariables");+ assertNotNull(stageVariables, "Event should have stageVariables field");+ assertFalse(stageVariables.isNull(), "stageVariables should not be null when stage has variables");+ assertTrue(stageVariables.isObject(), "stageVariables should be an object");++ // Verify the configured stage variables are present+ assertEquals("test", stageVariables.get("env").asText(),+ "stageVariables should contain 'env' = 'test'");+ assertEquals("1.0", stageVariables.get("version").asText(),+ "stageVariables should contain 'version' = '1.0'");+ }++ // ──────────────────────────── Test 10: Binary frame sets isBase64Encoded=true ────────────────────────────++ @Test+ @Order(100)+ void binaryFrameSetsIsBase64EncodedTrue() throws Exception {+ // Binary frames should be delivered with isBase64Encoded=true and base64-encoded body+ WebSocketTestSupport.MultiMessageCapture capture = new WebSocketTestSupport.MultiMessageCapture();+ WebSocket ws = connectWebSocketWithMultiCapture(wsApiId, "test", capture);+ assertNotNull(ws, "WebSocket connection should succeed");++ // Send a binary frame+ byte[] binaryData = new byte[]{0x01, 0x02, 0x03, 0x04, 0x05};+ ws.sendBinary(java.nio.ByteBuffer.wrap(binaryData), true).join();++ String response = capture.getNextMessage(15, TimeUnit.SECONDS);+ assertNotNull(response, "Should receive echoed event for binary frame");++ JsonNode wrapper = MAPPER.readTree(response);+ JsonNode event = wrapper.get("proxyEvent");+ assertNotNull(event, "Response should contain proxyEvent");++ // Verify isBase64Encoded is true for binary frames+ assertTrue(event.get("isBase64Encoded").asBoolean(),+ "isBase64Encoded should be true for binary frames");++ // Verify body is base64-encoded+ String body = event.get("body").asText();+ assertNotNull(body, "body should not be null for binary frames");+ // Decode and verify it matches the original binary data+ byte[] decoded = java.util.Base64.getDecoder().decode(body);+ assertArrayEquals(binaryData, decoded,+ "Decoded body should match the original binary data");++ ws.sendClose(WebSocket.NORMAL_CLOSURE, "done").join();+ Thread.sleep(500);+ }++ // ──────────────────────────── Test 11: Payload size limit enforcement ────────────────────────────++ @Test+ @Order(110)+ void payloadSizeLimitEnforced() throws Exception {+ // Messages exceeding 128 KB should receive an error frame+ WebSocketTestSupport.MultiMessageCapture capture = new WebSocketTestSupport.MultiMessageCapture();+ WebSocket ws = connectWebSocketWithMultiCapture(wsApiId, "test", capture);+ assertNotNull(ws, "WebSocket connection should succeed");++ // Create a message larger than 128 KB (128 * 1024 + 1 bytes)+ int oversizeLength = 128 * 1024 + 1;+ StringBuilder oversizeMessage = new StringBuilder(oversizeLength);+ for (int i = 0; i < oversizeLength; i++) {+ oversizeMessage.append('x');+ }++ ws.sendText(oversizeMessage.toString(), true).join();++ String response = capture.getNextMessage(15, TimeUnit.SECONDS);+ assertNotNull(response, "Should receive an error frame for oversized message");+ assertTrue(response.contains("Message too long"),+ "Error frame should indicate message too long, got: " + response);++ // Verify the connection is still alive after the error (not disconnected)+ ws.sendText("{\"action\":\"test\",\"data\":\"after-oversize\"}", true).join();+ String normalResponse = capture.getNextMessage(15, TimeUnit.SECONDS);+ assertNotNull(normalResponse, "Connection should still be alive after oversize rejection");++ ws.sendClose(WebSocket.NORMAL_CLOSURE, "done").join();+ Thread.sleep(500);+ }++ // ──────────────────────────── Cleanup ────────────────────────────++ @Test+ @Order(999)+ void cleanup() {+ if (wsApiId != null) {+ given().when().delete("/v2/apis/" + wsApiId);+ }+ given().when().delete("/2015-03-31/functions/" + echoFnName);+ }++ // ──────────────────────────── Helpers ────────────────────────────++ /**+ * Sends a message via WebSocket and returns the parsed proxy event from the echo response.+ * The echo Lambda wraps the event as { proxyEvent: event }, so this method extracts it.+ */+ private JsonNode sendMessageAndGetEvent(String message) throws Exception {+ WebSocketTestSupport.MessageCapture capture = new WebSocketTestSupport.MessageCapture();+ WebSocket ws = connectWebSocketWithListener(wsApiId, "test", capture);+ assertNotNull(ws, "WebSocket connection should succeed");++ ws.sendText(message, true).join();++ String response = capture.getResponse(15, TimeUnit.SECONDS);+ assertNotNull(response, "Should receive echoed event response");++ ws.sendClose(WebSocket.NORMAL_CLOSURE, "done").join();+ Thread.sleep(500);++ JsonNode wrapper = MAPPER.readTree(response);+ JsonNode event = wrapper.get("proxyEvent");+ assertNotNull(event, "Response wrapper should contain 'proxyEvent' field, got: " + response);+ return event;+ }++ private WebSocket connectWebSocketWithListener(String apiId, String stageName, WebSocketTestSupport.MessageCapture capture)+ throws Exception {+ String wsUrl = WebSocketTestSupport.buildWsUrl(baseUri, apiId, stageName);+ HttpClient client = HttpClient.newHttpClient();+ return client.newWebSocketBuilder()+ .buildAsync(URI.create(wsUrl), capture)+ .get(60, TimeUnit.SECONDS);+ }++ private WebSocket connectWebSocketWithMultiCapture(String apiId, String stageName, WebSocketTestSupport.MultiMessageCapture capture)+ throws Exception {+ String wsUrl = WebSocketTestSupport.buildWsUrl(baseUri, apiId, stageName);+ HttpClient client = HttpClient.newHttpClient();+ return client.newWebSocketBuilder()+ .buildAsync(URI.create(wsUrl), capture)+ .get(60, TimeUnit.SECONDS);+ }+}diff --git a/src/test/java/io/github/hectorvent/floci/services/apigatewayv2/WebSocketRouteResponseTest.java b/src/test/java/io/github/hectorvent/floci/services/apigatewayv2/WebSocketRouteResponseTest.javanew file mode 100644index 0000000000..e6f0ca0305--- /dev/null+++ b/src/test/java/io/github/hectorvent/floci/services/apigatewayv2/WebSocketRouteResponseTest.java@@ -0,0 +1,214 @@+package io.github.hectorvent.floci.services.apigatewayv2;++import io.quarkus.test.junit.QuarkusTest;+import io.restassured.http.ContentType;+import org.junit.jupiter.api.MethodOrderer;+import org.junit.jupiter.api.Order;+import org.junit.jupiter.api.Test;+import org.junit.jupiter.api.TestMethodOrder;++import java.net.URI;+import java.net.http.HttpClient;+import java.net.http.WebSocket;+import java.util.concurrent.TimeUnit;+import java.util.concurrent.TimeoutException;++import static io.restassured.RestAssured.given;+import static org.hamcrest.Matchers.notNullValue;+import static org.junit.jupiter.api.Assertions.*;++/**+ * Integration tests for WebSocket route response selection expression.+ */+@QuarkusTest+@TestMethodOrder(MethodOrderer.OrderAnnotation.class)+class WebSocketRouteResponseTest {++ @io.quarkus.test.common.http.TestHTTPResource("/")+ URI baseUri;++ private static String wsApiId;+ private static String lambdaFnName = "ws-route-response-fn";+ private static String integrationId;+ private static String routeWithResponseId;+ private static String routeWithoutResponseId;++ // ──────────────────────────── Setup ────────────────────────────++ @Test+ @Order(1)+ void setupApi() {+ // Create a WEBSOCKET API with routeSelectionExpression: $request.body.action+ wsApiId = given()+ .contentType(ContentType.JSON)+ .body("""+ {"name":"ws-route-response-test","protocolType":"WEBSOCKET","routeSelectionExpression":"$request.body.action"}+ """)+ .when().post("/v2/apis")+ .then()+ .statusCode(201)+ .body("apiId", notNullValue())+ .extract().path("apiId");++ // Create a stage+ given()+ .contentType(ContentType.JSON)+ .body("""+ {"stageName":"test"}+ """)+ .when().post("/v2/apis/" + wsApiId + "/stages")+ .then()+ .statusCode(201);+ }++ @Test+ @Order(2)+ void setupLambdaFunction() throws Exception {+ // Lambda that returns {"statusCode": 200, "body": "extracted-body"}+ String zip = WebSocketTestSupport.createLambdaZip(+ "exports.handler = async (event) => ({ statusCode: 200, body: 'extracted-body' });");+ given()+ .contentType(ContentType.JSON)+ .body("""+ {"FunctionName":"%s","Runtime":"nodejs20.x","Role":"arn:aws:iam::000000000000:role/lambda-role","Handler":"index.handler","Timeout":30,"Code":{"ZipFile":"%s"}}+ """.formatted(lambdaFnName, zip))+ .when().post("/2015-03-31/functions")+ .then()+ .statusCode(201);+ }++ @Test+ @Order(3)+ void prewarmLambdaFunction() {+ given().contentType(ContentType.JSON).body("{}")+ .when().post("/2015-03-31/functions/" + lambdaFnName + "/invocations")+ .then().statusCode(200);+ }++ @Test+ @Order(4)+ void setupIntegrationsAndRoutes() {+ // Create integration pointing to the Lambda function+ integrationId = given()+ .contentType(ContentType.JSON)+ .body("""+ {"integrationType":"AWS_PROXY","integrationUri":"arn:aws:lambda:us-east-1:000000000000:function:%s/invocations","integrationMethod":"POST"}+ """.formatted(lambdaFnName))+ .when().post("/v2/apis/" + wsApiId + "/integrations")+ .then()+ .statusCode(201)+ .extract().path("integrationId");++ // Route WITH routeResponseSelectionExpression (response should be sent back)+ routeWithResponseId = given()+ .contentType(ContentType.JSON)+ .body("""+ {"routeKey":"withResponse","target":"integrations/%s","routeResponseSelectionExpression":"$default"}+ """.formatted(integrationId))+ .when().post("/v2/apis/" + wsApiId + "/routes")+ .then()+ .statusCode(201)+ .extract().path("routeId");++ // Route WITHOUT routeResponseSelectionExpression (response should NOT be sent back)+ routeWithoutResponseId = given()+ .contentType(ContentType.JSON)+ .body("""+ {"routeKey":"noResponse","target":"integrations/%s"}+ """.formatted(integrationId))+ .when().post("/v2/apis/" + wsApiId + "/routes")+ .then()+ .statusCode(201)+ .extract().path("routeId");+ }++ // ──────────────────────────── Test 1: Response returned when routeResponseSelectionExpression set ────────────────────────────++ @Test+ @Order(10)+ void responseReturnedWhenRouteResponseExpressionSet() throws Exception {+ // When a route has a non-null routeResponseSelectionExpression,+ // the integration response body is sent back to the client+ WebSocketTestSupport.MessageCapture capture = new WebSocketTestSupport.MessageCapture();+ WebSocket ws = connectWebSocketWithListener(wsApiId, "test", capture);+ assertNotNull(ws);++ // Send a message that routes to the "withResponse" route+ ws.sendText("{\"action\":\"withResponse\",\"data\":\"hello\"}", true).join();++ // Should receive a response back from the Lambda+ String response = capture.getResponse(15, TimeUnit.SECONDS);+ assertNotNull(response, "Should receive a response when routeResponseSelectionExpression is set");++ ws.sendClose(WebSocket.NORMAL_CLOSURE, "done").join();+ Thread.sleep(500);+ }++ // ──────────────────────────── Test 2: No response when routeResponseSelectionExpression is null ────────────────────────────++ @Test+ @Order(20)+ void noResponseWhenRouteResponseExpressionNull() throws Exception {+ // When a route has null routeResponseSelectionExpression,+ // no response is sent back to the client+ WebSocketTestSupport.MessageCapture capture = new WebSocketTestSupport.MessageCapture();+ WebSocket ws = connectWebSocketWithListener(wsApiId, "test", capture);+ assertNotNull(ws);++ // Send a message that routes to the "noResponse" route+ ws.sendText("{\"action\":\"noResponse\",\"data\":\"hello\"}", true).join();++ // Should NOT receive a response — expect a timeout+ assertThrows(TimeoutException.class, () -> {+ capture.getResponse(3, TimeUnit.SECONDS);+ }, "Should NOT receive a response when routeResponseSelectionExpression is null");++ ws.sendClose(WebSocket.NORMAL_CLOSURE, "done").join();+ Thread.sleep(500);+ }++ // ──────────────────────────── Test 3: Body field extracted from Lambda response ────────────────────────────++ @Test+ @Order(30)+ void responseBodyExtractedFromLambdaResponse() throws Exception {+ // The "body" field is extracted from the Lambda JSON response+ // and sent to the client (not the full JSON)+ WebSocketTestSupport.MessageCapture capture = new WebSocketTestSupport.MessageCapture();+ WebSocket ws = connectWebSocketWithListener(wsApiId, "test", capture);+ assertNotNull(ws);++ // Send a message that routes to the "withResponse" route+ ws.sendText("{\"action\":\"withResponse\",\"data\":\"test\"}", true).join();++ // Should receive exactly "extracted-body" (the body field value from the Lambda response)+ String response = capture.getResponse(15, TimeUnit.SECONDS);+ assertEquals("extracted-body", response,+ "Response should be the extracted 'body' field value from the Lambda JSON response");++ ws.sendClose(WebSocket.NORMAL_CLOSURE, "done").join();+ Thread.sleep(500);+ }++ // ──────────────────────────── Cleanup ────────────────────────────++ @Test+ @Order(999)+ void cleanup() {+ if (wsApiId != null) {+ given().when().delete("/v2/apis/" + wsApiId);+ }+ given().when().delete("/2015-03-31/functions/" + lambdaFnName);+ }++ // ──────────────────────────── Helpers ────────────────────────────++ private WebSocket connectWebSocketWithListener(String apiId, String stageName, WebSocketTestSupport.MessageCapture capture)+ throws Exception {+ String wsUrl = WebSocketTestSupport.buildWsUrl(baseUri, apiId, stageName);+ HttpClient client = HttpClient.newHttpClient();+ return client.newWebSocketBuilder()+ .buildAsync(URI.create(wsUrl), capture)+ .get(60, TimeUnit.SECONDS);+ }+}diff --git a/src/test/java/io/github/hectorvent/floci/services/apigatewayv2/WebSocketStageVariablesTest.java b/src/test/java/io/github/hectorvent/floci/services/apigatewayv2/WebSocketStageVariablesTest.javanew file mode 100644index 0000000000..981ab13ba5--- /dev/null+++ b/src/test/java/io/github/hectorvent/floci/services/apigatewayv2/WebSocketStageVariablesTest.java@@ -0,0 +1,297 @@+package io.github.hectorvent.floci.services.apigatewayv2;++import io.quarkus.test.junit.QuarkusTest;+import io.restassured.http.ContentType;+import org.junit.jupiter.api.MethodOrderer;+import org.junit.jupiter.api.Order;+import org.junit.jupiter.api.Test;+import org.junit.jupiter.api.TestMethodOrder;++import java.net.URI;+import java.net.http.HttpClient;+import java.net.http.WebSocket;+import java.util.concurrent.TimeUnit;+import java.util.concurrent.TimeoutException;++import static io.restassured.RestAssured.given;+import static org.hamcrest.Matchers.notNullValue;+import static org.junit.jupiter.api.Assertions.*;++/**+ * Integration tests for WebSocket stage variable substitution in integration URIs.+ *+ * Stage variable references in integrationUri are substituted with configured values.+ * Undefined stage variable references are replaced with empty string.+ * Multiple stage variable references in a single URI are all substituted.+ */+@QuarkusTest+@TestMethodOrder(MethodOrderer.OrderAnnotation.class)+class WebSocketStageVariablesTest {++ @io.quarkus.test.common.http.TestHTTPResource("/")+ URI baseUri;++ private static String wsApiId;+ private static String stageVarFnName = "ws-stage-var-fn";++ // ──────────────────────────── Setup ────────────────────────────++ @Test+ @Order(1)+ void setupLambdaFunction() throws Exception {+ // Create a Lambda function that returns a fixed response to verify it was invoked+ String zip = WebSocketTestSupport.createLambdaZip(+ "exports.handler = async (event) => ({ statusCode: 200, body: JSON.stringify({handler:'stage-var-success', routeKey: (event.requestContext || {}).routeKey || 'none'}) });");+ given()+ .contentType(ContentType.JSON)+ .body("""+ {"FunctionName":"%s","Runtime":"nodejs20.x","Role":"arn:aws:iam::000000000000:role/lambda-role","Handler":"index.handler","Timeout":30,"Code":{"ZipFile":"%s"}}+ """.formatted(stageVarFnName, zip))+ .when().post("/2015-03-31/functions")+ .then()+ .statusCode(201);++ // Prewarm the Lambda function+ given().contentType(ContentType.JSON).body("{}")+ .when().post("/2015-03-31/functions/" + stageVarFnName + "/invocations")+ .then().statusCode(200);+ }++ @Test+ @Order(2)+ void setupWebSocketApi() {+ // Create a WEBSOCKET API+ wsApiId = given()+ .contentType(ContentType.JSON)+ .body("""+ {"name":"ws-stage-var-test","protocolType":"WEBSOCKET","routeSelectionExpression":"$request.body.action"}+ """)+ .when().post("/v2/apis")+ .then()+ .statusCode(201)+ .body("apiId", notNullValue())+ .extract().path("apiId");+ }++ // ──────────────────────────── Test 1: Stage variable substituted in Lambda URI ────────────────────────────++ @Test+ @Order(10)+ void stageVariableSubstitutedInLambdaUri() throws Exception {+ // Stage variable in integration URI is substituted with the configured value+ // before Lambda invocation.++ // Create a stage with stageVariables containing the function name+ given()+ .contentType(ContentType.JSON)+ .body("""+ {"stageName":"stagevar1","stageVariables":{"functionName":"ws-stage-var-fn"}}+ """)+ .when().post("/v2/apis/" + wsApiId + "/stages")+ .then()+ .statusCode(201);++ // Create an integration with a stage variable reference in the URI+ String integrationId = given()+ .contentType(ContentType.JSON)+ .body("""+ {"integrationType":"AWS_PROXY","integrationUri":"arn:aws:lambda:us-east-1:000000000000:function:${stageVariables.functionName}/invocations","integrationMethod":"POST"}+ """)+ .when().post("/v2/apis/" + wsApiId + "/integrations")+ .then()+ .statusCode(201)+ .body("integrationId", notNullValue())+ .extract().path("integrationId");++ // Create a $default route with routeResponseSelectionExpression so we get a response back+ String routeId = given()+ .contentType(ContentType.JSON)+ .body("""+ {"routeKey":"$default","target":"integrations/%s","routeResponseSelectionExpression":"$default"}+ """.formatted(integrationId))+ .when().post("/v2/apis/" + wsApiId + "/routes")+ .then()+ .statusCode(201)+ .extract().path("routeId");++ try {+ // Connect and send a message+ WebSocketTestSupport.MessageCapture capture = new WebSocketTestSupport.MessageCapture();+ WebSocket ws = connectWebSocketWithListener(wsApiId, "stagevar1", capture);+ assertNotNull(ws, "WebSocket connection should succeed");++ ws.sendText("{\"action\":\"test\",\"data\":\"stage-var-test\"}", true).join();++ // Wait for response — if stage variable substitution works, the Lambda is invoked successfully+ String response = capture.getResponse(15, TimeUnit.SECONDS);+ assertNotNull(response, "Should receive a response when stage variable is substituted correctly");+ assertTrue(response.contains("stage-var-success"),+ "Response should indicate the Lambda was invoked successfully via stage variable substitution, got: " + response);++ ws.sendClose(WebSocket.NORMAL_CLOSURE, "done").join();+ Thread.sleep(500);+ } finally {+ // Cleanup route+ given().when().delete("/v2/apis/" + wsApiId + "/routes/" + routeId)+ .then().statusCode(204);+ }+ }++ // ──────────────────────────── Test 2: Undefined stage variable substituted with empty string ────────────────────────────++ @Test+ @Order(20)+ void undefinedStageVariableSubstitutedWithEmpty() throws Exception {+ // Undefined stage variable reference is replaced with empty string.+ // This results in an invalid/empty function name, so the Lambda invocation fails+ // and no successful response is returned to the client.++ // Create a stage WITHOUT the referenced variable+ given()+ .contentType(ContentType.JSON)+ .body("""+ {"stageName":"stagevar2","stageVariables":{"otherVar":"someValue"}}+ """)+ .when().post("/v2/apis/" + wsApiId + "/stages")+ .then()+ .statusCode(201);++ // Create an integration referencing a variable that doesn't exist in the stage+ String missingVarIntegrationId = given()+ .contentType(ContentType.JSON)+ .body("""+ {"integrationType":"AWS_PROXY","integrationUri":"arn:aws:lambda:us-east-1:000000000000:function:${stageVariables.missingVar}/invocations","integrationMethod":"POST"}+ """)+ .when().post("/v2/apis/" + wsApiId + "/integrations")+ .then()+ .statusCode(201)+ .body("integrationId", notNullValue())+ .extract().path("integrationId");++ // Create a $default route with routeResponseSelectionExpression+ String routeId = given()+ .contentType(ContentType.JSON)+ .body("""+ {"routeKey":"$default","target":"integrations/%s","routeResponseSelectionExpression":"$default"}+ """.formatted(missingVarIntegrationId))+ .when().post("/v2/apis/" + wsApiId + "/routes")+ .then()+ .statusCode(201)+ .extract().path("routeId");++ try {+ // Connect and send a message+ WebSocketTestSupport.MessageCapture capture = new WebSocketTestSupport.MessageCapture();+ WebSocket ws = connectWebSocketWithListener(wsApiId, "stagevar2", capture);+ assertNotNull(ws, "WebSocket connection should succeed");++ ws.sendText("{\"action\":\"test\",\"data\":\"missing-var-test\"}", true).join();++ // The substitution replaces ${stageVariables.missingVar} with empty string,+ // resulting in an empty function name. The invoker returns IntegrationResult(500, null, ...)+ // Since body is null, no response is sent back to the client.+ // We verify this by expecting a timeout — proving the substitution happened+ // (empty string was used) and the Lambda was NOT successfully invoked.+ assertThrows(TimeoutException.class, () -> {+ capture.getResponse(3, TimeUnit.SECONDS);+ }, "Should not receive a successful response when stage variable is undefined (function name becomes empty)");++ ws.sendClose(WebSocket.NORMAL_CLOSURE, "done").join();+ Thread.sleep(500);+ } finally {+ // Cleanup route+ given().when().delete("/v2/apis/" + wsApiId + "/routes/" + routeId)+ .then().statusCode(204);+ }+ }++ // ──────────────────────────── Test 3: Multiple stage variables substituted ────────────────────────────++ @Test+ @Order(30)+ void multipleStageVariablesSubstituted() throws Exception {+ // Multiple stage variable references in a single URI are all substituted.++ // Create a stage with multiple variables that together form the function name+ given()+ .contentType(ContentType.JSON)+ .body("""+ {"stageName":"stagevar3","stageVariables":{"prefix":"ws","suffix":"stage-var-fn"}}+ """)+ .when().post("/v2/apis/" + wsApiId + "/stages")+ .then()+ .statusCode(201);++ // Create an integration with multiple stage variable references+ // After substitution: "...function:ws-stage-var-fn/invocations"+ String multiVarIntegrationId = given()+ .contentType(ContentType.JSON)+ .body("""+ {"integrationType":"AWS_PROXY","integrationUri":"arn:aws:lambda:us-east-1:000000000000:function:${stageVariables.prefix}-${stageVariables.suffix}/invocations","integrationMethod":"POST"}+ """)+ .when().post("/v2/apis/" + wsApiId + "/integrations")+ .then()+ .statusCode(201)+ .body("integrationId", notNullValue())+ .extract().path("integrationId");++ // Create a $default route with routeResponseSelectionExpression+ String routeId = given()+ .contentType(ContentType.JSON)+ .body("""+ {"routeKey":"$default","target":"integrations/%s","routeResponseSelectionExpression":"$default"}+ """.formatted(multiVarIntegrationId))+ .when().post("/v2/apis/" + wsApiId + "/routes")+ .then()+ .statusCode(201)+ .extract().path("routeId");++ try {+ // Connect and send a message+ WebSocketTestSupport.MessageCapture capture = new WebSocketTestSupport.MessageCapture();+ WebSocket ws = connectWebSocketWithListener(wsApiId, "stagevar3", capture);+ assertNotNull(ws, "WebSocket connection should succeed");++ ws.sendText("{\"action\":\"test\",\"data\":\"multi-var-test\"}", true).join();++ // After substitution, the URI becomes "...function:ws-stage-var-fn/invocations"+ // which should invoke the Lambda successfully+ String response = capture.getResponse(15, TimeUnit.SECONDS);+ assertNotNull(response, "Should receive a response when multiple stage variables are substituted");+ assertTrue(response.contains("stage-var-success"),+ "Response should indicate the Lambda was invoked successfully via multiple stage variable substitution, got: " + response);++ ws.sendClose(WebSocket.NORMAL_CLOSURE, "done").join();+ Thread.sleep(500);+ } finally {+ // Cleanup route+ given().when().delete("/v2/apis/" + wsApiId + "/routes/" + routeId)+ .then().statusCode(204);+ }+ }++ // ──────────────────────────── Cleanup ────────────────────────────++ @Test+ @Order(999)+ void cleanup() {+ // Delete API (cascades integrations, routes, stages)+ if (wsApiId != null) {+ given().when().delete("/v2/apis/" + wsApiId);+ }++ // Delete Lambda function+ given().when().delete("/2015-03-31/functions/" + stageVarFnName);+ }++ // ──────────────────────────── Helpers ────────────────────────────++ private WebSocket connectWebSocketWithListener(String apiId, String stageName, WebSocketTestSupport.MessageCapture capture)+ throws Exception {+ String wsUrl = WebSocketTestSupport.buildWsUrl(baseUri, apiId, stageName);+ HttpClient client = HttpClient.newHttpClient();+ return client.newWebSocketBuilder()+ .buildAsync(URI.create(wsUrl), capture)+ .get(60, TimeUnit.SECONDS);+ }+}diff --git a/src/test/java/io/github/hectorvent/floci/services/apigatewayv2/WebSocketTestSupport.java b/src/test/java/io/github/hectorvent/floci/services/apigatewayv2/WebSocketTestSupport.javanew file mode 100644index 0000000000..569ac1454b--- /dev/null+++ b/src/test/java/io/github/hectorvent/floci/services/apigatewayv2/WebSocketTestSupport.java@@ -0,0 +1,203 @@+package io.github.hectorvent.floci.services.apigatewayv2;++import java.io.ByteArrayOutputStream;+import java.net.URI;+import java.net.http.HttpClient;+import java.net.http.WebSocket;+import java.util.Base64;+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;++/**+ * Shared test utilities for WebSocket integration tests.+ * Eliminates duplication of MessageCapture, MultiMessageCapture, createLambdaZip,+ * and WebSocket connection helpers across multiple test classes.+ */+public final class WebSocketTestSupport {++ private WebSocketTestSupport() {}++ // ──────────────────────────── Lambda ZIP creation ────────────────────────────++ /**+ * Creates a Base64-encoded ZIP file containing a single index.js with the given handler code.+ * Used to create Lambda function deployment packages in tests.+ */+ public static String createLambdaZip(String handlerCode) throws Exception {+ ByteArrayOutputStream baos = new ByteArrayOutputStream();+ try (ZipOutputStream zos = new ZipOutputStream(baos)) {+ zos.putNextEntry(new ZipEntry("index.js"));+ zos.write(handlerCode.getBytes());+ zos.closeEntry();+ }+ return Base64.getEncoder().encodeToString(baos.toByteArray());+ }++ // ──────────────────────────── WebSocket URL construction ────────────────────────────++ /**+ * Builds a WebSocket URL for connecting to a Floci WebSocket API.+ *+ * @param baseUri the base HTTP URI of the test server (e.g. http://localhost:8081/)+ * @param apiId the API Gateway API ID+ * @param stageName the stage name+ * @return the WebSocket URL (e.g. ws://localhost:8081/ws/{apiId}/{stageName})+ */+ public static String buildWsUrl(URI baseUri, String apiId, String stageName) {+ String wsUrl = baseUri.toString().replaceFirst("^http", "ws") + "ws/" + apiId + "/" + stageName;+ return wsUrl.replace("//ws/", "/ws/");+ }++ // ──────────────────────────── WebSocket connection helpers ────────────────────────────++ /**+ * Connect a WebSocket with a MessageCapture listener.+ */+ public static WebSocket connectWebSocket(URI baseUri, String apiId, String stageName,+ MessageCapture capture) throws Exception {+ String wsUrl = buildWsUrl(baseUri, apiId, stageName);+ HttpClient client = HttpClient.newHttpClient();+ return client.newWebSocketBuilder()+ .buildAsync(URI.create(wsUrl), capture)+ .get(60, TimeUnit.SECONDS);+ }++ /**+ * Connect a WebSocket with a MultiMessageCapture listener.+ */+ public static WebSocket connectWebSocket(URI baseUri, String apiId, String stageName,+ MultiMessageCapture capture) throws Exception {+ String wsUrl = buildWsUrl(baseUri, apiId, stageName);+ HttpClient client = HttpClient.newHttpClient();+ return client.newWebSocketBuilder()+ .buildAsync(URI.create(wsUrl), capture)+ .get(60, TimeUnit.SECONDS);+ }++ /**+ * Connect a WebSocket with a custom header (e.g. for authorizer identity source testing).+ */+ public static WebSocket connectWebSocketWithHeader(URI baseUri, String apiId, String stageName,+ String headerName, String headerValue,+ WebSocket.Listener listener) throws Exception {+ String wsUrl = buildWsUrl(baseUri, apiId, stageName);+ HttpClient client = HttpClient.newHttpClient();+ return client.newWebSocketBuilder()+ .header(headerName, headerValue)+ .buildAsync(URI.create(wsUrl), listener)+ .get(60, TimeUnit.SECONDS);+ }++ /**+ * Connect a WebSocket with a query string appended to the URL.+ */+ public static WebSocket connectWebSocketWithQuery(URI baseUri, String apiId, String stageName,+ String queryString, WebSocket.Listener listener) throws Exception {+ String wsUrl = buildWsUrl(baseUri, apiId, stageName) + "?" + queryString;+ HttpClient client = HttpClient.newHttpClient();+ return client.newWebSocketBuilder()+ .buildAsync(URI.create(wsUrl), listener)+ .get(60, TimeUnit.SECONDS);+ }++ // ──────────────────────────── Message Capture Listeners ────────────────────────────++ /**+ * WebSocket listener that captures the first text message received.+ * Use when you only need one response from the server.+ */+ public static class MessageCapture implements WebSocket.Listener {+ private final CompletableFuture<String> future = new CompletableFuture<>();+ private final StringBuilder buffer = new StringBuilder();++ @Override+ public void onOpen(WebSocket webSocket) {+ webSocket.request(10);+ }++ @Override+ public CompletionStage<?> onText(WebSocket webSocket, CharSequence data, boolean last) {+ buffer.append(data);+ if (last) {+ future.complete(buffer.toString());+ buffer.setLength(0);+ }+ webSocket.request(1);+ return null;+ }++ @Override+ public void onError(WebSocket webSocket, Throwable error) {+ future.completeExceptionally(error);+ }++ public String getResponse(long timeout, TimeUnit unit) throws Exception {+ return future.get(timeout, unit);+ }+ }++ /**+ * WebSocket listener that captures multiple text messages in a queue.+ * Use when you need to receive multiple responses or push messages.+ * Also supports close detection via setCloseFuture().+ */+ public static class MultiMessageCapture implements WebSocket.Listener {+ private final LinkedBlockingQueue<String> messages = new LinkedBlockingQueue<>();+ private final StringBuilder buffer = new StringBuilder();+ private volatile CompletableFuture<Integer> 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);+ }+ }++ /**+ * Set a future that will be completed when the WebSocket is closed.+ * Useful for testing server-initiated disconnections.+ */+ public void setCloseFuture(CompletableFuture<Integer> future) {+ this.closeFuture = future;+ }++ /**+ * Offer a message externally (e.g. from a custom close listener adapter).+ */+ public void complete(String message) {+ messages.offer(message);+ }++ public String getNextMessage(long timeout, TimeUnit unit) throws Exception {+ return messages.poll(timeout, unit);+ }+ }+}diff --git a/src/test/java/io/github/hectorvent/floci/services/apigatewayv2/websocket/WebSocketIntegrationInvokerSubstitutionTest.java b/src/test/java/io/github/hectorvent/floci/services/apigatewayv2/websocket/WebSocketIntegrationInvokerSubstitutionTest.javanew file mode 100644index 0000000000..40f986e26f--- /dev/null+++ b/src/test/java/io/github/hectorvent/floci/services/apigatewayv2/websocket/WebSocketIntegrationInvokerSubstitutionTest.java@@ -0,0 +1,116 @@+package io.github.hectorvent.floci.services.apigatewayv2.websocket;++import com.fasterxml.jackson.databind.ObjectMapper;+import io.github.hectorvent.floci.services.apigateway.AwsServiceRouter;+import io.github.hectorvent.floci.services.apigateway.VtlTemplateEngine;+import io.github.hectorvent.floci.services.lambda.LambdaService;+import org.junit.jupiter.api.BeforeEach;+import org.junit.jupiter.api.Test;++import java.util.Collections;+import java.util.Map;++import static org.junit.jupiter.api.Assertions.assertEquals;+import static org.junit.jupiter.api.Assertions.assertNull;+import static org.mockito.Mockito.mock;++/**+ * Unit tests for stage variable substitution in WebSocketIntegrationInvoker.+ */+class WebSocketIntegrationInvokerSubstitutionTest {++ private WebSocketIntegrationInvoker invoker;++ @BeforeEach+ void setUp() {+ invoker = new WebSocketIntegrationInvoker(+ mock(LambdaService.class),+ mock(AwsServiceRouter.class),+ new ObjectMapper(),+ mock(VtlTemplateEngine.class));+ }++ @Test+ void substituteStageVariables_singleVariable() {+ // substitute stage variable reference with corresponding value+ String uri = "arn:aws:lambda:us-east-1:123456789:function:${stageVariables.functionName}/invocations";+ Map<String, String> vars = Map.of("functionName", "myHandler");++ String result = invoker.substituteStageVariables(uri, vars);++ assertEquals("arn:aws:lambda:us-east-1:123456789:function:myHandler/invocations", result);+ }++ @Test+ void substituteStageVariables_undefinedVariableReplacedWithEmpty() {+ // undefined variable references replaced with empty string+ String uri = "arn:aws:lambda:us-east-1:123456789:function:${stageVariables.missingVar}/invocations";+ Map<String, String> vars = Map.of("otherVar", "value");++ String result = invoker.substituteStageVariables(uri, vars);++ assertEquals("arn:aws:lambda:us-east-1:123456789:function:/invocations", result);+ }++ @Test+ void substituteStageVariables_multipleReferences() {+ // multiple stage variable references in a single URI+ String uri = "arn:aws:lambda:${stageVariables.region}:${stageVariables.account}:function:${stageVariables.functionName}/invocations";+ Map<String, String> vars = Map.of(+ "region", "us-west-2",+ "account", "987654321",+ "functionName", "myFunc");++ String result = invoker.substituteStageVariables(uri, vars);++ assertEquals("arn:aws:lambda:us-west-2:987654321:function:myFunc/invocations", result);+ }++ @Test+ void substituteStageVariables_noReferences() {+ // URI without any stage variable references should be returned unchanged+ String uri = "arn:aws:lambda:us-east-1:123456789:function:myHandler/invocations";+ Map<String, String> vars = Map.of("functionName", "otherHandler");++ String result = invoker.substituteStageVariables(uri, vars);++ assertEquals("arn:aws:lambda:us-east-1:123456789:function:myHandler/invocations", result);+ }++ @Test+ void substituteStageVariables_nullUri() {+ String result = invoker.substituteStageVariables(null, Map.of("key", "value"));+ assertNull(result);+ }++ @Test+ void substituteStageVariables_nullStageVariables() {+ // Null stage variables map should treat all references as undefined (empty string)+ String uri = "arn:aws:lambda:us-east-1:123456789:function:${stageVariables.fn}/invocations";++ String result = invoker.substituteStageVariables(uri, null);++ assertEquals("arn:aws:lambda:us-east-1:123456789:function:/invocations", result);+ }++ @Test+ void substituteStageVariables_emptyStageVariables() {+ // Empty stage variables map should treat all references as undefined (empty string)+ String uri = "arn:aws:lambda:us-east-1:123456789:function:${stageVariables.fn}/invocations";++ String result = invoker.substituteStageVariables(uri, Collections.emptyMap());++ assertEquals("arn:aws:lambda:us-east-1:123456789:function:/invocations", result);+ }++ @Test+ void substituteStageVariables_mixedDefinedAndUndefined() {+ // Mix of defined and undefined variables+ String uri = "${stageVariables.prefix}-${stageVariables.missing}-${stageVariables.suffix}";+ Map<String, String> vars = Map.of("prefix", "hello", "suffix", "world");++ String result = invoker.substituteStageVariables(uri, vars);++ assertEquals("hello--world", result);+ }+}diff --git a/src/test/java/io/github/hectorvent/floci/services/lambda/LambdaArnUtilsTest.java b/src/test/java/io/github/hectorvent/floci/services/lambda/LambdaArnUtilsTest.javaindex 5d226d2aba..65ba7d1417 100644--- a/src/test/java/io/github/hectorvent/floci/services/lambda/LambdaArnUtilsTest.java+++ b/src/test/java/io/github/hectorvent/floci/services/lambda/LambdaArnUtilsTest.java@@ -95,4 +95,51 @@ class LambdaArnUtilsTest {private static String emptyToNull(String s) {return (s == null || s.isEmpty()) ? null : s;}++ // ──────────────────────────── extractFunctionNameFromUri tests ────────────────────────────++ @ParameterizedTest+ @CsvSource({+ // input URI, expected function name+ "arn:aws:lambda:us-east-1:000000000000:function:myFn/invocations, myFn",+ "arn:aws:lambda:us-east-1:000000000000:function:myFn, myFn",+ "arn:aws:lambda:eu-west-1:123456789012:function:my-handler/invocations, my-handler",+ "arn:aws:lambda:us-east-1:000000000000:function:my_fn-2/invocations, my_fn-2",+ "myFn, myFn",+ "my-handler, my-handler",+ })+ void extractFunctionNameFromUri_validInputs(String uri, String expectedName) {+ assertEquals(expectedName, LambdaArnUtils.extractFunctionNameFromUri(uri));+ }++ @Test+ void extractFunctionNameFromUri_nullReturnsNull() {+ assertNull(LambdaArnUtils.extractFunctionNameFromUri(null));+ }++ @Test+ void extractFunctionNameFromUri_noFunctionPrefixReturnsFull() {+ // When no "function:" prefix, the entire URI is treated as the function name+ assertEquals("just-a-name", LambdaArnUtils.extractFunctionNameFromUri("just-a-name"));+ }++ @Test+ void extractFunctionNameFromUri_stripsInvocationsSuffix() {+ String uri = "arn:aws:lambda:us-east-1:000000000000:function:handler/invocations";+ assertEquals("handler", LambdaArnUtils.extractFunctionNameFromUri(uri));+ }++ @Test+ void extractFunctionNameFromUri_handlesStageVariableSubstitutedUri() {+ // After stage variable substitution, the URI looks like a normal ARN+ String uri = "arn:aws:lambda:us-east-1:000000000000:function:ws-stage-var-fn/invocations";+ assertEquals("ws-stage-var-fn", LambdaArnUtils.extractFunctionNameFromUri(uri));+ }++ @Test+ void extractFunctionNameFromUri_handlesApiGatewayStyleUri() {+ // API Gateway v1 uses a longer URI format+ String uri = "arn:aws:apigateway:us-east-1:lambda:path/2015-03-31/functions/arn:aws:lambda:us-east-1:000000000000:function:myFn/invocations";+ assertEquals("myFn", LambdaArnUtils.extractFunctionNameFromUri(uri));+ }}