feat(apigatewayv2): route execute-api hosts to WebSocket $connect and @connections (#2188)

Consolidates AWS-style execute-api virtual-host support for WebSocket APIs onto the
existing ApiGatewayExecuteApiHostFilter (added in #2054) plus the WebSocket handler,
instead of adding a second host filter.

- @connections (#1846): ApiGatewayExecuteApiHostFilter now also rewrites a WebSocket
  API's @connections management calls (.../{stage}/@connections/{id}) to the canonical
  /execute-api/{apiId}/{stage}/... route, behind the same disableExecuteApiEndpoint->404
  check. It previously bailed for non-HTTP APIs, so @connections on the execute-api host
  was swallowed by the S3 controller.
- $connect (#1871): WebSocketHandler accepts the execute-api host for the WS handshake
  and resolves the API region -- from the host's region label when present, else a
  cross-region apiId lookup (ApiGatewayV2Service.resolveApiRegion) -- fixing the 403 for
  APIs created in a non-default region.
- Widen the filter host regex to accept the region-bearing AWS form
  ({apiId}.execute-api.{region}.localhost|amazonaws.com) alongside Floci's regionless
  built-in suffixes (.execute-api.localhost.floci.io / .localstack.cloud).
- Fix RegionResolver.resolveRegionFromHost to treat only a real region label as the
  region and return null for the built-in suffixes -- the old pattern parsed "localhost"
  as the region and broke the lookup.
- Remove the separate ExecuteApiSubdomainFilter; host parsing is shared via
  ApiGatewayExecuteApiHostFilter.extractApiId.
- Update docs and add Java unit + Node SDK compatibility coverage for both host forms.

Closes #1871
Closes #1846
This commit is contained in:
Dixit R Jain authored and GitHub committed 2026-08-13 14:40:50 -04:00
1 parent 9ebf9feb54
commit 45bb37f1fb
7 files changed
+594 -24

No files matched your search

@@ -17,6 +17,17 @@ public class RegionResolver {
private static final Pattern CREDENTIAL_REGION_PATTERN =
Pattern.compile("Credential=\\S+/\\d{8}/([^/]+)/");
// Matches ONLY a real AWS region label immediately after ".execute-api.", e.g.
// abc123.execute-api.ap-northeast-2.localhost:4566 -> "ap-northeast-2"
// abc123.execute-api.us-east-1.amazonaws.com -> "us-east-1"
// A region id is {geo}-{direction(s)}-{number} (us-east-1, ap-northeast-2, us-gov-east-1).
// This deliberately does NOT match Floci's built-in execute-api DNS suffixes
// (…execute-api.localhost, …execute-api.localhost.floci.io, …execute-api.localhost.localstack.cloud):
// those carry no region label, so the older `[a-zA-Z0-9-]+` pattern mis-parsed "localhost"
// as the region and broke the region-scoped API lookup. Case-insensitive per DNS.
private static final Pattern HOST_REGION_PATTERN =
Pattern.compile("\\.execute-api\\.([a-z]{2}-[a-z-]+-\\d+)\\.", Pattern.CASE_INSENSITIVE);
private final String defaultRegion;
private final String defaultAccountId;
@@ -82,6 +93,27 @@ public class RegionResolver {
return matcher.find() ? matcher.group(1) : null;
}
/**
* Resolves the AWS region embedded in a region-bearing execute-api virtual host, e.g.
* {@code {apiId}.execute-api.{region}.localhost:4566} or the real
* {@code {apiId}.execute-api.{region}.amazonaws.com}. A WebSocket handshake carries no
* SigV4 {@code Authorization} header, so a region-bearing host is the only place the region
* is available there. Returns {@code null} when the host is null, is not an execute-api host,
* or carries no region label — including Floci's built-in suffixes
* ({@code …execute-api.localhost[.floci.io|.localstack.cloud]}), which have no region — so the
* caller falls back (default region and/or a cross-region apiId lookup) rather than treating
* {@code localhost} as a region.
*/
public String resolveRegionFromHost(String host) {
if (host == null || host.isEmpty()) {
return null;
}
Matcher matcher = HOST_REGION_PATTERN.matcher(host);
// Region ids are lowercase (as are the region-scoped API store keys); normalize an
// uppercase host label like US-EAST-1 so the lookup does not 403 on a casing mismatch.
return matcher.find() ? matcher.group(1).toLowerCase(java.util.Locale.ROOT) : null;
}
public String getDefaultRegion() {
return defaultRegion;
}
@@ -25,8 +25,18 @@ import java.util.regex.Pattern;
public class ApiGatewayExecuteApiHostFilter implements ContainerRequestFilter {
private static final Logger LOG = Logger.getLogger(ApiGatewayExecuteApiHostFilter.class);
// Accepts both the region-bearing AWS shape and Floci's built-in DNS suffixes:
// {apiId}.execute-api.{region}.localhost[:port] (local, region-bearing)
// {apiId}.execute-api.{region}.amazonaws.com (real AWS shape)
// {apiId}.execute-api.localhost.floci.io (built-in suffix, regionless)
// {apiId}.execute-api.localhost.localstack.cloud (built-in suffix, regionless)
// AWS's invoke URL carries the region in the hostname, so the region-bearing form is the
// primary target; the regionless built-in suffixes are kept for local convenience (region is
// then recovered from the SigV4 scope or a cross-region apiId lookup). Group 1 = apiId.
private static final Pattern EXECUTE_API_HOST = Pattern.compile(
"^([a-z0-9-]+)\\.execute-api\\.localhost\\.(?:floci\\.io|localstack\\.cloud)$",
"^([a-z0-9-]+)\\.execute-api\\."
+ "(?:[a-z]{2}-[a-z-]+-\\d+\\.(?:localhost|amazonaws\\.com)"
+ "|localhost\\.(?:floci\\.io|localstack\\.cloud))$",
Pattern.CASE_INSENSITIVE);
private final ApiGatewayLookup apiGatewayLookup;
@@ -84,11 +94,35 @@ public class ApiGatewayExecuteApiHostFilter implements ContainerRequestFilter {
}
String apiId = matcher.group(1).toLowerCase(Locale.ROOT);
String preferredRegion = regionResolver.resolveRegionFromAuth(
requestContext.getHeaderString("Authorization"));
// Region: the host label when it is a real AWS region (…execute-api.{region}.…), else the
// SigV4 credential scope. The cross-region apiId scan (resolveApiRegion) is the final
// fallback so an API created outside the default region still resolves — including on the
// regionless built-in suffixes, which carry no region label (issue #1871).
String hostRegion = regionResolver.resolveRegionFromHost(host);
String preferredRegion = hostRegion != null
? hostRegion
: regionResolver.resolveRegionFromAuth(requestContext.getHeaderString("Authorization"));
String region = apiGatewayLookup.resolveApiRegion(preferredRegion, apiId);
URI originalUri = requestContext.getUriInfo().getRequestUri();
String originalPath = originalUri.getRawPath();
// Host matching alone cannot tell whether this request was already rewritten: the Host
// header still names the execute-api subdomain afterwards. Rewriting twice would produce
// /execute-api/{apiId}/execute-api/{apiId}/... and a 404, so bail out if another
// execute-api filter got here first.
if (originalPath != null && originalPath.startsWith("/execute-api/")) {
return;
}
try {
if (!"HTTP".equals(apiGatewayLookup.protocolType(region, apiId))) {
String protocolType = apiGatewayLookup.protocolType(region, apiId);
// HTTP APIs route all their invoke traffic through this filter. WEBSOCKET APIs route
// ONLY their @connections management calls (issue #1846) — the $connect upgrade itself
// is a Vert.x WebSocket handshake handled earlier by WebSocketHandler, never here.
boolean routable = "HTTP".equals(protocolType)
|| ("WEBSOCKET".equals(protocolType) && isConnectionsManagementPath(originalPath));
if (!routable) {
return;
}
if (apiGatewayLookup.executeApiEndpointDisabled(region, apiId)) {
@@ -99,22 +133,11 @@ public class ApiGatewayExecuteApiHostFilter implements ContainerRequestFilter {
return;
}
} catch (AwsException e) {
LOG.debugv(e, "Execute API host did not resolve to an HTTP API: apiId={0}, region={1}",
LOG.debugv(e, "Execute API host did not resolve to a routable API: apiId={0}, region={1}",
apiId, region);
return;
}
URI originalUri = requestContext.getUriInfo().getRequestUri();
String originalPath = originalUri.getRawPath();
// Host matching alone cannot tell whether this request was already rewritten: the Host
// header still names the execute-api subdomain afterwards. Rewriting twice would produce
// /execute-api/{apiId}/execute-api/{apiId}/... and a 404, so bail out if another
// execute-api filter got here first.
if (originalPath != null && originalPath.startsWith("/execute-api/")) {
return;
}
String path = originalPath == null ? "" : stripLeadingSlash(originalPath);
String firstSegment = firstSegment(path);
@@ -161,6 +184,28 @@ public class ApiGatewayExecuteApiHostFilter implements ContainerRequestFilter {
void requireStage(String region, String apiId, String stageName);
}
/**
* Extracts the {@code apiId} from an execute-api virtual host, or {@code null} when the host
* is not an execute-api host. Shared with the WebSocket {@code $connect} handler so the host
* grammar lives in exactly one place (this filter and the handler must agree on which hosts
* are execute-api hosts).
*/
public static String extractApiId(String host) {
if (host == null) {
return null;
}
Matcher matcher = EXECUTE_API_HOST.matcher(stripPort(host));
return matcher.matches() ? matcher.group(1).toLowerCase(Locale.ROOT) : null;
}
/**
* True when the path is a WebSocket {@code @connections} management route,
* {@code /{stage}/@connections[/{connectionId}]} (raw or percent-encoded {@code @}).
*/
private static boolean isConnectionsManagementPath(String path) {
return path != null && (path.contains("/@connections") || path.contains("/%40connections"));
}
private static String stripPort(String host) {
int colonIndex = host.lastIndexOf(':');
if (colonIndex > 0) {
@@ -74,8 +74,68 @@ public class WebSocketHandler {
* This runs before JAX-RS routing and intercepts WebSocket upgrade requests.
*/
void init(@Observes Router router) {
// Path form: ws://localhost:4566/ws/{apiId}/{stage}
router.route("/ws/*").handler(this::handleWebSocketUpgrade);
LOG.debug("Registered WebSocket handler on /ws/*");
// AWS-style subdomain host form: ws://{apiId}.execute-api.{region}.localhost:4566/{stage}
// The connect URL is a single stage segment; a host+Upgrade check inside the handler
// keeps this route transparent to every other request (issue #1871).
router.route("/:stage").handler(this::handleSubdomainWebSocketUpgrade);
LOG.debug("Registered WebSocket handler on /ws/* and execute-api subdomain hosts");
}
/**
* Handle a WebSocket upgrade addressed with the AWS-style execute-api subdomain host,
* {@code ws://{apiId}.execute-api.{region}.localhost:4566/{stage}} (also the regionless
* built-in suffixes, e.g. {@code …execute-api.localhost.floci.io}). The apiId comes from the
* host and the stage from the single path segment. The region is taken from the host when it
* carries one, else the default; a cross-region apiId lookup then resolves an API created
* outside that region (issue #1871). Host parsing is shared with
* {@link io.github.hectorvent.floci.services.apigateway.ApiGatewayExecuteApiHostFilter} so the
* filter and this handler agree on the host grammar. Any request that is not a WebSocket
* upgrade on an execute-api host is passed through untouched so JAX-RS (and that filter, which
* routes {@code @connections}) handle it.
*/
private void handleSubdomainWebSocketUpgrade(RoutingContext ctx) {
String host = resolveRequestHost(ctx);
String apiId = io.github.hectorvent.floci.services.apigateway.ApiGatewayExecuteApiHostFilter.extractApiId(host);
if (apiId == null) {
ctx.next();
return;
}
String upgrade = ctx.request().getHeader("Upgrade");
if (upgrade == null || !"websocket".equalsIgnoreCase(upgrade)) {
// Non-WebSocket traffic on the execute-api host (e.g. @connections) — defer to JAX-RS.
ctx.next();
return;
}
String stageName = ctx.pathParam("stage");
if (stageName == null || stageName.isEmpty()) {
ctx.response().setStatusCode(403).end();
return;
}
String hostRegion = regionResolver.resolveRegionFromHost(host);
String preferredRegion = hostRegion != null ? hostRegion : regionResolver.getDefaultRegion();
// Cross-region apiId scan: resolves an API created outside the preferred region, and is
// the fallback for the regionless built-in suffixes that carry no region label.
String region = apiGatewayV2Service.resolveApiRegion(preferredRegion, apiId);
processUpgrade(ctx, apiId, stageName, region);
}
/**
* Resolve the request authority: the {@code Host} header (HTTP/1.1), falling back to the
* URI authority ({@code :authority}) for HTTP/2.
*/
private static String resolveRequestHost(RoutingContext ctx) {
String host = ctx.request().getHeader("Host");
if (host != null) {
return host;
}
io.vertx.core.net.HostAndPort authority = ctx.request().authority();
return authority != null ? authority.host() : null;
}
/**
@@ -99,9 +159,17 @@ public class WebSocketHandler {
// 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
// Resolve region from the request Authorization header, or the execute-api host.
String region = resolveRegionFromVertxRequest(ctx);
processUpgrade(ctx, apiId, stageName, region);
}
/**
* Validate the API and stage, run the $connect lifecycle, and complete the upgrade.
* Shared by the path form ({@code /ws/{apiId}/{stage}}) and the AWS-style execute-api
* subdomain host route.
*/
private void processUpgrade(RoutingContext ctx, String apiId, String stageName, String region) {
// Validate the API exists and is a WEBSOCKET protocol API
Api api;
try {
@@ -680,12 +748,15 @@ public class WebSocketHandler {
*/
private String resolveRegionFromVertxRequest(RoutingContext ctx) {
String authHeader = ctx.request().getHeader("Authorization");
if (authHeader == null || authHeader.isEmpty()) {
return regionResolver.getDefaultRegion();
if (authHeader != null && !authHeader.isEmpty()) {
// Use a simple JAX-RS HttpHeaders adapter to delegate to RegionResolver
jakarta.ws.rs.core.HttpHeaders headers = new SimpleHttpHeaders(authHeader);
return regionResolver.resolveRegion(headers);
}
// Use a simple JAX-RS HttpHeaders adapter to delegate to RegionResolver
jakarta.ws.rs.core.HttpHeaders headers = new SimpleHttpHeaders(authHeader);
return regionResolver.resolveRegion(headers);
// A WebSocket handshake carries no SigV4 Authorization header, so fall back to the
// region embedded in an execute-api subdomain host, else the configured default.
String region = regionResolver.resolveRegionFromHost(resolveRequestHost(ctx));
return region != null ? region : regionResolver.getDefaultRegion();
}
/**