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

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

An HTTP API with a CorsConfiguration answered the preflight from it, but the
responses of its integrations went out with no Access-Control-Allow-Origin, so
a browser refused to hand the page any answer of the API. AWS documents both
halves ("Configuring CORS for an HTTP API"): for a CORS request API Gateway
adds the configured headers to the integration's response, and once an API
has a CORS configuration it ignores the CORS headers the integration returns.

Measured on HTTP APIs (eu-west-1, 2026-10-16 and 2026-10-18):
- API Gateway's own refusals on a matched route get the same headers: a JWT
  authorizer's 401 and its 403 for a missing scope, an unsigned call to an
  AWS_IAM route's 403, a Lambda authorizer's 401 (no identity) and 403
  (isAuthorized false); so does a function that is gone, which answers 500
  Internal Server Error (Floci answered 404 "Function not found" without
  them).
- A preflight a route matches (an OPTIONS or ANY route, $default) goes
  through that route, its authorizer and its integration, and gets the
  preflight headers on whatever answers; only a preflight no route matches
  is answered 204 by API Gateway. Floci answered every preflight itself, so
  a route behind an authorizer looked open to a browser's preflight.
- A preflight gets the preflight headers only when its origin, its method
  and every header it asks for are allowed, and never the exposed headers;
  otherwise, or for an OPTIONS without Access-Control-Request-Method, no CORS
  header at all. An actual request gets them whatever its method. Lists are
  joined with a bare comma.
- A preflight that gets the headers always carries
  Access-Control-Allow-Headers, empty when none are configured, and
  Vary: origin unless AllowOrigins is a single exact origin or "*" (two
  origins, the "https://*" prefix, and "*" beside an exact origin all
  vary). No other response gets a Vary; an integration's own is kept.
  Floci sent no Allow-Headers when none were configured, and Vary: Origin
  on every preflight that echoed the origin.
- A route without a target answers 404 Not Found with no CORS header, as an
  unmatched route does (Floci answered 500).

The configuration is now applied once, by withHttpApiCors, on whatever the
matched route answers, so no response path can miss it: it drops the six
headers the configuration owns from the response and, when the Origin is
allowed (exactly, by "*", or by a prefix wildcard such as https://*), adds
Access-Control-Allow-Origin, plus Credentials and Expose-Headers when
configured, or the preflight's set for a preflight. An API without a
configuration still leaves CORS to its integrations.

Tests: ApiGatewayExecuteControllerTest for the headers withHttpApiCors
sets and when a preflight varies, HttpApiCorsIntegrationTest for the
routing, the refusals and the custom domain;
HttpApiJwtAuthorizerScopesTest and HttpApiRequestAuthorizerTest for the
measured refusals of a JWT scope and of a Lambda authorizer, on their own
fixtures; ApiGatewayV2CorsTest in sdk-test-java for the refusals, an
unmatched preflight and a two-origin API's Vary through the SDK;
ApiGatewayV2UnsignedAccountRoutingTest now tells a route found in its
account by AWS's 500 instead of Floci's "Function not found".

* fix(apigatewayv2): answer a failed invocation with API Gateway's own status and CORS headers

Review of #5935 (Qodo). Measured on an HTTP API with a CORS configuration
(eu-west-1, 2026-10-18), with an allowed Origin:
- a Lambda integration API Gateway may not invoke, and a function that
  raises, answer 500 {"message":"Internal Server Error"}; a function Lambda
  throttles (reserved concurrency 0) answers 503 {"message":"Service
  Unavailable"}; each carries Access-Control-Allow-Origin and
  Access-Control-Expose-Headers;
- an OPTIONS request no route matches is answered 204 with no CORS header
  whether or not it carries Origin or Access-Control-Request-Method, so the
  unmatched OPTIONS answer stays as it is, now pinned by a test.

Any AwsException from the invocation now becomes API Gateway's answer
inside the matched route, so the CORS configuration reaches it: 503 for
Lambda's throttling, 500 otherwise. Only the function that is gone did
before; the others escaped to the exception mapper without the headers.

A configured list with a null entry no longer fails a preflight: the
entry matches nothing and is left out of the header.

Tests: HttpApiCorsIntegrationTest gains a throttled function's 503 and an
unmatched OPTIONS that is not a preflight, ApiGatewayExecuteControllerTest
a null entry, and ApiGatewayV2CorsTest in sdk-test-java both new cases
through the SDK; the throttled and null cases fail on the previous head.

* test(apigatewayv2): share the HTTP_PROXY API fixture and the Lambda zip helper

Review of #5935. HttpApiCorsIntegrationTest.createProxyApi repeated the
API, stage, HTTP_PROXY integration and route sequence of
HttpApiHttpProxyMultiValueIntegrationTest.createProxyApi: both now call
HttpProxyApiFixtures.createProxyApi, which takes the API's extra fields,
the stage, the backend port and the path. The stage is auto-deployed for
both, as an API needs to be served on AWS.

The throttled function is a Node.js one built with
WebSocketTestSupport.createLambdaZip; it never runs, so its runtime does
not matter.
This commit is contained in:
Alessandro Lattao authored and GitHub committed 2026-10-18 12:05:07 -04:00
1 parent fc1488d17a
commit dd832b45dc
12 files changed
+1175 -73

No files matched your search

@@ -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));
}
}
@@ -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"));
}
@@ -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
@@ -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);
}
}
@@ -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
@@ -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
@@ -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
@@ -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;
}
}