mirror of
https://github.com/floci-io/floci.git
synced 2026-11-28 16:11:48 -05:00
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:
1 parent
fc1488d17a
commit
dd832b45dc
12 files changed
+1175
-73
No files matched your search
+205
@@ -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();
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user