Skip to content

armgit / floci

Public Imported from GitHub
0

Light, fluffy, and always free - The AWS Local Emulator alternative

fix(apigatewayv2): apply an HTTP API's CORS configuration to its actual responses (#5935)

Alessandro Lattaodd832b45dcc3
diff --git a/compatibility-tests/sdk-test-java/src/main/java/com/floci/test/TestFixtures.java b/compatibility-tests/sdk-test-java/src/main/java/com/floci/test/TestFixtures.java
index dc696db6c4..e26ea9e342 100644
--- a/compatibility-tests/sdk-test-java/src/main/java/com/floci/test/TestFixtures.java
+++ b/compatibility-tests/sdk-test-java/src/main/java/com/floci/test/TestFixtures.java
@@ -415,7 +415,8 @@ public final class TestFixtures {
}
}
- private static byte[] probeZip() {
+ /** A Node.js deployment package whose handler answers 200, for a function the test only has to create. */
+ static byte[] probeZip() {
String code = "exports.handler = async () => ({ statusCode: 200 });";
try {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
diff --git a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/ApiGatewayV2CorsTest.java b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/ApiGatewayV2CorsTest.java
new file mode 100644
index 0000000000..3fc79cca11
--- /dev/null
+++ b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/ApiGatewayV2CorsTest.java
@@ -0,0 +1,205 @@
+package com.floci.test;
+
+import org.junit.jupiter.api.AfterAll;
+import org.junit.jupiter.api.BeforeAll;
+import org.junit.jupiter.api.DisplayName;
+import org.junit.jupiter.api.Test;
+import software.amazon.awssdk.core.SdkBytes;
+import software.amazon.awssdk.services.apigatewayv2.ApiGatewayV2Client;
+import software.amazon.awssdk.services.apigatewayv2.model.AuthorizerType;
+import software.amazon.awssdk.services.apigatewayv2.model.IntegrationType;
+import software.amazon.awssdk.services.lambda.LambdaClient;
+import software.amazon.awssdk.services.lambda.model.Runtime;
+
+import java.io.IOException;
+import java.net.URI;
+import java.net.http.HttpClient;
+import java.net.http.HttpRequest;
+import java.net.http.HttpResponse;
+import java.time.Duration;
+import java.util.List;
+import java.util.Locale;
+
+import static org.assertj.core.api.Assertions.assertThat;
+
+/**
+ * An HTTP API's CORS configuration on the answers API Gateway gives itself, set up through the SDK.
+ * Measured on AWS (eu-west-1, 2026-10-16 and 2026-10-18): a JWT authorizer's 401, an unsigned
+ * AWS_IAM call's 403 and a throttled function's 503 carry Access-Control-Allow-Origin and
+ * Access-Control-Expose-Headers for an allowed origin and no CORS header for another. A preflight
+ * no route matches is answered 204 with the preflight's headers for an allowed origin and with none
+ * for another, and so is an OPTIONS request that is not a preflight. That preflight always carries
+ * Access-Control-Allow-Headers, empty when none are configured, and Vary: origin when the
+ * configuration names two origins, none when it names one.
+ */
+@DisplayName("API Gateway v2 HTTP API CORS")
+class ApiGatewayV2CorsTest {
+
+ private static final String ORIGIN = "https://app.example.com";
+ private static final String OTHER_ORIGIN = "https://evil.example";
+
+ private static final HttpClient HTTP = HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(5)).build();
+
+ private static ApiGatewayV2Client apiGatewayV2;
+ private static LambdaClient lambda;
+ private static String throttledFunction;
+ private static String apiId;
+ private static String twoOriginsApiId;
+
+ @BeforeAll
+ static void setup() {
+ apiGatewayV2 = TestFixtures.apiGatewayV2Client();
+ apiId = apiGatewayV2.createApi(request -> request
+ .name(TestFixtures.uniqueName("compat-http-api-cors"))
+ .protocolType("HTTP")
+ .corsConfiguration(cors -> cors
+ .allowOrigins(ORIGIN)
+ .allowMethods("GET")
+ .allowHeaders("authorization")
+ .exposeHeaders("x-probe")
+ .maxAge(300))).apiId();
+ String integrationId = apiGatewayV2.createIntegration(request -> request
+ .apiId(apiId)
+ .integrationType(IntegrationType.HTTP_PROXY)
+ .integrationMethod("GET")
+ .integrationUri("https://example.com")
+ .payloadFormatVersion("1.0")).integrationId();
+ String authorizerId = apiGatewayV2.createAuthorizer(request -> request
+ .apiId(apiId)
+ .name("jwt")
+ .authorizerType(AuthorizerType.JWT)
+ .identitySource("$request.header.Authorization")
+ .jwtConfiguration(jwt -> jwt.issuer("https://issuer.example.com").audience("cors"))).authorizerId();
+ apiGatewayV2.createRoute(request -> request.apiId(apiId).routeKey("GET /jwt")
+ .authorizationType("JWT").authorizerId(authorizerId).target("integrations/" + integrationId));
+ apiGatewayV2.createRoute(request -> request.apiId(apiId).routeKey("GET /iam")
+ .authorizationType("AWS_IAM").target("integrations/" + integrationId));
+
+ lambda = TestFixtures.lambdaClient();
+ throttledFunction = TestFixtures.uniqueName("compat-cors-throttled");
+ String functionArn = lambda.createFunction(request -> request
+ .functionName(throttledFunction)
+ .runtime(Runtime.NODEJS20_X)
+ .role("arn:aws:iam::000000000000:role/lambda-role")
+ .handler("index.handler")
+ .code(code -> code.zipFile(SdkBytes.fromByteArray(TestFixtures.probeZip())))).functionArn();
+ lambda.putFunctionConcurrency(request -> request.functionName(throttledFunction)
+ .reservedConcurrentExecutions(0));
+ String lambdaIntegrationId = apiGatewayV2.createIntegration(request -> request
+ .apiId(apiId)
+ .integrationType(IntegrationType.AWS_PROXY)
+ .integrationUri(functionArn)
+ .payloadFormatVersion("2.0")).integrationId();
+ apiGatewayV2.createRoute(request -> request.apiId(apiId).routeKey("GET /throttled")
+ .target("integrations/" + lambdaIntegrationId));
+ apiGatewayV2.createStage(request -> request.apiId(apiId).stageName("$default").autoDeploy(true));
+
+ twoOriginsApiId = apiGatewayV2.createApi(request -> request
+ .name(TestFixtures.uniqueName("compat-http-api-cors-two"))
+ .protocolType("HTTP")
+ .corsConfiguration(cors -> cors.allowOrigins(ORIGIN, "https://other.example.com").allowMethods("GET")))
+ .apiId();
+ apiGatewayV2.createStage(request -> request.apiId(twoOriginsApiId).stageName("$default").autoDeploy(true));
+ }
+
+ @AfterAll
+ static void cleanup() {
+ if (apiGatewayV2 != null) {
+ if (apiId != null) {
+ apiGatewayV2.deleteApi(request -> request.apiId(apiId));
+ }
+ if (twoOriginsApiId != null) {
+ apiGatewayV2.deleteApi(request -> request.apiId(twoOriginsApiId));
+ }
+ apiGatewayV2.close();
+ }
+ if (lambda != null) {
+ if (throttledFunction != null) {
+ lambda.deleteFunction(request -> request.functionName(throttledFunction));
+ }
+ lambda.close();
+ }
+ }
+
+ @Test
+ @DisplayName("an authorizer's refusal carries the CORS headers for an allowed origin only")
+ void anAuthorizersRefusalCarriesTheCorsHeaders() throws IOException, InterruptedException {
+ HttpResponse<String> jwt = send(apiId, "GET", "/jwt", ORIGIN, null);
+ assertThat(jwt.statusCode()).isEqualTo(401);
+ assertThat(jwt.headers().firstValue("Access-Control-Allow-Origin")).contains(ORIGIN);
+ assertThat(jwt.headers().firstValue("Access-Control-Expose-Headers")).contains("x-probe");
+
+ HttpResponse<String> iam = send(apiId, "GET", "/iam", ORIGIN, null);
+ assertThat(iam.statusCode()).isEqualTo(403);
+ assertThat(iam.headers().firstValue("Access-Control-Allow-Origin")).contains(ORIGIN);
+ assertThat(iam.headers().firstValue("Access-Control-Expose-Headers")).contains("x-probe");
+
+ HttpResponse<String> other = send(apiId, "GET", "/jwt", OTHER_ORIGIN, null);
+ assertThat(other.statusCode()).isEqualTo(401);
+ assertThat(corsHeaderNames(other)).isEmpty();
+ }
+
+ @Test
+ @DisplayName("a preflight no route matches gets the preflight's headers for an allowed origin only")
+ void aPreflightNoRouteMatchesIsAnsweredFromTheConfiguration() throws IOException, InterruptedException {
+ HttpResponse<String> allowed = send(apiId, "OPTIONS", "/anything", ORIGIN, "GET");
+ assertThat(allowed.statusCode()).isEqualTo(204);
+ assertThat(allowed.headers().firstValue("Access-Control-Allow-Origin")).contains(ORIGIN);
+ assertThat(allowed.headers().firstValue("Access-Control-Allow-Methods")).contains("GET");
+ assertThat(allowed.headers().firstValue("Access-Control-Allow-Headers")).contains("authorization");
+ assertThat(allowed.headers().firstValue("Access-Control-Max-Age")).contains("300");
+ assertThat(allowed.headers().firstValue("Access-Control-Expose-Headers")).isEmpty();
+ assertThat(allowed.headers().firstValue("Vary")).isEmpty();
+
+ HttpResponse<String> other = send(apiId, "OPTIONS", "/anything", OTHER_ORIGIN, "GET");
+ assertThat(other.statusCode()).isEqualTo(204);
+ assertThat(corsHeaderNames(other)).isEmpty();
+
+ HttpResponse<String> notAPreflight = send(apiId, "OPTIONS", "/anything", null, null);
+ assertThat(notAPreflight.statusCode()).isEqualTo(204);
+ assertThat(corsHeaderNames(notAPreflight)).isEmpty();
+ }
+
+ @Test
+ @DisplayName("a throttled function's 503 carries the CORS headers")
+ void aThrottledFunctionsAnswerCarriesTheCorsHeaders() throws IOException, InterruptedException {
+ HttpResponse<String> throttled = send(apiId, "GET", "/throttled", ORIGIN, null);
+ assertThat(throttled.statusCode()).isEqualTo(503);
+ assertThat(throttled.body()).contains("Service Unavailable");
+ assertThat(throttled.headers().firstValue("Access-Control-Allow-Origin")).contains(ORIGIN);
+ assertThat(throttled.headers().firstValue("Access-Control-Expose-Headers")).contains("x-probe");
+ }
+
+ @Test
+ @DisplayName("a preflight to an API with two origins varies by origin and names no headers")
+ void aPreflightToAnApiWithTwoOriginsVariesByOrigin() throws IOException, InterruptedException {
+ HttpResponse<String> preflight = send(twoOriginsApiId, "OPTIONS", "/anything", ORIGIN, "GET");
+ assertThat(preflight.statusCode()).isEqualTo(204);
+ assertThat(preflight.headers().firstValue("Access-Control-Allow-Origin")).contains(ORIGIN);
+ assertThat(preflight.headers().firstValue("Access-Control-Allow-Methods")).contains("GET");
+ assertThat(preflight.headers().firstValue("Access-Control-Allow-Headers")).contains("");
+ assertThat(preflight.headers().firstValue("Vary")).hasValueSatisfying(
+ vary -> assertThat(vary).isEqualToIgnoringCase("origin"));
+ }
+
+ private static HttpResponse<String> send(String api, String method, String path, String origin,
+ String requestMethod) throws IOException, InterruptedException {
+ URI uri = URI.create(TestFixtures.endpoint() + "/execute-api/" + api + "/$default" + path);
+ HttpRequest.Builder request = HttpRequest.newBuilder(uri)
+ .timeout(Duration.ofSeconds(10))
+ .method(method, HttpRequest.BodyPublishers.noBody());
+ if (origin != null) {
+ request.header("Origin", origin);
+ }
+ if (requestMethod != null) {
+ request.header("Access-Control-Request-Method", requestMethod);
+ }
+ return HTTP.send(request.build(), HttpResponse.BodyHandlers.ofString());
+ }
+
+ private static List<String> corsHeaderNames(HttpResponse<String> response) {
+ return response.headers().map().keySet().stream()
+ .filter(name -> name.toLowerCase(Locale.ROOT).startsWith("access-control-"))
+ .toList();
+ }
+}
diff --git a/docs/services/api-gateway.md b/docs/services/api-gateway.md
index 8f03dff012..7a8ab4a1ed 100644
--- a/docs/services/api-gateway.md
+++ b/docs/services/api-gateway.md
@@ -656,6 +656,25 @@ curl http://{apiId}.execute-api.{region}.localhost.floci.io:4566/{stageName}/{pa
APIs created or updated with `disableExecuteApiEndpoint` reject requests to
this default hostname with `404 Not Found`, matching AWS HTTP API behavior.
+An API with a `corsConfiguration` applies it as AWS does (measured). It ignores the CORS headers an
+integration returns, and sets its own on whatever answers a route: the integration, or API Gateway
+itself refusing the request (a JWT or Lambda authorizer's `401` or `403`, an unsigned call to an
+`AWS_IAM` route's `403`) or failing it (a function that is gone, or that API Gateway may not invoke,
+answers `500` `Internal Server Error`; one Lambda throttles, `503` `Service Unavailable`). An
+`OPTIONS` request no route matches is answered `204`, preflight or not. A request whose `Origin` is
+allowed gets `Access-Control-Allow-Origin`, and `Access-Control-Allow-Credentials` and
+`Access-Control-Expose-Headers` when configured, whatever its method. A preflight (an `OPTIONS`
+request with `Origin` and `Access-Control-Request-Method`) gets the origin, credentials,
+`Access-Control-Allow-Methods`, `Access-Control-Allow-Headers` and `Access-Control-Max-Age` instead,
+and only when the method and every header it asks for are allowed; otherwise no CORS header at all.
+A preflight a route matches (an `OPTIONS` or `ANY` route, or `$default`) goes through that route, so
+its authorizer and its integration answer it; one no route matches is answered `204` by API Gateway.
+A preflight that gets them always carries `Access-Control-Allow-Headers`, empty when none are
+configured, and `Vary: origin` unless `allowOrigins` is a single exact origin or `*`; no other
+response gets a `Vary`. Lists are joined with a bare comma. A path no route matches, or a route
+without a target, answers `404` with none of them. An API without a configuration leaves CORS to its
+integrations.
+
Routes carrying `authorizationType: AWS_IAM`: including those an OpenAPI import resolves from an
`awsSigv4` security scheme: require a signed caller; see
[IAM Authorization](#iam-authorization).
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 78e9170127..6292fdaabd 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
@@ -77,6 +77,7 @@ import java.util.LinkedHashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
+import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import java.util.TreeMap;
@@ -85,6 +86,7 @@ import java.util.concurrent.ConcurrentHashMap;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;
+import java.util.stream.Collectors;
/**
* Executes API Gateway stage requests, routing them through the configured
@@ -2504,25 +2506,114 @@ 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");
+ /**
+ * The headers an HTTP API's CORS configuration sets, which API Gateway ignores when an
+ * integration returns them, lowercased for a case-insensitive match.
+ */
+ private static final Set<String> HTTP_API_CORS_HEADERS = Set.of(
+ "access-control-allow-origin",
+ "access-control-allow-credentials",
+ "access-control-expose-headers",
+ "access-control-max-age",
+ "access-control-allow-methods",
+ "access-control-allow-headers");
+
+ /**
+ * Applies an HTTP API's CORS configuration to the response of one of its requests, as measured
+ * on AWS (eu-west-1, 2026-10-16 and 2026-10-18). Once the API has a configuration, AWS drops
+ * the CORS headers an integration returns and sets its own on whatever answers: the
+ * integration, or API Gateway itself refusing the request (an authorizer's 401 or 403, an
+ * unsigned AWS_IAM call's 403) or failing it (a function that is gone, throttled or not
+ * invocable). A request whose {@code Origin} is allowed gets
+ * {@code Access-Control-Allow-Origin}, and {@code Access-Control-Allow-Credentials} and
+ * {@code Access-Control-Expose-Headers} when configured, whatever its method. An OPTIONS
+ * request is a preflight instead: it gets the origin, credentials,
+ * {@code Access-Control-Allow-Methods}, {@code Access-Control-Allow-Headers} and
+ * {@code Access-Control-Max-Age}, and only when the method and every header it asks for are
+ * allowed; otherwise, or without {@code Access-Control-Request-Method}, no CORS header at all.
+ * A preflight that gets them always carries {@code Access-Control-Allow-Headers}, empty when
+ * none are configured. Lists are joined with a bare comma, and AWS adds no {@code Vary} except
+ * to a preflight (see {@link #preflightVariesByOrigin}).
+ */
+ private static Response withHttpApiCors(Api.Cors cors, String httpMethod, HttpHeaders headers,
+ Response response) {
+ return headers == null
+ ? withHttpApiCors(cors, httpMethod, null, null, null, response)
+ : withHttpApiCors(cors, httpMethod, headers.getHeaderString("Origin"),
+ headers.getHeaderString("Access-Control-Request-Method"),
+ headers.getHeaderString("Access-Control-Request-Headers"), response);
+ }
+
+ static Response withHttpApiCors(Api.Cors cors, String httpMethod, String origin, String requestedMethod,
+ String requestedHeaders, Response response) {
+ if (cors == null) {
+ return response;
+ }
+ Response.ResponseBuilder builder = Response.status(response.getStatus()).entity(response.getEntity());
+ for (Map.Entry<String, List<Object>> header : response.getHeaders().entrySet()) {
+ if (HTTP_API_CORS_HEADERS.contains(header.getKey().toLowerCase(Locale.ROOT))) {
+ continue;
+ }
+ for (Object value : header.getValue()) {
+ builder.header(header.getKey(), value);
}
}
- 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());
+ String allowOrigin = matchingCorsOrigin(cors.allowOrigins(), origin);
+ if (allowOrigin == null) {
+ return builder.build();
+ }
+ if ("OPTIONS".equalsIgnoreCase(httpMethod)) {
+ if (requestedMethod == null || !corsAllows(cors.allowMethods(), requestedMethod)
+ || !corsAllowsEvery(cors.allowHeaders(), requestedHeaders)) {
+ return builder.build();
+ }
+ builder.header("Access-Control-Allow-Origin", allowOrigin);
+ putCorsListHeader(builder, "Access-Control-Allow-Methods", cors.allowMethods());
+ builder.header("Access-Control-Allow-Headers", corsList(cors.allowHeaders()));
+ if (Boolean.TRUE.equals(cors.allowCredentials())) {
+ builder.header("Access-Control-Allow-Credentials", "true");
+ }
+ if (cors.maxAge() != null) {
+ builder.header("Access-Control-Max-Age", cors.maxAge());
+ }
+ if (preflightVariesByOrigin(cors.allowOrigins())) {
+ builder.header("Vary", "origin");
+ }
+ return builder.build();
}
+ builder.header("Access-Control-Allow-Origin", allowOrigin);
if (Boolean.TRUE.equals(cors.allowCredentials())) {
- response.header("Access-Control-Allow-Credentials", "true");
+ builder.header("Access-Control-Allow-Credentials", "true");
}
- return response.build();
+ putCorsListHeader(builder, "Access-Control-Expose-Headers", cors.exposeHeaders());
+ return builder.build();
+ }
+
+ /**
+ * Whether a preflight's answer depends on its {@code Origin}, which AWS marks with
+ * {@code Vary: origin}: unless the configuration names a single exact origin or {@code *}, even
+ * when the answer is {@code *} (measured, eu-west-1, 2026-10-18).
+ */
+ private static boolean preflightVariesByOrigin(List<String> allowOrigins) {
+ String first = allowOrigins.get(0);
+ return allowOrigins.size() > 1 || (!"*".equals(first) && first.endsWith("*"));
+ }
+
+ private static boolean corsAllows(List<String> allowed, String value) {
+ return allowed != null && allowed.stream()
+ .anyMatch(item -> item != null && ("*".equals(item) || item.equalsIgnoreCase(value)));
+ }
+
+ private static boolean corsAllowsEvery(List<String> allowed, String requestedHeaders) {
+ if (requestedHeaders == null || requestedHeaders.isBlank()) {
+ return true;
+ }
+ for (String header : requestedHeaders.split(",")) {
+ if (!header.isBlank() && !corsAllows(allowed, header.trim())) {
+ return false;
+ }
+ }
+ return true;
}
private static String matchingCorsOrigin(List<String> allowedOrigins, String requestOrigin) {
@@ -2544,11 +2635,17 @@ public class ApiGatewayExecuteController {
private static void putCorsListHeader(Response.ResponseBuilder response, String headerName,
List<String> values) {
- if (values != null && !values.isEmpty()) {
- response.header(headerName, String.join(", ", values));
+ String list = corsList(values);
+ if (!list.isEmpty()) {
+ response.header(headerName, list);
}
}
+ /** A configured list as a CORS header value: its entries joined with a bare comma, null ones left out. */
+ private static String corsList(List<String> values) {
+ return values == null ? "" : values.stream().filter(Objects::nonNull).collect(Collectors.joining(","));
+ }
+
private Response dispatchV2(String httpMethod, String apiId, String stageName,
String proxy, HttpHeaders headers, UriInfo uriInfo,
byte[] body, String region) {
@@ -2570,23 +2667,30 @@ 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);
+ Api.Cors cors = api == null ? null : api.getCorsConfiguration();
Route route = apiGatewayV2Service.findMatchingRoute(region, apiId, httpMethod, path);
- if (route == null) {
+ if (route == null && cors != null && "OPTIONS".equalsIgnoreCase(httpMethod)) {
+ // A preflight no route matches is API Gateway's to answer. One a route matches (an
+ // OPTIONS or ANY route, $default) goes through it, authorizer and integration, and gets
+ // the preflight headers on whatever answers (measured).
+ return withHttpApiCors(cors, httpMethod, headers,
+ Response.noContent().type(MediaType.TEXT_PLAIN_TYPE).build());
+ }
+ // A route without a target answers as an unmatched one, with no CORS header (measured).
+ if (route == null || route.getTarget() == null) {
return Response.status(404)
.entity(jsonMessage("Not Found"))
.type(MediaType.APPLICATION_JSON).build();
}
+ return withHttpApiCors(cors, httpMethod, headers, dispatchMatchedRouteV2(route, httpMethod, apiId, stageName,
+ path, headers, uriInfo, body, region));
+ }
+ private Response dispatchMatchedRouteV2(Route route, String httpMethod, String apiId, String stageName,
+ String path, HttpHeaders headers, UriInfo uriInfo, byte[] body,
+ String region) {
Map<String, String> stageVariables = apiGatewayV2Service.getStageVariables(region, apiId, stageName);
// A route carries exactly one authorizationType, so AWS_IAM, JWT and CUSTOM are mutually
@@ -2622,12 +2726,6 @@ public class ApiGatewayExecuteController {
lambdaAuthorizerContext = requestResult.context();
}
- if (route.getTarget() == null) {
- return Response.status(500)
- .entity(jsonMessage("No integration configured"))
- .type(MediaType.APPLICATION_JSON).build();
- }
-
// target is "integrations/{integrationId}"
String integrationId = route.getTarget().startsWith("integrations/")
? route.getTarget().substring("integrations/".length()) : route.getTarget();
@@ -2673,12 +2771,14 @@ public class ApiGatewayExecuteController {
eventJson.getBytes(), InvocationType.RequestResponse);
return buildProxyResponse(result, true, !payloadV1);
} catch (AwsException e) {
- if (e.getHttpStatus() == 404) {
- return Response.status(404)
- .entity(jsonMessage("Function not found: " + functionName))
- .type(MediaType.APPLICATION_JSON).build();
- }
- throw e;
+ // Measured: API Gateway answers an invocation Lambda refuses itself, with the CORS
+ // headers like any response to the route: 503 when Lambda throttles it, 500 otherwise (a
+ // function that is gone, or one API Gateway may not invoke).
+ LOG.debugv("execute-api v2: invoking {0} failed: {1}", functionName, e.getMessage());
+ boolean throttled = e.getHttpStatus() == 429;
+ return Response.status(throttled ? 503 : 500)
+ .entity(jsonMessage(throttled ? "Service Unavailable" : "Internal Server Error"))
+ .type(MediaType.APPLICATION_JSON).build();
}
}
diff --git a/src/test/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayExecuteControllerTest.java b/src/test/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayExecuteControllerTest.java
index 8c7e7cc870..919002796d 100644
--- a/src/test/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayExecuteControllerTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayExecuteControllerTest.java
@@ -20,6 +20,8 @@ import java.nio.charset.StandardCharsets;
import java.time.Instant;
import java.time.ZoneOffset;
import java.time.ZonedDateTime;
+import java.util.Arrays;
+import java.util.LinkedHashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
@@ -704,4 +706,249 @@ class ApiGatewayExecuteControllerTest {
long timeEpoch = ctx.path("timeEpoch").asLong();
assertTrue(timeEpoch >= timeMillis && timeEpoch - timeMillis < 2000, time + " vs " + timeEpoch);
}
+
+ // ──────────────────────────── HTTP API CORS on integration responses ────────────────────────────
+
+ private static final String APP_ORIGIN = "https://app.example.com";
+
+ private static Api.Cors cors(List<String> allowOrigins, Boolean allowCredentials, List<String> exposeHeaders) {
+ return new Api.Cors(allowOrigins, List.of("GET", "POST"), List.of("authorization"), exposeHeaders,
+ 600, allowCredentials);
+ }
+
+ private static Response integrationResponseWithItsOwnCors() {
+ return Response.status(201)
+ .entity("{\"ok\":true}".getBytes(StandardCharsets.UTF_8))
+ .type("application/json")
+ .header("X-Trace", "kept")
+ .header("Access-Control-Allow-Origin", "https://backend.example.com")
+ .header("access-control-allow-methods", "PUT")
+ .header("Access-Control-Allow-Headers", "x-backend")
+ .header("Access-Control-Max-Age", "1")
+ .header("Access-Control-Expose-Headers", "x-backend")
+ .header("Access-Control-Allow-Credentials", "false")
+ .build();
+ }
+
+ @Test
+ void httpApiCorsAddsTheConfiguredHeadersForAnAllowedOrigin() {
+ Response response = ApiGatewayExecuteController.withHttpApiCors(
+ cors(List.of(APP_ORIGIN), true, List.of("x-request-id", "date")), "GET", APP_ORIGIN, null, null,
+ integrationResponseWithItsOwnCors());
+
+ assertEquals(201, response.getStatus());
+ assertEquals("{\"ok\":true}", new String((byte[]) response.getEntity(), StandardCharsets.UTF_8));
+ assertEquals("application/json", response.getHeaderString("Content-Type"));
+ assertEquals("kept", response.getHeaderString("X-Trace"));
+ assertEquals(List.of(APP_ORIGIN), response.getStringHeaders().get("Access-Control-Allow-Origin"));
+ assertEquals(List.of("true"), response.getStringHeaders().get("Access-Control-Allow-Credentials"));
+ assertEquals(List.of("x-request-id,date"), response.getStringHeaders().get("Access-Control-Expose-Headers"));
+ assertNull(response.getHeaderString("Vary"), "AWS adds no Vary to an HTTP API response");
+ assertNull(response.getHeaderString("Access-Control-Allow-Methods"));
+ assertNull(response.getHeaderString("Access-Control-Allow-Headers"));
+ assertNull(response.getHeaderString("Access-Control-Max-Age"));
+ }
+
+ @Test
+ void httpApiCorsOmitsCredentialsAndExposeHeadersThatAreNotConfigured() {
+ Response response = ApiGatewayExecuteController.withHttpApiCors(
+ cors(List.of(APP_ORIGIN), null, null), "GET", APP_ORIGIN, null, null, integrationResponseWithItsOwnCors());
+
+ assertEquals(APP_ORIGIN, response.getHeaderString("Access-Control-Allow-Origin"));
+ assertNull(response.getHeaderString("Access-Control-Allow-Credentials"));
+ assertNull(response.getHeaderString("Access-Control-Expose-Headers"));
+ }
+
+ @Test
+ void httpApiCorsIgnoresTheIntegrationsCorsHeadersForADisallowedOrigin() {
+ Response response = ApiGatewayExecuteController.withHttpApiCors(
+ cors(List.of(APP_ORIGIN), true, List.of("x-request-id")), "GET", "https://evil.example", null, null,
+ integrationResponseWithItsOwnCors());
+
+ assertEquals(201, response.getStatus());
+ assertEquals("kept", response.getHeaderString("X-Trace"));
+ for (String header : List.of("Access-Control-Allow-Origin", "Access-Control-Allow-Credentials",
+ "Access-Control-Expose-Headers", "Access-Control-Allow-Methods",
+ "Access-Control-Allow-Headers", "Access-Control-Max-Age", "Vary")) {
+ assertNull(response.getHeaderString(header), header);
+ }
+ }
+
+ @Test
+ void httpApiCorsAddsNothingWithoutAnOriginHeader() {
+ Response response = ApiGatewayExecuteController.withHttpApiCors(
+ cors(List.of("*"), null, List.of("x-request-id")), "GET", null, null, null, integrationResponseWithItsOwnCors());
+
+ assertNull(response.getHeaderString("Access-Control-Allow-Origin"));
+ assertNull(response.getHeaderString("Access-Control-Expose-Headers"));
+ assertEquals("kept", response.getHeaderString("X-Trace"));
+ }
+
+ @Test
+ void httpApiCorsAnswersAWildcardWithAStarAndNoVary() {
+ Response response = ApiGatewayExecuteController.withHttpApiCors(
+ cors(List.of("*"), null, null), "GET", APP_ORIGIN, null, null, integrationResponseWithItsOwnCors());
+
+ assertEquals("*", response.getHeaderString("Access-Control-Allow-Origin"));
+ assertNull(response.getHeaderString("Vary"));
+ }
+
+ @Test
+ void httpApiCorsEchoesAnOriginAPrefixWildcardAllows() {
+ Response allowed = ApiGatewayExecuteController.withHttpApiCors(
+ cors(List.of("https://*"), null, null), "GET", APP_ORIGIN, null, null, integrationResponseWithItsOwnCors());
+ Response refused = ApiGatewayExecuteController.withHttpApiCors(
+ cors(List.of("https://*"), null, null), "GET", "http://app.example.com", null, null, integrationResponseWithItsOwnCors());
+
+ assertEquals(APP_ORIGIN, allowed.getHeaderString("Access-Control-Allow-Origin"));
+ assertNull(refused.getHeaderString("Access-Control-Allow-Origin"));
+ }
+
+ @Test
+ void httpApiCorsKeepsTheIntegrationsOwnVary() {
+ Response integration = Response.ok().header("Vary", "Accept-Encoding, origin").build();
+
+ Response response = ApiGatewayExecuteController.withHttpApiCors(
+ cors(List.of(APP_ORIGIN), null, null), "GET", APP_ORIGIN, null, null, integration);
+
+ assertEquals(List.of("Accept-Encoding, origin"), response.getStringHeaders().get("Vary"));
+ }
+
+ /**
+ * Measured (eu-west-1, 2026-10-16): a preflight gets the methods, headers, credentials and max
+ * age, but no exposed headers, joined with a bare comma.
+ */
+ @Test
+ void httpApiCorsAnswersAPreflightThatAsksForWhatIsAllowed() {
+ Response response = ApiGatewayExecuteController.withHttpApiCors(
+ new Api.Cors(List.of(APP_ORIGIN), List.of("GET", "POST"), List.of("authorization", "x-a"),
+ List.of("x-one"), 60, true),
+ "OPTIONS", APP_ORIGIN, "GET", "Authorization, X-A", Response.noContent().build());
+
+ assertEquals(APP_ORIGIN, response.getHeaderString("Access-Control-Allow-Origin"));
+ assertEquals("GET,POST", response.getHeaderString("Access-Control-Allow-Methods"));
+ assertEquals("authorization,x-a", response.getHeaderString("Access-Control-Allow-Headers"));
+ assertEquals("true", response.getHeaderString("Access-Control-Allow-Credentials"));
+ assertEquals("60", response.getHeaderString("Access-Control-Max-Age"));
+ assertNull(response.getHeaderString("Access-Control-Expose-Headers"));
+ assertNull(response.getHeaderString("Vary"), "a single exact origin does not vary");
+ }
+
+ /**
+ * Measured (eu-west-1, 2026-10-18): a preflight carries {@code Vary: origin} unless the
+ * configuration names a single exact origin or {@code *}, also when {@code *} is listed beside an
+ * exact origin and answers for every origin.
+ */
+ @Test
+ void httpApiCorsPreflightVariesByOriginUnlessOneOriginOrAStarIsConfigured() {
+ Map<List<String>, String> expectedVary = new LinkedHashMap<>();
+ expectedVary.put(List.of(APP_ORIGIN), null);
+ expectedVary.put(List.of("*"), null);
+ expectedVary.put(List.of(APP_ORIGIN, "https://other.example.com"), "origin");
+ expectedVary.put(List.of("https://*"), "origin");
+ expectedVary.put(List.of("*", APP_ORIGIN), "origin");
+ expectedVary.forEach((origins, vary) -> {
+ Response preflight = ApiGatewayExecuteController.withHttpApiCors(
+ new Api.Cors(origins, List.of("GET"), null, null, null, null),
+ "OPTIONS", APP_ORIGIN, "GET", null, Response.noContent().build());
+ Response actual = ApiGatewayExecuteController.withHttpApiCors(
+ new Api.Cors(origins, List.of("GET"), null, null, null, null),
+ "GET", APP_ORIGIN, null, null, Response.ok().build());
+
+ assertEquals(vary, preflight.getHeaderString("Vary"), origins.toString());
+ assertNull(actual.getHeaderString("Vary"), origins + " on an actual request");
+ });
+ assertEquals("*", ApiGatewayExecuteController.withHttpApiCors(
+ new Api.Cors(List.of("*", APP_ORIGIN), List.of("GET"), null, null, null, null),
+ "OPTIONS", APP_ORIGIN, "GET", null, Response.noContent().build())
+ .getHeaderString("Access-Control-Allow-Origin"));
+ }
+
+ /** Measured: a preflight names the allowed headers even when none are configured, with an empty value. */
+ @Test
+ void httpApiCorsPreflightNamesNoHeadersWhenNoneAreConfigured() {
+ Response response = ApiGatewayExecuteController.withHttpApiCors(
+ new Api.Cors(List.of(APP_ORIGIN), List.of("GET"), null, null, null, null),
+ "OPTIONS", APP_ORIGIN, "GET", null, Response.noContent().build());
+
+ assertEquals(List.of(""), response.getStringHeaders().get("Access-Control-Allow-Headers"));
+ assertNull(response.getHeaderString("Access-Control-Max-Age"));
+ assertNull(response.getHeaderString("Access-Control-Allow-Credentials"));
+ }
+
+ /**
+ * Measured: a preflight asking for a method or a header the configuration does not allow, an
+ * API without AllowMethods, and an OPTIONS request that is not a preflight get no CORS header.
+ */
+ @Test
+ void httpApiCorsAddsNothingToAPreflightItRefuses() {
+ Api.Cors configured = new Api.Cors(List.of(APP_ORIGIN), List.of("GET", "POST"), List.of("authorization"),
+ null, 60, null);
+ Api.Cors noMethods = new Api.Cors(List.of(APP_ORIGIN), null, List.of("authorization"), null, null, null);
+ List<Response> refused = List.of(
+ ApiGatewayExecuteController.withHttpApiCors(configured, "OPTIONS", APP_ORIGIN, "DELETE", null,
+ Response.noContent().build()),
+ ApiGatewayExecuteController.withHttpApiCors(configured, "OPTIONS", APP_ORIGIN, "GET", "x-not-allowed",
+ Response.noContent().build()),
+ ApiGatewayExecuteController.withHttpApiCors(noMethods, "OPTIONS", APP_ORIGIN, "GET", null,
+ Response.noContent().build()),
+ ApiGatewayExecuteController.withHttpApiCors(configured, "OPTIONS", APP_ORIGIN, null, null,
+ Response.ok().build()));
+ for (Response response : refused) {
+ assertNull(response.getHeaderString("Access-Control-Allow-Origin"));
+ assertNull(response.getHeaderString("Access-Control-Allow-Methods"));
+ }
+ }
+
+ /** A configured list may hold a null entry: it matches nothing and is left out of the header. */
+ @Test
+ void httpApiCorsSkipsANullEntryOfAConfiguredList() {
+ Response response = ApiGatewayExecuteController.withHttpApiCors(
+ new Api.Cors(List.of(APP_ORIGIN), Arrays.asList(null, "GET"), Arrays.asList(null, "x-a"),
+ null, null, null),
+ "OPTIONS", APP_ORIGIN, "GET", "x-a", Response.noContent().build());
+
+ assertEquals(APP_ORIGIN, response.getHeaderString("Access-Control-Allow-Origin"));
+ assertEquals("GET", response.getHeaderString("Access-Control-Allow-Methods"));
+ assertEquals("x-a", response.getHeaderString("Access-Control-Allow-Headers"));
+ }
+
+ /** Measured: wildcards allow any method and header, and are sent back as they are. */
+ @Test
+ void httpApiCorsAllowsAnyMethodAndHeaderForWildcards() {
+ Response response = ApiGatewayExecuteController.withHttpApiCors(
+ new Api.Cors(List.of("*"), List.of("*"), List.of("*"), null, null, null),
+ "OPTIONS", APP_ORIGIN, "DELETE", "x-anything", Response.noContent().build());
+
+ assertEquals("*", response.getHeaderString("Access-Control-Allow-Origin"));
+ assertEquals("*", response.getHeaderString("Access-Control-Allow-Methods"));
+ assertEquals("*", response.getHeaderString("Access-Control-Allow-Headers"));
+ }
+
+ /** Measured: an actual request gets the headers whatever its method, DELETE when only GET is allowed too. */
+ @Test
+ void httpApiCorsAddsTheActualHeadersWhateverTheMethod() {
+ Response response = ApiGatewayExecuteController.withHttpApiCors(
+ cors(List.of(APP_ORIGIN), null, List.of("x-one", "x-two")), "DELETE", APP_ORIGIN, null, null,
+ Response.ok().build());
+
+ assertEquals(APP_ORIGIN, response.getHeaderString("Access-Control-Allow-Origin"));
+ assertEquals("x-one,x-two", response.getHeaderString("Access-Control-Expose-Headers"));
+ }
+
+ @Test
+ void httpApiCorsDropsTheCorsHeadersALambdaReturnsInLowercase() {
+ ApiGatewayExecuteController controller = controller(new ObjectMapper());
+ Response lambdaResponse = controller.buildProxyResponse(proxyPayload("""
+ {"statusCode":200,"headers":{"access-control-allow-origin":"*","x-trace":"lambda"},
+ "body":"hi"}
+ """), true);
+
+ Response response = ApiGatewayExecuteController.withHttpApiCors(
+ cors(List.of(APP_ORIGIN), null, null), "GET", "https://evil.example", null, null, lambdaResponse);
+
+ assertNull(response.getHeaderString("Access-Control-Allow-Origin"));
+ assertEquals("lambda", response.getHeaderString("x-trace"));
+ assertEquals("hi", new String((byte[]) response.getEntity(), StandardCharsets.UTF_8));
+ }
}
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
index 5c1a0981b4..e23bdeddc6 100644
--- a/src/test/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayPreflightRoutingIntegrationTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayPreflightRoutingIntegrationTest.java
@@ -12,6 +12,7 @@ import org.junit.jupiter.api.TestMethodOrder;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.notNullValue;
+import static org.hamcrest.Matchers.nullValue;
/**
* End-to-end coverage for CORS preflight (OPTIONS) handling on deployed API Gateway
@@ -233,9 +234,9 @@ class ApiGatewayPreflightRoutingIntegrationTest {
.then()
.statusCode(204)
.header("Access-Control-Allow-Origin", equalTo(ORIGIN))
- .header("Access-Control-Allow-Methods", equalTo("GET, POST"))
+ .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-Expose-Headers", nullValue())
.header("Access-Control-Max-Age", equalTo("600"))
.header("Access-Control-Allow-Credentials", equalTo("true"));
}
diff --git a/src/test/java/io/github/hectorvent/floci/services/apigatewayv2/ApiGatewayV2UnsignedAccountRoutingTest.java b/src/test/java/io/github/hectorvent/floci/services/apigatewayv2/ApiGatewayV2UnsignedAccountRoutingTest.java
index f436da1a9d..ce07ae7efc 100644
--- a/src/test/java/io/github/hectorvent/floci/services/apigatewayv2/ApiGatewayV2UnsignedAccountRoutingTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/apigatewayv2/ApiGatewayV2UnsignedAccountRoutingTest.java
@@ -19,19 +19,21 @@ class ApiGatewayV2UnsignedAccountRoutingTest {
String apiA = createApiGraph(ACCOUNT_A, "account-a-function");
String apiB = createApiGraph(ACCOUNT_B, "account-b-function");
+ // Each route is found in its API's account and reaches its integration, whose function does
+ // not exist: API Gateway's 500, where an API it could not find would be a 404.
given()
.header("Authorization", authorization(ACCOUNT_B, "execute-api"))
.when().get("/execute-api/" + apiA + "/$default/health")
.then()
- .statusCode(404)
- .body(containsString("Function not found: account-a-function"));
+ .statusCode(500)
+ .body(containsString("Internal Server Error"));
given()
.header("Host", apiB + ".execute-api.localhost.floci.io")
.when().get("/health")
.then()
- .statusCode(404)
- .body(containsString("Function not found: account-b-function"));
+ .statusCode(500)
+ .body(containsString("Internal Server Error"));
}
@Test
diff --git a/src/test/java/io/github/hectorvent/floci/services/apigatewayv2/HttpApiCorsIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/apigatewayv2/HttpApiCorsIntegrationTest.java
new file mode 100644
index 0000000000..a44979ef0d
--- /dev/null
+++ b/src/test/java/io/github/hectorvent/floci/services/apigatewayv2/HttpApiCorsIntegrationTest.java
@@ -0,0 +1,421 @@
+package io.github.hectorvent.floci.services.apigatewayv2;
+
+import com.sun.net.httpserver.HttpExchange;
+import com.sun.net.httpserver.HttpServer;
+import io.quarkus.test.junit.QuarkusTest;
+import io.restassured.http.ContentType;
+import org.junit.jupiter.api.AfterAll;
+import org.junit.jupiter.api.BeforeAll;
+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.io.IOException;
+import java.net.InetSocketAddress;
+import java.nio.charset.StandardCharsets;
+
+import static io.restassured.RestAssured.given;
+import static org.hamcrest.Matchers.containsString;
+import static org.hamcrest.Matchers.equalTo;
+import static org.hamcrest.Matchers.nullValue;
+
+/**
+ * CORS on the actual responses of an HTTP API, not only on its preflights. AWS documents that once
+ * an HTTP API has a CORS configuration, API Gateway adds the configured CORS headers to the
+ * integration's response for a request carrying an allowed {@code Origin}, and ignores the CORS
+ * headers the integration returns. Before the fix the configuration answered the preflight only,
+ * so a browser refused to hand the page any response of the API.
+ *
+ * <p>The backend sets its own CORS headers on every response, so each case also shows them gone.
+ */
+@QuarkusTest
+@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
+class HttpApiCorsIntegrationTest {
+
+ private static final String APP_ORIGIN = "https://app.localhost.floci.io";
+ private static final String DOMAIN = "cors-probe.localhost.floci.io";
+ private static final String BACKEND_BODY = "{\"from\":\"backend\"}";
+ private static final String THROTTLED_FUNCTION = "http-api-cors-throttled";
+
+ private static HttpServer backend;
+ private static int backendPort;
+ private static String corsApiId;
+ private static String plainApiId;
+
+ @BeforeAll
+ static void startBackend() throws IOException {
+ backend = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0);
+ backend.createContext("/", HttpApiCorsIntegrationTest::handle);
+ backend.start();
+ backendPort = backend.getAddress().getPort();
+ }
+
+ @AfterAll
+ static void stopBackend() {
+ if (backend != null) {
+ backend.stop(0);
+ }
+ }
+
+ private static void handle(HttpExchange exchange) throws IOException {
+ byte[] response = BACKEND_BODY.getBytes(StandardCharsets.UTF_8);
+ exchange.getResponseHeaders().add("Content-Type", "application/json");
+ exchange.getResponseHeaders().add("X-Request-Id", "backend-request");
+ exchange.getResponseHeaders().add("Access-Control-Allow-Origin", "https://backend.example.com");
+ exchange.getResponseHeaders().add("Access-Control-Allow-Methods", "PUT");
+ exchange.getResponseHeaders().add("Access-Control-Expose-Headers", "x-backend");
+ exchange.sendResponseHeaders(200, response.length);
+ exchange.getResponseBody().write(response);
+ exchange.close();
+ }
+
+ @Test
+ @Order(1)
+ void createApis() {
+ corsApiId = HttpProxyApiFixtures.createProxyApi("http-api-cors", """
+ ,"corsConfiguration":{
+ "allowOrigins":["%s"],
+ "allowMethods":["GET","POST","DELETE"],
+ "allowHeaders":["authorization","content-type"],
+ "exposeHeaders":["x-request-id"],
+ "maxAge":3600,
+ "allowCredentials":true
+ }""".formatted(APP_ORIGIN), "$default", backendPort, "/hello");
+ plainApiId = HttpProxyApiFixtures.createProxyApi("http-api-no-cors", "", "$default", backendPort, "/hello");
+
+ given()
+ .contentType(ContentType.JSON)
+ .body("""
+ {"domainName":"%s","domainNameConfigurations":[
+ {"certificateArn":"arn:aws:acm:us-east-1:000000000000:certificate/abc",
+ "endpointType":"REGIONAL","securityPolicy":"TLS_1_2"}]}
+ """.formatted(DOMAIN))
+ .when().post("/v2/domainnames")
+ .then().statusCode(201);
+ given()
+ .contentType(ContentType.JSON)
+ .body("{\"apiId\":\"" + corsApiId + "\",\"stage\":\"$default\"}")
+ .when().post("/v2/domainnames/" + DOMAIN + "/apimappings")
+ .then().statusCode(201);
+ }
+
+ @Test
+ @Order(2)
+ void anAllowedOriginGetsTheConfiguredHeadersOnTheActualResponse() {
+ given()
+ .header("Origin", APP_ORIGIN)
+ .when().get("/execute-api/" + corsApiId + "/$default/hello")
+ .then()
+ .statusCode(200)
+ .body(equalTo(BACKEND_BODY))
+ .header("X-Request-Id", equalTo("backend-request"))
+ .header("Access-Control-Allow-Origin", equalTo(APP_ORIGIN))
+ .header("Access-Control-Allow-Credentials", equalTo("true"))
+ .header("Access-Control-Expose-Headers", equalTo("x-request-id"))
+ .header("Vary", nullValue())
+ .header("Access-Control-Allow-Methods", nullValue());
+ }
+
+ @Test
+ @Order(3)
+ void theSameHeadersArriveThroughTheCustomDomain() {
+ given()
+ .header("Host", DOMAIN)
+ .header("Origin", APP_ORIGIN)
+ .when().get("/hello")
+ .then()
+ .statusCode(200)
+ .body(equalTo(BACKEND_BODY))
+ .header("Access-Control-Allow-Origin", equalTo(APP_ORIGIN))
+ .header("Access-Control-Allow-Credentials", equalTo("true"));
+ }
+
+ @Test
+ @Order(4)
+ void aDisallowedOriginGetsNoCorsHeaders() {
+ given()
+ .header("Origin", "https://evil.example")
+ .when().get("/execute-api/" + corsApiId + "/$default/hello")
+ .then()
+ .statusCode(200)
+ .body(equalTo(BACKEND_BODY))
+ .header("Access-Control-Allow-Origin", nullValue())
+ .header("Access-Control-Allow-Credentials", nullValue())
+ .header("Access-Control-Expose-Headers", nullValue())
+ .header("Access-Control-Allow-Methods", nullValue());
+ }
+
+ @Test
+ @Order(5)
+ void aRequestWithoutAnOriginGetsNoCorsHeaders() {
+ given()
+ .when().get("/execute-api/" + corsApiId + "/$default/hello")
+ .then()
+ .statusCode(200)
+ .header("Access-Control-Allow-Origin", nullValue())
+ .header("Access-Control-Expose-Headers", nullValue());
+ }
+
+ @Test
+ @Order(6)
+ void aPreflightNoRouteMatchesIsAnsweredFromTheConfiguration() {
+ given()
+ .header("Origin", APP_ORIGIN)
+ .header("Access-Control-Request-Method", "POST")
+ .when().options("/execute-api/" + corsApiId + "/$default/hello")
+ .then()
+ .statusCode(204)
+ .header("Access-Control-Allow-Origin", equalTo(APP_ORIGIN))
+ .header("Access-Control-Allow-Methods", equalTo("GET,POST,DELETE"))
+ .header("Access-Control-Allow-Headers", equalTo("authorization,content-type"))
+ .header("Access-Control-Allow-Credentials", equalTo("true"))
+ .header("Access-Control-Max-Age", equalTo("3600"))
+ .header("Access-Control-Expose-Headers", nullValue())
+ .header("Vary", nullValue());
+ // Measured: an OPTIONS request no route matches is answered 204 even when it is not a
+ // preflight, with no CORS header.
+ given()
+ .when().options("/execute-api/" + corsApiId + "/$default/hello")
+ .then()
+ .statusCode(204)
+ .header("Access-Control-Allow-Origin", nullValue());
+ given()
+ .header("Origin", APP_ORIGIN)
+ .when().options("/execute-api/" + corsApiId + "/$default/hello")
+ .then()
+ .statusCode(204)
+ .header("Access-Control-Allow-Origin", nullValue());
+ }
+
+ /**
+ * API Gateway's own refusals carry the CORS headers too: on AWS a JWT authorizer's 401, an
+ * unsigned call to an AWS_IAM route's 403 and a Lambda authorizer's 401 and 403 all answer an
+ * allowed Origin with Access-Control-Allow-Origin, so a browser can read the status.
+ */
+ @Test
+ @Order(8)
+ void anAuthorizersRefusalCarriesTheCorsHeaders() {
+ String integrationId = given()
+ .contentType(ContentType.JSON)
+ .body("{\"integrationType\":\"HTTP_PROXY\",\"integrationUri\":\"http://127.0.0.1:"
+ + backendPort + "/hello\",\"payloadFormatVersion\":\"1.0\"}")
+ .when().post("/v2/apis/" + corsApiId + "/integrations")
+ .then().statusCode(201)
+ .extract().path("integrationId");
+ String authorizerId = given()
+ .contentType(ContentType.JSON)
+ .body("""
+ {"name":"jwt","authorizerType":"JWT",
+ "identitySource":["$request.header.Authorization"],
+ "jwtConfiguration":{"audience":["cors"],"issuer":"https://issuer.example.com"}}""")
+ .when().post("/v2/apis/" + corsApiId + "/authorizers")
+ .then().statusCode(201)
+ .extract().path("authorizerId");
+ given()
+ .contentType(ContentType.JSON)
+ .body("{\"routeKey\":\"GET /jwt\",\"authorizationType\":\"JWT\",\"authorizerId\":\""
+ + authorizerId + "\",\"target\":\"integrations/" + integrationId + "\"}")
+ .when().post("/v2/apis/" + corsApiId + "/routes")
+ .then().statusCode(201);
+ given()
+ .contentType(ContentType.JSON)
+ .body("{\"routeKey\":\"GET /iam\",\"authorizationType\":\"AWS_IAM\","
+ + "\"target\":\"integrations/" + integrationId + "\"}")
+ .when().post("/v2/apis/" + corsApiId + "/routes")
+ .then().statusCode(201);
+
+ given()
+ .header("Origin", APP_ORIGIN)
+ .when().get("/execute-api/" + corsApiId + "/$default/jwt")
+ .then()
+ .statusCode(401)
+ .header("Access-Control-Allow-Origin", equalTo(APP_ORIGIN))
+ .header("Access-Control-Allow-Credentials", equalTo("true"))
+ .header("Vary", nullValue());
+ given()
+ .header("Origin", APP_ORIGIN)
+ .when().get("/execute-api/" + corsApiId + "/$default/iam")
+ .then()
+ .statusCode(403)
+ .header("Access-Control-Allow-Origin", equalTo(APP_ORIGIN));
+ given()
+ .header("Origin", "https://evil.example")
+ .when().get("/execute-api/" + corsApiId + "/$default/jwt")
+ .then()
+ .statusCode(401)
+ .header("Access-Control-Allow-Origin", nullValue());
+ }
+
+ /** Without a CORS configuration API Gateway leaves CORS to the integration. */
+ @Test
+ @Order(7)
+ void anApiWithoutCorsConfigurationPassesTheIntegrationsHeadersThrough() {
+ given()
+ .header("Origin", APP_ORIGIN)
+ .when().get("/execute-api/" + plainApiId + "/$default/hello")
+ .then()
+ .statusCode(200)
+ .header("Access-Control-Allow-Origin", equalTo("https://backend.example.com"))
+ .header("Access-Control-Allow-Methods", equalTo("PUT"))
+ .header("Access-Control-Expose-Headers", equalTo("x-backend"));
+ }
+
+ /**
+ * Measured (eu-west-1, 2026-10-16): a preflight a route matches goes through that route, so an
+ * ANY route's integration answers it and an authorizer refuses it, and either answer carries the
+ * preflight headers.
+ */
+ @Test
+ @Order(9)
+ void aPreflightARouteMatchesGoesThroughTheRoute() {
+ String integrationId = given()
+ .contentType(ContentType.JSON)
+ .body("{\"integrationType\":\"HTTP_PROXY\",\"integrationUri\":\"http://127.0.0.1:"
+ + backendPort + "/hello\",\"payloadFormatVersion\":\"1.0\"}")
+ .when().post("/v2/apis/" + corsApiId + "/integrations")
+ .then().statusCode(201)
+ .extract().path("integrationId");
+ String authorizerId = given()
+ .contentType(ContentType.JSON)
+ .body("""
+ {"name":"jwt-any","authorizerType":"JWT",
+ "identitySource":["$request.header.Authorization"],
+ "jwtConfiguration":{"audience":["cors"],"issuer":"https://issuer.example.com"}}""")
+ .when().post("/v2/apis/" + corsApiId + "/authorizers")
+ .then().statusCode(201)
+ .extract().path("authorizerId");
+ given()
+ .contentType(ContentType.JSON)
+ .body("{\"routeKey\":\"ANY /open/{proxy+}\",\"target\":\"integrations/" + integrationId + "\"}")
+ .when().post("/v2/apis/" + corsApiId + "/routes")
+ .then().statusCode(201);
+ given()
+ .contentType(ContentType.JSON)
+ .body("{\"routeKey\":\"ANY /secure/{proxy+}\",\"authorizationType\":\"JWT\",\"authorizerId\":\""
+ + authorizerId + "\",\"target\":\"integrations/" + integrationId + "\"}")
+ .when().post("/v2/apis/" + corsApiId + "/routes")
+ .then().statusCode(201);
+
+ given()
+ .header("Origin", APP_ORIGIN)
+ .header("Access-Control-Request-Method", "GET")
+ .when().options("/execute-api/" + corsApiId + "/$default/open/x")
+ .then()
+ .statusCode(200)
+ .body(equalTo(BACKEND_BODY))
+ .header("Access-Control-Allow-Origin", equalTo(APP_ORIGIN))
+ .header("Access-Control-Allow-Methods", equalTo("GET,POST,DELETE"))
+ .header("Access-Control-Max-Age", equalTo("3600"));
+ given()
+ .header("Origin", APP_ORIGIN)
+ .header("Access-Control-Request-Method", "GET")
+ .when().options("/execute-api/" + corsApiId + "/$default/secure/x")
+ .then()
+ .statusCode(401)
+ .header("Access-Control-Allow-Origin", equalTo(APP_ORIGIN))
+ .header("Access-Control-Allow-Methods", equalTo("GET,POST,DELETE"));
+ given()
+ .header("Origin", APP_ORIGIN)
+ .header("Access-Control-Request-Method", "PATCH")
+ .when().options("/execute-api/" + corsApiId + "/$default/open/x")
+ .then()
+ .statusCode(200)
+ .header("Access-Control-Allow-Origin", nullValue())
+ .header("Access-Control-Allow-Methods", nullValue());
+ }
+
+ /**
+ * Measured: a function that is gone fails the request with API Gateway's 500 and one Lambda
+ * throttles with its 503, both carrying the CORS headers, while a route without a target
+ * answers as an unmatched one, without them.
+ */
+ @Test
+ @Order(10)
+ void apiGatewaysOwnAnswersOnARoute() throws Exception {
+ String integrationId = given()
+ .contentType(ContentType.JSON)
+ .body("{\"integrationType\":\"AWS_PROXY\",\"integrationUri\":"
+ + "\"arn:aws:lambda:us-east-1:000000000000:function:cors-gone\",\"payloadFormatVersion\":\"2.0\"}")
+ .when().post("/v2/apis/" + corsApiId + "/integrations")
+ .then().statusCode(201)
+ .extract().path("integrationId");
+ given()
+ .contentType(ContentType.JSON)
+ .body("{\"routeKey\":\"GET /gone\",\"target\":\"integrations/" + integrationId + "\"}")
+ .when().post("/v2/apis/" + corsApiId + "/routes")
+ .then().statusCode(201);
+ given()
+ .contentType(ContentType.JSON)
+ .body("{\"routeKey\":\"GET /notarget\"}")
+ .when().post("/v2/apis/" + corsApiId + "/routes")
+ .then().statusCode(201);
+ given()
+ .contentType(ContentType.JSON)
+ .body("""
+ {"FunctionName":"%s","Runtime":"nodejs20.x","Handler":"index.handler",
+ "Role":"arn:aws:iam::000000000000:role/lambda-role","Code":{"ZipFile":"%s"}}
+ """.formatted(THROTTLED_FUNCTION,
+ WebSocketTestSupport.createLambdaZip("exports.handler = async () => 'ok';")))
+ .when().post("/2015-03-31/functions")
+ .then().statusCode(201);
+ given()
+ .contentType(ContentType.JSON)
+ .body("{\"ReservedConcurrentExecutions\":0}")
+ .when().put("/2017-10-31/functions/" + THROTTLED_FUNCTION + "/concurrency")
+ .then().statusCode(200);
+ String throttledIntegrationId = given()
+ .contentType(ContentType.JSON)
+ .body("{\"integrationType\":\"AWS_PROXY\",\"integrationUri\":"
+ + "\"arn:aws:lambda:us-east-1:000000000000:function:" + THROTTLED_FUNCTION + "\","
+ + "\"payloadFormatVersion\":\"2.0\"}")
+ .when().post("/v2/apis/" + corsApiId + "/integrations")
+ .then().statusCode(201)
+ .extract().path("integrationId");
+ given()
+ .contentType(ContentType.JSON)
+ .body("{\"routeKey\":\"GET /throttled\",\"target\":\"integrations/"
+ + throttledIntegrationId + "\"}")
+ .when().post("/v2/apis/" + corsApiId + "/routes")
+ .then().statusCode(201);
+
+ given()
+ .header("Origin", APP_ORIGIN)
+ .when().get("/execute-api/" + corsApiId + "/$default/gone")
+ .then()
+ .statusCode(500)
+ .body(containsString("Internal Server Error"))
+ .header("Access-Control-Allow-Origin", equalTo(APP_ORIGIN))
+ .header("Access-Control-Expose-Headers", equalTo("x-request-id"));
+ given()
+ .header("Origin", APP_ORIGIN)
+ .when().get("/execute-api/" + corsApiId + "/$default/notarget")
+ .then()
+ .statusCode(404)
+ .body(containsString("Not Found"))
+ .header("Access-Control-Allow-Origin", nullValue());
+ given()
+ .header("Origin", APP_ORIGIN)
+ .when().get("/execute-api/" + corsApiId + "/$default/throttled")
+ .then()
+ .statusCode(503)
+ .body(containsString("Service Unavailable"))
+ .header("Access-Control-Allow-Origin", equalTo(APP_ORIGIN))
+ .header("Access-Control-Expose-Headers", equalTo("x-request-id"));
+ }
+
+ @Test
+ @Order(20)
+ void cleanup() {
+ String mappingId = given()
+ .when().get("/v2/domainnames/" + DOMAIN + "/apimappings")
+ .then().statusCode(200)
+ .extract().path("items[0].apiMappingId");
+ given().when().delete("/v2/domainnames/" + DOMAIN + "/apimappings/" + mappingId)
+ .then().statusCode(204);
+ given().when().delete("/v2/domainnames/" + DOMAIN).then().statusCode(204);
+ given().when().delete("/v2/apis/" + corsApiId).then().statusCode(204);
+ given().when().delete("/v2/apis/" + plainApiId).then().statusCode(204);
+ given().when().delete("/2015-03-31/functions/" + THROTTLED_FUNCTION).then().statusCode(204);
+ }
+}
diff --git a/src/test/java/io/github/hectorvent/floci/services/apigatewayv2/HttpApiHttpProxyMultiValueIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/apigatewayv2/HttpApiHttpProxyMultiValueIntegrationTest.java
index 493bee3de2..9e9ea85867 100644
--- a/src/test/java/io/github/hectorvent/floci/services/apigatewayv2/HttpApiHttpProxyMultiValueIntegrationTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/apigatewayv2/HttpApiHttpProxyMultiValueIntegrationTest.java
@@ -3,7 +3,6 @@ package io.github.hectorvent.floci.services.apigatewayv2;
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpServer;
import io.quarkus.test.junit.QuarkusTest;
-import io.restassured.http.ContentType;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
@@ -84,34 +83,7 @@ class HttpApiHttpProxyMultiValueIntegrationTest {
* the fixture backend, deployed to stage {@code test}.
*/
private String createProxyApi(String name) {
- String apiId = given()
- .contentType(ContentType.JSON)
- .body("{\"name\":\"" + name + "\",\"protocolType\":\"HTTP\"}")
- .when().post("/v2/apis")
- .then().statusCode(201)
- .extract().path("apiId");
-
- given()
- .contentType(ContentType.JSON)
- .body("{\"stageName\":\"test\"}")
- .when().post("/v2/apis/" + apiId + "/stages")
- .then().statusCode(201);
-
- String integrationId = given()
- .contentType(ContentType.JSON)
- .body("{\"integrationType\":\"HTTP_PROXY\",\"integrationUri\":\"http://127.0.0.1:"
- + backendPort + "/orders\",\"payloadFormatVersion\":\"1.0\"}")
- .when().post("/v2/apis/" + apiId + "/integrations")
- .then().statusCode(201)
- .extract().path("integrationId");
-
- given()
- .contentType(ContentType.JSON)
- .body("{\"routeKey\":\"GET /orders\",\"target\":\"integrations/" + integrationId + "\"}")
- .when().post("/v2/apis/" + apiId + "/routes")
- .then().statusCode(201);
-
- return apiId;
+ return HttpProxyApiFixtures.createProxyApi(name, "", "test", backendPort, "/orders");
}
@Test
diff --git a/src/test/java/io/github/hectorvent/floci/services/apigatewayv2/HttpApiJwtAuthorizerScopesTest.java b/src/test/java/io/github/hectorvent/floci/services/apigatewayv2/HttpApiJwtAuthorizerScopesTest.java
index 6201e7aaca..6cdfa3d5cf 100644
--- a/src/test/java/io/github/hectorvent/floci/services/apigatewayv2/HttpApiJwtAuthorizerScopesTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/apigatewayv2/HttpApiJwtAuthorizerScopesTest.java
@@ -29,6 +29,7 @@ import java.util.zip.ZipOutputStream;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.equalTo;
+import static org.hamcrest.Matchers.nullValue;
import static org.junit.jupiter.api.Assertions.*;
/**
@@ -253,6 +254,42 @@ class HttpApiJwtAuthorizerScopesTest {
.body("message", equalTo("Forbidden"));
}
+ /**
+ * Measured on AWS (eu-west-1, 2026-10-18): once the API has a CORS configuration, the 403 of a
+ * token without the route's scope carries {@code Access-Control-Allow-Origin} and
+ * {@code Access-Control-Expose-Headers} for an allowed origin, and no CORS header for another.
+ */
+ @Test
+ @Order(13)
+ void scopeRefusalCarriesTheCorsHeadersOfTheApi() throws Exception {
+ given()
+ .contentType(ContentType.JSON)
+ .body("""
+ {"corsConfiguration":{"allowOrigins":["https://app.example.com"],"allowMethods":["GET"],
+ "allowHeaders":["authorization"],"exposeHeaders":["x-probe"],"maxAge":300}}
+ """)
+ .when().patch("/v2/apis/" + httpApiId)
+ .then().statusCode(200);
+ try {
+ String token = signedToken(Map.of("iss", issuer, "aud", AUDIENCE, "exp", farFuture()));
+ given()
+ .header("Origin", "https://app.example.com")
+ .header("Authorization", "Bearer " + token)
+ .when().get("/execute-api/" + httpApiId + "/test/scoped")
+ .then().statusCode(403)
+ .header("Access-Control-Allow-Origin", equalTo("https://app.example.com"))
+ .header("Access-Control-Expose-Headers", equalTo("x-probe"));
+ given()
+ .header("Origin", "https://evil.example")
+ .header("Authorization", "Bearer " + token)
+ .when().get("/execute-api/" + httpApiId + "/test/scoped")
+ .then().statusCode(403)
+ .header("Access-Control-Allow-Origin", nullValue());
+ } finally {
+ given().when().delete("/v2/apis/" + httpApiId + "/cors").then().statusCode(204);
+ }
+ }
+
// ──────────────────────────── Cleanup ────────────────────────────
@Test
diff --git a/src/test/java/io/github/hectorvent/floci/services/apigatewayv2/HttpApiRequestAuthorizerTest.java b/src/test/java/io/github/hectorvent/floci/services/apigatewayv2/HttpApiRequestAuthorizerTest.java
index 04131a8760..3ca83470e9 100644
--- a/src/test/java/io/github/hectorvent/floci/services/apigatewayv2/HttpApiRequestAuthorizerTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/apigatewayv2/HttpApiRequestAuthorizerTest.java
@@ -22,7 +22,9 @@ import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
import static io.restassured.RestAssured.given;
+import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.notNullValue;
+import static org.hamcrest.Matchers.nullValue;
import static org.junit.jupiter.api.Assertions.*;
/**
@@ -531,6 +533,57 @@ class HttpApiRequestAuthorizerTest {
.then().statusCode(200);
}
+ // ──────────────────────────── Test: The refusals carry the API's CORS headers ────────────────────────────
+
+ /**
+ * Measured on AWS (eu-west-1, 2026-10-18): once the API has a CORS configuration, a Lambda
+ * authorizer's refusals, 401 without the identity source and 403 when it denies, carry
+ * {@code Access-Control-Allow-Origin} and {@code Access-Control-Expose-Headers} for an allowed
+ * origin, and no CORS header for another.
+ */
+ @Test
+ @Order(62)
+ void refusalsCarryTheCorsHeadersOfTheApi() {
+ given()
+ .contentType(ContentType.JSON)
+ .body("""
+ {"corsConfiguration":{"allowOrigins":["https://app.example.com"],"allowMethods":["GET"],
+ "allowHeaders":["authorization"],"exposeHeaders":["x-probe"],"maxAge":300}}
+ """)
+ .when().patch("/v2/apis/" + httpApiId)
+ .then().statusCode(200);
+ try {
+ // Route still has identitySourceAuthorizerId from the previous tests
+ given()
+ .header("Origin", "https://app.example.com")
+ .when().get("/execute-api/" + httpApiId + "/test/hello")
+ .then().statusCode(401)
+ .header("Access-Control-Allow-Origin", equalTo("https://app.example.com"))
+ .header("Access-Control-Expose-Headers", equalTo("x-probe"));
+
+ given()
+ .contentType(ContentType.JSON)
+ .body("""
+ {"authorizationType":"CUSTOM","authorizerId":"%s"}
+ """.formatted(simpleDenyAuthorizerId))
+ .when().patch("/v2/apis/" + httpApiId + "/routes/" + routeId)
+ .then().statusCode(200);
+ given()
+ .header("Origin", "https://app.example.com")
+ .when().get("/execute-api/" + httpApiId + "/test/hello")
+ .then().statusCode(403)
+ .header("Access-Control-Allow-Origin", equalTo("https://app.example.com"))
+ .header("Access-Control-Expose-Headers", equalTo("x-probe"));
+ given()
+ .header("Origin", "https://evil.example")
+ .when().get("/execute-api/" + httpApiId + "/test/hello")
+ .then().statusCode(403)
+ .header("Access-Control-Allow-Origin", nullValue());
+ } finally {
+ given().when().delete("/v2/apis/" + httpApiId + "/cors").then().statusCode(204);
+ }
+ }
+
// ──────────────────────────── Test: Query string identity source validation ────────────────────────────
@Test
diff --git a/src/test/java/io/github/hectorvent/floci/services/apigatewayv2/HttpProxyApiFixtures.java b/src/test/java/io/github/hectorvent/floci/services/apigatewayv2/HttpProxyApiFixtures.java
new file mode 100644
index 0000000000..c72bc216db
--- /dev/null
+++ b/src/test/java/io/github/hectorvent/floci/services/apigatewayv2/HttpProxyApiFixtures.java
@@ -0,0 +1,44 @@
+package io.github.hectorvent.floci.services.apigatewayv2;
+
+import io.restassured.http.ContentType;
+
+import static io.restassured.RestAssured.given;
+
+/** A deployed HTTP API whose one route is an {@code HTTP_PROXY} integration on a test's fixture backend. */
+final class HttpProxyApiFixtures {
+
+ private HttpProxyApiFixtures() {
+ }
+
+ /**
+ * Creates an HTTP API, {@code apiFields} appended to its CreateApi body, with the auto-deployed
+ * stage {@code stageName} and a {@code GET path} route to an {@code HTTP_PROXY} integration on
+ * {@code http://127.0.0.1:backendPort path}; returns its id.
+ */
+ static String createProxyApi(String name, String apiFields, String stageName, int backendPort, String path) {
+ String apiId = given()
+ .contentType(ContentType.JSON)
+ .body("{\"name\":\"" + name + "\",\"protocolType\":\"HTTP\"" + apiFields + "}")
+ .when().post("/v2/apis")
+ .then().statusCode(201)
+ .extract().path("apiId");
+ given()
+ .contentType(ContentType.JSON)
+ .body("{\"stageName\":\"" + stageName + "\",\"autoDeploy\":true}")
+ .when().post("/v2/apis/" + apiId + "/stages")
+ .then().statusCode(201);
+ String integrationId = given()
+ .contentType(ContentType.JSON)
+ .body("{\"integrationType\":\"HTTP_PROXY\",\"integrationUri\":\"http://127.0.0.1:"
+ + backendPort + path + "\",\"payloadFormatVersion\":\"1.0\"}")
+ .when().post("/v2/apis/" + apiId + "/integrations")
+ .then().statusCode(201)
+ .extract().path("integrationId");
+ given()
+ .contentType(ContentType.JSON)
+ .body("{\"routeKey\":\"GET " + path + "\",\"target\":\"integrations/" + integrationId + "\"}")
+ .when().post("/v2/apis/" + apiId + "/routes")
+ .then().statusCode(201);
+ return apiId;
+ }
+}