From 0e3391cac2de0823f4b30b3b89127b2cbb7d89ba Mon Sep 17 00:00:00 2001 From: Aniket Shukla <0aniketshukla1@gmail.com> Date: Mon, 24 Aug 2026 00:36:20 +0530 Subject: [PATCH] =?UTF-8?q?fix(apigateway):=20route=20CORS=20preflight=20(?= =?UTF-8?q?OPTIONS)=20to=20deployed=20API=20integ=E2=80=A6=20(#1955)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * fix(apigateway): route CORS preflight (OPTIONS) to deployed API integrations Browsers send an OPTIONS preflight before a cross-origin call to a deployed API. GlobalCorsFilter short-circuited every OPTIONS preflight with Floci's own CORS response, so the request never reached the API Gateway integration — a Lambda (or a configured OPTIONS method) that handles CORS itself never ran. The deployed-API execute controllers also had no OPTIONS handler. - Skip GlobalCorsFilter for deployed-API paths (execute-api, _aws/execute-api, and the _user_request_ form) on both the request and response sides, so the integration owns CORS — matching the filter's documented "integrations keep precedence" contract. - Add @OPTIONS handlers to the three execute controllers, dispatching to the configured OPTIONS/ANY method like the other verbs. Adds unit tests for the deployed-API path matcher. Closes #1928 * test(apigateway): cover CORS preflight (OPTIONS) routing end-to-end Add ApiGatewayPreflightRoutingIntegrationTest driving a real browser preflight through the full chain: global CORS filter skip on deployed paths, route matching, OPTIONS/ANY method resolution, and integration invocation. A contrasting preflight to a management path (/restapis) asserts the filter still short-circuits non-deployed paths, so the deployed-path cases run with CORS genuinely enabled. * fix(apigatewayv2): preserve configured CORS preflight --- .../floci/core/common/GlobalCorsFilter.java | 31 ++ .../ApiGatewayAwsExecuteController.java | 10 + .../ApiGatewayExecuteController.java | 69 ++++- .../ApiGatewayUserRequestController.java | 10 + .../core/common/GlobalCorsFilterTest.java | 45 +++ ...atewayPreflightRoutingIntegrationTest.java | 273 ++++++++++++++++++ 6 files changed, 437 insertions(+), 1 deletion(-) create mode 100644 src/test/java/io/github/hectorvent/floci/core/common/GlobalCorsFilterTest.java create mode 100644 src/test/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayPreflightRoutingIntegrationTest.java diff --git a/src/main/java/io/github/hectorvent/floci/core/common/GlobalCorsFilter.java b/src/main/java/io/github/hectorvent/floci/core/common/GlobalCorsFilter.java index ad0b61f7b7..f448d71ebd 100644 --- a/src/main/java/io/github/hectorvent/floci/core/common/GlobalCorsFilter.java +++ b/src/main/java/io/github/hectorvent/floci/core/common/GlobalCorsFilter.java @@ -88,6 +88,13 @@ public class GlobalCorsFilter implements ContainerRequestFilter, ContainerRespon return; } + // The API Gateway data plane owns CORS for deployed routes. REST APIs dispatch + // OPTIONS to an integration, while HTTP APIs answer from CorsConfiguration in + // ApiGatewayExecuteController; neither should be short-circuited here (#1928). + if (isDeployedApiPath(requestContext.getUriInfo().getPath())) { + return; + } + String origin = requestContext.getHeaderString(ORIGIN); if (origin == null || !s.matchesOrigin(origin)) { return; @@ -123,6 +130,12 @@ public class GlobalCorsFilter implements ContainerRequestFilter, ContainerRespon return; } + // See filter(request): deployed API Gateway responses carry either integration-owned + // REST CORS headers or API-owned HTTP API CORS headers. + if (isDeployedApiPath(requestContext.getUriInfo().getPath())) { + return; + } + String origin = requestContext.getHeaderString(ORIGIN); if (origin == null || !s.matchesOrigin(origin)) { return; @@ -146,6 +159,24 @@ public class GlobalCorsFilter implements ContainerRequestFilter, ContainerRespon } } + /** + * True for requests to a deployed API Gateway stage — the {@code execute-api} + * paths and the LocalStack-compatible {@code _user_request_} form. Floci's global CORS + * must not intercept these: the API Gateway data plane owns their CORS behavior, and + * short-circuiting here prevents REST integrations or HTTP API configuration from handling + * the preflight (#1928). Management endpoints such as {@code /restapis/{id}/resources/...} + * are unaffected. + */ + static boolean isDeployedApiPath(String path) { + if (path == null) { + return false; + } + String p = path.startsWith("/") ? path : "/" + path; + return p.startsWith("/execute-api/") + || p.startsWith("/_aws/execute-api/") + || p.contains("/_user_request_"); + } + private record CorsSettings(boolean disabled, Set allowedOrigins, Set extraAllowedHeaders, diff --git a/src/main/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayAwsExecuteController.java b/src/main/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayAwsExecuteController.java index 6c13e974c4..85f79a030f 100644 --- a/src/main/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayAwsExecuteController.java +++ b/src/main/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayAwsExecuteController.java @@ -71,4 +71,14 @@ public class ApiGatewayAwsExecuteController { byte[] body) { return executeController.dispatch("PATCH", apiId, stageName, proxy, headers, uriInfo, body); } + + @OPTIONS + @Path("/{proxy: .*}") + public Response handleOptions(@Context HttpHeaders headers, @Context UriInfo uriInfo, + @PathParam("apiId") String apiId, + @PathParam("stageName") String stageName, + @PathParam("proxy") String proxy, + byte[] body) { + return executeController.dispatch("OPTIONS", apiId, stageName, proxy, headers, uriInfo, body); + } } diff --git a/src/main/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayExecuteController.java b/src/main/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayExecuteController.java index b7a5ce5154..af7a69e8e3 100644 --- a/src/main/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayExecuteController.java +++ b/src/main/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayExecuteController.java @@ -15,6 +15,7 @@ import io.github.hectorvent.floci.services.apigateway.model.UsagePlan; import io.github.hectorvent.floci.services.apigateway.model.UsagePlanKey; import io.github.hectorvent.floci.services.apigatewayv2.ApiGatewayV2Service; import io.github.hectorvent.floci.services.apigatewayv2.JwtSignatureVerifier; +import io.github.hectorvent.floci.services.apigatewayv2.model.Api; 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; @@ -253,6 +254,17 @@ public class ApiGatewayExecuteController { return dispatch("PATCH", apiId, stageName, proxy, headers, uriInfo, body); } + @OPTIONS + @Blocking + @Path("/{proxy: .*}") + public Response handleOptions(@Context HttpHeaders headers, @Context UriInfo uriInfo, + @PathParam("apiId") String apiId, + @PathParam("stageName") String stageName, + @PathParam("proxy") String proxy, + byte[] body) { + return dispatch("OPTIONS", apiId, stageName, proxy, headers, uriInfo, body); + } + // ──────────────────────────── Core dispatch ──────────────────────────── Response dispatch(String httpMethod, String apiId, String stageName, @@ -1342,6 +1354,51 @@ public class ApiGatewayExecuteController { // ──────────────────────────── API Gateway v2 dispatch ──────────────────────────── + private static Response httpApiCorsPreflight(Api.Cors cors, String requestOrigin) { + Response.ResponseBuilder response = Response.noContent().type(MediaType.TEXT_PLAIN_TYPE); + String allowOrigin = matchingCorsOrigin(cors.allowOrigins(), requestOrigin); + if (allowOrigin != null) { + response.header("Access-Control-Allow-Origin", allowOrigin); + if (!"*".equals(allowOrigin)) { + response.header("Vary", "Origin"); + } + } + putCorsListHeader(response, "Access-Control-Allow-Methods", cors.allowMethods()); + putCorsListHeader(response, "Access-Control-Allow-Headers", cors.allowHeaders()); + putCorsListHeader(response, "Access-Control-Expose-Headers", cors.exposeHeaders()); + if (cors.maxAge() != null) { + response.header("Access-Control-Max-Age", cors.maxAge()); + } + if (Boolean.TRUE.equals(cors.allowCredentials())) { + response.header("Access-Control-Allow-Credentials", "true"); + } + return response.build(); + } + + private static String matchingCorsOrigin(List allowedOrigins, String requestOrigin) { + if (allowedOrigins == null || requestOrigin == null) { + return null; + } + for (String allowedOrigin : allowedOrigins) { + if ("*".equals(allowedOrigin)) { + return "*"; + } + if (allowedOrigin != null && (allowedOrigin.equals(requestOrigin) + || (allowedOrigin.endsWith("*") + && requestOrigin.startsWith(allowedOrigin.substring(0, allowedOrigin.length() - 1))))) { + return requestOrigin; + } + } + return null; + } + + private static void putCorsListHeader(Response.ResponseBuilder response, String headerName, + List values) { + if (values != null && !values.isEmpty()) { + response.header(headerName, String.join(", ", values)); + } + } + private Response dispatchV2(String httpMethod, String apiId, String stageName, String proxy, HttpHeaders headers, UriInfo uriInfo, byte[] body, String region) { @@ -1350,8 +1407,10 @@ public class ApiGatewayExecuteController { // and the direct /execute-api/{apiId}/{stage}/... route land here. Checking at the single // choke point keeps the two entry points from disagreeing about whether an API is invokable. // A missing API is not this method's error to report — findMatchingRoute below 404s. + Api api = null; try { - if (apiGatewayV2Service.getApi(region, apiId).isDisableExecuteApiEndpoint()) { + api = apiGatewayV2Service.getApi(region, apiId); + if (api.isDisableExecuteApiEndpoint()) { return Response.status(Response.Status.NOT_FOUND) .entity(jsonMessage("Not Found")) .type(MediaType.APPLICATION_JSON).build(); @@ -1361,6 +1420,14 @@ public class ApiGatewayExecuteController { apiId, region); } + if (api != null && api.getCorsConfiguration() != null + && "OPTIONS".equalsIgnoreCase(httpMethod) + && headers != null + && headers.getHeaderString("Origin") != null + && headers.getHeaderString("Access-Control-Request-Method") != null) { + return httpApiCorsPreflight(api.getCorsConfiguration(), headers.getHeaderString("Origin")); + } + String path = "/" + (proxy == null ? "" : proxy); Route route = apiGatewayV2Service.findMatchingRoute(region, apiId, httpMethod, path); diff --git a/src/main/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayUserRequestController.java b/src/main/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayUserRequestController.java index 656f3e9a3c..4a3db8bdb1 100644 --- a/src/main/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayUserRequestController.java +++ b/src/main/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayUserRequestController.java @@ -71,4 +71,14 @@ public class ApiGatewayUserRequestController { byte[] body) { return executeController.dispatch("PATCH", apiId, stageName, proxy, headers, uriInfo, body); } + + @OPTIONS + @Path("/{proxy: .*}") + public Response handleOptions(@Context HttpHeaders headers, @Context UriInfo uriInfo, + @PathParam("apiId") String apiId, + @PathParam("stageName") String stageName, + @PathParam("proxy") String proxy, + byte[] body) { + return executeController.dispatch("OPTIONS", apiId, stageName, proxy, headers, uriInfo, body); + } } diff --git a/src/test/java/io/github/hectorvent/floci/core/common/GlobalCorsFilterTest.java b/src/test/java/io/github/hectorvent/floci/core/common/GlobalCorsFilterTest.java new file mode 100644 index 0000000000..0e8d84d6f6 --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/core/common/GlobalCorsFilterTest.java @@ -0,0 +1,45 @@ +package io.github.hectorvent.floci.core.common; + +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.CsvSource; + +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +class GlobalCorsFilterTest { + + // Deployed API Gateway stages own their CORS — the global filter must skip them (#1928). + @ParameterizedTest + @CsvSource({ + "/execute-api/abc123/prod/graphql", + "/execute-api/abc123/prod/", + "/_aws/execute-api/abc123/prod/graphql", + "/restapis/abc123/prod/_user_request_/graphql", + "/restapis/abc123/prod/_user_request_", + // tolerant of the leading-slash-less form UriInfo.getPath() can return + "execute-api/abc123/prod/graphql", + }) + void deployedApiPathsAreExcludedFromGlobalCors(String path) { + assertTrue(GlobalCorsFilter.isDeployedApiPath(path)); + } + + // Management API and everything else keep Floci's global CORS handling. + @ParameterizedTest + @CsvSource({ + "/restapis/abc123/resources/xyz/methods/GET", + "/restapis/abc123/deployments", + "/restapis", + "/my-bucket/key.txt", + "/", + "/_health", + }) + void managementAndOtherPathsKeepGlobalCors(String path) { + assertFalse(GlobalCorsFilter.isDeployedApiPath(path)); + } + + @Test + void nullPathIsNotDeployedApi() { + assertFalse(GlobalCorsFilter.isDeployedApiPath(null)); + } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayPreflightRoutingIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayPreflightRoutingIntegrationTest.java new file mode 100644 index 0000000000..8db230e503 --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayPreflightRoutingIntegrationTest.java @@ -0,0 +1,273 @@ +package io.github.hectorvent.floci.services.apigateway; + +import io.quarkus.test.junit.QuarkusTest; +import io.quarkus.test.junit.QuarkusTestProfile; +import io.quarkus.test.junit.TestProfile; +import io.restassured.http.ContentType; +import org.junit.jupiter.api.MethodOrderer; +import org.junit.jupiter.api.Order; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestMethodOrder; + +import java.util.Map; + +import static io.restassured.RestAssured.given; +import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.notNullValue; + +/** + * End-to-end coverage for CORS preflight (OPTIONS) handling on deployed API Gateway + * REST and HTTP APIs (#1928). + * + *

{@code GlobalCorsFilterTest} unit-tests {@link io.github.hectorvent.floci.core.common.GlobalCorsFilter#isDeployedApiPath} + * in isolation, and {@code GlobalCorsFilterIntegrationTest} verifies the filter still + * short-circuits preflights on non-deployed paths. Neither exercises the flow this + * PR actually changes: with global CORS enabled, a browser preflight to a deployed + * {@code /execute-api/...} path must be skipped by the filter and routed all the way to the + * integration. This test drives that full chain — filter skip → route match → OPTIONS/ANY + * method resolution → integration invocation — so a regression in any single stage fails here.

+ */ +@QuarkusTest +@TestProfile(ApiGatewayPreflightRoutingIntegrationTest.CorsEnabledProfile.class) +@TestMethodOrder(MethodOrderer.OrderAnnotation.class) +class ApiGatewayPreflightRoutingIntegrationTest { + + private static final String ORIGIN = "http://localhost:3000"; + private static final String STAGE = "cors"; + + private static String apiId; + private static String rootId; + private static String optionsResourceId; + private static String anyResourceId; + private static String deploymentId; + private static String httpApiId; + + @Test @Order(1) + void createRestApi() { + apiId = given() + .contentType(ContentType.JSON) + .body("{\"name\":\"preflight-routing-test-api\"}") + .when().post("/restapis") + .then() + .statusCode(201) + .body("id", notNullValue()) + .extract().path("id"); + } + + @Test @Order(2) + void setupExplicitOptionsMethodIntegration() { + rootId = given() + .when().get("/restapis/" + apiId + "/resources") + .then() + .statusCode(200) + .extract().path("item[0].id"); + + optionsResourceId = given() + .contentType(ContentType.JSON) + .body("{\"pathPart\":\"widgets\"}") + .when().post("/restapis/" + apiId + "/resources/" + rootId) + .then() + .statusCode(201) + .extract().path("id"); + + given() + .contentType(ContentType.JSON) + .body("{\"authorizationType\":\"NONE\"}") + .when().put("/restapis/" + apiId + "/resources/" + optionsResourceId + "/methods/OPTIONS") + .then() + .statusCode(201); + + given() + .contentType(ContentType.JSON) + .body("{\"responseParameters\":{}}") + .when().put("/restapis/" + apiId + "/resources/" + optionsResourceId + "/methods/OPTIONS/responses/200") + .then() + .statusCode(201); + + given() + .contentType(ContentType.JSON) + .body("{\"type\":\"MOCK\",\"requestTemplates\":{\"application/json\":\"{\\\"statusCode\\\": 200}\"}}") + .when().put("/restapis/" + apiId + "/resources/" + optionsResourceId + "/methods/OPTIONS/integration") + .then() + .statusCode(201); + + given() + .contentType(ContentType.JSON) + .body("{\"selectionPattern\":\"\",\"responseTemplates\":{\"application/json\":\"{\\\"handledBy\\\":\\\"options-integration\\\"}\"}}") + .when().put("/restapis/" + apiId + "/resources/" + optionsResourceId + "/methods/OPTIONS/integration/responses/200") + .then() + .statusCode(201); + } + + @Test @Order(3) + void setupAnyMethodIntegration() { + anyResourceId = given() + .contentType(ContentType.JSON) + .body("{\"pathPart\":\"any\"}") + .when().post("/restapis/" + apiId + "/resources/" + rootId) + .then() + .statusCode(201) + .extract().path("id"); + + given() + .contentType(ContentType.JSON) + .body("{\"authorizationType\":\"NONE\"}") + .when().put("/restapis/" + apiId + "/resources/" + anyResourceId + "/methods/ANY") + .then() + .statusCode(201); + + given() + .contentType(ContentType.JSON) + .body("{\"responseParameters\":{}}") + .when().put("/restapis/" + apiId + "/resources/" + anyResourceId + "/methods/ANY/responses/200") + .then() + .statusCode(201); + + given() + .contentType(ContentType.JSON) + .body("{\"type\":\"MOCK\",\"requestTemplates\":{\"application/json\":\"{\\\"statusCode\\\": 200}\"}}") + .when().put("/restapis/" + apiId + "/resources/" + anyResourceId + "/methods/ANY/integration") + .then() + .statusCode(201); + + given() + .contentType(ContentType.JSON) + .body("{\"selectionPattern\":\"\",\"responseTemplates\":{\"application/json\":\"{\\\"matched\\\":\\\"any\\\"}\"}}") + .when().put("/restapis/" + apiId + "/resources/" + anyResourceId + "/methods/ANY/integration/responses/200") + .then() + .statusCode(201); + } + + @Test @Order(4) + void createDeploymentAndStage() { + deploymentId = given() + .contentType(ContentType.JSON) + .body("{\"description\":\"v1\"}") + .when().post("/restapis/" + apiId + "/deployments") + .then() + .statusCode(201) + .extract().path("id"); + + given() + .contentType(ContentType.JSON) + .body("{\"stageName\":\"" + STAGE + "\",\"deploymentId\":\"" + deploymentId + "\"}") + .when().post("/restapis/" + apiId + "/stages") + .then() + .statusCode(201); + } + + /** + * The regression guard: a real browser preflight (carries {@code Origin} and + * {@code Access-Control-Request-Method}) to a deployed path must NOT be answered by the + * global CORS filter (which would return 204 with no body). The deployed-path exclusion + * lets it fall through to the explicit OPTIONS method's integration, whose body proves the + * integration was actually invoked. + */ + @Test @Order(5) + void preflightToDeployedPathReachesExplicitOptionsIntegration() { + given() + .header("Origin", ORIGIN) + .header("Access-Control-Request-Method", "GET") + .header("Access-Control-Request-Headers", "content-type") + .when().options("/execute-api/" + apiId + "/" + STAGE + "/widgets") + .then() + .statusCode(200) + .body("handledBy", equalTo("options-integration")); + } + + /** An OPTIONS preflight must also resolve to a resource configured with the ANY method. */ + @Test @Order(6) + void preflightResolvesToAnyMethodIntegration() { + given() + .header("Origin", ORIGIN) + .header("Access-Control-Request-Method", "POST") + .when().options("/execute-api/" + apiId + "/" + STAGE + "/any") + .then() + .statusCode(200) + .body("matched", equalTo("any")); + } + + /** + * HTTP APIs differ from REST APIs: API Gateway itself answers preflight from the API's + * CorsConfiguration, even when no OPTIONS route exists. + */ + @Test @Order(7) + void setupHttpApiWithCorsConfiguration() { + httpApiId = given() + .contentType(ContentType.JSON) + .body(""" + { + "name":"preflight-routing-http-api", + "protocolType":"HTTP", + "corsConfiguration":{ + "allowOrigins":["%s"], + "allowMethods":["GET","POST"], + "allowHeaders":["content-type"], + "exposeHeaders":["x-request-id"], + "maxAge":600, + "allowCredentials":true + } + } + """.formatted(ORIGIN)) + .when().post("/v2/apis") + .then() + .statusCode(201) + .extract().path("apiId"); + + given() + .contentType(ContentType.JSON) + .body("{\"routeKey\":\"GET /items\"}") + .when().post("/v2/apis/" + httpApiId + "/routes") + .then() + .statusCode(201); + } + + @Test @Order(8) + void httpApiPreflightUsesApiCorsConfigurationWithoutOptionsRoute() { + given() + .header("Origin", ORIGIN) + .header("Access-Control-Request-Method", "GET") + .header("Access-Control-Request-Headers", "content-type") + .when().options("/execute-api/" + httpApiId + "/$default/items") + .then() + .statusCode(204) + .header("Access-Control-Allow-Origin", equalTo(ORIGIN)) + .header("Access-Control-Allow-Methods", equalTo("GET, POST")) + .header("Access-Control-Allow-Headers", equalTo("content-type")) + .header("Access-Control-Expose-Headers", equalTo("x-request-id")) + .header("Access-Control-Max-Age", equalTo("600")) + .header("Access-Control-Allow-Credentials", equalTo("true")); + } + + /** + * The discriminator: a preflight to a non-deployed management path ({@code /restapis}) is + * still owned by the global CORS filter — short-circuited with 204 and CORS headers, never + * routed to an integration. Proves the deployed-path exclusion is scoped, not blanket. + */ + @Test @Order(9) + void preflightToManagementPathIsShortCircuitedByFilter() { + given() + .header("Origin", ORIGIN) + .header("Access-Control-Request-Method", "GET") + .when().options("/restapis") + .then() + .statusCode(204) + .header("Access-Control-Allow-Origin", equalTo(ORIGIN)) + .body(equalTo("")); + } + + @Test @Order(10) + void cleanup() { + given().when().delete("/restapis/" + apiId).then().statusCode(202); + given().when().delete("/v2/apis/" + httpApiId).then().statusCode(204); + } + + public static final class CorsEnabledProfile implements QuarkusTestProfile { + @Override + public Map getConfigOverrides() { + // Global CORS on: without the deployed-path exclusion, this filter would answer the + // preflight itself and the integration would never run. + return Map.of("floci.security.extra-cors-allowed-origins", ORIGIN); + } + } +}