mirror of
https://github.com/floci-io/floci.git
synced 2026-12-01 01:12:48 -05:00
feat(apigatewayv2): Add WebSocket data-plane support (#712)
* feat: implement API Gateway v2 WebSocket data-plane support Implement full WebSocket data-plane for API Gateway v2, including: - Real WebSocket connection handling via Vert.x (ws://localhost:4566/ws/{apiId}/{stage}) - $connect/$disconnect/$default route lifecycle with Lambda integration - Custom route selection via routeSelectionExpression ($request.body.{field}) - @connections management API (POST/GET/DELETE) for server-to-client messaging - Lambda REQUEST authorizer support on $connect with identity source validation - Stage variable substitution in integration URIs - Multiple integration types: AWS_PROXY, AWS (VTL), HTTP_PROXY, HTTP (VTL), MOCK - Route response selection expression for bidirectional messaging - Binary frame support (isBase64Encoded: true) - 128 KB payload size limit enforcement (frames and @connections POST) - 10-minute idle timeout and 2-hour max connection duration - GoneException (410) for disconnected connections - $connect response headers propagation - Server-initiated close via @connections DELETE (skips $disconnect Lambda) Also includes: - Refactored LambdaArnUtils.extractFunctionNameFromUri as shared utility - Extended Authorizer/Integration/Stage models with new fields - Comprehensive Java integration tests (WebSocket lifecycle, routing, auth, etc.) - Node.js SDK compatibility tests using ws client and @aws-sdk/client-apigatewaymanagementapi - Updated documentation with full feature matrix
* test(apigatewayv2): support custom WebSocket endpoint via env var
- Update wsUrl helper to read FLOCI_ENDPOINT environment variable
- Convert http/https schemes to ws/wss for WebSocket compatibility
- Strip trailing slashes from endpoint URL for consistent formatting
- Enable testing against non-localhost endpoints for CI/CD flexibility
* fix: use AwsErrorResponse for @connections API error responses
Replace raw JSON string literals in handlePostToConnection,
handleGetConnectionInfo, and handleDeleteConnection with the
project-standard AwsErrorResponse record, which serialises to
the correct {"__type": ..., "message": ...} wire shape.
* fix: simplify extractFunctionNameFromUri using AwsArnUtils.parse
Adopt AwsArnUtils.parse() as the core of the implementation per
reviewer suggestion. One addition beyond the suggested snippet:
the API Gateway v1 integration URI format embeds a Lambda ARN
inside an apigateway ARN (resource starts with 'path/.../functions/'),
so we detect that pattern and recurse on the embedded ARN before
applying the standard function-name extraction. All 43
LambdaArnUtilsTest cases pass, including the API Gateway v1 style URI.
This commit is contained in:
1 parent
01dbc76fc8
commit
3ae5c7b467
35 files changed
+8782
-27
No files matched your search
+537
@@ -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);
|
||||
}
|
||||
}
|
||||
+548
@@ -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);
|
||||
}
|
||||
}
|
||||
+529
@@ -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);
|
||||
}
|
||||
}
|
||||
+631
@@ -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);
|
||||
}
|
||||
}
|
||||
}
|
||||
+489
@@ -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);
|
||||
}
|
||||
}
|
||||
+264
@@ -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);
|
||||
}
|
||||
}
|
||||
}
|
||||
+492
@@ -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);
|
||||
}
|
||||
}
|
||||
+214
@@ -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);
|
||||
}
|
||||
}
|
||||
+297
@@ -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);
|
||||
}
|
||||
}
|
||||
+203
@@ -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);
|
||||
}
|
||||
}
|
||||
}
|
||||
+116
@@ -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);
|
||||
}
|
||||
}
|
||||
@@ -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));
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user