mirror of
https://github.com/floci-io/floci.git
synced 2026-11-27 07:39:24 -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
+137
-37
@@ -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();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
Reference in new issue
Block a user