mirror of
https://github.com/floci-io/floci.git
synced 2026-11-22 21:50:46 -05:00
fix(apigatewayv2): infer the 2.0 response body and answer function errors with a message (#5153)
* fix(apigatewayv2): infer the 2.0 response body and answer function errors with a message * fix(apigatewayv2): keep format 1.0 response rules for 1.0 integrations on HTTP APIs
This commit is contained in:
1 parent
1f1d4f94dd
commit
ecdecf2ae2
3 files changed
+276
-2
No files matched your search
+23
-2
@@ -1544,11 +1544,32 @@ public class ApiGatewayExecuteController {
|
||||
}
|
||||
|
||||
Response buildProxyResponse(InvokeResult result, boolean httpApiV2) {
|
||||
return buildProxyResponse(result, httpApiV2, httpApiV2);
|
||||
}
|
||||
|
||||
// httpApi selects the HTTP API error response; payloadV2 selects the integration's format 2.0
|
||||
// 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();
|
||||
}
|
||||
if (result.getPayload() == null || result.getPayload().length == 0) {
|
||||
return Response.status(result.getFunctionError() != null ? 502 : result.getStatusCode()).build();
|
||||
}
|
||||
try {
|
||||
JsonNode node = objectMapper.readTree(result.getPayload());
|
||||
if (payloadV2 && !node.has("statusCode")) {
|
||||
// Format 2.0 infers the response when the function's JSON result carries no
|
||||
// statusCode: 200, application/json, and the result itself as the body. A string
|
||||
// result is the body text; any other result is returned exactly as the function
|
||||
// produced it, response-shaped fields included.
|
||||
byte[] inferredBody = node.isTextual()
|
||||
? node.textValue().getBytes(StandardCharsets.UTF_8)
|
||||
: result.getPayload();
|
||||
return Response.status(200).entity(inferredBody).type(MediaType.APPLICATION_JSON).build();
|
||||
}
|
||||
int statusCode = node.path("statusCode").asInt(200);
|
||||
if (result.getFunctionError() != null && !node.has("statusCode")) statusCode = 502;
|
||||
|
||||
@@ -1564,7 +1585,7 @@ public class ApiGatewayExecuteController {
|
||||
if (e.getValue().isArray()) e.getValue().forEach(v -> builder.header(e.getKey(), v.asText()));
|
||||
});
|
||||
}
|
||||
if (httpApiV2) {
|
||||
if (payloadV2) {
|
||||
JsonNode cookies = node.get("cookies");
|
||||
if (cookies != null && cookies.isArray()) {
|
||||
cookies.forEach(cookie -> builder.header(HttpHeaders.SET_COOKIE, cookie.asText()));
|
||||
@@ -2608,7 +2629,7 @@ public class ApiGatewayExecuteController {
|
||||
try {
|
||||
InvokeResult result = lambdaService.invoke(region, functionName,
|
||||
eventJson.getBytes(), InvocationType.RequestResponse);
|
||||
return buildProxyResponse(result, true);
|
||||
return buildProxyResponse(result, true, !"1.0".equals(integration.getPayloadFormatVersion()));
|
||||
} catch (AwsException e) {
|
||||
if (e.getHttpStatus() == 404) {
|
||||
return Response.status(404)
|
||||
|
||||
+102
@@ -495,6 +495,108 @@ class ApiGatewayExecuteControllerTest {
|
||||
}
|
||||
}
|
||||
|
||||
// ── HTTP API (v2) payload format 2.0 response inference ──────
|
||||
//
|
||||
// https://docs.aws.amazon.com/apigateway/latest/developerguide/http-api-develop-integrations-lambda.html
|
||||
// "Lambda function response for format 2.0": valid JSON without a statusCode is answered with
|
||||
// statusCode 200, content-type application/json, and the function's response as the body.
|
||||
|
||||
private static InvokeResult functionError(String payloadJson) {
|
||||
return new InvokeResult(200, "Unhandled", payloadJson.getBytes(StandardCharsets.UTF_8), null, "req-1");
|
||||
}
|
||||
|
||||
private static String bodyOf(Response response) {
|
||||
Object entity = response.getEntity();
|
||||
return entity instanceof byte[] bytes ? new String(bytes, StandardCharsets.UTF_8) : (String) entity;
|
||||
}
|
||||
|
||||
@Test
|
||||
void httpApiV2ObjectWithoutStatusCodeIsTheBody() {
|
||||
ApiGatewayExecuteController controller = controller(new ObjectMapper());
|
||||
try (Response response = controller.buildProxyResponse(
|
||||
proxyPayload("{\"message\":\"Hello from Lambda!\"}"), true)) {
|
||||
assertEquals(200, response.getStatus());
|
||||
assertEquals("application/json", String.valueOf(response.getMediaType()));
|
||||
assertEquals("{\"message\":\"Hello from Lambda!\"}", bodyOf(response));
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void httpApiV2StringResultIsTheBody() {
|
||||
ApiGatewayExecuteController controller = controller(new ObjectMapper());
|
||||
try (Response response = controller.buildProxyResponse(
|
||||
proxyPayload("\"Hello from Lambda!\""), true)) {
|
||||
assertEquals(200, response.getStatus());
|
||||
assertEquals("application/json", String.valueOf(response.getMediaType()));
|
||||
assertEquals("Hello from Lambda!", bodyOf(response));
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void httpApiV2ResponseFieldsWithoutStatusCodeAreReturnedAsTheBody() {
|
||||
// Without a statusCode nothing is interpreted: headers and body are part of the JSON body.
|
||||
String payload = "{\"headers\":{\"X-Trace\":\"inferred\"},\"body\":\"inner\"}";
|
||||
ApiGatewayExecuteController controller = controller(new ObjectMapper());
|
||||
try (Response response = controller.buildProxyResponse(proxyPayload(payload), true)) {
|
||||
assertEquals(200, response.getStatus());
|
||||
assertEquals("application/json", String.valueOf(response.getMediaType()));
|
||||
assertEquals(payload, bodyOf(response));
|
||||
assertNull(response.getHeaderString("X-Trace"));
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void httpApiV2FunctionErrorAnswersInternalServerErrorMessage() {
|
||||
ApiGatewayExecuteController controller = controller(new ObjectMapper());
|
||||
try (Response response = controller.buildProxyResponse(functionError(
|
||||
"{\"errorType\":\"Error\",\"errorMessage\":\"boom\",\"trace\":[]}"), true)) {
|
||||
assertEquals(502, 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.
|
||||
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"));
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void httpApiPayloadV1FunctionErrorAnswersInternalServerErrorMessage() {
|
||||
ApiGatewayExecuteController controller = controller(new ObjectMapper());
|
||||
try (Response response = controller.buildProxyResponse(functionError(
|
||||
"{\"errorType\":\"Error\",\"errorMessage\":\"boom\",\"trace\":[]}"), true, false)) {
|
||||
assertEquals(502, response.getStatus());
|
||||
assertEquals("{\"message\":\"Internal Server Error\"}", bodyOf(response));
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void restApiV1ResponseWithoutStatusCodeIsNotInferred() {
|
||||
ApiGatewayExecuteController controller = controller(new ObjectMapper());
|
||||
try (Response response = controller.buildProxyResponse(proxyPayload("{\"body\":\"inner\"}"), false)) {
|
||||
assertEquals(200, response.getStatus());
|
||||
assertEquals("inner", bodyOf(response));
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void restApiV1FunctionErrorKeepsEmptyBody() {
|
||||
ApiGatewayExecuteController controller = controller(new ObjectMapper());
|
||||
try (Response response = controller.buildProxyResponse(functionError(
|
||||
"{\"errorType\":\"Error\",\"errorMessage\":\"boom\",\"trace\":[]}"), false)) {
|
||||
assertEquals(502, response.getStatus());
|
||||
assertNull(response.getEntity());
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void requestTimeUsesEnglishMonthUnderNonEnglishDefaultLocale() {
|
||||
// The formatter is built at class initialisation, so switching the default locale here
|
||||
|
||||
+151
@@ -0,0 +1,151 @@
|
||||
package io.github.hectorvent.floci.services.apigatewayv2;
|
||||
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import io.restassured.http.ContentType;
|
||||
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 static io.restassured.RestAssured.given;
|
||||
import static org.hamcrest.Matchers.equalTo;
|
||||
import static org.hamcrest.Matchers.notNullValue;
|
||||
import static org.hamcrest.Matchers.startsWith;
|
||||
|
||||
/**
|
||||
* End to end check of how an HTTP API answers a payload format 2.0 Lambda proxy integration whose
|
||||
* function returns no {@code statusCode} or throws. AWS infers a 200 JSON response whose body is
|
||||
* the function's result, and answers a function error with {@code {"message":"Internal Server
|
||||
* Error"}}. An integration configured with format 1.0 keeps the 1.0 response rules.
|
||||
*/
|
||||
@QuarkusTest
|
||||
@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
|
||||
class HttpApiLambdaProxyResponseInferenceIntegrationTest {
|
||||
|
||||
private static final String BARE_FUNCTION = "httpv2-inference-bare-fn";
|
||||
private static final String STRING_FUNCTION = "httpv2-inference-string-fn";
|
||||
private static final String THROW_FUNCTION = "httpv2-inference-throw-fn";
|
||||
private static final String V1_FUNCTION = "httpv2-inference-v1-fn";
|
||||
|
||||
private static String apiId;
|
||||
|
||||
@Test
|
||||
@Order(1)
|
||||
void setupLambdasAndHttpApi() throws Exception {
|
||||
apiId = given()
|
||||
.contentType(ContentType.JSON)
|
||||
.body("""
|
||||
{"name":"response-inference-test","protocolType":"HTTP"}
|
||||
""")
|
||||
.when().post("/v2/apis")
|
||||
.then()
|
||||
.statusCode(201)
|
||||
.body("apiId", notNullValue())
|
||||
.extract().path("apiId");
|
||||
|
||||
given()
|
||||
.contentType(ContentType.JSON)
|
||||
.body("""
|
||||
{"stageName":"test"}
|
||||
""")
|
||||
.when().post("/v2/apis/" + apiId + "/stages")
|
||||
.then().statusCode(201);
|
||||
|
||||
createProxyRoute(BARE_FUNCTION, "/bare",
|
||||
"exports.handler = async () => ({ message: 'Hello from Lambda!' });");
|
||||
createProxyRoute(STRING_FUNCTION, "/string",
|
||||
"exports.handler = async () => 'Hello from Lambda!';");
|
||||
createProxyRoute(THROW_FUNCTION, "/throw",
|
||||
"exports.handler = async () => { throw new Error('boom'); };");
|
||||
createProxyRoute(V1_FUNCTION, "/v1", "1.0",
|
||||
"exports.handler = async () => ({ headers: { 'X-Trace': 'value' }, body: 'inner' });");
|
||||
}
|
||||
|
||||
private static void createProxyRoute(String functionName, String path, String handlerCode) throws Exception {
|
||||
createProxyRoute(functionName, path, "2.0", handlerCode);
|
||||
}
|
||||
|
||||
private static void createProxyRoute(String functionName, String path, String payloadFormatVersion,
|
||||
String handlerCode) throws Exception {
|
||||
String zip = WebSocketTestSupport.createLambdaZip(handlerCode);
|
||||
|
||||
given()
|
||||
.contentType(ContentType.JSON)
|
||||
.body("""
|
||||
{"FunctionName":"%s","Runtime":"nodejs20.x","Role":"arn:aws:iam::000000000000:role/lambda-role","Handler":"index.handler","Timeout":30,"Code":{"ZipFile":"%s"}}
|
||||
""".formatted(functionName, zip))
|
||||
.when().post("/2015-03-31/functions")
|
||||
.then().statusCode(201);
|
||||
|
||||
String integrationId = given()
|
||||
.contentType(ContentType.JSON)
|
||||
.body("""
|
||||
{"integrationType":"AWS_PROXY","integrationUri":"arn:aws:lambda:us-east-1:000000000000:function:%s/invocations","integrationMethod":"POST","payloadFormatVersion":"%s"}
|
||||
""".formatted(functionName, payloadFormatVersion))
|
||||
.when().post("/v2/apis/" + apiId + "/integrations")
|
||||
.then()
|
||||
.statusCode(201)
|
||||
.extract().path("integrationId");
|
||||
|
||||
given()
|
||||
.contentType(ContentType.JSON)
|
||||
.body("""
|
||||
{"routeKey":"GET %s","target":"integrations/%s"}
|
||||
""".formatted(path, integrationId))
|
||||
.when().post("/v2/apis/" + apiId + "/routes")
|
||||
.then().statusCode(201);
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(10)
|
||||
void objectWithoutStatusCodeIsReturnedAsJsonBody() {
|
||||
given()
|
||||
.when().get("/execute-api/" + apiId + "/test/bare")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.contentType(startsWith("application/json"))
|
||||
.body("message", equalTo("Hello from Lambda!"));
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(11)
|
||||
void stringResultIsReturnedAsBody() {
|
||||
given()
|
||||
.when().get("/execute-api/" + apiId + "/test/string")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.contentType(startsWith("application/json"))
|
||||
.body(equalTo("Hello from Lambda!"));
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(12)
|
||||
void functionErrorAnswersInternalServerErrorMessage() {
|
||||
given()
|
||||
.when().get("/execute-api/" + apiId + "/test/throw")
|
||||
.then()
|
||||
.statusCode(502)
|
||||
.contentType(startsWith("application/json"))
|
||||
.body("message", equalTo("Internal Server Error"));
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(13)
|
||||
void payloadV1ResponseFieldsAreNotInferred() {
|
||||
given()
|
||||
.when().get("/execute-api/" + apiId + "/test/v1")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.header("X-Trace", "value")
|
||||
.body(equalTo("inner"));
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(999)
|
||||
void cleanup() throws Exception {
|
||||
if (apiId != null) {
|
||||
given().when().delete("/v2/apis/" + apiId);
|
||||
}
|
||||
WebSocketTestSupport.deleteFunctions(BARE_FUNCTION, STRING_FUNCTION, THROW_FUNCTION, V1_FUNCTION);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user