fix(apigatewayv2): resolve body, stage and context sources in HTTP_PROXY parameter mapping (#8062)

HTTP_PROXY request parameter mappings on HTTP APIs now read $request.body, $request.body.<JSONPath>, $stageVariables.<name> and $context.<name>, the sources the AWS service integration subtypes already read, resolved by ContextValueResolver for both integration types. A header mapping that carries a control character is refused with 502 before anything reaches the backend, and an overwrite:path reads each embedded source expression whole, bracketed JSONPath selectors included.

Signed-off-by: Tyler Webb <tyler.webb@verkada.com>
This commit is contained in:
Tyler Webb authored and GitHub committed 2026-11-15 19:36:07 -04:00
1 parent 0999528349
commit 63124253f2
13 files changed
+620 -118

No files matched your search

@@ -2,6 +2,9 @@ package io.floci.aws.services.apigatewayv2;
import io.restassured.http.ContentType;
import java.util.LinkedHashMap;
import java.util.Map;
import static io.restassured.RestAssured.given;
/** A deployed HTTP API whose one route is an {@code HTTP_PROXY} integration on a test's fixture backend. */
@@ -16,15 +19,31 @@ public final class HttpProxyApiFixtures {
* {@code http://127.0.0.1:backendPort path}; returns its id.
*/
public static String createProxyApi(String name, String apiFields, String stageName, int backendPort, String path) {
return createProxyApi(name, apiFields, stageName, Map.of(), "GET", backendPort, path);
}
/**
* Creates an HTTP API as {@link #createProxyApi(String, String, String, int, String)} does, with
* {@code stageVariables} on its stage and a {@code routeMethod path} route; returns its id.
*/
public static String createProxyApi(String name, String apiFields, String stageName,
Map<String, String> stageVariables, String routeMethod, int backendPort,
String path) {
String apiId = given()
.contentType(ContentType.JSON)
.body("{\"name\":\"" + name + "\",\"protocolType\":\"HTTP\"" + apiFields + "}")
.when().post("/v2/apis")
.then().statusCode(201)
.extract().path("apiId");
Map<String, Object> stage = new LinkedHashMap<>();
stage.put("stageName", stageName);
stage.put("autoDeploy", true);
if (!stageVariables.isEmpty()) {
stage.put("stageVariables", stageVariables);
}
given()
.contentType(ContentType.JSON)
.body("{\"stageName\":\"" + stageName + "\",\"autoDeploy\":true}")
.body(stage)
.when().post("/v2/apis/" + apiId + "/stages")
.then().statusCode(201);
String integrationId = given()
@@ -36,7 +55,8 @@ public final class HttpProxyApiFixtures {
.extract().path("integrationId");
given()
.contentType(ContentType.JSON)
.body("{\"routeKey\":\"GET " + path + "\",\"target\":\"integrations/" + integrationId + "\"}")
.body("{\"routeKey\":\"" + routeMethod + " " + path + "\",\"target\":\"integrations/"
+ integrationId + "\"}")
.when().post("/v2/apis/" + apiId + "/routes")
.then().statusCode(201);
return apiId;
@@ -0,0 +1,155 @@
package io.floci.aws.services.apigatewayv2;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.sun.net.httpserver.HttpServer;
import io.quarkus.test.junit.QuarkusTest;
import io.restassured.http.ContentType;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.net.InetSocketAddress;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicReference;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.equalTo;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
@QuarkusTest
class HttpProxyRequestSourceMappingIntegrationTest {
private static final ObjectMapper MAPPER = new ObjectMapper();
private static final List<String> HEADERS = List.of("x-order", "x-backend", "x-stage", "x-route", "x-api",
"x-account", "x-path", "x-epoch", "x-missing", "x-missing-stage");
private final AtomicReference<JsonNode> received = new AtomicReference<>();
private HttpServer backend;
private String apiId;
@BeforeEach
void startBackend() throws Exception {
backend = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0);
backend.createContext("/", exchange -> {
ObjectNode request = MAPPER.createObjectNode();
for (String header : HEADERS) {
request.put(header, exchange.getRequestHeaders().getFirst(header));
}
request.put("path", exchange.getRequestURI().getPath());
request.put("query", exchange.getRequestURI().getRawQuery());
received.set(request);
byte[] bytes = "ok".getBytes(StandardCharsets.UTF_8);
exchange.sendResponseHeaders(200, bytes.length);
exchange.getResponseBody().write(bytes);
exchange.close();
});
backend.start();
}
@AfterEach
void cleanUp() {
try {
if (apiId != null) {
given().delete("/v2/apis/" + apiId).then().statusCode(204);
}
} finally {
if (backend != null) {
backend.stop(0);
}
}
}
@Test
void mapsBodyStageVariablesAndContextToHeadersQueryAndPath() {
configureApi();
long before = System.currentTimeMillis();
invoke("{\"order\":{\"id\":\"o-42\"}}");
JsonNode request = received.get();
assertNotNull(request);
assertEquals("o-42", request.path("x-order").asText());
assertEquals("blue", request.path("x-backend").asText());
assertEquals("test", request.path("x-stage").asText());
assertEquals("POST /orders", request.path("x-route").asText());
assertEquals(apiId, request.path("x-api").asText());
assertEquals("000000000000", request.path("x-account").asText());
assertEquals("/test/orders", request.path("x-path").asText());
assertTrue(Long.parseLong(request.path("x-epoch").asText()) >= before - 1000);
assertTrue(request.path("x-missing").isNull());
assertTrue(request.path("x-missing-stage").isNull());
assertEquals("/orders/o-42/test", request.path("path").asText());
assertEquals("order=o-42", request.path("query").asText());
}
@Test
void bodyThatIsNotJsonSkipsBodyMappings() {
configureApi();
invoke("not json");
JsonNode request = received.get();
assertTrue(request.path("x-order").isNull());
assertTrue(request.path("query").isNull());
assertEquals("blue", request.path("x-backend").asText());
}
@Test
void indexedBodyValueFillsAnEmbeddedPath() {
configureApi(Map.of("overwrite:path", "/orders/$request.body.items[1].id/lines"));
invoke("{\"items\":[{\"id\":\"i-1\"},{\"id\":\"i-2\"}]}");
assertEquals("/orders/i-2/lines", received.get().path("path").asText());
}
@Test
void wholeBodyCarryingALineBreakIsRejectedBeforeTheBackend() {
configureApi(Map.of("overwrite:header.x-order", "$request.body"));
invokeExpectingRejectedHeader("o-1\r\nX-Injected: 1", "x-order");
}
@Test
void wholeBodyCarryingALineBreakIsRejectedWhenTheHostIsMapped() {
configureApi(Map.of("overwrite:header.Host", "orders.internal",
"overwrite:header.x-order", "$request.body"));
invokeExpectingRejectedHeader("o-1\r\nX-Injected: 1", "x-order");
}
private void configureApi() {
configureApi(Map.ofEntries(
Map.entry("overwrite:header.x-order", "$request.body.order.id"),
Map.entry("overwrite:header.x-backend", "$stageVariables.backend"),
Map.entry("overwrite:header.x-stage", "$context.stage"),
Map.entry("overwrite:header.x-route", "$context.routeKey"),
Map.entry("overwrite:header.x-api", "$context.apiId"),
Map.entry("overwrite:header.x-account", "$context.accountId"),
Map.entry("overwrite:header.x-path", "$context.path"),
Map.entry("overwrite:header.x-epoch", "$context.requestTimeEpoch"),
Map.entry("overwrite:header.x-missing", "$request.body.order.missing"),
Map.entry("overwrite:header.x-missing-stage", "$stageVariables.missing"),
Map.entry("overwrite:querystring.order", "$request.body.order.id"),
Map.entry("overwrite:path", "/orders/$request.body.order.id/$context.stage")));
}
private void configureApi(Map<String, String> requestParameters) {
apiId = HttpProxyApiFixtures.createProxyApi("request-source-mapping", "", "test", Map.of("backend", "blue"),
"POST", backend.getAddress().getPort(), "/orders");
String apiPath = "/v2/apis/" + apiId;
String integrationId = given().get(apiPath + "/integrations").then().statusCode(200)
.extract().path("items[0].integrationId");
given().contentType(ContentType.JSON).body(Map.of("requestParameters", requestParameters))
.patch(apiPath + "/integrations/" + integrationId).then().statusCode(200);
}
private void invoke(String body) {
given().contentType(ContentType.JSON).body(body)
.post("/execute-api/" + apiId + "/test/orders").then().statusCode(200);
}
private void invokeExpectingRejectedHeader(String body, String header) {
given().contentType(ContentType.TEXT).body(body)
.post("/execute-api/" + apiId + "/test/orders").then().statusCode(502)
.body("message", equalTo("Bad Gateway: invalid request header value for " + header));
assertNull(received.get());
}
}
@@ -2,6 +2,7 @@ package io.floci.aws.services.apigatewayv2.proxy;
import org.junit.jupiter.api.Test;
import java.nio.charset.StandardCharsets;
import java.util.Map;
import static org.junit.jupiter.api.Assertions.assertEquals;
@@ -9,7 +10,7 @@ import static org.junit.jupiter.api.Assertions.assertNull;
/**
* Verifies {@link ContextValueResolver} resolves the documented HTTP API v2
* source value expressions: $context.*, $request.*, and literal pass-through.
* source value expressions: $context.*, $request.*, $stageVariables.*, and literal pass-through.
*/
class ContextValueResolverTest {
@@ -20,6 +21,16 @@ class ContextValueResolverTest {
"req-1", "1.2.3.4", headers, query, pathParams, null, claims, authContext);
}
private RequestContext withBody(String body) {
return new RequestContext("api1", "$default", "POST", "/foo", "foo", "POST /foo",
"req-1", "1.2.3.4", Map.of(), Map.of(), Map.of(),
body == null ? null : body.getBytes(StandardCharsets.UTF_8), Map.of(), Map.of());
}
private RequestContext withVariables(Map<String, String> stageVariables, Map<String, String> contextVariables) {
return ctx(Map.of(), Map.of(), Map.of(), Map.of(), Map.of()).withVariables(stageVariables, contextVariables);
}
@Test
void literalValuePassesThrough() {
ContextValueResolver r = new ContextValueResolver();
@@ -100,4 +111,59 @@ class ContextValueResolverTest {
ContextValueResolver r = new ContextValueResolver();
assertNull(r.resolve(null, ctx(Map.of(), Map.of(), Map.of(), Map.of(), Map.of())));
}
@Test
void requestBodyResolvesToTheWholeBody() {
ContextValueResolver r = new ContextValueResolver();
assertEquals("{\"order\":{\"id\":\"o-42\"}}",
r.resolve("$request.body", withBody("{\"order\":{\"id\":\"o-42\"}}")));
}
@Test
void emptyRequestBodyReturnsNull() {
ContextValueResolver r = new ContextValueResolver();
assertNull(r.resolve("$request.body", withBody(null)));
assertNull(r.resolve("$request.body", withBody("")));
}
@Test
void requestBodyPathResolvesScalarsAndJson() {
ContextValueResolver r = new ContextValueResolver();
RequestContext c = withBody("{\"order\":{\"id\":\"o-42\",\"qty\":3,\"tags\":[\"a\",\"b\"]}}");
assertEquals("o-42", r.resolve("$request.body.order.id", c));
assertEquals("3", r.resolve("$request.body.order.qty", c));
assertEquals("a", r.resolve("$request.body.order.tags[0]", c));
assertEquals("[\"a\",\"b\"]", r.resolve("$request.body.order.tags", c));
}
@Test
void requestBodyPathMissingOrUnreadableReturnsNull() {
ContextValueResolver r = new ContextValueResolver();
assertNull(r.resolve("$request.body.order.missing", withBody("{\"order\":{\"id\":\"o-42\"}}")));
assertNull(r.resolve("$request.body.order.id", withBody("not json")));
assertNull(r.resolve("$request.body.order.id", withBody(null)));
}
@Test
void stageVariableResolves() {
ContextValueResolver r = new ContextValueResolver();
RequestContext c = withVariables(Map.of("backend", "blue"), null);
assertEquals("blue", r.resolve("$stageVariables.backend", c));
assertNull(r.resolve("$stageVariables.missing", c));
}
@Test
void stageVariableWithoutStageVariablesReturnsNull() {
ContextValueResolver r = new ContextValueResolver();
assertNull(r.resolve("$stageVariables.backend", ctx(Map.of(), Map.of(), Map.of(), Map.of(), Map.of())));
}
@Test
void contextVariableResolves() {
ContextValueResolver r = new ContextValueResolver();
RequestContext c = withVariables(null, Map.of("stage", "prod", "routeKey", "ANY /foo"));
assertEquals("prod", r.resolve("$context.stage", c));
assertEquals("ANY /foo", r.resolve("$context.routeKey", c));
assertNull(r.resolve("$context.unknown", c));
}
}
@@ -501,4 +501,66 @@ class HttpProxyInvokerTest {
assertEquals(502, result.statusCode());
assertNull(received.get());
}
@Test
void rejectsAWholeBodyMappingCarryingALineBreakToANamedHost() {
HttpProxyInvoker invoker = new HttpProxyInvoker(
host -> new InetAddress[] {InetAddress.getByAddress(new byte[] {127, 0, 0, 1})});
Integration integration = httpProxyIntegration("http://named.example.test:" + backendPort + "/ok",
Map.of("overwrite:header.x-payload", "$request.body"));
RequestContext ctx = ctxFor("POST", "/wallet/x", "x", Map.of(), Map.of(),
"a\r\nX-Injected: 1".getBytes(StandardCharsets.UTF_8), Map.of());
ProxyResult result = invoker.invoke(integration, ctx);
assertEquals(502, result.statusCode());
assertEquals("{\"message\":\"Bad Gateway: invalid request header value for x-payload\"}",
new String(result.body(), StandardCharsets.UTF_8));
assertNull(received.get());
}
@Test
void rejectsAMappedHostHeaderCarryingALineBreak() {
Integration integration = httpProxyIntegration("http://127.0.0.1:" + backendPort + "/ok",
Map.of("overwrite:header.Host", "$request.querystring.host"));
RequestContext ctx = ctxFor("GET", "/wallet/x", "x", Map.of(),
Map.of("host", "lb.localhost.test\r\nX-Injected: 1"), null, Map.of());
ProxyResult result = new HttpProxyInvoker().invoke(integration, ctx);
assertEquals(502, result.statusCode());
assertEquals("{\"message\":\"Bad Gateway: invalid request header value for Host\"}",
new String(result.body(), StandardCharsets.UTF_8));
assertNull(received.get());
}
@Test
void rejectsAMappedBodyFieldCarryingAControlCharacterToAnAddressTarget() {
Integration integration = httpProxyIntegration("http://127.0.0.1:" + backendPort + "/ok",
Map.of("overwrite:header.x-note", "$request.body.note"));
for (String note : new String[] {"a\\r\\nX-Injected: 1", "a\\nb", "a\\u0000b", "a\\u007fb"}) {
RequestContext ctx = ctxFor("POST", "/wallet/x", "x", Map.of(), Map.of(),
("{\"note\":\"" + note + "\"}").getBytes(StandardCharsets.UTF_8), Map.of());
ProxyResult result = new HttpProxyInvoker().invoke(integration, ctx);
assertEquals(502, result.statusCode());
assertEquals("{\"message\":\"Bad Gateway: invalid request header value for x-note\"}",
new String(result.body(), StandardCharsets.UTF_8));
assertNull(received.get());
}
}
@Test
void forwardsAMappedHeaderValueContainingATab() {
Integration integration = httpProxyIntegration("http://127.0.0.1:" + backendPort + "/ok",
Map.of("overwrite:header.x-note", "$request.body.note"));
RequestContext ctx = ctxFor("POST", "/wallet/x", "x", Map.of(), Map.of(),
"{\"note\":\"a\\tb\"}".getBytes(StandardCharsets.UTF_8), Map.of());
ProxyResult result = new HttpProxyInvoker().invoke(integration, ctx);
assertEquals(200, result.statusCode());
assertTrue(received.get().headers().getFirst("x-note").matches("a[\\t ]b"));
}
}
@@ -3,6 +3,7 @@ package io.floci.aws.services.apigatewayv2.proxy;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.nio.charset.StandardCharsets;
import java.util.LinkedHashMap;
import java.util.Map;
@@ -164,4 +165,51 @@ class RequestParameterMapperTest {
assertEquals("b c", builder.headers().get("x-name").get(0));
}
private RequestContext withBody(String body, Map<String, String> stageVariables) {
return new RequestContext("api1", "$default", "POST", "/orders", null, "POST /orders", "req-1", "1.2.3.4",
Map.of(), Map.of(), Map.of("proxy", "balance"), body.getBytes(StandardCharsets.UTF_8),
Map.of(), Map.of()).withVariables(stageVariables, Map.of());
}
@Test
void overwritePathSelectsAnIndexedBodyValue() {
RequestContext withItems = withBody("{\"items\":[{\"id\":\"i-1\"},{\"id\":\"i-2\"}]}", Map.of());
mapper.apply(Map.of("overwrite:path", "/orders/$request.body.items[1].id/lines"), builder, withItems);
assertEquals("http://backend.local/orders/i-2/lines", builder.url());
}
@Test
void overwritePathSelectsQuotedKeys() {
RequestContext withKeys = withBody("{\"order id\":\"o 42\",\"meta\":{\"a.b\":\"v\"}}", Map.of());
mapper.apply(Map.of("overwrite:path", "/o/$request.body.['order id']/$request.body.meta[\"a.b\"]/x"),
builder, withKeys);
assertEquals("http://backend.local/o/o%2042/v/x", builder.url());
}
@Test
void overwritePathReadsNamesThatStartWithAnUnderscoreOrDigit() {
RequestContext withNames = withBody("{\"_id\":\"x1\",\"2nd\":\"two\"}",
Map.of("_backend", "blue", "1st", "one"));
mapper.apply(Map.of("overwrite:path",
"/$stageVariables._backend/$stageVariables.1st/$request.body._id/$request.body.2nd"),
builder, withNames);
assertEquals("http://backend.local/blue/one/x1/two", builder.url());
}
@Test
void overwritePathEndsAnEmbeddedNameWhereItsSyntaxEnds() {
RequestContext withEnv = withBody("{\"id\":\"o-1\"}", Map.of("env", "blue"));
mapper.apply(Map.of("overwrite:path", "/$stageVariables.env-v2/$request.path.proxy.json"),
builder, withEnv);
assertEquals("http://backend.local/blue-v2/balance.json", builder.url());
}
}