fix(apigatewayv2): answer the Lambda proxy results an HTTP API cannot read with 500 (#5985)

* fix(apigatewayv2): answer the Lambda proxy results an HTTP API cannot read with 500

Measured on HTTP APIs (eu-west-1), with payload formats 1.0 and 2.0:
a function that raises is answered 500 with {"message":"Internal Server
Error"}, not the 502 Floci sent. The same 500 answers what API Gateway
cannot read as a response: in format 1.0 a result that is not an object
with a statusCode (a result without one, a string, a number, null), and
in either format a statusCode that is not a whole number from 100 to 599
(99, 600, 201.5, "abc"); a statusCode given as text that spells one,
"201", is taken, and headers that are not an object are left out.
Format 2.0 keeps inferring a 200 for a result without a statusCode.

Floci answered a format 1.0 result without a statusCode with 200 and
its headers and body, as HttpApiLambdaProxyResponseInferenceIntegrationTest
pinned since #5153; AWS answers 500, and that test and the unit tests
that pinned 502 now expect what AWS answers. A REST API's Lambda proxy
keeps its own 502, untouched.

The HTTP API's generic error responses come from one helper, which the
invocation failures from #5935 (500, or 503 when Lambda throttles) use
too.

* test(compat): skip the HTTP API proxy cases unless the API reaches Lambda

Review of #5985: the test checked only that Lambda can be invoked, not
that API Gateway dispatches to it. It now sends a readable result through
the API first, as ApiGatewayV2ExecuteTest does, and skips the cases when
that does not come back.
This commit is contained in:
Alessandro Lattao authored and GitHub committed 2026-10-19 09:18:20 -04:00
1 parent 241806a4f3
commit 49d2d74f3f
6 files changed
+256 -19

No files matched your search

@@ -0,0 +1,135 @@
package com.floci.test;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.Assumptions;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.CsvSource;
import software.amazon.awssdk.core.SdkBytes;
import software.amazon.awssdk.services.apigatewayv2.ApiGatewayV2Client;
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 static org.assertj.core.api.Assertions.assertThat;
/**
* How an HTTP API answers the Lambda proxy results it cannot read, in payload formats 1.0 and 2.0.
* Measured on AWS (eu-west-1, 2026-10-19): a function that raises, a 1.0 result without a
* statusCode, and a statusCode that is not a whole number from 100 to 599 are answered 500 with
* {"message":"Internal Server Error"}; a statusCode given as text that spells one is taken; format
* 2.0 takes a result without a statusCode as a 200 whose body is the result itself.
*/
@DisplayName("API Gateway V2 Lambda proxy responses")
class ApiGatewayV2LambdaProxyResponseTest {
private static final String ROLE = "arn:aws:iam::000000000000:role/lambda-role";
private static final String ERROR = "{\"message\":\"Internal Server Error\"}";
private static final String STAGE = "test";
private static ApiGatewayV2Client apiGatewayV2;
private static LambdaClient lambda;
private static HttpClient http;
private static String functionName;
private static String apiId;
@BeforeAll
static void setup() {
Assumptions.assumeTrue(TestFixtures.isLambdaDispatchAvailable(), "Lambda dispatch is unavailable here");
apiGatewayV2 = TestFixtures.apiGatewayV2Client();
lambda = TestFixtures.lambdaClient();
http = HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(5)).build();
functionName = TestFixtures.uniqueName("http-api-proxy-fn");
String functionArn = lambda.createFunction(request -> request
.functionName(functionName)
.runtime(Runtime.NODEJS20_X)
.role(ROLE)
.handler("index.handler")
.timeout(30)
.code(code -> code.zipFile(SdkBytes.fromByteArray(LambdaUtils.proxyResponseZip())))).functionArn();
apiId = apiGatewayV2.createApi(request -> request
.name(TestFixtures.uniqueName("http-api-proxy"))
.protocolType("HTTP")).apiId();
for (String format : new String[] {"1.0", "2.0"}) {
String integrationId = apiGatewayV2.createIntegration(request -> request
.apiId(apiId)
.integrationType(IntegrationType.AWS_PROXY)
.integrationUri(functionArn)
.payloadFormatVersion(format)).integrationId();
apiGatewayV2.createRoute(request -> request
.apiId(apiId)
.routeKey("GET /v" + format.charAt(0) + "/{mode}")
.target("integrations/" + integrationId));
}
apiGatewayV2.createStage(request -> request.apiId(apiId).stageName(STAGE).autoDeploy(true));
// As ApiGatewayV2ExecuteTest does: a result the gateway can read must come back through the
// API before the cases run, or this environment cannot dispatch from API Gateway to Lambda.
boolean dispatches;
try {
HttpResponse<String> warmup = get("2.0", "ok");
dispatches = warmup.statusCode() == 200 && "ok".equals(warmup.body());
} catch (IOException e) {
dispatches = false;
}
Assumptions.assumeTrue(dispatches, "API Gateway does not dispatch to Lambda here");
}
@AfterAll
static void cleanup() {
if (apiGatewayV2 != null) {
if (apiId != null) {
apiGatewayV2.deleteApi(request -> request.apiId(apiId));
}
apiGatewayV2.close();
}
if (lambda != null) {
lambda.deleteFunction(request -> request.functionName(functionName));
lambda.close();
}
}
@ParameterizedTest(name = "{1} in payload {0}")
@CsvSource(delimiter = '|', value = {
"1.0|raise|500|" + ERROR,
"2.0|raise|500|" + ERROR,
"1.0|nostatus|500|" + ERROR,
"1.0|badstatus|500|" + ERROR,
"2.0|badstatus|500|" + ERROR,
"1.0|highstatus|500|" + ERROR,
"2.0|highstatus|500|" + ERROR,
"1.0|textstatus|201|x",
"2.0|textstatus|201|x",
"2.0|nostatus|200|{\"body\":\"x\",\"headers\":{\"x-probe\":\"1\"}}"
})
void aResultIsAnsweredAsAwsReadsIt(String format, String mode, int status, String body) throws Exception {
HttpResponse<String> response = get(format, mode);
assertThat(response.statusCode()).isEqualTo(status);
assertThat(response.body()).isEqualTo(body);
}
private static HttpResponse<String> get(String format, String mode) throws IOException {
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create(TestFixtures.endpoint() + "/execute-api/" + apiId + "/" + STAGE + "/v"
+ format.charAt(0) + "/" + mode))
.timeout(Duration.ofSeconds(30))
.GET()
.build();
try {
return http.send(request, HttpResponse.BodyHandlers.ofString());
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new IOException("interrupted waiting for " + request.uri(), e);
}
}
}
@@ -334,6 +334,26 @@ public final class LambdaUtils {
return createZip("lambda_function.py", code);
}
/**
* ZIP containing a Node.js handler that returns the Lambda proxy result its {@code mode} path
* parameter names: one that raises, one without a statusCode, one whose statusCode is not a
* number, one whose statusCode is text that spells one, and one outside 100 to 599.
*/
public static byte[] proxyResponseZip() {
String code = """
exports.handler = async (event) => {
const mode = (event.pathParameters || {}).mode;
if (mode === 'raise') throw new Error('boom');
if (mode === 'nostatus') return { body: 'x', headers: { 'x-probe': '1' } };
if (mode === 'badstatus') return { statusCode: 'abc', body: 'x' };
if (mode === 'textstatus') return { statusCode: '201', body: 'x' };
if (mode === 'highstatus') return { statusCode: 600, body: 'x' };
return { statusCode: 200, body: 'ok' };
};
""";
return createZip("index.js", code);
}
private static byte[] createZip(String filename, String content) {
try {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
+6
View File
@@ -656,6 +656,12 @@ 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.
A Lambda proxy integration's response is read as AWS reads it (measured): a function that raises, a
format 1.0 result that is not an object with a `statusCode`, and a `statusCode` that is not a whole
number from 100 to 599 (text that spells one, such as `"201"`, is taken) are answered `500` with
`{"message":"Internal Server Error"}`. Format 2.0 takes a result without a `statusCode` as a `200`
whose body is the result itself.
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
@@ -1586,9 +1586,9 @@ public class ApiGatewayExecuteController {
// response rules (inference and cookies). An HTTP API integration can still use format 1.0.
Response buildProxyResponse(InvokeResult result, boolean httpApi, boolean payloadV2) {
if (httpApi && result.getFunctionError() != null) {
// An HTTP API never relays the error payload: the client gets AWS's generic message.
return Response.status(502).entity(jsonMessage("Internal Server Error"))
.type(MediaType.APPLICATION_JSON).build();
// An HTTP API never relays the error payload: the client gets AWS's generic message, as
// a 500 (measured, both payload formats, eu-west-1, 2026-10-19).
return httpApiError(500, "Internal Server Error");
}
if (result.getPayload() == null || result.getPayload().length == 0) {
return Response.status(result.getFunctionError() != null ? 502 : result.getStatusCode()).build();
@@ -1605,7 +1605,14 @@ public class ApiGatewayExecuteController {
: result.getPayload();
return Response.status(200).entity(inferredBody).type(MediaType.APPLICATION_JSON).build();
}
int statusCode = node.path("statusCode").asInt(200);
if (httpApi && httpApiStatusCode(node) == null) {
// Measured (eu-west-1, 2026-10-19): an HTTP API answers a response it cannot read
// with 500 and its generic message, in format 1.0 a result that is not an object with
// a statusCode, and in either format a statusCode that is not a whole number from 100
// to 599, though text spelling one ("201") is taken.
return httpApiError(500, "Internal Server Error");
}
int statusCode = httpApi ? httpApiStatusCode(node) : node.path("statusCode").asInt(200);
if (result.getFunctionError() != null && !node.has("statusCode")) statusCode = 502;
Response.ResponseBuilder builder = Response.status(statusCode);
@@ -1644,6 +1651,27 @@ public class ApiGatewayExecuteController {
}
}
/** The status and generic message an HTTP API answers with when its Lambda integration fails. */
private Response httpApiError(int status, String message) {
return Response.status(status).entity(jsonMessage(message)).type(MediaType.APPLICATION_JSON).build();
}
private static final Pattern WHOLE_STATUS = Pattern.compile("\\d{1,3}");
/**
* The status an HTTP API takes from a Lambda proxy response, or null when it cannot read one: a
* whole number from 100 to 599, or text that spells one.
*/
private static Integer httpApiStatusCode(JsonNode response) {
JsonNode status = response.path("statusCode");
String text = status.isIntegralNumber() ? status.asText() : status.isTextual() ? status.textValue() : "";
if (!WHOLE_STATUS.matcher(text).matches()) {
return null;
}
int code = Integer.parseInt(text);
return code >= 100 && code <= 599 ? code : null;
}
/**
* HTTP header names are case-insensitive on the wire (RFC 7230 §3.2), and Lambda proxy
* integrations commonly return lowercased names (e.g. the AWS Lambda Web Adapter emits
@@ -2776,9 +2804,7 @@ public class ApiGatewayExecuteController {
// 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();
return throttled ? httpApiError(503, "Service Unavailable") : httpApiError(500, "Internal Server Error");
}
}
@@ -14,6 +14,9 @@ import jakarta.ws.rs.core.MultivaluedMap;
import jakarta.ws.rs.core.Response;
import jakarta.ws.rs.core.UriInfo;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;
import java.net.URI;
import java.nio.charset.StandardCharsets;
@@ -27,6 +30,7 @@ import java.util.Locale;
import java.util.Map;
import java.util.TimeZone;
import java.util.function.Supplier;
import java.util.stream.Stream;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
@@ -247,6 +251,47 @@ class ApiGatewayExecuteControllerTest {
assertNull(ApiGatewayExecuteController.vtlAuthorizerContext(null, Map.of()));
}
// ── HTTP API Lambda proxy responses AWS cannot read ──────
/**
* Measured on HTTP APIs (eu-west-1, 2026-10-19), for payload formats 1.0 and 2.0: a 1.0 result
* that is not an object with a statusCode, and a statusCode that is not a whole number from 100
* to 599, are answered with 500 and the generic message; a statusCode given as text that spells
* one is taken, and headers that are not an object are left out. A function that raises is
* covered below.
*/
@ParameterizedTest(name = "{0} payload {1}")
@MethodSource("httpApiProxyResponses")
void httpApiAnswersAProxyResponseAsAwsReadsIt(String result, String format, int status, String body) {
ApiGatewayExecuteController controller = controller(new ObjectMapper());
try (Response response = controller.buildProxyResponse(proxyPayload(result), true, "2.0".equals(format))) {
assertEquals(status, response.getStatus());
assertEquals(body, bodyOf(response));
}
}
static Stream<Arguments> httpApiProxyResponses() {
String error = "{\"message\":\"Internal Server Error\"}";
return Stream.of(
Arguments.of("\"hello\"", "1.0", 500, error),
Arguments.of("null", "1.0", 500, error),
Arguments.of("5", "1.0", 500, error),
Arguments.of("{\"statusCode\":\"abc\",\"body\":\"x\"}", "1.0", 500, error),
Arguments.of("{\"statusCode\":\"abc\",\"body\":\"x\"}", "2.0", 500, error),
Arguments.of("{\"statusCode\":99,\"body\":\"x\"}", "1.0", 500, error),
Arguments.of("{\"statusCode\":99,\"body\":\"x\"}", "2.0", 500, error),
Arguments.of("{\"statusCode\":600,\"body\":\"x\"}", "1.0", 500, error),
Arguments.of("{\"statusCode\":600,\"body\":\"x\"}", "2.0", 500, error),
Arguments.of("{\"statusCode\":201.5,\"body\":\"x\"}", "1.0", 500, error),
Arguments.of("{\"statusCode\":201.5,\"body\":\"x\"}", "2.0", 500, error),
Arguments.of("{\"statusCode\":\"201\",\"body\":\"x\"}", "1.0", 201, "x"),
Arguments.of("{\"statusCode\":\"201\",\"body\":\"x\"}", "2.0", 201, "x"),
Arguments.of("{\"statusCode\":201,\"headers\":\"x\",\"body\":\"x\"}", "1.0", 201, "x"),
Arguments.of("{\"statusCode\":201,\"headers\":\"x\",\"body\":\"x\"}", "2.0", 201, "x"),
Arguments.of("null", "2.0", 200, "null"),
Arguments.of("5", "2.0", 200, "5"));
}
// ── Lambda proxy response Content-Type header matching ──────
private static InvokeResult proxyPayload(String payloadJson) {
@@ -552,21 +597,21 @@ class ApiGatewayExecuteControllerTest {
ApiGatewayExecuteController controller = controller(new ObjectMapper());
try (Response response = controller.buildProxyResponse(functionError(
"{\"errorType\":\"Error\",\"errorMessage\":\"boom\",\"trace\":[]}"), true)) {
assertEquals(502, response.getStatus());
assertEquals(500, response.getStatus());
assertEquals("application/json", String.valueOf(response.getMediaType()));
assertEquals("{\"message\":\"Internal Server Error\"}", bodyOf(response));
}
}
@Test
void httpApiPayloadV1ResponseWithoutStatusCodeIsNotInferred() {
// An HTTP API integration configured with payloadFormatVersion 1.0 keeps the 1.0 response rules.
void httpApiPayloadV1ResponseWithoutStatusCodeAnswersInternalServerErrorMessage() {
// Format 1.0 infers nothing, so a result without a statusCode is one the HTTP API cannot read.
String payload = "{\"headers\":{\"X-Trace\":\"value\"},\"body\":\"inner\"}";
ApiGatewayExecuteController controller = controller(new ObjectMapper());
try (Response response = controller.buildProxyResponse(proxyPayload(payload), true, false)) {
assertEquals(200, response.getStatus());
assertEquals("inner", bodyOf(response));
assertEquals("value", response.getHeaderString("X-Trace"));
assertEquals(500, response.getStatus());
assertEquals("{\"message\":\"Internal Server Error\"}", bodyOf(response));
assertNull(response.getHeaderString("X-Trace"));
}
}
@@ -575,7 +620,7 @@ class ApiGatewayExecuteControllerTest {
ApiGatewayExecuteController controller = controller(new ObjectMapper());
try (Response response = controller.buildProxyResponse(functionError(
"{\"errorType\":\"Error\",\"errorMessage\":\"boom\",\"trace\":[]}"), true, false)) {
assertEquals(502, response.getStatus());
assertEquals(500, response.getStatus());
assertEquals("{\"message\":\"Internal Server Error\"}", bodyOf(response));
}
}
@@ -10,6 +10,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;
import static org.hamcrest.Matchers.startsWith;
/**
@@ -121,23 +122,27 @@ class HttpApiLambdaProxyResponseInferenceIntegrationTest {
@Test
@Order(12)
void functionErrorAnswersInternalServerErrorMessage() {
// Measured on HTTP APIs (eu-west-1, 2026-10-19): 500, in both payload formats.
given()
.when().get("/execute-api/" + apiId + "/test/throw")
.then()
.statusCode(502)
.statusCode(500)
.contentType(startsWith("application/json"))
.body("message", equalTo("Internal Server Error"));
}
@Test
@Order(13)
void payloadV1ResponseFieldsAreNotInferred() {
void payloadV1ResponseWithoutStatusCodeAnswersInternalServerErrorMessage() {
// Format 1.0 infers nothing: a result with headers and a body but no statusCode is one
// the HTTP API cannot read, and it answers 500 (measured, eu-west-1, 2026-10-19).
given()
.when().get("/execute-api/" + apiId + "/test/v1")
.then()
.statusCode(200)
.header("X-Trace", "value")
.body(equalTo("inner"));
.statusCode(500)
.contentType(startsWith("application/json"))
.header("X-Trace", nullValue())
.body("message", equalTo("Internal Server Error"));
}
@Test