fix(apigateway): forward the request body on DELETE (#6868)

This commit is contained in:
MosesWayCo authored and GitHub committed 2026-10-30 23:13:16 -04:00
1 parent 4d21ea66cf
commit b3d9f2f576
9 files changed
+157 -16

No files matched your search

@@ -58,8 +58,9 @@ public class ApiGatewayAwsExecuteController {
public Response handleDelete(@Context HttpHeaders headers, @Context UriInfo uriInfo,
@PathParam("apiId") String apiId,
@PathParam("stageName") String stageName,
@PathParam("proxy") String proxy) {
return executeController.dispatch("DELETE", apiId, stageName, proxy, headers, uriInfo, null);
@PathParam("proxy") String proxy,
byte[] body) {
return executeController.dispatch("DELETE", apiId, stageName, proxy, headers, uriInfo, body);
}
@PATCH
@@ -320,12 +320,13 @@ public class ApiGatewayExecuteController {
public Response handleDelete(@Context HttpHeaders headers, @Context UriInfo uriInfo,
@PathParam("apiId") String apiId,
@PathParam("stageName") String stageName,
@PathParam("proxy") String proxy) {
@PathParam("proxy") String proxy,
byte[] body) {
if (isWebSocketConnectionRequest(apiId, proxy)) {
String connectionId = decodeConnectionId(proxy.substring(CONNECTIONS_PREFIX.length()));
return handleDeleteConnection(connectionId);
}
return dispatch("DELETE", apiId, stageName, proxy, headers, uriInfo, null);
return dispatch("DELETE", apiId, stageName, proxy, headers, uriInfo, body);
}
@PATCH
@@ -58,8 +58,9 @@ public class ApiGatewayUserRequestController {
public Response handleDelete(@Context HttpHeaders headers, @Context UriInfo uriInfo,
@PathParam("apiId") String apiId,
@PathParam("stageName") String stageName,
@PathParam("proxy") String proxy) {
return executeController.dispatch("DELETE", apiId, stageName, proxy, headers, uriInfo, null);
@PathParam("proxy") String proxy,
byte[] body) {
return executeController.dispatch("DELETE", apiId, stageName, proxy, headers, uriInfo, body);
}
@PATCH
@@ -344,7 +344,6 @@ public class HttpProxyInvoker {
switch (method.toUpperCase()) {
case "GET" -> hrb.GET();
case "DELETE" -> hrb.DELETE();
case "HEAD" -> hrb.method("HEAD", HttpRequest.BodyPublishers.noBody());
case "OPTIONS" -> hrb.method("OPTIONS", HttpRequest.BodyPublishers.noBody());
default -> hrb.method(method.toUpperCase(),
@@ -89,8 +89,9 @@ public class ApiGatewayController {
@Path("/{proxy: .*}")
public Response handleDelete(@Context HttpHeaders headers, @Context UriInfo uriInfo,
@PathParam("functionName") String functionName,
@PathParam("proxy") String proxy) {
return proxyRequest("DELETE", functionName, proxy, headers, uriInfo, null);
@PathParam("proxy") String proxy,
byte[] body) {
return proxyRequest("DELETE", functionName, proxy, headers, uriInfo, body);
}
@PATCH
@@ -96,8 +96,9 @@ public class LambdaUrlInvocationController {
@DELETE
@Path("/{proxy: .*}")
public Response handleDelete(@PathParam("urlId") String urlId, @PathParam("proxy") String proxy,
@Context HttpHeaders headers, @Context UriInfo uriInfo) {
return invoke("DELETE", urlId, proxy, headers, uriInfo, null);
@Context HttpHeaders headers, @Context UriInfo uriInfo,
byte[] body) {
return invoke("DELETE", urlId, proxy, headers, uriInfo, body);
}
@PATCH
@@ -366,6 +366,42 @@ class ApiGatewayHttpProxyIntegrationTest {
assertEquals("{\"symbol\":\"ACME\"}", lastBody.get());
}
// AWS forwards a DELETE body like any other (e.g. a batch delete taking a list of ids), and
// every execute-api URL form reaches the same dispatch, so each must hand the body over.
@ParameterizedTest
@CsvSource({
"/execute-api/{apiId}/test/orders",
"/_aws/execute-api/{apiId}/test/orders",
"/restapis/{apiId}/test/_user_request_/orders",
})
void forwardsRequestBodyOnDelete(String urlTemplate) {
resetRecordings();
String apiId = createProxyApi("http-proxy-delete-api", backendUri(), null);
given()
.contentType(ContentType.JSON)
.body("{\"ids\":[\"a\",\"b\"]}")
.when().delete(urlTemplate.replace("{apiId}", apiId))
.then().statusCode(200);
assertEquals("DELETE", lastMethod.get());
assertEquals("/orders", lastPath.get());
assertEquals("{\"ids\":[\"a\",\"b\"]}", lastBody.get());
}
@Test
void deleteWithoutBodyStillReachesTheBackend() {
resetRecordings();
String apiId = createProxyApi("http-proxy-delete-empty-api", backendUri(), null);
given()
.when().delete("/execute-api/" + apiId + "/test/orders/42")
.then().statusCode(200);
assertEquals("DELETE", lastMethod.get());
assertEquals("", lastBody.get());
}
@Test
void relaysBackendErrorStatusVerbatim() {
resetRecordings();
@@ -0,0 +1,80 @@
package io.github.hectorvent.floci.services.lambda;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.github.hectorvent.floci.core.common.RegionResolver;
import io.github.hectorvent.floci.services.cloudwatch.logs.CloudWatchLogsService;
import io.github.hectorvent.floci.services.lambda.model.InvocationType;
import io.github.hectorvent.floci.services.lambda.model.InvokeResult;
import jakarta.ws.rs.core.HttpHeaders;
import jakarta.ws.rs.core.MultivaluedHashMap;
import jakarta.ws.rs.core.UriInfo;
import org.junit.jupiter.api.Test;
import org.mockito.ArgumentCaptor;
import java.nio.charset.StandardCharsets;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
/**
* The {@code /_api/{functionName}} proxy packages a request as an API Gateway v1 proxy event and
* invokes the function with it.
*/
class ApiGatewayControllerTest {
private static final String REGION = "us-east-1";
private static final String FUNCTION = "my-function";
@Test
void deleteRequestBodyIsPassedToTheFunction() {
JsonNode eventNode = deleteEventFor("{\"ids\":[\"a\",\"b\"]}".getBytes(StandardCharsets.UTF_8));
assertEquals("DELETE", eventNode.get("httpMethod").asText());
assertEquals("{\"ids\":[\"a\",\"b\"]}", eventNode.get("body").asText());
}
@Test
void deleteWithoutBodyHasNullBody() {
JsonNode eventNode = deleteEventFor(new byte[0]);
assertTrue(eventNode.get("body").isNull());
}
private JsonNode deleteEventFor(byte[] body) {
LambdaService lambdaService = mock(LambdaService.class);
InvokeResult invokeResult = new InvokeResult();
invokeResult.setStatusCode(200);
invokeResult.setPayload("{\"statusCode\":204}".getBytes(StandardCharsets.UTF_8));
when(lambdaService.invoke(eq(REGION), eq(FUNCTION), any(byte[].class), eq(InvocationType.RequestResponse)))
.thenReturn(invokeResult);
HttpHeaders headers = mock(HttpHeaders.class);
MultivaluedHashMap<String, String> requestHeaders = new MultivaluedHashMap<>();
requestHeaders.putSingle("content-type", "application/json");
when(headers.getRequestHeaders()).thenReturn(requestHeaders);
UriInfo uriInfo = mock(UriInfo.class);
when(uriInfo.getQueryParameters()).thenReturn(new MultivaluedHashMap<>());
RegionResolver regionResolver = mock(RegionResolver.class);
when(regionResolver.resolveRegion(headers)).thenReturn(REGION);
ApiGatewayController controller = new ApiGatewayController(
lambdaService, regionResolver, new ObjectMapper(), mock(CloudWatchLogsService.class));
controller.handleDelete(headers, uriInfo, FUNCTION, "items", body);
ArgumentCaptor<byte[]> event = ArgumentCaptor.forClass(byte[].class);
verify(lambdaService).invoke(eq(REGION), eq(FUNCTION), event.capture(), eq(InvocationType.RequestResponse));
try {
return new ObjectMapper().readTree(event.getValue());
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
@@ -20,6 +20,7 @@ import java.nio.charset.StandardCharsets;
import java.util.Base64;
import java.util.List;
import java.util.Locale;
import java.util.function.Function;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
@@ -250,6 +251,25 @@ class LambdaUrlInvocationControllerTest {
assertEquals("{\"hello\":\"world\"}", eventNode.get("body").asText());
}
@Test
void deleteRequestBodyIsPassedToTheFunction() {
byte[] body = "{\"ids\":[\"a\",\"b\"]}".getBytes(StandardCharsets.UTF_8);
JsonNode eventNode = eventFor(controller -> controller.handleDelete("url-id", "items",
headersWith("application/json"), uriInfoFor("http://localhost/lambda-url/url-id/items"), body));
assertEquals("DELETE", eventNode.get("requestContext").get("http").get("method").asText());
assertFalse(eventNode.get("isBase64Encoded").asBoolean());
assertEquals("{\"ids\":[\"a\",\"b\"]}", eventNode.get("body").asText());
}
@Test
void deleteWithoutBodyHasNullBody() {
JsonNode eventNode = eventFor(controller -> controller.handleDelete("url-id", "items",
headersWith("application/json"), uriInfoFor("http://localhost/lambda-url/url-id/items"), new byte[0]));
assertTrue(eventNode.get("body").isNull());
}
@Test
void responseCookiesArrayBecomesMultipleSetCookieHeaders() {
LambdaFunction fn = new LambdaFunction();
@@ -301,7 +321,7 @@ class LambdaUrlInvocationControllerTest {
assertNull(response.getEntity());
}
private JsonNode eventFor(HttpHeaders headers) {
private JsonNode eventFor(Function<LambdaUrlInvocationController, Response> call) {
LambdaFunction fn = new LambdaFunction();
fn.setFunctionName("my-function");
fn.setFunctionArn(FUNCTION_ARN);
@@ -315,8 +335,7 @@ class LambdaUrlInvocationControllerTest {
when(lambdaService.invokeArn(eq(FUNCTION_ARN), any(byte[].class), eq(InvocationType.RequestResponse)))
.thenReturn(invokeResult);
newController(lambdaService).handleGet("url-id", "", headers,
uriInfoFor("http://localhost/lambda-url/url-id/"));
call.apply(newController(lambdaService));
ArgumentCaptor<byte[]> event = ArgumentCaptor.forClass(byte[].class);
verify(lambdaService).invokeArn(eq(FUNCTION_ARN), event.capture(), eq(InvocationType.RequestResponse));
@@ -330,7 +349,8 @@ class LambdaUrlInvocationControllerTest {
headers.getRequestHeaders().add("cookie", " c=3 ");
headers.getRequestHeaders().putSingle("x-other", "v");
JsonNode eventNode = eventFor(headers);
JsonNode eventNode = eventFor(controller -> controller.handleGet("url-id", "", headers,
uriInfoFor("http://localhost/lambda-url/url-id/")));
assertEquals(3, eventNode.get("cookies").size());
assertEquals("a=1", eventNode.get("cookies").get(0).asText());
@@ -342,7 +362,8 @@ class LambdaUrlInvocationControllerTest {
@Test
void requestWithoutCookiesOmitsCookiesField() {
JsonNode eventNode = eventFor(headersWith(null));
JsonNode eventNode = eventFor(controller -> controller.handleGet("url-id", "", headersWith(null),
uriInfoFor("http://localhost/lambda-url/url-id/")));
assertFalse(eventNode.has("cookies"));
}