diff --git a/compatibility-tests/sdk-test-node/tests/apigatewayv2-execute-api-subdomain.test.ts b/compatibility-tests/sdk-test-node/tests/apigatewayv2-execute-api-subdomain.test.ts new file mode 100644 index 0000000000..d8256e8979 --- /dev/null +++ b/compatibility-tests/sdk-test-node/tests/apigatewayv2-execute-api-subdomain.test.ts @@ -0,0 +1,292 @@ +/** + * API Gateway v2 execute-api host compatibility tests. + * + * Validates AWS-style virtual-host addressing for WebSocket APIs. Floci accepts both a + * region-bearing host (mirroring AWS's `{apiId}.execute-api.{region}.amazonaws.com`, locally + * `{apiId}.execute-api.{region}.localhost:4566`) and its regionless built-in suffix + * (`{apiId}.execute-api.localhost.floci.io:4566`): + * + * - #1846: the `@connections` Management API reaches the API Gateway controller + * via the execute-api host instead of being swallowed by the S3 controller. + * - #1871: a WebSocket `$connect` addressed via the execute-api host resolves an API + * created in a non-default region (from the host region label when present, else a + * cross-region apiId lookup) so it no longer returns 403. + * - The regionless built-in suffix must NOT be mis-parsed as region `localhost` + * (the defect that consolidating onto `ApiGatewayExecuteApiHostFilter` fixes). + * + * Routing is exercised deterministically by overriding the `Host` header to the + * execute-api form while the connection still targets the real test endpoint — this + * avoids depending on wildcard `*.localhost` DNS resolution. + */ + +import { describe, it, expect, beforeAll, afterAll } from 'vitest'; +import { + ApiGatewayV2Client, + CreateApiCommand, + DeleteApiCommand, + CreateIntegrationCommand, + CreateRouteCommand, + CreateRouteResponseCommand, + CreateStageCommand, + CreateDeploymentCommand, +} from '@aws-sdk/client-apigatewayv2'; +import { + ApiGatewayManagementApiClient, + PostToConnectionCommand, + GetConnectionCommand, + DeleteConnectionCommand, +} from '@aws-sdk/client-apigatewaymanagementapi'; +import { LambdaClient, CreateFunctionCommand, DeleteFunctionCommand } from '@aws-sdk/client-lambda'; +import WebSocket from 'ws'; +import { makeClient, uniqueName, ENDPOINT, REGION, ACCOUNT, buildMinimalZip, sleep } from './setup'; + +// ── Helpers ────────────────────────────────────────────────────────────────── + +/** The local endpoint authority, e.g. `localhost:4566`. */ +function authority(): string { + return ENDPOINT.replace(/^https?:\/\//, '').replace(/\/$/, ''); +} + +/** + * Floci's advertised local execute-api domain, e.g. `{apiId}.execute-api.localhost.floci.io:4566` + * (regionless — see docs/services/api-gateway.md and the TLS SANs). This is the host form these + * end-to-end tests exercise: it is what floci actually serves/routes, and the region is recovered + * by a cross-region apiId lookup rather than a host label. The region-bearing AWS shape + * (`{apiId}.execute-api.{region}.amazonaws.com`) is covered by the Java filter/resolver unit tests. + */ +function builtinSuffixHost(apiId: string): string { + const port = authority().includes(':') ? `:${authority().split(':')[1]}` : ''; + return `${apiId}.execute-api.localhost.floci.io${port}`; +} + +/** + * A Management API client that presents an execute-api Host header while still connecting to the + * real test endpoint. A build-step middleware overrides the `Host` header (before SigV4 signing) + * to the given execute-api host; the request path stays `/{stage}/@connections/{id}`. This is + * exactly what floci's `ApiGatewayExecuteApiHostFilter` keys on, so it proves host-based routing + * without relying on `*.localhost` DNS. + */ +function managementClientForHost(host: string, stage: string, region: string): ApiGatewayManagementApiClient { + const client = makeClient(ApiGatewayManagementApiClient, { + endpoint: `${ENDPOINT}/${stage}`, + region, + }); + client.middlewareStack.add( + (next) => async (args) => { + const req = args.request as { headers?: Record }; + if (req && req.headers) { + req.headers['host'] = host; + } + return next(args); + }, + { step: 'build', name: 'setExecuteApiHost', priority: 'high' } + ); + return client; +} + +function subdomainManagementClient(apiId: string, stage: string, region: string): ApiGatewayManagementApiClient { + return managementClientForHost(builtinSuffixHost(apiId), stage, region); +} + +/** Connect a WebSocket to the real endpoint but with the execute-api Host header. */ +function connectWsViaSubdomain(apiId: string, stage: string): Promise { + const url = `ws://${authority()}/${stage}`; + return new Promise((resolve, reject) => { + const ws = new WebSocket(url, { headers: { Host: builtinSuffixHost(apiId) } }); + ws.on('open', () => resolve(ws)); + ws.on('error', (err) => reject(err)); + }); +} + +function waitForMessage(ws: WebSocket, timeoutMs = 5000): Promise { + return new Promise((resolve, reject) => { + const timer = setTimeout(() => reject(new Error('Timeout waiting for message')), timeoutMs); + ws.once('message', (data) => { + clearTimeout(timer); + resolve(data.toString()); + }); + }); +} + +const ROLE_ARN = `arn:aws:iam::${ACCOUNT}:role/lambda-role`; + +// Echo handler that can report its own connectionId (mirrors the data-plane suite). +const ECHO_HANDLER = ` +exports.handler = async (event) => { + const body = event.body || ''; + try { + const parsed = JSON.parse(body); + if (parsed.action === 'getConnectionId') { + return { statusCode: 200, body: JSON.stringify({ connectionId: event.requestContext.connectionId }) }; + } + } catch (e) {} + return { statusCode: 200, body: body || 'echo' }; +}; +`; + +// ── Test suite ───────────────────────────────────────────────────────────── + +describe('API Gateway v2 execute-api subdomain routing', () => { + const createdApis: Array<{ apiId: string; region: string }> = []; + const createdFunctions: string[] = []; + let lambda: LambdaClient; + + beforeAll(() => { + lambda = makeClient(LambdaClient); + }); + + afterAll(async () => { + for (const fnName of createdFunctions) { + try { await lambda.send(new DeleteFunctionCommand({ FunctionName: fnName })); } catch { /* ignore */ } + } + for (const { apiId, region } of createdApis) { + try { + const gw = makeClient(ApiGatewayV2Client, { region }); + await gw.send(new DeleteApiCommand({ ApiId: apiId })); + } catch { /* ignore */ } + } + }); + + async function createWsApiWithStage(name: string, region: string, stage: string): Promise { + const gw = makeClient(ApiGatewayV2Client, { region }); + const res = await gw.send(new CreateApiCommand({ + Name: uniqueName(name), + ProtocolType: 'WEBSOCKET', + RouteSelectionExpression: '$request.body.action', + })); + const apiId = res.ApiId!; + createdApis.push({ apiId, region }); + const deploy = await gw.send(new CreateDeploymentCommand({ ApiId: apiId })); + await gw.send(new CreateStageCommand({ ApiId: apiId, StageName: stage, DeploymentId: deploy.DeploymentId! })); + return apiId; + } + + // ── #1846: @connections Management API via subdomain host ────────────────── + + it('routes @connections via the subdomain host to the API (not S3): unknown connection -> GoneException', async () => { + const stage = 'prod'; + const apiId = await createWsApiWithStage('subdomain-conn', REGION, stage); + const mgmt = subdomainManagementClient(apiId, stage, REGION); + + // A GET for a non-existent connection must reach the API Gateway controller and + // return GoneException (410). Before the fix the S3 controller intercepted this + // host, so it would NOT surface as GoneException. + await expect( + mgmt.send(new GetConnectionCommand({ ConnectionId: 'does-not-exist' })) + ).rejects.toMatchObject({ name: 'GoneException' }); + + await expect( + mgmt.send(new DeleteConnectionCommand({ ConnectionId: 'does-not-exist' })) + ).rejects.toMatchObject({ name: 'GoneException' }); + + await expect( + mgmt.send(new PostToConnectionCommand({ ConnectionId: 'does-not-exist', Data: Buffer.from('hi') })) + ).rejects.toMatchObject({ name: 'GoneException' }); + }); + + it('delivers a message to a live connection via the subdomain PostToConnection endpoint', async () => { + const stage = 'prod'; + const region = REGION; + const gw = makeClient(ApiGatewayV2Client, { region }); + const fnName = uniqueName('subdomain-echo'); + await lambda.send(new CreateFunctionCommand({ + FunctionName: fnName, + Runtime: 'nodejs22.x', + Role: ROLE_ARN, + Handler: 'index.handler', + Code: { ZipFile: buildMinimalZip('index.js', Buffer.from(ECHO_HANDLER)) }, + })); + createdFunctions.push(fnName); + + const res = await gw.send(new CreateApiCommand({ + Name: uniqueName('subdomain-live'), + ProtocolType: 'WEBSOCKET', + RouteSelectionExpression: '$request.body.action', + })); + const apiId = res.ApiId!; + createdApis.push({ apiId, region }); + const integ = await gw.send(new CreateIntegrationCommand({ + ApiId: apiId, + IntegrationType: 'AWS_PROXY', + IntegrationUri: `arn:aws:lambda:${region}:${ACCOUNT}:function:${fnName}`, + })); + // $default with a route response so the echo reply is delivered back to the + // client (matches the data-plane suite; without a route response no frame is sent). + const route = await gw.send(new CreateRouteCommand({ + ApiId: apiId, + RouteKey: '$default', + Target: `integrations/${integ.IntegrationId}`, + RouteResponseSelectionExpression: '$default', + })); + await gw.send(new CreateRouteResponseCommand({ + ApiId: apiId, + RouteId: route.RouteId!, + RouteResponseKey: '$default', + })); + const deploy = await gw.send(new CreateDeploymentCommand({ ApiId: apiId })); + await gw.send(new CreateStageCommand({ ApiId: apiId, StageName: stage, DeploymentId: deploy.DeploymentId! })); + + const ws = await connectWsViaSubdomain(apiId, stage); + try { + // Learn our own connectionId via the echo integration (first invoke is a + // Lambda cold start, so allow extra headroom here). + ws.send(JSON.stringify({ action: 'getConnectionId' })); + const idResponse = await waitForMessage(ws, 15000); + const connectionId = JSON.parse(idResponse).connectionId as string; + expect(connectionId).toBeTruthy(); + + // Push a server-initiated message through the subdomain Management endpoint. + const mgmt = subdomainManagementClient(apiId, stage, region); + const pushed = waitForMessage(ws); + await mgmt.send(new PostToConnectionCommand({ ConnectionId: connectionId, Data: Buffer.from('via-subdomain') })); + expect(await pushed).toBe('via-subdomain'); + } finally { + if (ws.readyState !== WebSocket.CLOSED) ws.close(); + } + }); + + // ── #1871: WebSocket $connect via subdomain host resolves region ─────────── + + it('connects a WebSocket in a non-default region via the subdomain host (no 403)', async () => { + const region = 'ap-northeast-2'; + const stage = 'prod'; + const apiId = await createWsApiWithStage('subdomain-region', region, stage); + + // The execute-api host (regionless built-in suffix) carries no region and a handshake has no + // Authorization header, so the API is found by a cross-region apiId lookup. Before the fix a + // connect to a non-default-region WS API returned 403. + const ws = await connectWsViaSubdomain(apiId, stage); + try { + expect(ws.readyState).toBe(WebSocket.OPEN); + } finally { + if (ws.readyState !== WebSocket.CLOSED) ws.close(); + } + + // Sanity: the region-less PATH form (/ws/{apiId}/{stage}) resolves only the default region and + // must NOT connect to this ap-northeast-2 API — confirming the execute-api host is what routed it. + await expect(new Promise((resolve, reject) => { + const bad = new WebSocket(`ws://${authority()}/ws/${apiId}/${stage}`); + bad.on('open', () => resolve(bad)); + bad.on('error', (err) => reject(err)); + })).rejects.toBeTruthy(); + + await sleep(50); + }); + + // ── Regionless built-in suffix must not be mis-parsed as region "localhost" ── + + it('routes @connections via the regionless built-in suffix host for a non-default-region API', async () => { + const region = 'ap-northeast-2'; + const stage = 'prod'; + const apiId = await createWsApiWithStage('builtin-suffix', region, stage); + + // Host is {apiId}.execute-api.localhost.floci.io:4566 — NO region label. The old parser + // read "localhost" as the region and the lookup missed; the consolidated filter resolves + // the API by id across regions and still routes @connections to the controller (410 Gone), + // not S3. + const mgmt = managementClientForHost(builtinSuffixHost(apiId), stage, region); + await expect( + mgmt.send(new GetConnectionCommand({ ConnectionId: 'does-not-exist' })) + ).rejects.toMatchObject({ name: 'GoneException' }); + }); +}); diff --git a/docs/services/api-gateway.md b/docs/services/api-gateway.md index 8df935de2e..cf587960c5 100644 --- a/docs/services/api-gateway.md +++ b/docs/services/api-gateway.md @@ -279,7 +279,12 @@ DELETE /execute-api/{apiId}/{stageName}/@connections/{connectionId} — Disconn #### Behavior Notes -- **Connection URL**: Floci uses `ws://localhost:4566/ws/{apiId}/{stage}` instead of AWS's `wss://{api-id}.execute-api.{region}.amazonaws.com/{stage}`. +- **Connection URL**: Floci accepts the AWS-style execute-api host as well as the path form. All of these reach the same WebSocket API: + - `ws://{apiId}.execute-api.{region}.localhost:4566/{stage}` — region-bearing, mirroring AWS's `wss://{api-id}.execute-api.{region}.amazonaws.com/{stage}` + - `ws://{apiId}.execute-api.localhost.floci.io:4566/{stage}` — Floci's built-in execute-api domain (regionless; the region is resolved by an apiId lookup) + - `ws://localhost:4566/ws/{apiId}/{stage}` — the explicit path form + + The `@connections` management API is likewise reachable on the execute-api host (`http://{apiId}.execute-api.{region}.localhost:4566/{stage}/@connections/{connectionId}`). - **Idle timeout**: 10 minutes (matching AWS default). Not configurable per-API. - **Max connection duration**: 2 hours (matching AWS). Connections are closed automatically. - **Payload size limit**: 128 KB per frame (matching AWS). Oversized messages receive an error frame. diff --git a/src/main/java/io/github/hectorvent/floci/core/common/RegionResolver.java b/src/main/java/io/github/hectorvent/floci/core/common/RegionResolver.java index bb3e90c92b..dbfaf0abdd 100644 --- a/src/main/java/io/github/hectorvent/floci/core/common/RegionResolver.java +++ b/src/main/java/io/github/hectorvent/floci/core/common/RegionResolver.java @@ -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; } diff --git a/src/main/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayExecuteApiHostFilter.java b/src/main/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayExecuteApiHostFilter.java index b19c3a9740..421ff05182 100644 --- a/src/main/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayExecuteApiHostFilter.java +++ b/src/main/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayExecuteApiHostFilter.java @@ -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) { diff --git a/src/main/java/io/github/hectorvent/floci/services/apigatewayv2/websocket/WebSocketHandler.java b/src/main/java/io/github/hectorvent/floci/services/apigatewayv2/websocket/WebSocketHandler.java index e0df3af33c..03f4a3b27b 100644 --- a/src/main/java/io/github/hectorvent/floci/services/apigatewayv2/websocket/WebSocketHandler.java +++ b/src/main/java/io/github/hectorvent/floci/services/apigatewayv2/websocket/WebSocketHandler.java @@ -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(); } /** diff --git a/src/test/java/io/github/hectorvent/floci/core/common/RegionResolverTest.java b/src/test/java/io/github/hectorvent/floci/core/common/RegionResolverTest.java index aa16934eb6..329c03d13c 100644 --- a/src/test/java/io/github/hectorvent/floci/core/common/RegionResolverTest.java +++ b/src/test/java/io/github/hectorvent/floci/core/common/RegionResolverTest.java @@ -127,6 +127,51 @@ class RegionResolverTest { assertEquals("us-east-1", resolver.resolveRegionFromPresignedCredential("only-two/parts")); } + // --- resolveRegionFromHost(String host) tests (issue #1871) --- + + @Test + void resolveRegionFromHost_regionBearingHost_returnsRegion() { + assertEquals("ap-northeast-2", + resolver.resolveRegionFromHost("abc123.execute-api.ap-northeast-2.localhost:4566")); + assertEquals("us-west-2", + resolver.resolveRegionFromHost("abc123.execute-api.us-west-2.localhost")); + assertEquals("eu-west-1", + resolver.resolveRegionFromHost("abc123.execute-api.eu-west-1.amazonaws.com")); + assertEquals("us-gov-east-1", + resolver.resolveRegionFromHost("abc123.execute-api.us-gov-east-1.amazonaws.com")); + } + + @Test + void resolveRegionFromHost_normalizesUppercaseRegionToLowercase() { + // Hostnames are case-insensitive; the region must be lowercased so the region-scoped + // API lookup does not 403 on a casing mismatch (PR review P1). + assertEquals("us-east-1", + resolver.resolveRegionFromHost("abc123.execute-api.US-EAST-1.localhost:4566")); + } + + @Test + void resolveRegionFromHost_builtinDnsSuffixes_returnNull() { + // Floci's built-in execute-api suffixes carry NO region label. The old pattern parsed + // "localhost" as the region and broke the lookup — these must return null so the caller + // falls back (default region / cross-region apiId scan) instead. (PR #2188 review.) + assertNull(resolver.resolveRegionFromHost("abc123.execute-api.localhost:4566")); + assertNull(resolver.resolveRegionFromHost("abc123.execute-api.localhost.floci.io:4566")); + assertNull(resolver.resolveRegionFromHost("abc123.execute-api.localhost.localstack.cloud:4566")); + } + + @Test + void resolveRegionFromHost_nonExecuteApiHost_returnsNull() { + assertNull(resolver.resolveRegionFromHost("localhost:4566")); + assertNull(resolver.resolveRegionFromHost("my-bucket.localhost:4566")); + assertNull(resolver.resolveRegionFromHost("abc123.lambda-url.us-east-1.localhost")); + } + + @Test + void resolveRegionFromHost_nullOrEmpty_returnsNull() { + assertNull(resolver.resolveRegionFromHost(null)); + assertNull(resolver.resolveRegionFromHost("")); + } + private static HttpHeaders stubHeaders(String authorizationValue) { return new HttpHeaders() { @Override public List getRequestHeader(String name) { diff --git a/src/test/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayExecuteApiHostFilterTest.java b/src/test/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayExecuteApiHostFilterTest.java index d26ac51be2..8a5e0eb408 100644 --- a/src/test/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayExecuteApiHostFilterTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayExecuteApiHostFilterTest.java @@ -148,6 +148,86 @@ class ApiGatewayExecuteApiHostFilterTest { assertNull(request.routedUri()); } + @Test + void routesRegionBearingAwsHost() { + FakeApiGatewayLookup lookup = new FakeApiGatewayLookup(); + lookup.addApi(API_ID); + lookup.addStage(API_ID, "prod"); + RecordingRequest request = new RecordingRequest( + "abc123.execute-api.us-east-1.amazonaws.com", + URI.create("http://abc123.execute-api.us-east-1.amazonaws.com/prod/accounts")); + + new ApiGatewayExecuteApiHostFilter(lookup, new RegionResolver(REGION, "000000000000")) + .filter(request.context()); + + assertEquals("/execute-api/abc123/prod/accounts", request.routedUri().getRawPath()); + } + + @Test + void routesRegionBearingLocalHostInNonDefaultRegion() { + FakeApiGatewayLookup lookup = new FakeApiGatewayLookup(); + lookup.addApi("ap-northeast-2", API_ID, "HTTP"); + lookup.addStage("ap-northeast-2", API_ID, "$default"); + RecordingRequest request = new RecordingRequest( + "abc123.execute-api.ap-northeast-2.localhost:4566", + URI.create("http://abc123.execute-api.ap-northeast-2.localhost:4566/accounts")); + ApiGatewayExecuteRouteContext routeContext = new ApiGatewayExecuteRouteContext(); + + new ApiGatewayExecuteApiHostFilter( + lookup, new RegionResolver(REGION, "000000000000"), routeContext) + .filter(request.context()); + + assertEquals("/execute-api/abc123/$default/accounts", request.routedUri().getRawPath()); + assertEquals("ap-northeast-2", routeContext.httpApiRegion()); + } + + @Test + void routesWebSocketConnectionsManagementCall() { + FakeApiGatewayLookup lookup = new FakeApiGatewayLookup(); + lookup.addApi(REGION, API_ID, "WEBSOCKET"); + lookup.addStage(API_ID, "prod"); + RecordingRequest request = new RecordingRequest( + "abc123.execute-api.us-east-1.amazonaws.com", + URI.create("http://abc123.execute-api.us-east-1.amazonaws.com/prod/@connections/xyz")); + + new ApiGatewayExecuteApiHostFilter(lookup, new RegionResolver(REGION, "000000000000")) + .filter(request.context()); + + assertEquals("/execute-api/abc123/prod/@connections/xyz", request.routedUri().getRawPath()); + } + + @Test + void routesWebSocketConnectionsViaBuiltinSuffixHostAcrossRegions() { + FakeApiGatewayLookup lookup = new FakeApiGatewayLookup(); + lookup.addApi("ap-northeast-2", API_ID, "WEBSOCKET"); + lookup.addStage("ap-northeast-2", API_ID, "prod"); + RecordingRequest request = new RecordingRequest( + "abc123.execute-api.localhost.floci.io:4566", + URI.create("http://abc123.execute-api.localhost.floci.io:4566/prod/@connections/xyz")); + + new ApiGatewayExecuteApiHostFilter(lookup, new RegionResolver(REGION, "000000000000")) + .filter(request.context()); + + assertEquals("/execute-api/abc123/prod/@connections/xyz", request.routedUri().getRawPath()); + } + + @Test + void rejectsDisabledExecuteApiEndpointForWebSocketConnections() { + FakeApiGatewayLookup lookup = new FakeApiGatewayLookup(); + lookup.addApi(REGION, API_ID, "WEBSOCKET"); + lookup.addStage(API_ID, "prod"); + lookup.disableExecuteApiEndpoint(API_ID); + RecordingRequest request = new RecordingRequest( + "abc123.execute-api.us-east-1.amazonaws.com", + URI.create("http://abc123.execute-api.us-east-1.amazonaws.com/prod/@connections/xyz")); + + new ApiGatewayExecuteApiHostFilter(lookup, new RegionResolver(REGION, "000000000000")) + .filter(request.context()); + + assertNull(request.routedUri()); + assertEquals(404, request.abortedResponse().getStatus()); + } + @Test void doesNotMarkHttpRouteWhenNoStageMatches() { FakeApiGatewayLookup lookup = new FakeApiGatewayLookup();