mirror of
https://github.com/floci-io/floci.git
synced 2026-11-23 22:11:36 -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
+30
@@ -1578,6 +1578,23 @@ public class ApiGatewayController {
|
||||
node.put("integrationType", i.getIntegrationType());
|
||||
node.put("payloadFormatVersion", i.getPayloadFormatVersion());
|
||||
if (i.getIntegrationUri() != null) node.put("integrationUri", i.getIntegrationUri());
|
||||
if (i.getRequestTemplates() != null) {
|
||||
ObjectNode requestTemplates = node.putObject("requestTemplates");
|
||||
i.getRequestTemplates().forEach(requestTemplates::put);
|
||||
}
|
||||
if (i.getResponseTemplates() != null) {
|
||||
ObjectNode responseTemplates = node.putObject("responseTemplates");
|
||||
i.getResponseTemplates().forEach(responseTemplates::put);
|
||||
}
|
||||
if (i.getTemplateSelectionExpression() != null) {
|
||||
node.put("templateSelectionExpression", i.getTemplateSelectionExpression());
|
||||
}
|
||||
if (i.getIntegrationMethod() != null) {
|
||||
node.put("integrationMethod", i.getIntegrationMethod());
|
||||
}
|
||||
if (i.getTimeoutInMillis() != 0) {
|
||||
node.put("timeoutInMillis", i.getTimeoutInMillis());
|
||||
}
|
||||
return node;
|
||||
}
|
||||
|
||||
@@ -1588,6 +1605,10 @@ public class ApiGatewayController {
|
||||
node.put("autoDeploy", s.isAutoDeploy());
|
||||
node.put("createdDate", java.time.Instant.ofEpochMilli(s.getCreatedDate()).toString());
|
||||
node.put("lastUpdatedDate", java.time.Instant.ofEpochMilli(s.getLastUpdatedDate()).toString());
|
||||
if (s.getStageVariables() != null) {
|
||||
ObjectNode stageVariables = node.putObject("stageVariables");
|
||||
s.getStageVariables().forEach(stageVariables::put);
|
||||
}
|
||||
return node;
|
||||
}
|
||||
|
||||
@@ -1619,6 +1640,15 @@ public class ApiGatewayController {
|
||||
jwt.put("issuer", a.getJwtConfiguration().issuer());
|
||||
}
|
||||
}
|
||||
if (a.getAuthorizerUri() != null) {
|
||||
node.put("authorizerUri", a.getAuthorizerUri());
|
||||
}
|
||||
if (a.getAuthorizerPayloadFormatVersion() != null) {
|
||||
node.put("authorizerPayloadFormatVersion", a.getAuthorizerPayloadFormatVersion());
|
||||
}
|
||||
if (a.getAuthorizerResultTtlInSeconds() != null) {
|
||||
node.put("authorizerResultTtlInSeconds", a.getAuthorizerResultTtlInSeconds());
|
||||
}
|
||||
return node;
|
||||
}
|
||||
|
||||
|
||||
+83
-22
@@ -1,6 +1,7 @@
|
||||
package io.github.hectorvent.floci.services.apigateway;
|
||||
|
||||
import io.github.hectorvent.floci.core.common.AwsArnUtils;
|
||||
import io.github.hectorvent.floci.core.common.AwsErrorResponse;
|
||||
import io.github.hectorvent.floci.core.common.AwsException;
|
||||
import io.github.hectorvent.floci.core.common.RegionResolver;
|
||||
import io.github.hectorvent.floci.services.apigateway.model.ApiGatewayResource;
|
||||
@@ -10,6 +11,9 @@ import io.github.hectorvent.floci.services.apigateway.model.MethodConfig;
|
||||
import io.github.hectorvent.floci.services.apigatewayv2.ApiGatewayV2Service;
|
||||
import io.github.hectorvent.floci.services.apigatewayv2.model.Authorizer;
|
||||
import io.github.hectorvent.floci.services.apigatewayv2.model.Route;
|
||||
import io.github.hectorvent.floci.services.apigatewayv2.websocket.ConnectionInfo;
|
||||
import io.github.hectorvent.floci.services.apigatewayv2.websocket.WebSocketConnectionManager;
|
||||
import io.github.hectorvent.floci.services.lambda.LambdaArnUtils;
|
||||
import io.github.hectorvent.floci.services.lambda.LambdaService;
|
||||
import io.github.hectorvent.floci.services.lambda.model.InvocationType;
|
||||
import io.github.hectorvent.floci.services.lambda.model.InvokeResult;
|
||||
@@ -23,7 +27,9 @@ import jakarta.ws.rs.*;
|
||||
import jakarta.ws.rs.core.*;
|
||||
import org.jboss.logging.Logger;
|
||||
|
||||
import java.net.URLDecoder;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.time.Instant;
|
||||
import java.util.Base64;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
@@ -55,12 +61,14 @@ public class ApiGatewayExecuteController {
|
||||
private final ObjectMapper objectMapper;
|
||||
private final VtlTemplateEngine vtlEngine;
|
||||
private final AwsServiceRouter serviceRouter;
|
||||
private final WebSocketConnectionManager webSocketConnectionManager;
|
||||
|
||||
@Inject
|
||||
public ApiGatewayExecuteController(ApiGatewayService apiGatewayService, ApiGatewayV2Service apiGatewayV2Service,
|
||||
LambdaService lambdaService, RegionResolver regionResolver,
|
||||
ObjectMapper objectMapper, VtlTemplateEngine vtlEngine,
|
||||
AwsServiceRouter serviceRouter) {
|
||||
AwsServiceRouter serviceRouter,
|
||||
WebSocketConnectionManager webSocketConnectionManager) {
|
||||
this.apiGatewayService = apiGatewayService;
|
||||
this.apiGatewayV2Service = apiGatewayV2Service;
|
||||
this.lambdaService = lambdaService;
|
||||
@@ -68,16 +76,80 @@ public class ApiGatewayExecuteController {
|
||||
this.objectMapper = objectMapper;
|
||||
this.vtlEngine = vtlEngine;
|
||||
this.serviceRouter = serviceRouter;
|
||||
this.webSocketConnectionManager = webSocketConnectionManager;
|
||||
}
|
||||
|
||||
private record AuthorizerResult(Response errorResponse, String principalId, Map<String, Object> context) {}
|
||||
|
||||
// ──────────────────────────── @connections API ────────────────────────────
|
||||
|
||||
private static final String CONNECTIONS_PREFIX = "@connections/";
|
||||
|
||||
private String decodeConnectionId(String rawConnectionId) {
|
||||
return URLDecoder.decode(rawConnectionId, StandardCharsets.UTF_8);
|
||||
}
|
||||
|
||||
/** Maximum payload size for @connections POST (128 KB, matching AWS limit). */
|
||||
private static final int MAX_CONNECTIONS_PAYLOAD_BYTES = 128 * 1024;
|
||||
|
||||
private Response handlePostToConnection(String connectionId, byte[] body) {
|
||||
if (body != null && body.length > MAX_CONNECTIONS_PAYLOAD_BYTES) {
|
||||
return Response.status(413)
|
||||
.entity(new AwsErrorResponse("PayloadTooLargeException", "Payload too large"))
|
||||
.type(MediaType.APPLICATION_JSON)
|
||||
.build();
|
||||
}
|
||||
try {
|
||||
webSocketConnectionManager.sendMessage(connectionId, new String(body, StandardCharsets.UTF_8));
|
||||
return Response.ok().build();
|
||||
} catch (IllegalStateException e) {
|
||||
return Response.status(410)
|
||||
.entity(new AwsErrorResponse("GoneException", "GoneException"))
|
||||
.type(MediaType.APPLICATION_JSON)
|
||||
.build();
|
||||
}
|
||||
}
|
||||
|
||||
private Response handleGetConnectionInfo(String connectionId) {
|
||||
ConnectionInfo info = webSocketConnectionManager.getConnectionInfo(connectionId);
|
||||
if (info == null) {
|
||||
return Response.status(410)
|
||||
.entity(new AwsErrorResponse("GoneException", "GoneException"))
|
||||
.type(MediaType.APPLICATION_JSON)
|
||||
.build();
|
||||
}
|
||||
String connectedAt = Instant.ofEpochMilli(info.getConnectedAt()).toString();
|
||||
String lastActiveAt = Instant.ofEpochMilli(info.getLastActiveAt()).toString();
|
||||
String sourceIp = info.getSourceIp() != null ? info.getSourceIp() : "127.0.0.1";
|
||||
String userAgent = info.getUserAgent() != null ? info.getUserAgent() : "";
|
||||
String responseBody = String.format(
|
||||
"{\"connectedAt\":\"%s\",\"lastActiveAt\":\"%s\",\"identity\":{\"sourceIp\":\"%s\",\"userAgent\":\"%s\"}}",
|
||||
connectedAt, lastActiveAt, sourceIp, userAgent);
|
||||
return Response.ok(responseBody).type(MediaType.APPLICATION_JSON).build();
|
||||
}
|
||||
|
||||
private Response handleDeleteConnection(String connectionId) {
|
||||
try {
|
||||
webSocketConnectionManager.closeConnection(connectionId);
|
||||
return Response.noContent().build();
|
||||
} catch (IllegalStateException e) {
|
||||
return Response.status(410)
|
||||
.entity(new AwsErrorResponse("GoneException", "GoneException"))
|
||||
.type(MediaType.APPLICATION_JSON)
|
||||
.build();
|
||||
}
|
||||
}
|
||||
|
||||
@GET
|
||||
@Path("/{proxy: .*}")
|
||||
public Response handleGet(@Context HttpHeaders headers, @Context UriInfo uriInfo,
|
||||
@PathParam("apiId") String apiId,
|
||||
@PathParam("stageName") String stageName,
|
||||
@PathParam("proxy") String proxy) {
|
||||
if (proxy != null && proxy.startsWith(CONNECTIONS_PREFIX)) {
|
||||
String connectionId = decodeConnectionId(proxy.substring(CONNECTIONS_PREFIX.length()));
|
||||
return handleGetConnectionInfo(connectionId);
|
||||
}
|
||||
return dispatch("GET", apiId, stageName, proxy, headers, uriInfo, null);
|
||||
}
|
||||
|
||||
@@ -88,6 +160,10 @@ public class ApiGatewayExecuteController {
|
||||
@PathParam("stageName") String stageName,
|
||||
@PathParam("proxy") String proxy,
|
||||
byte[] body) {
|
||||
if (proxy != null && proxy.startsWith(CONNECTIONS_PREFIX)) {
|
||||
String connectionId = decodeConnectionId(proxy.substring(CONNECTIONS_PREFIX.length()));
|
||||
return handlePostToConnection(connectionId, body);
|
||||
}
|
||||
return dispatch("POST", apiId, stageName, proxy, headers, uriInfo, body);
|
||||
}
|
||||
|
||||
@@ -107,6 +183,10 @@ public class ApiGatewayExecuteController {
|
||||
@PathParam("apiId") String apiId,
|
||||
@PathParam("stageName") String stageName,
|
||||
@PathParam("proxy") String proxy) {
|
||||
if (proxy != null && proxy.startsWith(CONNECTIONS_PREFIX)) {
|
||||
String connectionId = decodeConnectionId(proxy.substring(CONNECTIONS_PREFIX.length()));
|
||||
return handleDeleteConnection(connectionId);
|
||||
}
|
||||
return dispatch("DELETE", apiId, stageName, proxy, headers, uriInfo, null);
|
||||
}
|
||||
|
||||
@@ -391,29 +471,10 @@ public class ApiGatewayExecuteController {
|
||||
/**
|
||||
* Extracts function name from integration URI like
|
||||
* {@code arn:aws:apigateway:...:lambda:path/2015-03-31/functions/{fnArn}/invocations}.
|
||||
* Delegates to {@link LambdaArnUtils#extractFunctionNameFromUri(String)}.
|
||||
*/
|
||||
private String functionNameFromUri(String uri) {
|
||||
if (uri == null) {
|
||||
return null;
|
||||
}
|
||||
// URI contains "function:{name}" or "function:{arn}"
|
||||
int idx = uri.indexOf("function:");
|
||||
if (idx < 0) {
|
||||
return null;
|
||||
}
|
||||
String after = uri.substring(idx + "function:".length());
|
||||
// after may be "myFn/invocations" or "arn:aws:lambda:...:function:myFn/invocations"
|
||||
// If it starts with "arn:" recurse on the remaining ARN
|
||||
if (after.startsWith("arn:")) {
|
||||
int fnIdx = after.lastIndexOf(":function:");
|
||||
if (fnIdx < 0) {
|
||||
return null;
|
||||
}
|
||||
after = after.substring(fnIdx + ":function:".length());
|
||||
}
|
||||
// Strip trailing "/invocations" or any path suffix
|
||||
int slash = after.indexOf('/');
|
||||
return slash >= 0 ? after.substring(0, slash) : after;
|
||||
return LambdaArnUtils.extractFunctionNameFromUri(uri);
|
||||
}
|
||||
|
||||
private String buildProxyEvent(String httpMethod, String path, String proxy,
|
||||
|
||||
+30
@@ -530,6 +530,15 @@ public class ApiGatewayV2JsonHandler {
|
||||
auth.getJwtConfiguration().audience().forEach(aud::add);
|
||||
}
|
||||
}
|
||||
if (auth.getAuthorizerUri() != null) {
|
||||
node.put("AuthorizerUri", auth.getAuthorizerUri());
|
||||
}
|
||||
if (auth.getAuthorizerPayloadFormatVersion() != null) {
|
||||
node.put("AuthorizerPayloadFormatVersion", auth.getAuthorizerPayloadFormatVersion());
|
||||
}
|
||||
if (auth.getAuthorizerResultTtlInSeconds() != null) {
|
||||
node.put("AuthorizerResultTtlInSeconds", auth.getAuthorizerResultTtlInSeconds());
|
||||
}
|
||||
return node;
|
||||
}
|
||||
|
||||
@@ -552,6 +561,23 @@ public class ApiGatewayV2JsonHandler {
|
||||
node.put("IntegrationType", i.getIntegrationType());
|
||||
node.put("PayloadFormatVersion", i.getPayloadFormatVersion());
|
||||
if (i.getIntegrationUri() != null) node.put("IntegrationUri", i.getIntegrationUri());
|
||||
if (i.getRequestTemplates() != null) {
|
||||
ObjectNode requestTemplates = node.putObject("RequestTemplates");
|
||||
i.getRequestTemplates().forEach(requestTemplates::put);
|
||||
}
|
||||
if (i.getResponseTemplates() != null) {
|
||||
ObjectNode responseTemplates = node.putObject("ResponseTemplates");
|
||||
i.getResponseTemplates().forEach(responseTemplates::put);
|
||||
}
|
||||
if (i.getTemplateSelectionExpression() != null) {
|
||||
node.put("TemplateSelectionExpression", i.getTemplateSelectionExpression());
|
||||
}
|
||||
if (i.getIntegrationMethod() != null) {
|
||||
node.put("IntegrationMethod", i.getIntegrationMethod());
|
||||
}
|
||||
if (i.getTimeoutInMillis() != 0) {
|
||||
node.put("TimeoutInMillis", i.getTimeoutInMillis());
|
||||
}
|
||||
return node;
|
||||
}
|
||||
|
||||
@@ -562,6 +588,10 @@ public class ApiGatewayV2JsonHandler {
|
||||
node.put("CreatedDate", s.getCreatedDate() / 1000.0);
|
||||
node.put("LastUpdatedDate", s.getLastUpdatedDate() / 1000.0);
|
||||
if (s.getDeploymentId() != null) node.put("DeploymentId", s.getDeploymentId());
|
||||
if (s.getStageVariables() != null) {
|
||||
ObjectNode stageVariables = node.putObject("StageVariables");
|
||||
s.getStageVariables().forEach(stageVariables::put);
|
||||
}
|
||||
return node;
|
||||
}
|
||||
|
||||
|
||||
+72
-1
@@ -170,8 +170,14 @@ public class ApiGatewayV2Service {
|
||||
auth.setJwtConfiguration(new Authorizer.JwtConfiguration(audience, issuer));
|
||||
}
|
||||
|
||||
auth.setAuthorizerUri((String) request.get("authorizerUri"));
|
||||
auth.setAuthorizerPayloadFormatVersion((String) request.get("authorizerPayloadFormatVersion"));
|
||||
if (request.get("authorizerResultTtlInSeconds") != null) {
|
||||
auth.setAuthorizerResultTtlInSeconds(((Number) request.get("authorizerResultTtlInSeconds")).intValue());
|
||||
}
|
||||
|
||||
authorizerStore.put(authorizerKey(region, apiId, auth.getAuthorizerId()), auth);
|
||||
LOG.infov("Created JWT authorizer: {0} ({1}) for API {2}", auth.getName(), auth.getAuthorizerId(), apiId);
|
||||
LOG.infov("Created authorizer: {0} ({1}) for API {2}", auth.getName(), auth.getAuthorizerId(), apiId);
|
||||
return auth;
|
||||
}
|
||||
|
||||
@@ -218,6 +224,15 @@ public class ApiGatewayV2Service {
|
||||
String issuer = (String) jwtConfig.get("issuer");
|
||||
auth.setJwtConfiguration(new Authorizer.JwtConfiguration(audience, issuer));
|
||||
}
|
||||
if (request.containsKey("authorizerUri") && request.get("authorizerUri") != null) {
|
||||
auth.setAuthorizerUri((String) request.get("authorizerUri"));
|
||||
}
|
||||
if (request.containsKey("authorizerPayloadFormatVersion") && request.get("authorizerPayloadFormatVersion") != null) {
|
||||
auth.setAuthorizerPayloadFormatVersion((String) request.get("authorizerPayloadFormatVersion"));
|
||||
}
|
||||
if (request.containsKey("authorizerResultTtlInSeconds") && request.get("authorizerResultTtlInSeconds") != null) {
|
||||
auth.setAuthorizerResultTtlInSeconds(((Number) request.get("authorizerResultTtlInSeconds")).intValue());
|
||||
}
|
||||
|
||||
authorizerStore.put(authorizerKey(region, apiId, authorizerId), auth);
|
||||
return auth;
|
||||
@@ -304,6 +319,20 @@ public class ApiGatewayV2Service {
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Finds a route by its exact routeKey (e.g. "$connect", "$disconnect", "$default").
|
||||
* Returns null if no route with the given key exists on the API.
|
||||
*/
|
||||
public Route findRouteByKey(String region, String apiId, String routeKey) {
|
||||
List<Route> routes = getRoutes(region, apiId);
|
||||
for (Route r : routes) {
|
||||
if (routeKey.equals(r.getRouteKey())) {
|
||||
return r;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
private boolean routeKeyMatchesPath(String routeKey, String httpMethod, String path) {
|
||||
int space = routeKey.indexOf(' ');
|
||||
if (space < 0) return false;
|
||||
@@ -335,6 +364,20 @@ public class ApiGatewayV2Service {
|
||||
integration.setIntegrationType((String) request.get("integrationType"));
|
||||
integration.setIntegrationUri((String) request.get("integrationUri"));
|
||||
integration.setPayloadFormatVersion((String) request.getOrDefault("payloadFormatVersion", "2.0"));
|
||||
integration.setIntegrationMethod((String) request.get("integrationMethod"));
|
||||
integration.setTemplateSelectionExpression((String) request.get("templateSelectionExpression"));
|
||||
|
||||
if (request.get("timeoutInMillis") != null) {
|
||||
integration.setTimeoutInMillis(((Number) request.get("timeoutInMillis")).intValue());
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
Map<String, String> requestTemplates = (Map<String, String>) request.get("requestTemplates");
|
||||
integration.setRequestTemplates(requestTemplates);
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
Map<String, String> responseTemplates = (Map<String, String>) request.get("responseTemplates");
|
||||
integration.setResponseTemplates(responseTemplates);
|
||||
|
||||
integrationStore.put(integrationKey(region, apiId, integration.getIntegrationId()), integration);
|
||||
return integration;
|
||||
@@ -368,6 +411,25 @@ public class ApiGatewayV2Service {
|
||||
if (request.containsKey("payloadFormatVersion") && request.get("payloadFormatVersion") != null) {
|
||||
integration.setPayloadFormatVersion((String) request.get("payloadFormatVersion"));
|
||||
}
|
||||
if (request.containsKey("integrationMethod") && request.get("integrationMethod") != null) {
|
||||
integration.setIntegrationMethod((String) request.get("integrationMethod"));
|
||||
}
|
||||
if (request.containsKey("templateSelectionExpression") && request.get("templateSelectionExpression") != null) {
|
||||
integration.setTemplateSelectionExpression((String) request.get("templateSelectionExpression"));
|
||||
}
|
||||
if (request.containsKey("timeoutInMillis") && request.get("timeoutInMillis") != null) {
|
||||
integration.setTimeoutInMillis(((Number) request.get("timeoutInMillis")).intValue());
|
||||
}
|
||||
if (request.containsKey("requestTemplates") && request.get("requestTemplates") != null) {
|
||||
@SuppressWarnings("unchecked")
|
||||
Map<String, String> requestTemplates = (Map<String, String>) request.get("requestTemplates");
|
||||
integration.setRequestTemplates(requestTemplates);
|
||||
}
|
||||
if (request.containsKey("responseTemplates") && request.get("responseTemplates") != null) {
|
||||
@SuppressWarnings("unchecked")
|
||||
Map<String, String> responseTemplates = (Map<String, String>) request.get("responseTemplates");
|
||||
integration.setResponseTemplates(responseTemplates);
|
||||
}
|
||||
|
||||
integrationStore.put(integrationKey(region, apiId, integrationId), integration);
|
||||
return integration;
|
||||
@@ -384,6 +446,10 @@ public class ApiGatewayV2Service {
|
||||
stage.setCreatedDate(System.currentTimeMillis());
|
||||
stage.setLastUpdatedDate(System.currentTimeMillis());
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
Map<String, String> stageVariables = (Map<String, String>) request.get("stageVariables");
|
||||
stage.setStageVariables(stageVariables);
|
||||
|
||||
stageStore.put(stageKey(region, apiId, stage.getStageName()), stage);
|
||||
LOG.infov("Created stage: {0} for API {1}", stage.getStageName(), apiId);
|
||||
return stage;
|
||||
@@ -414,6 +480,11 @@ public class ApiGatewayV2Service {
|
||||
if (request.containsKey("autoDeploy") && request.get("autoDeploy") != null) {
|
||||
stage.setAutoDeploy(Boolean.parseBoolean(String.valueOf(request.get("autoDeploy"))));
|
||||
}
|
||||
if (request.containsKey("stageVariables") && request.get("stageVariables") != null) {
|
||||
@SuppressWarnings("unchecked")
|
||||
Map<String, String> stageVariables = (Map<String, String>) request.get("stageVariables");
|
||||
stage.setStageVariables(stageVariables);
|
||||
}
|
||||
|
||||
stage.setLastUpdatedDate(System.currentTimeMillis());
|
||||
stageStore.put(stageKey(region, apiId, stageName), stage);
|
||||
|
||||
@@ -13,6 +13,9 @@ public class Authorizer {
|
||||
private String name;
|
||||
private JwtConfiguration jwtConfiguration;
|
||||
private List<String> identitySource;
|
||||
private String authorizerUri;
|
||||
private String authorizerPayloadFormatVersion;
|
||||
private Integer authorizerResultTtlInSeconds;
|
||||
|
||||
public Authorizer() {}
|
||||
|
||||
@@ -31,6 +34,15 @@ public class Authorizer {
|
||||
public List<String> getIdentitySource() { return identitySource; }
|
||||
public void setIdentitySource(List<String> identitySource) { this.identitySource = identitySource; }
|
||||
|
||||
public String getAuthorizerUri() { return authorizerUri; }
|
||||
public void setAuthorizerUri(String authorizerUri) { this.authorizerUri = authorizerUri; }
|
||||
|
||||
public String getAuthorizerPayloadFormatVersion() { return authorizerPayloadFormatVersion; }
|
||||
public void setAuthorizerPayloadFormatVersion(String authorizerPayloadFormatVersion) { this.authorizerPayloadFormatVersion = authorizerPayloadFormatVersion; }
|
||||
|
||||
public Integer getAuthorizerResultTtlInSeconds() { return authorizerResultTtlInSeconds; }
|
||||
public void setAuthorizerResultTtlInSeconds(Integer authorizerResultTtlInSeconds) { this.authorizerResultTtlInSeconds = authorizerResultTtlInSeconds; }
|
||||
|
||||
@RegisterForReflection
|
||||
public record JwtConfiguration(List<String> audience, String issuer) {}
|
||||
}
|
||||
@@ -3,6 +3,8 @@ package io.github.hectorvent.floci.services.apigatewayv2.model;
|
||||
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
|
||||
import io.quarkus.runtime.annotations.RegisterForReflection;
|
||||
|
||||
import java.util.Map;
|
||||
|
||||
@RegisterForReflection
|
||||
@JsonIgnoreProperties(ignoreUnknown = true)
|
||||
public class Integration {
|
||||
@@ -12,6 +14,9 @@ public class Integration {
|
||||
private String payloadFormatVersion; // 1.0, 2.0
|
||||
private String integrationMethod;
|
||||
private int timeoutInMillis;
|
||||
private Map<String, String> requestTemplates;
|
||||
private Map<String, String> responseTemplates;
|
||||
private String templateSelectionExpression;
|
||||
|
||||
public Integration() {}
|
||||
|
||||
@@ -32,4 +37,13 @@ public class Integration {
|
||||
|
||||
public int getTimeoutInMillis() { return timeoutInMillis; }
|
||||
public void setTimeoutInMillis(int timeoutInMillis) { this.timeoutInMillis = timeoutInMillis; }
|
||||
|
||||
public Map<String, String> getRequestTemplates() { return requestTemplates; }
|
||||
public void setRequestTemplates(Map<String, String> requestTemplates) { this.requestTemplates = requestTemplates; }
|
||||
|
||||
public Map<String, String> getResponseTemplates() { return responseTemplates; }
|
||||
public void setResponseTemplates(Map<String, String> responseTemplates) { this.responseTemplates = responseTemplates; }
|
||||
|
||||
public String getTemplateSelectionExpression() { return templateSelectionExpression; }
|
||||
public void setTemplateSelectionExpression(String templateSelectionExpression) { this.templateSelectionExpression = templateSelectionExpression; }
|
||||
}
|
||||
@@ -3,6 +3,8 @@ package io.github.hectorvent.floci.services.apigatewayv2.model;
|
||||
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
|
||||
import io.quarkus.runtime.annotations.RegisterForReflection;
|
||||
|
||||
import java.util.Map;
|
||||
|
||||
@RegisterForReflection
|
||||
@JsonIgnoreProperties(ignoreUnknown = true)
|
||||
public class Stage {
|
||||
@@ -11,6 +13,7 @@ public class Stage {
|
||||
private boolean autoDeploy;
|
||||
private long createdDate;
|
||||
private long lastUpdatedDate;
|
||||
private Map<String, String> stageVariables;
|
||||
|
||||
public Stage() {}
|
||||
|
||||
@@ -28,4 +31,7 @@ public class Stage {
|
||||
|
||||
public long getLastUpdatedDate() { return lastUpdatedDate; }
|
||||
public void setLastUpdatedDate(long lastUpdatedDate) { this.lastUpdatedDate = lastUpdatedDate; }
|
||||
|
||||
public Map<String, String> getStageVariables() { return stageVariables; }
|
||||
public void setStageVariables(Map<String, String> stageVariables) { this.stageVariables = stageVariables; }
|
||||
}
|
||||
+55
@@ -0,0 +1,55 @@
|
||||
package io.github.hectorvent.floci.services.apigatewayv2.websocket;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
|
||||
import io.quarkus.runtime.annotations.RegisterForReflection;
|
||||
|
||||
@RegisterForReflection
|
||||
@JsonIgnoreProperties(ignoreUnknown = true)
|
||||
public class ConnectionInfo {
|
||||
private String connectionId;
|
||||
private String apiId;
|
||||
private String stageName;
|
||||
private String region;
|
||||
private long connectedAt;
|
||||
private long lastActiveAt;
|
||||
private String sourceIp;
|
||||
private String userAgent;
|
||||
|
||||
public ConnectionInfo() {}
|
||||
|
||||
public ConnectionInfo(String connectionId, String apiId, String stageName, String region,
|
||||
long connectedAt, long lastActiveAt, String sourceIp, String userAgent) {
|
||||
this.connectionId = connectionId;
|
||||
this.apiId = apiId;
|
||||
this.stageName = stageName;
|
||||
this.region = region;
|
||||
this.connectedAt = connectedAt;
|
||||
this.lastActiveAt = lastActiveAt;
|
||||
this.sourceIp = sourceIp;
|
||||
this.userAgent = userAgent;
|
||||
}
|
||||
|
||||
public String getConnectionId() { return connectionId; }
|
||||
public void setConnectionId(String connectionId) { this.connectionId = connectionId; }
|
||||
|
||||
public String getApiId() { return apiId; }
|
||||
public void setApiId(String apiId) { this.apiId = apiId; }
|
||||
|
||||
public String getStageName() { return stageName; }
|
||||
public void setStageName(String stageName) { this.stageName = stageName; }
|
||||
|
||||
public String getRegion() { return region; }
|
||||
public void setRegion(String region) { this.region = region; }
|
||||
|
||||
public long getConnectedAt() { return connectedAt; }
|
||||
public void setConnectedAt(long connectedAt) { this.connectedAt = connectedAt; }
|
||||
|
||||
public long getLastActiveAt() { return lastActiveAt; }
|
||||
public void setLastActiveAt(long lastActiveAt) { this.lastActiveAt = lastActiveAt; }
|
||||
|
||||
public String getSourceIp() { return sourceIp; }
|
||||
public void setSourceIp(String sourceIp) { this.sourceIp = sourceIp; }
|
||||
|
||||
public String getUserAgent() { return userAgent; }
|
||||
public void setUserAgent(String userAgent) { this.userAgent = userAgent; }
|
||||
}
|
||||
+79
@@ -0,0 +1,79 @@
|
||||
package io.github.hectorvent.floci.services.apigatewayv2.websocket;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import jakarta.enterprise.context.ApplicationScoped;
|
||||
import jakarta.inject.Inject;
|
||||
import org.jboss.logging.Logger;
|
||||
|
||||
/**
|
||||
* Evaluates the API's routeSelectionExpression against a message payload
|
||||
* to determine which route to invoke.
|
||||
*
|
||||
* Supports the $request.body.{fieldName} expression format, extracting
|
||||
* the named top-level JSON field from the message body.
|
||||
*/
|
||||
@ApplicationScoped
|
||||
public class RouteSelectionEvaluator {
|
||||
|
||||
private static final Logger LOG = Logger.getLogger(RouteSelectionEvaluator.class);
|
||||
private static final String EXPRESSION_PREFIX = "$request.body.";
|
||||
|
||||
@Inject
|
||||
ObjectMapper objectMapper;
|
||||
|
||||
/**
|
||||
* Extracts the route key from a message using the route selection expression.
|
||||
*
|
||||
* @param routeSelectionExpression the expression (e.g. "$request.body.action")
|
||||
* @param messageBody the raw message body (expected to be JSON)
|
||||
* @return the extracted route key, or null if extraction fails
|
||||
*/
|
||||
public String evaluate(String routeSelectionExpression, String messageBody) {
|
||||
if (routeSelectionExpression == null || messageBody == null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
String fieldName = parseFieldName(routeSelectionExpression);
|
||||
if (fieldName == null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
try {
|
||||
JsonNode root = objectMapper.readTree(messageBody);
|
||||
JsonNode fieldNode = root.get(fieldName);
|
||||
if (fieldNode == null || fieldNode.isMissingNode()) {
|
||||
return null;
|
||||
}
|
||||
|
||||
if (fieldNode.isTextual()) {
|
||||
return fieldNode.asText();
|
||||
}
|
||||
|
||||
// For non-string values (number, boolean, object, array), convert to string
|
||||
return fieldNode.asText();
|
||||
} catch (Exception e) {
|
||||
LOG.debugv("Failed to parse message body as JSON: {0}", e.getMessage());
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Parses a $request.body.{fieldName} expression and returns the field name.
|
||||
*
|
||||
* @param expression the route selection expression
|
||||
* @return the field name, or null if the expression format is not recognized
|
||||
*/
|
||||
String parseFieldName(String expression) {
|
||||
if (expression == null || !expression.startsWith(EXPRESSION_PREFIX)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
String fieldName = expression.substring(EXPRESSION_PREFIX.length());
|
||||
if (fieldName.isEmpty()) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return fieldName;
|
||||
}
|
||||
}
|
||||
+233
@@ -0,0 +1,233 @@
|
||||
package io.github.hectorvent.floci.services.apigatewayv2.websocket;
|
||||
|
||||
import com.fasterxml.jackson.core.type.TypeReference;
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import io.github.hectorvent.floci.services.apigatewayv2.ApiGatewayV2Service;
|
||||
import io.github.hectorvent.floci.services.apigatewayv2.model.Authorizer;
|
||||
import io.github.hectorvent.floci.services.lambda.LambdaArnUtils;
|
||||
import io.github.hectorvent.floci.services.lambda.LambdaService;
|
||||
import io.github.hectorvent.floci.services.lambda.model.InvocationType;
|
||||
import io.github.hectorvent.floci.services.lambda.model.InvokeResult;
|
||||
import jakarta.enterprise.context.ApplicationScoped;
|
||||
import jakarta.inject.Inject;
|
||||
import org.jboss.logging.Logger;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* Service responsible for invoking and evaluating Lambda REQUEST authorizers
|
||||
* for WebSocket $connect routes.
|
||||
*
|
||||
* Extracted from WebSocketHandler to keep the handler thin (controller responsibility)
|
||||
* and make authorizer logic independently testable.
|
||||
*/
|
||||
@ApplicationScoped
|
||||
public class WebSocketAuthorizerService {
|
||||
|
||||
private static final Logger LOG = Logger.getLogger(WebSocketAuthorizerService.class);
|
||||
private static final TypeReference<Map<String, Object>> MAP_TYPE = new TypeReference<>() {};
|
||||
|
||||
private final ApiGatewayV2Service apiGatewayV2Service;
|
||||
private final LambdaService lambdaService;
|
||||
private final WebSocketProxyEventBuilder proxyEventBuilder;
|
||||
private final ObjectMapper objectMapper;
|
||||
|
||||
@Inject
|
||||
public WebSocketAuthorizerService(ApiGatewayV2Service apiGatewayV2Service,
|
||||
LambdaService lambdaService,
|
||||
WebSocketProxyEventBuilder proxyEventBuilder,
|
||||
ObjectMapper objectMapper) {
|
||||
this.apiGatewayV2Service = apiGatewayV2Service;
|
||||
this.lambdaService = lambdaService;
|
||||
this.proxyEventBuilder = proxyEventBuilder;
|
||||
this.objectMapper = objectMapper;
|
||||
}
|
||||
|
||||
/**
|
||||
* Result of authorizer evaluation.
|
||||
*
|
||||
* @param allowed whether the connection is allowed
|
||||
* @param statusCode HTTP status code to return if denied (403 for Deny, 500 for errors, 401 for missing identity)
|
||||
* @param context authorizer context map (may be null)
|
||||
*/
|
||||
public record AuthorizerResult(boolean allowed, int statusCode, Map<String, Object> context) {
|
||||
|
||||
public static AuthorizerResult allow(Map<String, Object> context) {
|
||||
return new AuthorizerResult(true, 200, context);
|
||||
}
|
||||
|
||||
public static AuthorizerResult deny() {
|
||||
return new AuthorizerResult(false, 403, null);
|
||||
}
|
||||
|
||||
public static AuthorizerResult unauthorized() {
|
||||
return new AuthorizerResult(false, 401, null);
|
||||
}
|
||||
|
||||
public static AuthorizerResult error() {
|
||||
return new AuthorizerResult(false, 500, null);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Invoke the Lambda REQUEST authorizer for a $connect route.
|
||||
* Validates identity source values, invokes the authorizer Lambda,
|
||||
* and parses the policy document to determine Allow/Deny.
|
||||
*
|
||||
* @return AuthorizerResult indicating whether the connection is allowed
|
||||
*/
|
||||
public AuthorizerResult invokeAndEvaluate(String region, String apiId, String stageName,
|
||||
String authorizerId, String connectionId, long connectedAt,
|
||||
Map<String, List<String>> headers,
|
||||
Map<String, List<String>> queryParams,
|
||||
String sourceIp, String userAgent,
|
||||
Map<String, String> stageVariables) {
|
||||
// Fetch the authorizer model
|
||||
Authorizer authorizer = apiGatewayV2Service.getAuthorizer(region, apiId, authorizerId);
|
||||
|
||||
if (!"REQUEST".equals(authorizer.getAuthorizerType())) {
|
||||
// Only REQUEST type authorizers are supported for WebSocket APIs
|
||||
LOG.debugv("Authorizer {0} is not REQUEST type (is {1}), allowing by default",
|
||||
authorizerId, authorizer.getAuthorizerType());
|
||||
return AuthorizerResult.allow(null);
|
||||
}
|
||||
|
||||
// Validate identity source expressions
|
||||
List<String> identitySources = authorizer.getIdentitySource();
|
||||
if (identitySources != null && !identitySources.isEmpty()) {
|
||||
for (String expression : identitySources) {
|
||||
if (expression.startsWith("$request.header.")) {
|
||||
String headerName = expression.substring("$request.header.".length());
|
||||
if (!hasHeaderValue(headers, headerName)) {
|
||||
LOG.debugv("Missing required identity source header: {0}", headerName);
|
||||
return AuthorizerResult.unauthorized();
|
||||
}
|
||||
} else if (expression.startsWith("$request.querystring.")) {
|
||||
String paramName = expression.substring("$request.querystring.".length());
|
||||
if (!hasQueryParamValue(queryParams, paramName)) {
|
||||
LOG.debugv("Missing required identity source query param: {0}", paramName);
|
||||
return AuthorizerResult.unauthorized();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Build the authorizer event payload
|
||||
String authorizerEventJson = proxyEventBuilder.buildAuthorizerEvent(
|
||||
connectionId, apiId, stageName, region, connectedAt,
|
||||
headers, queryParams, sourceIp, userAgent, stageVariables);
|
||||
|
||||
// Extract the Lambda function name from the authorizer URI
|
||||
String functionName = extractFunctionNameFromUri(authorizer.getAuthorizerUri());
|
||||
if (functionName == null) {
|
||||
LOG.warnv("Cannot extract function name from authorizer URI: {0}",
|
||||
authorizer.getAuthorizerUri());
|
||||
return AuthorizerResult.error();
|
||||
}
|
||||
|
||||
// Invoke the authorizer Lambda
|
||||
InvokeResult invokeResult;
|
||||
try {
|
||||
invokeResult = lambdaService.invoke(region, functionName,
|
||||
authorizerEventJson.getBytes(), InvocationType.RequestResponse);
|
||||
} catch (Exception e) {
|
||||
LOG.warnv("Lambda authorizer invocation failed for API {0}: {1}", apiId, e.getMessage());
|
||||
return AuthorizerResult.error();
|
||||
}
|
||||
|
||||
// Parse the policy document
|
||||
return parseAuthorizerResponse(invokeResult, apiId);
|
||||
}
|
||||
|
||||
/**
|
||||
* Parse the authorizer Lambda response and extract the policy decision.
|
||||
*/
|
||||
private AuthorizerResult parseAuthorizerResponse(InvokeResult invokeResult, String apiId) {
|
||||
// Check for function error
|
||||
if (invokeResult.getFunctionError() != null) {
|
||||
LOG.warnv("Lambda authorizer returned function error for API {0}: {1}",
|
||||
apiId, invokeResult.getFunctionError());
|
||||
return AuthorizerResult.error();
|
||||
}
|
||||
|
||||
byte[] payload = invokeResult.getPayload();
|
||||
if (payload == null || payload.length == 0) {
|
||||
LOG.warnv("Lambda authorizer returned empty payload for API {0}", apiId);
|
||||
return AuthorizerResult.error();
|
||||
}
|
||||
|
||||
try {
|
||||
JsonNode policy = objectMapper.readTree(payload);
|
||||
JsonNode policyDocument = policy.path("policyDocument");
|
||||
if (policyDocument.isMissingNode() || policyDocument.isNull()) {
|
||||
LOG.warnv("Authorizer response missing policyDocument for API {0}", apiId);
|
||||
return AuthorizerResult.error();
|
||||
}
|
||||
|
||||
JsonNode statements = policyDocument.path("Statement");
|
||||
if (statements.isMissingNode() || statements.isNull()
|
||||
|| !statements.isArray() || statements.isEmpty()) {
|
||||
LOG.warnv("Authorizer response missing or empty Statement array for API {0}", apiId);
|
||||
return AuthorizerResult.error();
|
||||
}
|
||||
|
||||
String effect = statements.get(0).path("Effect").asText("Deny");
|
||||
if ("Deny".equalsIgnoreCase(effect)) {
|
||||
return AuthorizerResult.deny();
|
||||
}
|
||||
|
||||
if (!"Allow".equalsIgnoreCase(effect)) {
|
||||
LOG.warnv("Authorizer response has unrecognized Effect '{0}' for API {1}",
|
||||
effect, apiId);
|
||||
return AuthorizerResult.error();
|
||||
}
|
||||
|
||||
// Extract context map if present
|
||||
Map<String, Object> context = null;
|
||||
JsonNode contextNode = policy.path("context");
|
||||
if (!contextNode.isMissingNode() && !contextNode.isNull() && contextNode.isObject()) {
|
||||
context = objectMapper.convertValue(contextNode, MAP_TYPE);
|
||||
}
|
||||
|
||||
return AuthorizerResult.allow(context);
|
||||
} catch (Exception e) {
|
||||
LOG.warnv("Failed to parse authorizer policy for API {0}: {1}", apiId, e.getMessage());
|
||||
return AuthorizerResult.error();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if a header value is present (case-insensitive header name lookup).
|
||||
*/
|
||||
private boolean hasHeaderValue(Map<String, List<String>> headers, String headerName) {
|
||||
if (headers == null) return false;
|
||||
for (Map.Entry<String, List<String>> entry : headers.entrySet()) {
|
||||
if (entry.getKey().equalsIgnoreCase(headerName)) {
|
||||
List<String> values = entry.getValue();
|
||||
return values != null && !values.isEmpty()
|
||||
&& values.get(0) != null && !values.get(0).isEmpty();
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if a query parameter value is present.
|
||||
*/
|
||||
private boolean hasQueryParamValue(Map<String, List<String>> queryParams, String paramName) {
|
||||
if (queryParams == null) return false;
|
||||
List<String> values = queryParams.get(paramName);
|
||||
return values != null && !values.isEmpty()
|
||||
&& values.get(0) != null && !values.get(0).isEmpty();
|
||||
}
|
||||
|
||||
/**
|
||||
* Extract the Lambda function name from an authorizer URI.
|
||||
* Delegates to {@link LambdaArnUtils#extractFunctionNameFromUri(String)}.
|
||||
*/
|
||||
private String extractFunctionNameFromUri(String uri) {
|
||||
return LambdaArnUtils.extractFunctionNameFromUri(uri);
|
||||
}
|
||||
}
|
||||
+118
@@ -0,0 +1,118 @@
|
||||
package io.github.hectorvent.floci.services.apigatewayv2.websocket;
|
||||
|
||||
import io.vertx.core.http.ServerWebSocket;
|
||||
import jakarta.enterprise.context.ApplicationScoped;
|
||||
import org.jboss.logging.Logger;
|
||||
|
||||
import java.util.Set;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
|
||||
/**
|
||||
* In-memory manager for active WebSocket connections.
|
||||
* Tracks connection metadata and live socket references.
|
||||
*/
|
||||
@ApplicationScoped
|
||||
public class WebSocketConnectionManager {
|
||||
|
||||
private static final Logger LOG = Logger.getLogger(WebSocketConnectionManager.class);
|
||||
|
||||
private final ConcurrentHashMap<String, ConnectionInfo> connections = new ConcurrentHashMap<>();
|
||||
private final ConcurrentHashMap<String, ServerWebSocket> sockets = new ConcurrentHashMap<>();
|
||||
|
||||
/**
|
||||
* Tracks connections that were closed server-side via the @connections DELETE API.
|
||||
* When a connection is in this set, the $disconnect Lambda should NOT be invoked
|
||||
* because AWS does not invoke $disconnect for server-initiated disconnections via
|
||||
* the management API.
|
||||
*/
|
||||
private final Set<String> serverInitiatedCloses = ConcurrentHashMap.newKeySet();
|
||||
|
||||
/**
|
||||
* Register a new WebSocket connection.
|
||||
*/
|
||||
public void register(String connectionId, ConnectionInfo info, ServerWebSocket ws) {
|
||||
connections.put(connectionId, info);
|
||||
sockets.put(connectionId, ws);
|
||||
LOG.debugv("Registered WebSocket connection {0}", connectionId);
|
||||
}
|
||||
|
||||
/**
|
||||
* Unregister a WebSocket connection, removing both metadata and socket reference.
|
||||
*/
|
||||
public void unregister(String connectionId) {
|
||||
connections.remove(connectionId);
|
||||
sockets.remove(connectionId);
|
||||
serverInitiatedCloses.remove(connectionId);
|
||||
LOG.debugv("Unregistered WebSocket connection {0}", connectionId);
|
||||
}
|
||||
|
||||
/**
|
||||
* Send a text message to the specified connection.
|
||||
*
|
||||
* @throws IllegalStateException if the connection is not active
|
||||
*/
|
||||
public void sendMessage(String connectionId, String message) {
|
||||
ServerWebSocket ws = sockets.get(connectionId);
|
||||
if (ws == null) {
|
||||
throw new IllegalStateException("Connection " + connectionId + " is not active");
|
||||
}
|
||||
try {
|
||||
ws.writeTextMessage(message);
|
||||
} catch (Exception e) {
|
||||
LOG.debugv("Failed to write message to connection {0}: {1}", connectionId, e.getMessage());
|
||||
throw new IllegalStateException("Connection " + connectionId + " is not active");
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Close the specified connection via the @connections DELETE API.
|
||||
* Marks the connection as server-initiated so that the $disconnect Lambda
|
||||
* is NOT invoked when the close handler fires (matching AWS behavior).
|
||||
*
|
||||
* @throws IllegalStateException if the connection is not active
|
||||
*/
|
||||
public void closeConnection(String connectionId) {
|
||||
ServerWebSocket ws = sockets.get(connectionId);
|
||||
if (ws == null) {
|
||||
throw new IllegalStateException("Connection " + connectionId + " is not active");
|
||||
}
|
||||
// Mark as server-initiated BEFORE closing so the close handler knows to skip $disconnect
|
||||
serverInitiatedCloses.add(connectionId);
|
||||
ws.close();
|
||||
// Note: unregister is called by the close handler in WebSocketHandler.onClose()
|
||||
}
|
||||
|
||||
/**
|
||||
* Check whether a close was initiated by the server (via @connections DELETE API).
|
||||
* When true, the $disconnect Lambda should NOT be invoked.
|
||||
*/
|
||||
public boolean isServerInitiatedClose(String connectionId) {
|
||||
return serverInitiatedCloses.contains(connectionId);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get connection metadata for the specified connection.
|
||||
*
|
||||
* @return the ConnectionInfo, or null if the connection is not active
|
||||
*/
|
||||
public ConnectionInfo getConnectionInfo(String connectionId) {
|
||||
return connections.get(connectionId);
|
||||
}
|
||||
|
||||
/**
|
||||
* Update the lastActiveAt timestamp on the connection metadata.
|
||||
*/
|
||||
public void updateLastActiveAt(String connectionId) {
|
||||
ConnectionInfo info = connections.get(connectionId);
|
||||
if (info != null) {
|
||||
info.setLastActiveAt(System.currentTimeMillis());
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Check whether a connection is currently active.
|
||||
*/
|
||||
public boolean isConnected(String connectionId) {
|
||||
return sockets.containsKey(connectionId);
|
||||
}
|
||||
}
|
||||
+761
@@ -0,0 +1,761 @@
|
||||
package io.github.hectorvent.floci.services.apigatewayv2.websocket;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import io.github.hectorvent.floci.core.common.AwsException;
|
||||
import io.github.hectorvent.floci.core.common.RegionResolver;
|
||||
import io.github.hectorvent.floci.services.apigatewayv2.ApiGatewayV2Service;
|
||||
import io.github.hectorvent.floci.services.apigatewayv2.model.Api;
|
||||
import io.github.hectorvent.floci.services.apigatewayv2.model.Integration;
|
||||
import io.github.hectorvent.floci.services.apigatewayv2.model.Route;
|
||||
import io.github.hectorvent.floci.services.apigatewayv2.model.Stage;
|
||||
import io.vertx.core.buffer.Buffer;
|
||||
import io.vertx.core.http.ServerWebSocket;
|
||||
import io.vertx.ext.web.Router;
|
||||
import io.vertx.ext.web.RoutingContext;
|
||||
import jakarta.enterprise.context.ApplicationScoped;
|
||||
import jakarta.enterprise.event.Observes;
|
||||
import jakarta.inject.Inject;
|
||||
import org.jboss.logging.Logger;
|
||||
|
||||
import java.util.Collections;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.UUID;
|
||||
|
||||
/**
|
||||
* Vert.x-based WebSocket handler for API Gateway v2 WebSocket APIs.
|
||||
*
|
||||
* Registers a route on the Quarkus HTTP server via {@code @Observes Router} to handle
|
||||
* WebSocket upgrade requests at {@code /ws/{apiId}/{stageName}}.
|
||||
*
|
||||
* This handler validates the API and stage, generates a unique connectionId,
|
||||
* and delegates to the $connect/$disconnect/message lifecycle (implemented in Tasks 3-5).
|
||||
*/
|
||||
@ApplicationScoped
|
||||
public class WebSocketHandler {
|
||||
|
||||
private static final Logger LOG = Logger.getLogger(WebSocketHandler.class);
|
||||
|
||||
private final ApiGatewayV2Service apiGatewayV2Service;
|
||||
private final WebSocketConnectionManager connectionManager;
|
||||
private final RouteSelectionEvaluator routeSelectionEvaluator;
|
||||
private final WebSocketProxyEventBuilder proxyEventBuilder;
|
||||
private final WebSocketIntegrationInvoker integrationInvoker;
|
||||
private final WebSocketAuthorizerService authorizerService;
|
||||
private final RegionResolver regionResolver;
|
||||
private final ObjectMapper objectMapper;
|
||||
private final io.vertx.core.Vertx vertx;
|
||||
|
||||
@Inject
|
||||
public WebSocketHandler(ApiGatewayV2Service apiGatewayV2Service,
|
||||
WebSocketConnectionManager connectionManager,
|
||||
RouteSelectionEvaluator routeSelectionEvaluator,
|
||||
WebSocketProxyEventBuilder proxyEventBuilder,
|
||||
WebSocketIntegrationInvoker integrationInvoker,
|
||||
WebSocketAuthorizerService authorizerService,
|
||||
RegionResolver regionResolver,
|
||||
ObjectMapper objectMapper,
|
||||
io.vertx.core.Vertx vertx) {
|
||||
this.apiGatewayV2Service = apiGatewayV2Service;
|
||||
this.connectionManager = connectionManager;
|
||||
this.routeSelectionEvaluator = routeSelectionEvaluator;
|
||||
this.proxyEventBuilder = proxyEventBuilder;
|
||||
this.integrationInvoker = integrationInvoker;
|
||||
this.authorizerService = authorizerService;
|
||||
this.regionResolver = regionResolver;
|
||||
this.objectMapper = objectMapper;
|
||||
this.vertx = vertx;
|
||||
}
|
||||
|
||||
/**
|
||||
* Register the WebSocket route handler on the Vert.x Router.
|
||||
* This runs before JAX-RS routing and intercepts WebSocket upgrade requests.
|
||||
*/
|
||||
void init(@Observes Router router) {
|
||||
router.route("/ws/*").handler(this::handleWebSocketUpgrade);
|
||||
LOG.info("Registered WebSocket handler on /ws/*");
|
||||
}
|
||||
|
||||
/**
|
||||
* Handle a WebSocket upgrade request.
|
||||
* Parses apiId and stageName from the path, validates the API and stage,
|
||||
* generates a unique connectionId, and proceeds with the $connect lifecycle.
|
||||
*/
|
||||
private void handleWebSocketUpgrade(RoutingContext ctx) {
|
||||
String path = ctx.request().path();
|
||||
|
||||
// Strip the /ws/ prefix and parse apiId/stageName
|
||||
String pathAfterPrefix = path.substring("/ws/".length());
|
||||
String[] segments = pathAfterPrefix.split("/", 2);
|
||||
|
||||
if (segments.length < 2 || segments[0].isEmpty() || segments[1].isEmpty()) {
|
||||
ctx.response().setStatusCode(403).end();
|
||||
return;
|
||||
}
|
||||
|
||||
String apiId = segments[0];
|
||||
// stageName may contain additional path segments — take only the first segment
|
||||
String stageName = segments[1].contains("/") ? segments[1].split("/")[0] : segments[1];
|
||||
|
||||
// Resolve region from the request Authorization header
|
||||
String region = resolveRegionFromVertxRequest(ctx);
|
||||
|
||||
// Validate the API exists and is a WEBSOCKET protocol API
|
||||
Api api;
|
||||
try {
|
||||
api = apiGatewayV2Service.getApi(region, apiId);
|
||||
} catch (AwsException e) {
|
||||
LOG.debugv("WebSocket upgrade rejected: API {0} not found in region {1}", apiId, region);
|
||||
ctx.response().setStatusCode(403).end();
|
||||
return;
|
||||
}
|
||||
|
||||
if (!"WEBSOCKET".equals(api.getProtocolType())) {
|
||||
LOG.debugv("WebSocket upgrade rejected: API {0} is not WEBSOCKET protocol (is {1})",
|
||||
apiId, api.getProtocolType());
|
||||
ctx.response().setStatusCode(403).end();
|
||||
return;
|
||||
}
|
||||
|
||||
// Validate the stage exists
|
||||
Stage stage;
|
||||
try {
|
||||
stage = apiGatewayV2Service.getStage(region, apiId, stageName);
|
||||
} catch (AwsException e) {
|
||||
LOG.debugv("WebSocket upgrade rejected: stage {0} not found on API {1}", stageName, apiId);
|
||||
ctx.response().setStatusCode(403).end();
|
||||
return;
|
||||
}
|
||||
|
||||
// Generate a unique connectionId (AWS format: base64-encoded random bytes, ~10-14 chars)
|
||||
String connectionId = generateConnectionId();
|
||||
long connectedAt = System.currentTimeMillis();
|
||||
|
||||
// Extract source IP and user agent from the upgrade request
|
||||
String sourceIp = ctx.request().remoteAddress() != null
|
||||
? ctx.request().remoteAddress().host() : "127.0.0.1";
|
||||
String userAgent = ctx.request().getHeader("User-Agent");
|
||||
|
||||
// Load stage variables (default to empty map if null)
|
||||
Map<String, String> stageVariables = stage.getStageVariables() != null
|
||||
? stage.getStageVariables() : Collections.emptyMap();
|
||||
|
||||
// Look up the $connect route
|
||||
Route connectRoute = apiGatewayV2Service.findRouteByKey(region, apiId, "$connect");
|
||||
|
||||
if (connectRoute != null && connectRoute.getTarget() != null) {
|
||||
// Check if the $connect route has a Lambda REQUEST authorizer configured
|
||||
if ("CUSTOM".equals(connectRoute.getAuthorizationType())
|
||||
&& connectRoute.getAuthorizerId() != null
|
||||
&& !connectRoute.getAuthorizerId().isEmpty()) {
|
||||
|
||||
// Build headers and query params from the upgrade request (needed for both authorizer and integration)
|
||||
Map<String, List<String>> headers = extractHeaders(ctx);
|
||||
Map<String, List<String>> queryParams = extractQueryParams(ctx);
|
||||
|
||||
// Invoke the authorizer on a worker thread (blocking Lambda call)
|
||||
final Map<String, String> finalStageVariables = stageVariables;
|
||||
final String finalConnectionId = connectionId;
|
||||
final long finalConnectedAt = connectedAt;
|
||||
final String finalSourceIp = sourceIp;
|
||||
final String finalUserAgent = userAgent;
|
||||
|
||||
vertx.<WebSocketAuthorizerService.AuthorizerResult>executeBlocking(() -> {
|
||||
return authorizerService.invokeAndEvaluate(region, apiId, stageName,
|
||||
connectRoute.getAuthorizerId(), finalConnectionId, finalConnectedAt,
|
||||
headers, queryParams, finalSourceIp, finalUserAgent, finalStageVariables);
|
||||
}).onSuccess(authResult -> {
|
||||
if (!authResult.allowed()) {
|
||||
ctx.response().setStatusCode(authResult.statusCode()).end();
|
||||
return;
|
||||
}
|
||||
// Authorizer allowed — proceed with $connect integration
|
||||
proceedWithConnectIntegration(ctx, connectRoute, region, apiId, stageName,
|
||||
finalConnectionId, finalConnectedAt, finalSourceIp, finalUserAgent,
|
||||
finalStageVariables, headers, queryParams, authResult.context());
|
||||
}).onFailure(e -> {
|
||||
LOG.warnv("Lambda authorizer invocation failed for API {0}: {1}",
|
||||
apiId, e.getMessage());
|
||||
ctx.response().setStatusCode(500).end();
|
||||
});
|
||||
} else {
|
||||
// No authorizer configured — proceed directly with $connect integration
|
||||
Map<String, List<String>> headers = extractHeaders(ctx);
|
||||
Map<String, List<String>> queryParams = extractQueryParams(ctx);
|
||||
proceedWithConnectIntegration(ctx, connectRoute, region, apiId, stageName,
|
||||
connectionId, connectedAt, sourceIp, userAgent,
|
||||
stageVariables, headers, queryParams, null);
|
||||
}
|
||||
} else {
|
||||
// No $connect route — complete the upgrade directly
|
||||
completeUpgrade(ctx, connectionId, apiId, stageName, region,
|
||||
connectedAt, sourceIp, userAgent);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Proceed with the $connect integration invocation after authorizer check.
|
||||
* The authorizerContext parameter holds the extracted authorizer context (may be null if no authorizer).
|
||||
*/
|
||||
private void proceedWithConnectIntegration(RoutingContext ctx, Route connectRoute,
|
||||
String region, String apiId, String stageName,
|
||||
String connectionId, long connectedAt,
|
||||
String sourceIp, String userAgent,
|
||||
Map<String, String> stageVariables,
|
||||
Map<String, List<String>> headers,
|
||||
Map<String, List<String>> queryParams,
|
||||
Map<String, Object> authorizerContext) {
|
||||
// Resolve the $connect integration
|
||||
String integrationId = parseIntegrationId(connectRoute.getTarget());
|
||||
Integration integration;
|
||||
try {
|
||||
integration = apiGatewayV2Service.getIntegration(region, apiId, integrationId);
|
||||
} catch (AwsException e) {
|
||||
LOG.warnv("$connect integration {0} not found for API {1}", integrationId, apiId);
|
||||
ctx.response().setStatusCode(500).end();
|
||||
return;
|
||||
}
|
||||
|
||||
// Build the CONNECT proxy event with authorizer context
|
||||
String eventJson = proxyEventBuilder.buildConnectEvent(
|
||||
connectionId, apiId, stageName, region, connectedAt,
|
||||
headers, queryParams, sourceIp, userAgent, stageVariables, authorizerContext);
|
||||
|
||||
// Execute the blocking Lambda invocation on a worker thread
|
||||
final Integration finalIntegration = integration;
|
||||
final Map<String, String> finalStageVariables = stageVariables;
|
||||
vertx.<WebSocketIntegrationInvoker.IntegrationResult>executeBlocking(() -> {
|
||||
return integrationInvoker.invoke(region, finalIntegration, eventJson,
|
||||
finalStageVariables, Collections.emptyMap(), Collections.emptyMap());
|
||||
}).onSuccess(result -> {
|
||||
// Check for function error (Lambda invocation error)
|
||||
if (result.functionError() != null) {
|
||||
LOG.debugv("$connect Lambda returned function error: {0}, rejecting upgrade for API {1}",
|
||||
result.functionError(), apiId);
|
||||
ctx.response().setStatusCode(500).end();
|
||||
return;
|
||||
}
|
||||
// Check the response status code
|
||||
if (result.statusCode() >= 200 && result.statusCode() <= 299) {
|
||||
// 2xx — complete the WebSocket upgrade with response headers from Lambda
|
||||
completeUpgradeWithHeaders(ctx, connectionId, apiId, stageName, region,
|
||||
connectedAt, sourceIp, userAgent, result.headers());
|
||||
} else {
|
||||
// Non-2xx — reject the upgrade
|
||||
LOG.debugv("$connect route returned status {0}, rejecting upgrade for API {1}",
|
||||
result.statusCode(), apiId);
|
||||
ctx.response().setStatusCode(403).end();
|
||||
}
|
||||
}).onFailure(e -> {
|
||||
LOG.warnv("$connect integration invocation failed for API {0}: {1}",
|
||||
apiId, e.getMessage());
|
||||
ctx.response().setStatusCode(500).end();
|
||||
});
|
||||
}
|
||||
|
||||
/** Maximum WebSocket frame payload size in bytes (128 KB, matching AWS limit). */
|
||||
private static final int MAX_FRAME_PAYLOAD_BYTES = 128 * 1024;
|
||||
|
||||
/** Idle timeout in milliseconds (10 minutes, matching AWS default). */
|
||||
private static final long IDLE_TIMEOUT_MS = 10 * 60 * 1000L;
|
||||
|
||||
/** Maximum connection duration in milliseconds (2 hours, matching AWS limit). */
|
||||
private static final long MAX_CONNECTION_DURATION_MS = 2 * 60 * 60 * 1000L;
|
||||
|
||||
/**
|
||||
* Complete the WebSocket upgrade, register the connection, and attach message/close handlers.
|
||||
*/
|
||||
private void completeUpgrade(RoutingContext ctx, String connectionId, String apiId,
|
||||
String stageName, String region, long connectedAt,
|
||||
String sourceIp, String userAgent) {
|
||||
ctx.request().toWebSocket().onSuccess(ws -> {
|
||||
// Register the connection
|
||||
ConnectionInfo connectionInfo = new ConnectionInfo(
|
||||
connectionId, apiId, stageName, region,
|
||||
connectedAt, connectedAt, sourceIp, userAgent);
|
||||
connectionManager.register(connectionId, connectionInfo, ws);
|
||||
|
||||
LOG.debugv("WebSocket connection {0} established for API {1}/{2}",
|
||||
connectionId, apiId, stageName);
|
||||
|
||||
// Attach text message handler
|
||||
ws.textMessageHandler(msg -> {
|
||||
// Enforce payload size limit (AWS: 128 KB for WebSocket frames)
|
||||
if (msg.length() > MAX_FRAME_PAYLOAD_BYTES) {
|
||||
LOG.debugv("Message exceeds 128 KB limit on connection {0} ({1} bytes)",
|
||||
connectionId, msg.length());
|
||||
safeWriteTextMessage(ws, "{\"message\":\"Message too long\",\"connectionId\":\""
|
||||
+ connectionId + "\"}", connectionId);
|
||||
return;
|
||||
}
|
||||
onMessage(ws, connectionId, apiId, stageName, region, msg, false);
|
||||
});
|
||||
|
||||
// Attach binary message handler (AWS supports binary frames with isBase64Encoded=true)
|
||||
ws.binaryMessageHandler(buffer -> {
|
||||
byte[] data = buffer.getBytes();
|
||||
// Enforce payload size limit
|
||||
if (data.length > MAX_FRAME_PAYLOAD_BYTES) {
|
||||
LOG.debugv("Binary message exceeds 128 KB limit on connection {0} ({1} bytes)",
|
||||
connectionId, data.length);
|
||||
safeWriteTextMessage(ws, "{\"message\":\"Message too long\",\"connectionId\":\""
|
||||
+ connectionId + "\"}", connectionId);
|
||||
return;
|
||||
}
|
||||
onBinaryMessage(ws, connectionId, apiId, stageName, region, data);
|
||||
});
|
||||
|
||||
// Attach close handler
|
||||
ws.closeHandler(v -> onClose(ws, connectionId, apiId, stageName, region));
|
||||
|
||||
// Schedule idle timeout check
|
||||
scheduleIdleTimeout(connectionId, connectedAt);
|
||||
}).onFailure(err -> {
|
||||
LOG.warnv("WebSocket upgrade failed for connection {0}: {1}",
|
||||
connectionId, err.getMessage());
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Complete the WebSocket upgrade with custom response headers from the $connect Lambda.
|
||||
* AWS allows the $connect Lambda to return headers that are included in the upgrade response.
|
||||
*/
|
||||
private void completeUpgradeWithHeaders(RoutingContext ctx, String connectionId, String apiId,
|
||||
String stageName, String region, long connectedAt,
|
||||
String sourceIp, String userAgent,
|
||||
Map<String, String> responseHeaders) {
|
||||
// Add custom headers to the upgrade response before completing the WebSocket handshake
|
||||
if (responseHeaders != null && !responseHeaders.isEmpty()) {
|
||||
for (Map.Entry<String, String> header : responseHeaders.entrySet()) {
|
||||
// Skip hop-by-hop headers that shouldn't be propagated
|
||||
String key = header.getKey().toLowerCase();
|
||||
if (key.equals("connection") || key.equals("upgrade") || key.equals("sec-websocket-accept")
|
||||
|| key.equals("sec-websocket-key") || key.equals("sec-websocket-version")) {
|
||||
continue;
|
||||
}
|
||||
ctx.response().putHeader(header.getKey(), header.getValue());
|
||||
}
|
||||
}
|
||||
completeUpgrade(ctx, connectionId, apiId, stageName, region, connectedAt, sourceIp, userAgent);
|
||||
}
|
||||
|
||||
/**
|
||||
* Schedule periodic idle timeout and max duration checks for a connection.
|
||||
* AWS enforces a 10-minute idle timeout and 2-hour maximum connection duration.
|
||||
*/
|
||||
private void scheduleIdleTimeout(String connectionId, long connectedAt) {
|
||||
// Check every 60 seconds
|
||||
vertx.setPeriodic(60_000L, timerId -> {
|
||||
ConnectionInfo info = connectionManager.getConnectionInfo(connectionId);
|
||||
if (info == null) {
|
||||
// Connection already closed — cancel the timer
|
||||
vertx.cancelTimer(timerId);
|
||||
return;
|
||||
}
|
||||
|
||||
long now = System.currentTimeMillis();
|
||||
|
||||
// Check max connection duration (2 hours)
|
||||
if (now - connectedAt > MAX_CONNECTION_DURATION_MS) {
|
||||
LOG.debugv("Connection {0} exceeded max duration (2h), closing", connectionId);
|
||||
vertx.cancelTimer(timerId);
|
||||
connectionManager.closeConnection(connectionId);
|
||||
return;
|
||||
}
|
||||
|
||||
// Check idle timeout (10 minutes since last activity)
|
||||
if (now - info.getLastActiveAt() > IDLE_TIMEOUT_MS) {
|
||||
LOG.debugv("Connection {0} idle timeout (10m), closing", connectionId);
|
||||
vertx.cancelTimer(timerId);
|
||||
connectionManager.closeConnection(connectionId);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Handle an incoming WebSocket binary message.
|
||||
* Encodes the binary data as base64 and routes it like a text message with isBase64Encoded=true.
|
||||
*/
|
||||
private void onBinaryMessage(ServerWebSocket ws, String connectionId, String apiId,
|
||||
String stageName, String region, byte[] data) {
|
||||
LOG.debugv("Received binary message on connection {0}: {1} bytes", connectionId, data.length);
|
||||
|
||||
// Update lastActiveAt timestamp
|
||||
connectionManager.updateLastActiveAt(connectionId);
|
||||
|
||||
// Base64-encode the binary data for the proxy event body
|
||||
String base64Body = java.util.Base64.getEncoder().encodeToString(data);
|
||||
|
||||
// Route using the base64 body (route selection won't match JSON fields in binary messages,
|
||||
// so it will fall through to $default)
|
||||
onMessage(ws, connectionId, apiId, stageName, region, base64Body, true);
|
||||
}
|
||||
|
||||
/**
|
||||
* Handle an incoming WebSocket text message.
|
||||
* Routes the message to the appropriate integration based on the API's routeSelectionExpression.
|
||||
*
|
||||
* @param isBinary if true, the body is base64-encoded binary data and isBase64Encoded should be set in the event
|
||||
*/
|
||||
private void onMessage(ServerWebSocket ws, String connectionId, String apiId,
|
||||
String stageName, String region, String message, boolean isBinary) {
|
||||
LOG.debugv("Received message on connection {0}: {1}", connectionId, message);
|
||||
|
||||
// Update lastActiveAt timestamp (Requirement 9.1)
|
||||
connectionManager.updateLastActiveAt(connectionId);
|
||||
|
||||
// Load the API to get routeSelectionExpression
|
||||
Api api;
|
||||
try {
|
||||
api = apiGatewayV2Service.getApi(region, apiId);
|
||||
} catch (AwsException e) {
|
||||
LOG.warnv("Failed to load API {0} for message routing: {1}", apiId, e.getMessage());
|
||||
return;
|
||||
}
|
||||
|
||||
String routeSelectionExpression = api.getRouteSelectionExpression();
|
||||
|
||||
// Evaluate routeSelectionExpression against the message
|
||||
String routeKey = routeSelectionEvaluator.evaluate(routeSelectionExpression, message);
|
||||
|
||||
// Look up matching route
|
||||
Route route = null;
|
||||
if (routeKey != null) {
|
||||
route = apiGatewayV2Service.findRouteByKey(region, apiId, routeKey);
|
||||
}
|
||||
|
||||
// Fall back to $default if no match
|
||||
if (route == null) {
|
||||
route = apiGatewayV2Service.findRouteByKey(region, apiId, "$default");
|
||||
}
|
||||
|
||||
// If no route found (no match and no $default)
|
||||
if (route == null) {
|
||||
String requestId = UUID.randomUUID().toString();
|
||||
if (routeKey == null) {
|
||||
// Message is non-JSON or field not found, and no $default
|
||||
String errorFrame = String.format(
|
||||
"{\"message\":\"Could not route message\",\"connectionId\":\"%s\",\"requestId\":\"%s\"}",
|
||||
connectionId, requestId);
|
||||
safeWriteTextMessage(ws, errorFrame, connectionId);
|
||||
} else {
|
||||
// Route key extracted but no matching route and no $default
|
||||
String errorFrame = String.format(
|
||||
"{\"message\":\"No route found\",\"connectionId\":\"%s\",\"requestId\":\"%s\"}",
|
||||
connectionId, requestId);
|
||||
safeWriteTextMessage(ws, errorFrame, connectionId);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
// Determine the effective route key for the proxy event
|
||||
String effectiveRouteKey = routeKey != null ? routeKey : "$default";
|
||||
|
||||
// Resolve integration
|
||||
if (route.getTarget() == null) {
|
||||
LOG.debugv("Route {0} has no target integration", route.getRouteKey());
|
||||
return;
|
||||
}
|
||||
|
||||
String integrationId = parseIntegrationId(route.getTarget());
|
||||
Integration integration;
|
||||
try {
|
||||
integration = apiGatewayV2Service.getIntegration(region, apiId, integrationId);
|
||||
} catch (AwsException e) {
|
||||
LOG.warnv("Integration {0} not found for route {1}: {2}",
|
||||
integrationId, route.getRouteKey(), e.getMessage());
|
||||
String requestId = UUID.randomUUID().toString();
|
||||
String errorFrame = String.format(
|
||||
"{\"message\":\"Internal server error\",\"connectionId\":\"%s\",\"requestId\":\"%s\"}",
|
||||
connectionId, requestId);
|
||||
safeWriteTextMessage(ws, errorFrame, connectionId);
|
||||
return;
|
||||
}
|
||||
|
||||
// Load stage variables
|
||||
Map<String, String> stageVariables = Collections.emptyMap();
|
||||
try {
|
||||
Stage stage = apiGatewayV2Service.getStage(region, apiId, stageName);
|
||||
if (stage.getStageVariables() != null) {
|
||||
stageVariables = stage.getStageVariables();
|
||||
}
|
||||
} catch (AwsException e) {
|
||||
LOG.debugv("Failed to load stage {0} for stage variables: {1}", stageName, e.getMessage());
|
||||
}
|
||||
|
||||
// Get connection info for connectedAt, sourceIp, userAgent
|
||||
ConnectionInfo connectionInfo = connectionManager.getConnectionInfo(connectionId);
|
||||
long connectedAt = connectionInfo != null ? connectionInfo.getConnectedAt() : System.currentTimeMillis();
|
||||
String sourceIp = connectionInfo != null ? connectionInfo.getSourceIp() : "127.0.0.1";
|
||||
String userAgent = connectionInfo != null ? connectionInfo.getUserAgent() : "";
|
||||
|
||||
// Build MESSAGE proxy event
|
||||
String eventJson = proxyEventBuilder.buildMessageEvent(
|
||||
connectionId, effectiveRouteKey, apiId, stageName, region,
|
||||
connectedAt, message, sourceIp, userAgent, stageVariables, isBinary);
|
||||
|
||||
// Invoke integration on a worker thread to avoid blocking the event loop
|
||||
final Integration finalIntegration = integration;
|
||||
final Map<String, String> finalStageVariables = stageVariables;
|
||||
final Route finalRoute = route;
|
||||
final String finalConnectionId = connectionId;
|
||||
vertx.executeBlocking(() -> {
|
||||
return integrationInvoker.invoke(region, finalIntegration, eventJson,
|
||||
finalStageVariables, Collections.emptyMap(), Collections.emptyMap());
|
||||
}).onSuccess(result -> {
|
||||
// Route response handling (Requirements 5.1–5.3)
|
||||
if (finalRoute.getRouteResponseSelectionExpression() != null && result.body() != null) {
|
||||
try {
|
||||
JsonNode responseJson = objectMapper.readTree(result.body());
|
||||
if (responseJson.has("body")) {
|
||||
String responseBody = responseJson.get("body").asText();
|
||||
safeWriteTextMessage(ws, responseBody, finalConnectionId);
|
||||
} else {
|
||||
// If no "body" field, send the entire body as-is
|
||||
safeWriteTextMessage(ws, result.body(), finalConnectionId);
|
||||
}
|
||||
} catch (Exception e) {
|
||||
// If parsing fails, send the raw body
|
||||
LOG.debugv("Failed to parse integration response as JSON, sending raw body: {0}",
|
||||
e.getMessage());
|
||||
safeWriteTextMessage(ws, result.body(), finalConnectionId);
|
||||
}
|
||||
}
|
||||
}).onFailure(e -> {
|
||||
LOG.warnv("Integration invocation failed for route {0} on connection {1}: {2}",
|
||||
finalRoute.getRouteKey(), finalConnectionId, e.getMessage());
|
||||
String requestId = UUID.randomUUID().toString();
|
||||
String errorFrame = String.format(
|
||||
"{\"message\":\"Internal server error\",\"connectionId\":\"%s\",\"requestId\":\"%s\"}",
|
||||
finalConnectionId, requestId);
|
||||
safeWriteTextMessage(ws, errorFrame, finalConnectionId);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Handle WebSocket connection close.
|
||||
* Invokes the $disconnect route's Lambda integration (if configured) and then
|
||||
* unregisters the connection from the ConnectionManager.
|
||||
* Errors during $disconnect invocation are logged but never propagated.
|
||||
*
|
||||
* AWS behavior: $disconnect is NOT invoked when the close was initiated by the server
|
||||
* via the @connections DELETE API. Only client-initiated disconnections trigger $disconnect.
|
||||
*/
|
||||
private void onClose(ServerWebSocket ws, String connectionId, String apiId,
|
||||
String stageName, String region) {
|
||||
LOG.debugv("WebSocket connection {0} closed", connectionId);
|
||||
|
||||
// Check if this close was initiated by the server via @connections DELETE API.
|
||||
// In AWS, server-initiated disconnections do NOT invoke the $disconnect Lambda.
|
||||
if (connectionManager.isServerInitiatedClose(connectionId)) {
|
||||
LOG.debugv("Skipping $disconnect for server-initiated close on connection {0}", connectionId);
|
||||
connectionManager.unregister(connectionId);
|
||||
return;
|
||||
}
|
||||
|
||||
// Retrieve connection info BEFORE unregistering so we have connectedAt, sourceIp, userAgent
|
||||
ConnectionInfo connectionInfo = connectionManager.getConnectionInfo(connectionId);
|
||||
long connectedAt = connectionInfo != null ? connectionInfo.getConnectedAt() : System.currentTimeMillis();
|
||||
String sourceIp = connectionInfo != null ? connectionInfo.getSourceIp() : "127.0.0.1";
|
||||
String userAgent = connectionInfo != null ? connectionInfo.getUserAgent() : "";
|
||||
|
||||
// Look up the $disconnect route
|
||||
Route disconnectRoute = apiGatewayV2Service.findRouteByKey(region, apiId, "$disconnect");
|
||||
|
||||
if (disconnectRoute != null && disconnectRoute.getTarget() != null) {
|
||||
// Load stage variables
|
||||
Map<String, String> stageVariables = Collections.emptyMap();
|
||||
try {
|
||||
Stage stage = apiGatewayV2Service.getStage(region, apiId, stageName);
|
||||
if (stage.getStageVariables() != null) {
|
||||
stageVariables = stage.getStageVariables();
|
||||
}
|
||||
} catch (AwsException e) {
|
||||
LOG.debugv("Failed to load stage {0} for $disconnect stage variables: {1}",
|
||||
stageName, e.getMessage());
|
||||
}
|
||||
|
||||
// Resolve integration and invoke on a worker thread
|
||||
String integrationId = parseIntegrationId(disconnectRoute.getTarget());
|
||||
Integration integration;
|
||||
try {
|
||||
integration = apiGatewayV2Service.getIntegration(region, apiId, integrationId);
|
||||
} catch (AwsException e) {
|
||||
LOG.warnv("$disconnect integration {0} not found for connection {1}: {2}",
|
||||
integrationId, connectionId, e.getMessage());
|
||||
connectionManager.unregister(connectionId);
|
||||
return;
|
||||
}
|
||||
|
||||
// Build DISCONNECT proxy event
|
||||
String eventJson = proxyEventBuilder.buildDisconnectEvent(
|
||||
connectionId, apiId, stageName, region, connectedAt,
|
||||
sourceIp, userAgent, stageVariables);
|
||||
|
||||
// Execute the blocking Lambda invocation on a worker thread
|
||||
final Integration finalIntegration = integration;
|
||||
final Map<String, String> finalStageVariables = stageVariables;
|
||||
vertx.executeBlocking(() -> {
|
||||
integrationInvoker.invoke(region, finalIntegration, eventJson,
|
||||
finalStageVariables, Collections.emptyMap(), Collections.emptyMap());
|
||||
return null;
|
||||
}).onComplete(ar -> {
|
||||
if (ar.failed()) {
|
||||
// $disconnect errors must never prevent cleanup — log and continue
|
||||
LOG.warnv("Error invoking $disconnect route for connection {0}: {1}",
|
||||
connectionId, ar.cause().getMessage());
|
||||
}
|
||||
// Always unregister the connection regardless of $disconnect outcome
|
||||
connectionManager.unregister(connectionId);
|
||||
});
|
||||
} else {
|
||||
// No $disconnect route — just unregister
|
||||
connectionManager.unregister(connectionId);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Safely write a text message to a WebSocket, catching any exceptions that may occur
|
||||
* if the connection is in a closing or closed state.
|
||||
*/
|
||||
private void safeWriteTextMessage(ServerWebSocket ws, String message, String connectionId) {
|
||||
try {
|
||||
ws.writeTextMessage(message);
|
||||
} catch (Exception e) {
|
||||
LOG.debugv("Failed to write message to connection {0}: {1}", connectionId, e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Generate a connection ID matching the AWS format.
|
||||
* AWS connection IDs are URL-safe base64-encoded random bytes, typically 10-14 characters
|
||||
* (e.g. "L0SM9cOFvHcCIhw", "d2ljbGVz").
|
||||
* Uses 9 random bytes → 12 base64url characters (no padding).
|
||||
*/
|
||||
private static String generateConnectionId() {
|
||||
byte[] bytes = new byte[9];
|
||||
java.util.concurrent.ThreadLocalRandom.current().nextBytes(bytes);
|
||||
return java.util.Base64.getUrlEncoder().withoutPadding().encodeToString(bytes);
|
||||
}
|
||||
|
||||
/**
|
||||
* Parse the integrationId from a route target string.
|
||||
* Target format: "integrations/{integrationId}"
|
||||
*/
|
||||
private String parseIntegrationId(String target) {
|
||||
if (target == null) {
|
||||
return null;
|
||||
}
|
||||
if (target.startsWith("integrations/")) {
|
||||
return target.substring("integrations/".length());
|
||||
}
|
||||
return target;
|
||||
}
|
||||
|
||||
/**
|
||||
* Extract headers from the Vert.x routing context as a multi-value map.
|
||||
*/
|
||||
private Map<String, List<String>> extractHeaders(RoutingContext ctx) {
|
||||
Map<String, List<String>> headers = new HashMap<>();
|
||||
ctx.request().headers().forEach(entry ->
|
||||
headers.computeIfAbsent(entry.getKey(), k -> new java.util.ArrayList<>())
|
||||
.add(entry.getValue()));
|
||||
return headers;
|
||||
}
|
||||
|
||||
/**
|
||||
* Extract query parameters from the Vert.x routing context as a multi-value map.
|
||||
*/
|
||||
private Map<String, List<String>> extractQueryParams(RoutingContext ctx) {
|
||||
Map<String, List<String>> params = new HashMap<>();
|
||||
ctx.request().params().forEach(entry ->
|
||||
params.computeIfAbsent(entry.getKey(), k -> new java.util.ArrayList<>())
|
||||
.add(entry.getValue()));
|
||||
return params;
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolve the AWS region from the Vert.x request headers.
|
||||
* Extracts the Authorization header and delegates to RegionResolver's parsing logic.
|
||||
* Falls back to the default region if no Authorization header is present.
|
||||
*/
|
||||
private String resolveRegionFromVertxRequest(RoutingContext ctx) {
|
||||
String authHeader = ctx.request().getHeader("Authorization");
|
||||
if (authHeader == null || authHeader.isEmpty()) {
|
||||
return regionResolver.getDefaultRegion();
|
||||
}
|
||||
// Use a simple JAX-RS HttpHeaders adapter to delegate to RegionResolver
|
||||
jakarta.ws.rs.core.HttpHeaders headers = new SimpleHttpHeaders(authHeader);
|
||||
return regionResolver.resolveRegion(headers);
|
||||
}
|
||||
|
||||
/**
|
||||
* Minimal HttpHeaders implementation that provides only the Authorization header.
|
||||
* Used to bridge Vert.x request headers to the RegionResolver API.
|
||||
*/
|
||||
private static class SimpleHttpHeaders implements jakarta.ws.rs.core.HttpHeaders {
|
||||
private final String authorizationHeader;
|
||||
|
||||
SimpleHttpHeaders(String authorizationHeader) {
|
||||
this.authorizationHeader = authorizationHeader;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getHeaderString(String name) {
|
||||
if ("Authorization".equalsIgnoreCase(name)) {
|
||||
return authorizationHeader;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public java.util.List<String> getRequestHeader(String name) {
|
||||
if ("Authorization".equalsIgnoreCase(name) && authorizationHeader != null) {
|
||||
return java.util.List.of(authorizationHeader);
|
||||
}
|
||||
return java.util.Collections.emptyList();
|
||||
}
|
||||
|
||||
@Override
|
||||
public jakarta.ws.rs.core.MultivaluedMap<String, String> getRequestHeaders() {
|
||||
return new jakarta.ws.rs.core.MultivaluedHashMap<>();
|
||||
}
|
||||
|
||||
@Override
|
||||
public java.util.List<jakarta.ws.rs.core.MediaType> getAcceptableMediaTypes() {
|
||||
return java.util.Collections.emptyList();
|
||||
}
|
||||
|
||||
@Override
|
||||
public java.util.List<java.util.Locale> getAcceptableLanguages() {
|
||||
return java.util.Collections.emptyList();
|
||||
}
|
||||
|
||||
@Override
|
||||
public jakarta.ws.rs.core.MediaType getMediaType() {
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public java.util.Locale getLanguage() {
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public java.util.Map<String, jakarta.ws.rs.core.Cookie> getCookies() {
|
||||
return java.util.Collections.emptyMap();
|
||||
}
|
||||
|
||||
@Override
|
||||
public java.util.Date getDate() {
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getLength() {
|
||||
return -1;
|
||||
}
|
||||
}
|
||||
}
|
||||
+532
@@ -0,0 +1,532 @@
|
||||
package io.github.hectorvent.floci.services.apigatewayv2.websocket;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import io.github.hectorvent.floci.services.apigateway.AwsServiceRouter;
|
||||
import io.github.hectorvent.floci.services.apigateway.VtlTemplateEngine;
|
||||
import io.github.hectorvent.floci.services.apigatewayv2.model.Integration;
|
||||
import io.github.hectorvent.floci.services.lambda.LambdaArnUtils;
|
||||
import io.github.hectorvent.floci.services.lambda.LambdaService;
|
||||
import io.github.hectorvent.floci.services.lambda.model.InvocationType;
|
||||
import io.github.hectorvent.floci.services.lambda.model.InvokeResult;
|
||||
import jakarta.annotation.PreDestroy;
|
||||
import jakarta.enterprise.context.ApplicationScoped;
|
||||
import jakarta.inject.Inject;
|
||||
import org.jboss.logging.Logger;
|
||||
|
||||
import java.net.URI;
|
||||
import java.net.http.HttpClient;
|
||||
import java.net.http.HttpRequest;
|
||||
import java.net.http.HttpResponse;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.Collections;
|
||||
import java.util.Map;
|
||||
import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
/**
|
||||
* Resolves and invokes integration targets for WebSocket routes.
|
||||
* Supports AWS_PROXY (Lambda), AWS (Lambda with VTL templates), HTTP_PROXY, HTTP (with VTL templates), and MOCK integration types.
|
||||
*/
|
||||
@ApplicationScoped
|
||||
public class WebSocketIntegrationInvoker {
|
||||
|
||||
private static final Logger LOG = Logger.getLogger(WebSocketIntegrationInvoker.class);
|
||||
|
||||
/**
|
||||
* Regex pattern matching ${stageVariables.variableName} references in URIs.
|
||||
*/
|
||||
private static final Pattern STAGE_VAR_PATTERN =
|
||||
Pattern.compile("\\$\\{stageVariables\\.([^}]+)}");
|
||||
|
||||
private final LambdaService lambdaService;
|
||||
private final AwsServiceRouter serviceRouter;
|
||||
private final ObjectMapper objectMapper;
|
||||
private final VtlTemplateEngine vtlEngine;
|
||||
private final HttpClient httpClient;
|
||||
|
||||
@Inject
|
||||
public WebSocketIntegrationInvoker(LambdaService lambdaService, AwsServiceRouter serviceRouter,
|
||||
ObjectMapper objectMapper, VtlTemplateEngine vtlEngine) {
|
||||
this.lambdaService = lambdaService;
|
||||
this.serviceRouter = serviceRouter;
|
||||
this.objectMapper = objectMapper;
|
||||
this.vtlEngine = vtlEngine;
|
||||
this.httpClient = HttpClient.newHttpClient();
|
||||
}
|
||||
|
||||
@PreDestroy
|
||||
void shutdown() {
|
||||
// HttpClient does not have an explicit close in Java 11-20.
|
||||
// In Java 21+ HttpClient implements AutoCloseable. For forward compatibility,
|
||||
// we attempt to close if the method is available.
|
||||
try {
|
||||
httpClient.close();
|
||||
} catch (UnsupportedOperationException | NoSuchMethodError e) {
|
||||
// Pre-Java 21 — no-op, GC will handle cleanup
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Result of an integration invocation.
|
||||
*
|
||||
* @param statusCode HTTP-like status code from the integration response
|
||||
* @param body response body (may be null)
|
||||
* @param functionError function error string if the Lambda reported an error (may be null)
|
||||
* @param headers response headers from the integration (may be null)
|
||||
*/
|
||||
public record IntegrationResult(int statusCode, String body, String functionError,
|
||||
Map<String, String> headers) {
|
||||
/** Convenience constructor without headers (backwards compatible). */
|
||||
public IntegrationResult(int statusCode, String body, String functionError) {
|
||||
this(statusCode, body, functionError, null);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Invoke the integration for a route.
|
||||
*
|
||||
* @param region the AWS region
|
||||
* @param integration the Integration model
|
||||
* @param eventJson the serialized proxy event JSON
|
||||
* @param stageVariables stage variables for URI substitution
|
||||
* @param requestTemplates request templates (for MOCK integration)
|
||||
* @param responseTemplates response templates (for MOCK integration)
|
||||
* @return the integration result
|
||||
*/
|
||||
public IntegrationResult invoke(String region, Integration integration, String eventJson,
|
||||
Map<String, String> stageVariables,
|
||||
Map<String, String> requestTemplates,
|
||||
Map<String, String> responseTemplates) {
|
||||
String integrationType = integration.getIntegrationType();
|
||||
if (integrationType == null) {
|
||||
integrationType = "AWS_PROXY";
|
||||
}
|
||||
|
||||
return switch (integrationType) {
|
||||
case "AWS_PROXY" -> invokeAwsProxy(region, integration, eventJson, stageVariables);
|
||||
case "AWS" -> invokeAws(region, integration, eventJson, stageVariables, requestTemplates, responseTemplates);
|
||||
case "HTTP_PROXY" -> invokeHttpProxy(integration, eventJson, stageVariables);
|
||||
case "HTTP" -> invokeHttp(integration, eventJson, stageVariables, requestTemplates, responseTemplates);
|
||||
case "MOCK" -> invokeMock(integration, stageVariables, requestTemplates, responseTemplates);
|
||||
default -> {
|
||||
LOG.warnv("Unsupported integration type: {0}", integrationType);
|
||||
yield new IntegrationResult(500, null, "Unsupported integration type: " + integrationType);
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Invoke a Lambda function via AWS_PROXY integration.
|
||||
*/
|
||||
private IntegrationResult invokeAwsProxy(String region, Integration integration,
|
||||
String eventJson, Map<String, String> stageVariables) {
|
||||
String uri = integration.getIntegrationUri();
|
||||
uri = substituteStageVariables(uri, stageVariables);
|
||||
|
||||
String functionName = extractFunctionName(uri);
|
||||
if (functionName == null || functionName.isEmpty()) {
|
||||
LOG.warnv("Could not extract function name from integration URI: {0}", uri);
|
||||
return new IntegrationResult(500, null, "Invalid integration URI");
|
||||
}
|
||||
|
||||
LOG.debugv("Invoking Lambda function {0} for AWS_PROXY integration", functionName);
|
||||
|
||||
InvokeResult result = lambdaService.invoke(region, functionName,
|
||||
eventJson.getBytes(StandardCharsets.UTF_8), InvocationType.RequestResponse);
|
||||
|
||||
int statusCode = 200;
|
||||
String body = null;
|
||||
String functionError = result.getFunctionError();
|
||||
Map<String, String> responseHeaders = null;
|
||||
|
||||
byte[] payload = result.getPayload();
|
||||
if (payload != null && payload.length > 0) {
|
||||
String payloadStr = new String(payload, StandardCharsets.UTF_8);
|
||||
try {
|
||||
JsonNode responseNode = objectMapper.readTree(payloadStr);
|
||||
if (responseNode.has("statusCode")) {
|
||||
statusCode = responseNode.get("statusCode").asInt(200);
|
||||
}
|
||||
if (responseNode.has("body")) {
|
||||
body = responseNode.get("body").asText();
|
||||
}
|
||||
// Extract response headers (used by $connect to propagate to upgrade response)
|
||||
if (responseNode.has("headers") && responseNode.get("headers").isObject()) {
|
||||
responseHeaders = new java.util.HashMap<>();
|
||||
var headersNode = responseNode.get("headers");
|
||||
var fields = headersNode.fields();
|
||||
while (fields.hasNext()) {
|
||||
var field = fields.next();
|
||||
responseHeaders.put(field.getKey(), field.getValue().asText());
|
||||
}
|
||||
}
|
||||
} catch (Exception e) {
|
||||
LOG.debugv("Failed to parse Lambda response as JSON: {0}", e.getMessage());
|
||||
body = payloadStr;
|
||||
}
|
||||
}
|
||||
|
||||
return new IntegrationResult(statusCode, body, functionError, responseHeaders);
|
||||
}
|
||||
|
||||
/**
|
||||
* Invoke a Lambda function via AWS integration with VTL template transformation.
|
||||
* Applies requestTemplates before invocation and responseTemplates after.
|
||||
* Uses templates from the method parameters first, falling back to the integration model's templates.
|
||||
*/
|
||||
private IntegrationResult invokeAws(String region, Integration integration, String eventJson,
|
||||
Map<String, String> stageVariables,
|
||||
Map<String, String> requestTemplates,
|
||||
Map<String, String> responseTemplates) {
|
||||
String uri = integration.getIntegrationUri();
|
||||
uri = substituteStageVariables(uri, stageVariables);
|
||||
|
||||
String functionName = extractFunctionName(uri);
|
||||
if (functionName == null || functionName.isEmpty()) {
|
||||
LOG.warnv("Could not extract function name from integration URI: {0}", uri);
|
||||
return new IntegrationResult(500, null, "Invalid integration URI");
|
||||
}
|
||||
|
||||
// Use passed templates, falling back to integration model's templates
|
||||
Map<String, String> effectiveRequestTemplates = (requestTemplates != null && !requestTemplates.isEmpty())
|
||||
? requestTemplates
|
||||
: integration.getRequestTemplates();
|
||||
Map<String, String> effectiveResponseTemplates = (responseTemplates != null && !responseTemplates.isEmpty())
|
||||
? responseTemplates
|
||||
: integration.getResponseTemplates();
|
||||
|
||||
// Apply request template transformation
|
||||
String transformedPayload = applyRequestTemplate(eventJson, effectiveRequestTemplates,
|
||||
integration.getTemplateSelectionExpression(), stageVariables);
|
||||
|
||||
LOG.debugv("Invoking Lambda function {0} for AWS integration", functionName);
|
||||
|
||||
InvokeResult result = lambdaService.invoke(region, functionName,
|
||||
transformedPayload.getBytes(StandardCharsets.UTF_8), InvocationType.RequestResponse);
|
||||
|
||||
int statusCode = 200;
|
||||
String body = null;
|
||||
String functionError = result.getFunctionError();
|
||||
|
||||
byte[] payload = result.getPayload();
|
||||
if (payload != null && payload.length > 0) {
|
||||
body = new String(payload, StandardCharsets.UTF_8);
|
||||
}
|
||||
|
||||
// Apply response template transformation
|
||||
if (body != null) {
|
||||
body = applyResponseTemplate(body, effectiveResponseTemplates,
|
||||
integration.getTemplateSelectionExpression(), stageVariables, statusCode);
|
||||
}
|
||||
|
||||
return new IntegrationResult(statusCode, body, functionError);
|
||||
}
|
||||
|
||||
/**
|
||||
* Invoke an HTTP endpoint via HTTP_PROXY integration (passthrough, no VTL transformation).
|
||||
* Forwards the event JSON as an HTTP POST to the resolved integration URI and returns
|
||||
* the HTTP response status code and body as the IntegrationResult.
|
||||
*/
|
||||
private IntegrationResult invokeHttpProxy(Integration integration, String eventJson,
|
||||
Map<String, String> stageVariables) {
|
||||
String uri = integration.getIntegrationUri();
|
||||
uri = substituteStageVariables(uri, stageVariables);
|
||||
|
||||
if (uri == null || uri.isEmpty()) {
|
||||
LOG.warnv("HTTP_PROXY integration URI is null or empty");
|
||||
return new IntegrationResult(500, null, "Invalid integration URI");
|
||||
}
|
||||
|
||||
LOG.debugv("Forwarding event to HTTP_PROXY endpoint: {0}", uri);
|
||||
|
||||
try {
|
||||
HttpRequest request = HttpRequest.newBuilder()
|
||||
.uri(URI.create(uri))
|
||||
.header("Content-Type", "application/json")
|
||||
.POST(HttpRequest.BodyPublishers.ofString(eventJson, StandardCharsets.UTF_8))
|
||||
.build();
|
||||
|
||||
HttpResponse<String> response = httpClient.send(request, HttpResponse.BodyHandlers.ofString());
|
||||
|
||||
return new IntegrationResult(response.statusCode(), response.body(), null);
|
||||
} catch (Exception e) {
|
||||
LOG.warnv("HTTP_PROXY integration call failed: {0}", e.getMessage());
|
||||
return new IntegrationResult(500, null, "HTTP_PROXY integration error: " + e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Invoke an HTTP endpoint via HTTP integration with VTL template transformation.
|
||||
* Applies requestTemplates to transform the event before forwarding, and
|
||||
* responseTemplates to transform the HTTP response before returning.
|
||||
* Stage variable substitution is applied to the integrationUri (Requirement 3.3).
|
||||
*/
|
||||
private IntegrationResult invokeHttp(Integration integration, String eventJson,
|
||||
Map<String, String> stageVariables,
|
||||
Map<String, String> requestTemplates,
|
||||
Map<String, String> responseTemplates) {
|
||||
String uri = integration.getIntegrationUri();
|
||||
uri = substituteStageVariables(uri, stageVariables);
|
||||
|
||||
if (uri == null || uri.isEmpty()) {
|
||||
LOG.warnv("HTTP integration URI is null or empty");
|
||||
return new IntegrationResult(500, null, "Invalid integration URI");
|
||||
}
|
||||
|
||||
// Use passed templates, falling back to integration model's templates
|
||||
Map<String, String> effectiveRequestTemplates = (requestTemplates != null && !requestTemplates.isEmpty())
|
||||
? requestTemplates
|
||||
: integration.getRequestTemplates();
|
||||
Map<String, String> effectiveResponseTemplates = (responseTemplates != null && !responseTemplates.isEmpty())
|
||||
? responseTemplates
|
||||
: integration.getResponseTemplates();
|
||||
|
||||
// Apply request template transformation (Requirement 3.1)
|
||||
String transformedPayload = applyRequestTemplate(eventJson, effectiveRequestTemplates,
|
||||
integration.getTemplateSelectionExpression(), stageVariables);
|
||||
|
||||
LOG.debugv("Forwarding transformed event to HTTP endpoint: {0}", uri);
|
||||
|
||||
try {
|
||||
HttpRequest request = HttpRequest.newBuilder()
|
||||
.uri(URI.create(uri))
|
||||
.header("Content-Type", "application/json")
|
||||
.POST(HttpRequest.BodyPublishers.ofString(transformedPayload, StandardCharsets.UTF_8))
|
||||
.build();
|
||||
|
||||
HttpResponse<String> response = httpClient.send(request, HttpResponse.BodyHandlers.ofString());
|
||||
|
||||
int statusCode = response.statusCode();
|
||||
String body = response.body();
|
||||
|
||||
// Apply response template transformation (Requirement 3.2)
|
||||
if (body != null) {
|
||||
body = applyResponseTemplate(body, effectiveResponseTemplates,
|
||||
integration.getTemplateSelectionExpression(), stageVariables, statusCode);
|
||||
}
|
||||
|
||||
return new IntegrationResult(statusCode, body, null);
|
||||
} catch (Exception e) {
|
||||
LOG.warnv("HTTP integration call failed: {0}", e.getMessage());
|
||||
return new IntegrationResult(500, null, "HTTP integration error: " + e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Handle a MOCK integration — no backend invocation.
|
||||
* Evaluates templateSelectionExpression against requestTemplates to determine status code,
|
||||
* then selects matching responseTemplate.
|
||||
* Stage variable substitution is applied to the integrationUri and templateSelectionExpression
|
||||
* per Requirement 8.4 (all integration types).
|
||||
*
|
||||
* If no request templates are provided but templateSelectionExpression is a numeric value,
|
||||
* it is used directly as the status code. This allows MOCK integrations to return non-200
|
||||
* status codes without requiring template configuration.
|
||||
*/
|
||||
private IntegrationResult invokeMock(Integration integration,
|
||||
Map<String, String> stageVariables,
|
||||
Map<String, String> requestTemplates,
|
||||
Map<String, String> responseTemplates) {
|
||||
// Apply stage variable substitution to integrationUri (Requirement 8.4)
|
||||
String uri = integration.getIntegrationUri();
|
||||
if (uri != null) {
|
||||
substituteStageVariables(uri, stageVariables);
|
||||
}
|
||||
|
||||
int statusCode = 200;
|
||||
String body = null;
|
||||
|
||||
String templateSelectionExpression = integration.getTemplateSelectionExpression();
|
||||
// Apply stage variable substitution to templateSelectionExpression
|
||||
if (templateSelectionExpression != null) {
|
||||
templateSelectionExpression = substituteStageVariables(templateSelectionExpression, stageVariables);
|
||||
}
|
||||
|
||||
// Evaluate request templates to determine status code
|
||||
if (templateSelectionExpression != null && requestTemplates != null && !requestTemplates.isEmpty()) {
|
||||
// The templateSelectionExpression for mock integrations typically evaluates to a status code
|
||||
// Try to find a matching request template key
|
||||
String matchedKey = null;
|
||||
for (String key : requestTemplates.keySet()) {
|
||||
if (templateSelectionExpression.contains(key) || key.equals(templateSelectionExpression)) {
|
||||
matchedKey = key;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (matchedKey != null) {
|
||||
try {
|
||||
statusCode = Integer.parseInt(matchedKey);
|
||||
} catch (NumberFormatException e) {
|
||||
// Key is not a numeric status code, keep default 200
|
||||
}
|
||||
}
|
||||
} else if (templateSelectionExpression != null && (requestTemplates == null || requestTemplates.isEmpty())) {
|
||||
// No request templates provided — try to parse templateSelectionExpression directly as a status code.
|
||||
// This supports MOCK integrations configured with a numeric templateSelectionExpression
|
||||
// to return a specific status code without requiring template maps.
|
||||
try {
|
||||
statusCode = Integer.parseInt(templateSelectionExpression);
|
||||
} catch (NumberFormatException e) {
|
||||
// Not a numeric value, keep default 200
|
||||
}
|
||||
}
|
||||
|
||||
// Select matching response template
|
||||
if (responseTemplates != null && !responseTemplates.isEmpty()) {
|
||||
String statusStr = String.valueOf(statusCode);
|
||||
body = responseTemplates.get(statusStr);
|
||||
if (body == null) {
|
||||
// Try to find a default or first available template
|
||||
body = responseTemplates.values().stream().findFirst().orElse(null);
|
||||
}
|
||||
}
|
||||
|
||||
return new IntegrationResult(statusCode, body, null);
|
||||
}
|
||||
|
||||
/**
|
||||
* Apply a request template (VTL) to transform the event payload.
|
||||
* Uses templateSelectionExpression to select which template to apply.
|
||||
* Falls back to the first available template if no match is found.
|
||||
*
|
||||
* @param eventJson the original event JSON
|
||||
* @param requestTemplates the request templates map (keyed by content type or selection key)
|
||||
* @param templateSelectionExpression expression to select which template to use
|
||||
* @param stageVariables stage variables for VTL context
|
||||
* @return the transformed payload, or the original eventJson if no template applies
|
||||
*/
|
||||
private String applyRequestTemplate(String eventJson, Map<String, String> requestTemplates,
|
||||
String templateSelectionExpression,
|
||||
Map<String, String> stageVariables) {
|
||||
if (requestTemplates == null || requestTemplates.isEmpty()) {
|
||||
return eventJson;
|
||||
}
|
||||
|
||||
String template = selectTemplate(requestTemplates, templateSelectionExpression);
|
||||
if (template == null || template.isEmpty()) {
|
||||
return eventJson;
|
||||
}
|
||||
|
||||
VtlTemplateEngine.VtlContext vtlCtx = new VtlTemplateEngine.VtlContext(
|
||||
eventJson, Map.of(), Map.of(), Map.of(), "", "", "", "", "000000000000",
|
||||
stageVariables != null ? stageVariables : Map.of());
|
||||
|
||||
VtlTemplateEngine.EvaluateResult result = vtlEngine.evaluate(template, vtlCtx);
|
||||
return result.body();
|
||||
}
|
||||
|
||||
/**
|
||||
* Apply a response template (VTL) to transform the Lambda response.
|
||||
* Uses templateSelectionExpression to select which template to apply.
|
||||
* Falls back to matching by status code, then the first available template.
|
||||
*
|
||||
* @param responseBody the Lambda response body
|
||||
* @param responseTemplates the response templates map (keyed by status code or selection key)
|
||||
* @param templateSelectionExpression expression to select which template to use
|
||||
* @param stageVariables stage variables for VTL context
|
||||
* @param statusCode the response status code
|
||||
* @return the transformed response body, or the original if no template applies
|
||||
*/
|
||||
private String applyResponseTemplate(String responseBody, Map<String, String> responseTemplates,
|
||||
String templateSelectionExpression,
|
||||
Map<String, String> stageVariables, int statusCode) {
|
||||
if (responseTemplates == null || responseTemplates.isEmpty()) {
|
||||
return responseBody;
|
||||
}
|
||||
|
||||
// Try to select template by templateSelectionExpression first, then by status code
|
||||
String template = selectTemplate(responseTemplates, templateSelectionExpression);
|
||||
if (template == null) {
|
||||
template = responseTemplates.get(String.valueOf(statusCode));
|
||||
}
|
||||
if (template == null) {
|
||||
// Fall back to first available template
|
||||
template = responseTemplates.values().stream().findFirst().orElse(null);
|
||||
}
|
||||
if (template == null || template.isEmpty()) {
|
||||
return responseBody;
|
||||
}
|
||||
|
||||
VtlTemplateEngine.VtlContext vtlCtx = new VtlTemplateEngine.VtlContext(
|
||||
responseBody, Map.of(), Map.of(), Map.of(), "", "", "", "", "000000000000",
|
||||
stageVariables != null ? stageVariables : Map.of());
|
||||
|
||||
VtlTemplateEngine.EvaluateResult result = vtlEngine.evaluate(template, vtlCtx);
|
||||
return result.body();
|
||||
}
|
||||
|
||||
/**
|
||||
* Select a template from the templates map using the templateSelectionExpression.
|
||||
* The expression is matched against template keys.
|
||||
*
|
||||
* @param templates the templates map
|
||||
* @param templateSelectionExpression the selection expression
|
||||
* @return the selected template value, or null if no match
|
||||
*/
|
||||
private String selectTemplate(Map<String, String> templates, String templateSelectionExpression) {
|
||||
if (templates == null || templates.isEmpty()) {
|
||||
return null;
|
||||
}
|
||||
|
||||
if (templateSelectionExpression != null && !templateSelectionExpression.isEmpty()) {
|
||||
// Try exact match with the expression value
|
||||
String template = templates.get(templateSelectionExpression);
|
||||
if (template != null) {
|
||||
return template;
|
||||
}
|
||||
// Try to find a key that the expression contains or matches
|
||||
for (Map.Entry<String, String> entry : templates.entrySet()) {
|
||||
if (templateSelectionExpression.contains(entry.getKey())
|
||||
|| entry.getKey().equals(templateSelectionExpression)) {
|
||||
return entry.getValue();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Fall back to first available template
|
||||
return templates.values().stream().findFirst().orElse(null);
|
||||
}
|
||||
|
||||
/**
|
||||
* Extract Lambda function name from an integration URI.
|
||||
* Delegates to {@link LambdaArnUtils#extractFunctionNameFromUri(String)}.
|
||||
*
|
||||
* @param uri the integration URI (Lambda ARN or function name)
|
||||
* @return the extracted function name, or null if not parseable
|
||||
*/
|
||||
String extractFunctionName(String uri) {
|
||||
return LambdaArnUtils.extractFunctionNameFromUri(uri);
|
||||
}
|
||||
|
||||
/**
|
||||
* Perform stage variable substitution on a URI.
|
||||
* Replaces all ${stageVariables.variableName} occurrences with the corresponding
|
||||
* value from the stageVariables map. Undefined variables are replaced with empty string.
|
||||
*
|
||||
* @param uri the URI containing stage variable references
|
||||
* @param stageVariables the stage variables map (may be null or empty)
|
||||
* @return the URI with all stage variable references substituted
|
||||
*/
|
||||
String substituteStageVariables(String uri, Map<String, String> stageVariables) {
|
||||
if (uri == null) {
|
||||
return null;
|
||||
}
|
||||
if (stageVariables == null) {
|
||||
stageVariables = Collections.emptyMap();
|
||||
}
|
||||
|
||||
Matcher matcher = STAGE_VAR_PATTERN.matcher(uri);
|
||||
StringBuilder result = new StringBuilder();
|
||||
Map<String, String> vars = stageVariables;
|
||||
|
||||
while (matcher.find()) {
|
||||
String variableName = matcher.group(1);
|
||||
String replacement = vars.getOrDefault(variableName, "");
|
||||
matcher.appendReplacement(result, Matcher.quoteReplacement(replacement));
|
||||
}
|
||||
matcher.appendTail(result);
|
||||
|
||||
return result.toString();
|
||||
}
|
||||
}
|
||||
+297
@@ -0,0 +1,297 @@
|
||||
package io.github.hectorvent.floci.services.apigatewayv2.websocket;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.databind.node.ArrayNode;
|
||||
import com.fasterxml.jackson.databind.node.ObjectNode;
|
||||
import jakarta.enterprise.context.ApplicationScoped;
|
||||
import jakarta.inject.Inject;
|
||||
import org.jboss.logging.Logger;
|
||||
|
||||
import java.time.ZoneOffset;
|
||||
import java.time.ZonedDateTime;
|
||||
import java.time.format.DateTimeFormatter;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Map;
|
||||
import java.util.UUID;
|
||||
|
||||
/**
|
||||
* Constructs AWS-compatible WebSocket proxy event JSON payloads for Lambda invocations.
|
||||
*
|
||||
* Produces CONNECT, MESSAGE, DISCONNECT, and Lambda REQUEST authorizer event formats
|
||||
* matching the AWS API Gateway v2 WebSocket proxy integration contract.
|
||||
*/
|
||||
@ApplicationScoped
|
||||
public class WebSocketProxyEventBuilder {
|
||||
|
||||
private static final Logger LOG = Logger.getLogger(WebSocketProxyEventBuilder.class);
|
||||
private static final DateTimeFormatter REQUEST_TIME_FORMATTER =
|
||||
DateTimeFormatter.ofPattern("dd/MMM/yyyy:HH:mm:ss +0000", Locale.ENGLISH);
|
||||
|
||||
@Inject
|
||||
ObjectMapper objectMapper;
|
||||
|
||||
/**
|
||||
* Build a CONNECT event from the upgrade request.
|
||||
*/
|
||||
public String buildConnectEvent(String connectionId, String apiId, String stageName,
|
||||
String region, long connectedAt,
|
||||
Map<String, List<String>> headers,
|
||||
Map<String, List<String>> queryParams,
|
||||
String sourceIp, String userAgent,
|
||||
Map<String, String> stageVariables,
|
||||
Map<String, Object> authorizerContext) {
|
||||
ObjectNode event = objectMapper.createObjectNode();
|
||||
|
||||
putHeaders(event, headers);
|
||||
putMultiValueHeaders(event, headers);
|
||||
putQueryStringParameters(event, queryParams);
|
||||
putMultiValueQueryStringParameters(event, queryParams);
|
||||
putStageVariables(event, stageVariables);
|
||||
|
||||
ObjectNode requestContext = buildRequestContext(connectionId, "$connect", "CONNECT",
|
||||
apiId, stageName, region, connectedAt, sourceIp, userAgent);
|
||||
|
||||
// Include authorizer context in requestContext if present
|
||||
if (authorizerContext != null && !authorizerContext.isEmpty()) {
|
||||
ObjectNode authorizerNode = objectMapper.valueToTree(authorizerContext);
|
||||
requestContext.set("authorizer", authorizerNode);
|
||||
}
|
||||
|
||||
event.set("requestContext", requestContext);
|
||||
|
||||
event.put("isBase64Encoded", false);
|
||||
|
||||
try {
|
||||
return objectMapper.writeValueAsString(event);
|
||||
} catch (Exception e) {
|
||||
throw new RuntimeException("Failed to serialize CONNECT proxy event", e);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Build a MESSAGE event from an incoming WebSocket message.
|
||||
*/
|
||||
public String buildMessageEvent(String connectionId, String routeKey, String apiId,
|
||||
String stageName, String region, long connectedAt,
|
||||
String body, String sourceIp, String userAgent,
|
||||
Map<String, String> stageVariables) {
|
||||
return buildMessageEvent(connectionId, routeKey, apiId, stageName, region, connectedAt,
|
||||
body, sourceIp, userAgent, stageVariables, false);
|
||||
}
|
||||
|
||||
/**
|
||||
* Build a MESSAGE event from an incoming WebSocket message with explicit base64 encoding flag.
|
||||
*
|
||||
* @param isBase64Encoded true if the body is base64-encoded binary data
|
||||
*/
|
||||
public String buildMessageEvent(String connectionId, String routeKey, String apiId,
|
||||
String stageName, String region, long connectedAt,
|
||||
String body, String sourceIp, String userAgent,
|
||||
Map<String, String> stageVariables, boolean isBase64Encoded) {
|
||||
ObjectNode event = objectMapper.createObjectNode();
|
||||
|
||||
ObjectNode requestContext = buildRequestContext(connectionId, routeKey, "MESSAGE",
|
||||
apiId, stageName, region, connectedAt, sourceIp, userAgent);
|
||||
event.set("requestContext", requestContext);
|
||||
|
||||
if (body != null) {
|
||||
event.put("body", body);
|
||||
} else {
|
||||
event.putNull("body");
|
||||
}
|
||||
|
||||
putStageVariables(event, stageVariables);
|
||||
event.put("isBase64Encoded", isBase64Encoded);
|
||||
|
||||
try {
|
||||
return objectMapper.writeValueAsString(event);
|
||||
} catch (Exception e) {
|
||||
throw new RuntimeException("Failed to serialize MESSAGE proxy event", e);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Build a DISCONNECT event.
|
||||
*/
|
||||
public String buildDisconnectEvent(String connectionId, String apiId, String stageName,
|
||||
String region, long connectedAt,
|
||||
String sourceIp, String userAgent,
|
||||
Map<String, String> stageVariables) {
|
||||
ObjectNode event = objectMapper.createObjectNode();
|
||||
|
||||
ObjectNode requestContext = buildRequestContext(connectionId, "$disconnect", "DISCONNECT",
|
||||
apiId, stageName, region, connectedAt, sourceIp, userAgent);
|
||||
event.set("requestContext", requestContext);
|
||||
|
||||
event.putNull("body");
|
||||
putStageVariables(event, stageVariables);
|
||||
event.put("isBase64Encoded", false);
|
||||
|
||||
try {
|
||||
return objectMapper.writeValueAsString(event);
|
||||
} catch (Exception e) {
|
||||
throw new RuntimeException("Failed to serialize DISCONNECT proxy event", e);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Build a Lambda REQUEST authorizer event for $connect.
|
||||
*/
|
||||
public String buildAuthorizerEvent(String connectionId, String apiId, String stageName,
|
||||
String region, long connectedAt,
|
||||
Map<String, List<String>> headers,
|
||||
Map<String, List<String>> queryParams,
|
||||
String sourceIp, String userAgent,
|
||||
Map<String, String> stageVariables) {
|
||||
ObjectNode event = objectMapper.createObjectNode();
|
||||
|
||||
event.put("type", "REQUEST");
|
||||
event.put("methodArn", buildMethodArn(region, apiId, stageName));
|
||||
|
||||
putHeaders(event, headers);
|
||||
putMultiValueHeaders(event, headers);
|
||||
putQueryStringParameters(event, queryParams);
|
||||
putMultiValueQueryStringParameters(event, queryParams);
|
||||
putStageVariables(event, stageVariables);
|
||||
|
||||
ObjectNode requestContext = objectMapper.createObjectNode();
|
||||
requestContext.put("apiId", apiId);
|
||||
requestContext.put("stage", stageName);
|
||||
requestContext.put("connectionId", connectionId);
|
||||
requestContext.put("domainName", buildDomainName(apiId, region));
|
||||
|
||||
String requestId = UUID.randomUUID().toString();
|
||||
requestContext.put("requestId", requestId);
|
||||
|
||||
long now = System.currentTimeMillis();
|
||||
requestContext.put("requestTime", formatRequestTime(now));
|
||||
requestContext.put("requestTimeEpoch", now);
|
||||
|
||||
ObjectNode identity = requestContext.putObject("identity");
|
||||
identity.put("sourceIp", sourceIp != null ? sourceIp : "127.0.0.1");
|
||||
identity.put("userAgent", userAgent != null ? userAgent : "");
|
||||
|
||||
requestContext.put("eventType", "CONNECT");
|
||||
|
||||
event.set("requestContext", requestContext);
|
||||
|
||||
try {
|
||||
return objectMapper.writeValueAsString(event);
|
||||
} catch (Exception e) {
|
||||
throw new RuntimeException("Failed to serialize authorizer event", e);
|
||||
}
|
||||
}
|
||||
|
||||
private ObjectNode buildRequestContext(String connectionId, String routeKey, String eventType,
|
||||
String apiId, String stageName, String region,
|
||||
long connectedAt, String sourceIp, String userAgent) {
|
||||
ObjectNode ctx = objectMapper.createObjectNode();
|
||||
|
||||
ctx.put("routeKey", routeKey);
|
||||
ctx.put("eventType", eventType);
|
||||
|
||||
String extendedRequestId = UUID.randomUUID().toString();
|
||||
ctx.put("extendedRequestId", extendedRequestId);
|
||||
|
||||
long now = System.currentTimeMillis();
|
||||
ctx.put("requestTime", formatRequestTime(now));
|
||||
ctx.put("messageDirection", "IN");
|
||||
ctx.put("stage", stageName);
|
||||
ctx.put("connectedAt", connectedAt);
|
||||
ctx.put("requestTimeEpoch", now);
|
||||
|
||||
ObjectNode identity = ctx.putObject("identity");
|
||||
identity.put("sourceIp", sourceIp != null ? sourceIp : "127.0.0.1");
|
||||
identity.put("userAgent", userAgent != null ? userAgent : "");
|
||||
|
||||
String requestId = UUID.randomUUID().toString();
|
||||
ctx.put("requestId", requestId);
|
||||
ctx.put("domainName", buildDomainName(apiId, region));
|
||||
ctx.put("connectionId", connectionId);
|
||||
ctx.put("apiId", apiId);
|
||||
|
||||
return ctx;
|
||||
}
|
||||
|
||||
private void putHeaders(ObjectNode event, Map<String, List<String>> headers) {
|
||||
if (headers != null && !headers.isEmpty()) {
|
||||
ObjectNode headersNode = event.putObject("headers");
|
||||
for (Map.Entry<String, List<String>> entry : headers.entrySet()) {
|
||||
if (entry.getValue() != null && !entry.getValue().isEmpty()) {
|
||||
headersNode.put(entry.getKey(), entry.getValue().get(0));
|
||||
}
|
||||
}
|
||||
} else {
|
||||
event.putNull("headers");
|
||||
}
|
||||
}
|
||||
|
||||
private void putMultiValueHeaders(ObjectNode event, Map<String, List<String>> headers) {
|
||||
if (headers != null && !headers.isEmpty()) {
|
||||
ObjectNode mvHeaders = event.putObject("multiValueHeaders");
|
||||
for (Map.Entry<String, List<String>> entry : headers.entrySet()) {
|
||||
if (entry.getValue() != null && !entry.getValue().isEmpty()) {
|
||||
ArrayNode arr = mvHeaders.putArray(entry.getKey());
|
||||
for (String val : entry.getValue()) {
|
||||
arr.add(val);
|
||||
}
|
||||
}
|
||||
}
|
||||
} else {
|
||||
event.putNull("multiValueHeaders");
|
||||
}
|
||||
}
|
||||
|
||||
private void putQueryStringParameters(ObjectNode event, Map<String, List<String>> queryParams) {
|
||||
if (queryParams != null && !queryParams.isEmpty()) {
|
||||
ObjectNode qsp = event.putObject("queryStringParameters");
|
||||
for (Map.Entry<String, List<String>> entry : queryParams.entrySet()) {
|
||||
if (entry.getValue() != null && !entry.getValue().isEmpty()) {
|
||||
qsp.put(entry.getKey(), entry.getValue().get(0));
|
||||
}
|
||||
}
|
||||
} else {
|
||||
event.putNull("queryStringParameters");
|
||||
}
|
||||
}
|
||||
|
||||
private void putMultiValueQueryStringParameters(ObjectNode event, Map<String, List<String>> queryParams) {
|
||||
if (queryParams != null && !queryParams.isEmpty()) {
|
||||
ObjectNode mvQsp = event.putObject("multiValueQueryStringParameters");
|
||||
for (Map.Entry<String, List<String>> entry : queryParams.entrySet()) {
|
||||
if (entry.getValue() != null && !entry.getValue().isEmpty()) {
|
||||
ArrayNode arr = mvQsp.putArray(entry.getKey());
|
||||
for (String val : entry.getValue()) {
|
||||
arr.add(val);
|
||||
}
|
||||
}
|
||||
}
|
||||
} else {
|
||||
event.putNull("multiValueQueryStringParameters");
|
||||
}
|
||||
}
|
||||
|
||||
private void putStageVariables(ObjectNode event, Map<String, String> stageVariables) {
|
||||
if (stageVariables != null && !stageVariables.isEmpty()) {
|
||||
ObjectNode svNode = event.putObject("stageVariables");
|
||||
stageVariables.forEach(svNode::put);
|
||||
} else {
|
||||
event.putNull("stageVariables");
|
||||
}
|
||||
}
|
||||
|
||||
private String buildDomainName(String apiId, String region) {
|
||||
return apiId + ".execute-api." + region + ".amazonaws.com";
|
||||
}
|
||||
|
||||
private String buildMethodArn(String region, String apiId, String stageName) {
|
||||
return "arn:aws:execute-api:" + region + ":000000000000:" + apiId + "/" + stageName + "/$connect";
|
||||
}
|
||||
|
||||
private String formatRequestTime(long epochMillis) {
|
||||
ZonedDateTime time = ZonedDateTime.ofInstant(
|
||||
java.time.Instant.ofEpochMilli(epochMillis), ZoneOffset.UTC);
|
||||
return REQUEST_TIME_FORMATTER.format(time);
|
||||
}
|
||||
}
|
||||
+101
@@ -0,0 +1,101 @@
|
||||
package io.github.hectorvent.floci.services.apigatewayv2.websocket;
|
||||
|
||||
import io.github.hectorvent.floci.core.common.AwsException;
|
||||
import io.github.hectorvent.floci.services.apigatewayv2.ApiGatewayV2Service;
|
||||
import io.github.hectorvent.floci.services.apigatewayv2.model.Api;
|
||||
import io.github.hectorvent.floci.services.apigatewayv2.model.Route;
|
||||
import jakarta.enterprise.context.ApplicationScoped;
|
||||
import jakarta.inject.Inject;
|
||||
import org.jboss.logging.Logger;
|
||||
|
||||
/**
|
||||
* Resolves the target route for an incoming WebSocket message based on the API's
|
||||
* routeSelectionExpression and configured routes.
|
||||
*
|
||||
* Extracted from WebSocketHandler for independent testability and to keep the handler thin.
|
||||
*/
|
||||
@ApplicationScoped
|
||||
public class WebSocketRouteResolver {
|
||||
|
||||
private static final Logger LOG = Logger.getLogger(WebSocketRouteResolver.class);
|
||||
|
||||
private final ApiGatewayV2Service apiGatewayV2Service;
|
||||
private final RouteSelectionEvaluator routeSelectionEvaluator;
|
||||
|
||||
@Inject
|
||||
public WebSocketRouteResolver(ApiGatewayV2Service apiGatewayV2Service,
|
||||
RouteSelectionEvaluator routeSelectionEvaluator) {
|
||||
this.apiGatewayV2Service = apiGatewayV2Service;
|
||||
this.routeSelectionEvaluator = routeSelectionEvaluator;
|
||||
}
|
||||
|
||||
/**
|
||||
* Result of route resolution.
|
||||
*
|
||||
* @param route the matched route (null if no route found)
|
||||
* @param effectiveRouteKey the route key to use in the proxy event
|
||||
* @param errorMessage error message to send to client if no route found (null if route was found)
|
||||
*/
|
||||
public record RouteResolution(Route route, String effectiveRouteKey, String errorMessage) {
|
||||
|
||||
public boolean hasRoute() {
|
||||
return route != null;
|
||||
}
|
||||
|
||||
public static RouteResolution matched(Route route, String effectiveRouteKey) {
|
||||
return new RouteResolution(route, effectiveRouteKey, null);
|
||||
}
|
||||
|
||||
public static RouteResolution noRoute(String errorMessage) {
|
||||
return new RouteResolution(null, null, errorMessage);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolve the target route for a message.
|
||||
*
|
||||
* @param region the AWS region
|
||||
* @param apiId the API ID
|
||||
* @param message the raw message body
|
||||
* @return RouteResolution with the matched route or an error message
|
||||
*/
|
||||
public RouteResolution resolve(String region, String apiId, String message) {
|
||||
// Load the API to get routeSelectionExpression
|
||||
Api api;
|
||||
try {
|
||||
api = apiGatewayV2Service.getApi(region, apiId);
|
||||
} catch (AwsException e) {
|
||||
LOG.warnv("Failed to load API {0} for message routing: {1}", apiId, e.getMessage());
|
||||
return RouteResolution.noRoute("Internal server error");
|
||||
}
|
||||
|
||||
String routeSelectionExpression = api.getRouteSelectionExpression();
|
||||
|
||||
// Evaluate routeSelectionExpression against the message
|
||||
String routeKey = routeSelectionEvaluator.evaluate(routeSelectionExpression, message);
|
||||
|
||||
// Look up matching route
|
||||
Route route = null;
|
||||
if (routeKey != null) {
|
||||
route = apiGatewayV2Service.findRouteByKey(region, apiId, routeKey);
|
||||
}
|
||||
|
||||
// Fall back to $default if no match
|
||||
if (route == null) {
|
||||
route = apiGatewayV2Service.findRouteByKey(region, apiId, "$default");
|
||||
}
|
||||
|
||||
// If no route found (no match and no $default)
|
||||
if (route == null) {
|
||||
if (routeKey == null) {
|
||||
return RouteResolution.noRoute("Could not route message");
|
||||
} else {
|
||||
return RouteResolution.noRoute("No route found");
|
||||
}
|
||||
}
|
||||
|
||||
// Determine the effective route key for the proxy event
|
||||
String effectiveRouteKey = routeKey != null ? routeKey : "$default";
|
||||
return RouteResolution.matched(route, effectiveRouteKey);
|
||||
}
|
||||
}
|
||||
@@ -161,4 +161,41 @@ public final class LambdaArnUtils {
|
||||
private static AwsException invalid(String message) {
|
||||
return new AwsException("InvalidParameterValueException", message, 400);
|
||||
}
|
||||
|
||||
/**
|
||||
* Extracts the Lambda function name from an API Gateway integration URI.
|
||||
* Handles formats like:
|
||||
* <ul>
|
||||
* <li>{@code arn:aws:lambda:us-east-1:000000000000:function:myFn/invocations}</li>
|
||||
* <li>{@code arn:aws:lambda:us-east-1:000000000000:function:myFn}</li>
|
||||
* <li>{@code myFn} (bare function name)</li>
|
||||
* </ul>
|
||||
*
|
||||
* @param uri the integration URI (may be null)
|
||||
* @return the extracted function name, or null if the URI is null or unparseable
|
||||
*/
|
||||
public static String extractFunctionNameFromUri(String uri) {
|
||||
if (uri == null) {
|
||||
return null;
|
||||
}
|
||||
try {
|
||||
// Parse as a full ARN — resource is "function:myFn" or "function:myFn/invocations"
|
||||
String resource = AwsArnUtils.parse(uri).resource();
|
||||
String[] parts = resource.split("/");
|
||||
// API Gateway v1 style: resource is "path/2015-03-31/functions/{lambdaArn}/invocations"
|
||||
// In this case recurse on the embedded Lambda ARN
|
||||
if (parts.length >= 4 && "path".equals(parts[0]) && "functions".equals(parts[2])) {
|
||||
// parts[3] onwards is the embedded Lambda ARN
|
||||
String embeddedArn = String.join("/", java.util.Arrays.copyOfRange(parts, 3, parts.length));
|
||||
return extractFunctionNameFromUri(embeddedArn);
|
||||
}
|
||||
// Standard Lambda ARN: parts[0] is "function:myFn", strip the "function:" prefix
|
||||
String functionPart = parts[0];
|
||||
int colon = functionPart.lastIndexOf(':');
|
||||
return colon >= 0 ? functionPart.substring(colon + 1) : functionPart;
|
||||
} catch (IllegalArgumentException e) {
|
||||
// Not a valid ARN — treat the entire URI as the function name
|
||||
return uri;
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user