fix(apigateway): share REST request context and complete mappings (#5035)

* fix(apigateway): share REST request context and complete parameter mappings

* fix(apigateway): resolve wildcard request body mappings

* fix(apigateway): distinguish scalar and multi-value mapping sources
This commit is contained in:
Abhigya authored and GitHub committed 2026-10-04 06:02:49 -04:00
1 parent 971dc01f34
commit 3f591f853d
8 files changed
+610 -151

No files matched your search

@@ -1002,10 +1002,12 @@ class ApiGatewayAwsIntegrationTest {
integrationNode.put("uri", "arn:aws:apigateway:us-east-1:dynamodb:action/PutItem");
ObjectNode reqParams = mapper.createObjectNode();
reqParams.put("integration.request.querystring.itemId", "method.request.querystring.itemId");
reqParams.put("integration.request.header.X-Mapped", "method.request.header.X-Source");
integrationNode.set("requestParameters", reqParams);
ObjectNode rt = mapper.createObjectNode();
rt.put("application/json",
"{\"TableName\": \"" + TABLE_NAME + "\", \"Item\": {\"id\": {\"S\": \"$input.params('itemId')\"}, \"source\": {\"S\": \"req-param-mapped\"}}}");
"{\"TableName\": \"" + TABLE_NAME + "\", \"Item\": {\"id\": {\"S\": \"$input.params('itemId')\"}, "
+ "\"source\": {\"S\": \"req-param-mapped\"}, \"header\": {\"S\": \"$input.params('X-Mapped')\"}}}");
integrationNode.set("requestTemplates", rt);
given()
@@ -1027,7 +1029,8 @@ class ApiGatewayAwsIntegrationTest {
given()
.contentType(ContentType.JSON)
.body("{}")
.queryParam("itemId", "param-123")
.queryParam("itemId", "param-123", "second-id")
.header("X-Source", "first-header", "second-header")
.when().post("/execute-api/" + apiId + "/test/req-param")
.then().statusCode(200);
@@ -1044,6 +1047,7 @@ class ApiGatewayAwsIntegrationTest {
assertTrue(result.has("Item"), "Item should exist with param-mapped key");
assertEquals("param-123", result.path("Item").path("id").path("S").asText());
assertEquals("req-param-mapped", result.path("Item").path("source").path("S").asText());
assertEquals("first-header", result.path("Item").path("header").path("S").asText());
}
// ──────────────── Test: Response body JSONPath (deep) ────────────────
@@ -0,0 +1,27 @@
package io.github.hectorvent.floci.services.apigateway;
import org.junit.jupiter.api.Test;
import java.util.UUID;
import static org.junit.jupiter.api.Assertions.*;
class ApiGatewayExecuteRouteContextTest {
@Test
void requestIdOverrideDoesNotReplaceExtendedIdOrChangeMidRequest() {
ApiGatewayExecuteRouteContext context = new ApiGatewayExecuteRouteContext();
String requestId = UUID.randomUUID().toString();
assertEquals(requestId, context.requestIdFromOverride(requestId));
assertEquals(requestId, context.requestIdFromOverride(UUID.randomUUID().toString()));
assertNotEquals(requestId, context.extendedRequestId());
}
@Test
void malformedUuidIsReplacedAndMarked() {
ApiGatewayExecuteRouteContext context = new ApiGatewayExecuteRouteContext();
String requestId = context.requestIdFromOverride("1-1-1-1-1");
String marker = "_REPLACED_INVALID_REQUEST_ID";
assertTrue(requestId.endsWith(marker));
assertDoesNotThrow(() -> UUID.fromString(requestId.substring(0, requestId.length() - marker.length())));
}
}
@@ -7,14 +7,19 @@ import com.sun.net.httpserver.HttpServer;
import io.github.hectorvent.floci.services.lambda.LambdaService;
import io.github.hectorvent.floci.services.lambda.model.InvocationType;
import io.github.hectorvent.floci.services.lambda.model.InvokeResult;
import io.github.hectorvent.floci.testutil.ExecuteApiRequestSigner;
import io.quarkus.test.InjectMock;
import io.quarkus.test.junit.QuarkusTest;
import io.restassured.RestAssured;
import io.restassured.http.ContentType;
import io.restassured.response.Response;
import io.restassured.specification.RequestSpecification;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.ArgumentCaptor;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.CsvSource;
import org.junit.jupiter.params.provider.ValueSource;
@@ -22,6 +27,7 @@ import org.junit.jupiter.params.provider.ValueSource;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.charset.StandardCharsets;
import java.time.Instant;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Locale;
@@ -30,6 +36,7 @@ import java.util.UUID;
import java.util.concurrent.atomic.AtomicInteger;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.equalTo;
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
@@ -135,6 +142,20 @@ class ApiGatewayHttpContextMappingIntegrationTest {
}
}
@ParameterizedTest
@ValueSource(strings = {"HTTP_PROXY", "HTTP"})
void rejectsObjectAuthorizerContextBeforeReachingBackend(String type) throws Exception {
configureAuthorizer(0, Map.of("objectKey", Map.of("nested", "value")));
configureIntegration(type, "GET", Map.of(
"integration.request.header.X-Object", "context.authorizer.objectKey",
"integration.request.path.principal", "context.authorizer.principalId",
"integration.request.path.proxy", "method.request.path.proxy"));
deploy();
given().header("Authorization", "Bearer allowed").header("X-Object", "forged")
.get("/execute-api/" + apiId + "/test/orders/42").then().statusCode(500);
assertEquals(0, backendRequests.get());
}
@ParameterizedTest
@ValueSource(strings = {"HTTP_PROXY", "HTTP"})
void missingAuthorizerClaimDoesNotFallBackToClientHeader(String type) throws Exception {
@@ -260,6 +281,234 @@ class ApiGatewayHttpContextMappingIntegrationTest {
assertDoesNotThrow(() -> UUID.fromString(response.path("headers").path("x-request-id").path(0).asText()));
}
@ParameterizedTest
@ValueSource(strings = {"HTTP_PROXY", "HTTP"})
void mapsDocumentedRequestMetadataAndValidClientRequestId(String type) throws Exception {
configureAuthorizer(0);
Map<String, String> parameters = new LinkedHashMap<>();
for (String field : List.of("requestId", "extendedRequestId", "domainName", "domainPrefix",
"requestTime", "requestTimeEpoch", "identity.sourceIp")) {
parameters.put("integration.request.header.X-" + field.replace('.', '-'), "context." + field);
}
parameters.put("integration.request.path.principal", "context.authorizer.principalId");
parameters.put("integration.request.path.proxy", "method.request.path.proxy");
configureIntegration(type, "GET", parameters);
deploy();
String requestId = UUID.randomUUID().toString();
long before = System.currentTimeMillis();
JsonNode response = MAPPER.readTree(given().header("Authorization", "Bearer allowed")
.header("x-amzn-RequestId", requestId).header("X-Forwarded-For", "192.0.2.10")
.get("/execute-api/" + apiId + "/test/orders/42")
.then().statusCode(200).header("x-amzn-RequestId", equalTo(requestId)).extract().asByteArray());
JsonNode headers = response.path("headers");
assertEquals(requestId, headers.path("x-requestid").path(0).asText());
String extendedId = headers.path("x-extendedrequestid").path(0).asText();
assertFalse(extendedId.isEmpty());
assertNotEquals(requestId, extendedId);
assertEquals("localhost", headers.path("x-domainname").path(0).asText());
assertEquals("localhost", headers.path("x-domainprefix").path(0).asText());
long requestTime = Long.parseLong(headers.path("x-requesttimeepoch").path(0).asText());
assertTrue(requestTime >= before && requestTime <= System.currentTimeMillis());
assertFalse(headers.path("x-requesttime").path(0).asText().isEmpty());
assertEquals("127.0.0.1", headers.path("x-identity-sourceip").path(0).asText());
if ("HTTP".equals(type)) {
assertEquals(requestId, MAPPER.readTree(response.path("body").asText()).path("requestId").asText());
}
}
@ParameterizedTest
@ValueSource(strings = {"bad_host", "bad_host:8080"})
void malformedHostDoesNotBreakMappingOrGatewayErrors(String host) throws Exception {
configureAuthorizer(0);
configureIntegration("HTTP_PROXY", "GET", Map.of(
"integration.request.header.X-Domain", "context.domainName",
"integration.request.path.principal", "context.authorizer.principalId",
"integration.request.path.proxy", "method.request.path.proxy"));
deploy();
given().header("Host", host).header("Authorization", "Bearer allowed")
.get("/execute-api/" + apiId + "/test/orders/42").then().statusCode(200)
.body("headers.x-domain[0]", equalTo(apiId + ".execute-api.us-east-1.amazonaws.com"));
given().contentType(ContentType.JSON).body(Map.of("responseParameters", Map.of(
"gatewayresponse.header.X-Domain", "context.domainName")))
.put("/restapis/" + apiId + "/gatewayresponses/ACCESS_DENIED").then().statusCode(201);
given().header("Host", host).header("Authorization", "Bearer forged")
.get("/execute-api/" + apiId + "/test/orders/42")
.then().statusCode(403).header("X-Domain", equalTo(apiId + ".execute-api.us-east-1.amazonaws.com"));
}
@ParameterizedTest
@ValueSource(strings = {"/execute-api/missing-api/test/orders", "/restapis/missing-api/test/_user_request_/orders"})
void missingRestApiErrorsHaveRequestIdentifiers(String path) {
String requestId = UUID.randomUUID().toString();
Response response = given().header("x-amzn-RequestId", requestId)
.get(path).then().statusCode(404).header("x-amzn-RequestId", equalTo(requestId)).extract().response();
assertDoesNotThrow(() -> UUID.fromString(response.header("x-amz-apigw-id")));
}
@ParameterizedTest
@ValueSource(strings = {"HTTP_PROXY", "HTTP"})
void mapsStageRepeatedValuesAndOriginalBodyFields(String type) throws Exception {
given().contentType(ContentType.JSON).body(Map.of("authorizationType", "NONE"))
.put(methodPath + "POST").then().statusCode(201);
Map<String, String> parameters = new LinkedHashMap<>();
parameters.put("integration.request.header.X-Header-Copy", "method.request.multivalueheader.X-Source");
parameters.put("integration.request.header.X-Scalar-Header", "method.request.header.X-Source");
parameters.put("integration.request.querystring.copied", "method.request.multivaluequerystring.source");
parameters.put("integration.request.querystring.scalar", "method.request.querystring.source");
parameters.put("integration.request.header.X-Raw-Body", "method.request.body");
parameters.put("integration.request.header.X-Body-Number", "method.request.body.items[0].number");
parameters.put("integration.request.header.X-Body-Items", "method.request.body.items[*]");
parameters.put("integration.request.header.X-Body-Numbers", "method.request.body.items[*].number");
parameters.put("integration.request.header.X-Body-Missing", "method.request.body.missing");
parameters.put("integration.request.header.X-Body-Invalid", "method.request.body.items[invalid]");
parameters.put("integration.request.header.X-Body-Boolean", "method.request.body.enabled");
parameters.put("integration.request.querystring.owner", "stageVariables.owner");
parameters.put("integration.request.path.principal", "stageVariables.owner");
parameters.put("integration.request.path.proxy", "method.request.path.proxy");
configureIntegration(type, "POST", parameters);
deploy();
given().contentType(ContentType.JSON).body(Map.of("patchOperations", List.of(Map.of(
"op", "add", "path", "/variables/owner", "value", "stage-owner"))))
.patch("/restapis/" + apiId + "/stages/test").then().statusCode(200);
String body = "{\"items\":[{\"number\":42},{\"number\":7}],\"enabled\":true}";
JsonNode response = MAPPER.readTree(given().contentType(ContentType.JSON).body(body)
.header("X-Source", "first", "second").queryParam("source", "one", "two")
.post("/execute-api/" + apiId + "/test/orders/42")
.then().statusCode(200).extract().asByteArray());
assertEquals(MAPPER.valueToTree(List.of("first", "second")), response.path("headers").path("x-header-copy"));
assertEquals(MAPPER.valueToTree(List.of("first")), response.path("headers").path("x-scalar-header"));
assertEquals(body, response.path("headers").path("x-raw-body").path(0).asText());
assertEquals("42", response.path("headers").path("x-body-number").path(0).asText());
assertEquals("[{\"number\":42},{\"number\":7}]", response.path("headers").path("x-body-items").path(0).asText());
assertEquals("[42,7]", response.path("headers").path("x-body-numbers").path(0).asText());
assertFalse(response.path("headers").has("x-body-missing"));
assertFalse(response.path("headers").has("x-body-invalid"));
assertEquals("true", response.path("headers").path("x-body-boolean").path(0).asText());
assertTrue(response.path("query").asText().contains("copied=one&copied=two"));
assertTrue(List.of(response.path("query").asText().split("&")).contains("scalar=one"));
assertTrue(response.path("query").asText().contains("owner=stage-owner"));
assertEquals("/users/stage-owner/orders/42", response.path("path").asText());
}
@ParameterizedTest
@ValueSource(strings = {"HTTP_PROXY", "HTTP"})
void mapsArrayRootBodyFields(String type) throws Exception {
given().contentType(ContentType.JSON).body(Map.of("authorizationType", "NONE"))
.put(methodPath + "POST").then().statusCode(201);
configureIntegration(type, "POST", Map.of(
"integration.request.header.X-First-Price", "method.request.body[0].price",
"integration.request.header.X-Prices", "method.request.body[*].price",
"integration.request.path.principal", "'array'",
"integration.request.path.proxy", "method.request.path.proxy"));
deploy();
JsonNode response = MAPPER.readTree(given().contentType(ContentType.JSON)
.body("[{\"price\":42},{\"price\":7}]")
.post("/execute-api/" + apiId + "/test/orders/42")
.then().statusCode(200).extract().asByteArray());
assertEquals("42", response.path("headers").path("x-first-price").path(0).asText());
assertEquals("[42,7]", response.path("headers").path("x-prices").path(0).asText());
}
@ParameterizedTest
@ValueSource(strings = {"HTTP_PROXY", "HTTP"})
void mapsCustomDomainAndPrefix(String type) throws Exception {
configureAuthorizer(0);
configureIntegration(type, "GET", Map.of("integration.request.header.X-Domain", "context.domainName",
"integration.request.header.X-Prefix", "context.domainPrefix",
"integration.request.path.principal", "context.authorizer.principalId",
"integration.request.path.proxy", "method.request.path.proxy"));
deploy();
String domain = apiId + ".example.test";
given().contentType(ContentType.JSON).body(Map.of("domainName", domain,
"certificateArn", "arn:aws:acm:us-east-1:000000000000:certificate/example"))
.post("/domainnames").then().statusCode(201);
try {
given().contentType(ContentType.JSON).body(Map.of("basePath", "v1", "restApiId", apiId, "stage", "test"))
.post("/domainnames/" + domain + "/basepathmappings").then().statusCode(201);
JsonNode response = MAPPER.readTree(given().header("Host", domain).header("Authorization", "Bearer allowed")
.get("/v1/orders/42").then().statusCode(200).extract().asByteArray());
assertEquals(domain, response.path("headers").path("x-domain").path(0).asText());
assertEquals(apiId, response.path("headers").path("x-prefix").path(0).asText());
} finally {
given().delete("/domainnames/" + domain).then().statusCode(202);
}
}
@ParameterizedTest
@ValueSource(strings = {"HTTP_PROXY", "HTTP"})
void requestAuthorizerAndBackendShareRequestMetadata(String type) throws Exception {
configureAuthorizer(0, Map.of("userClaims", "verified-claims"), "REQUEST");
Map<String, String> parameters = new LinkedHashMap<>();
for (String field : List.of("requestId", "extendedRequestId", "requestTimeEpoch")) {
parameters.put("integration.request.header.X-" + field, "context." + field);
}
parameters.put("integration.request.path.principal", "context.authorizer.principalId");
parameters.put("integration.request.path.proxy", "method.request.path.proxy");
configureIntegration(type, "GET", parameters);
deploy();
JsonNode response = MAPPER.readTree(given().header("Authorization", "Bearer allowed")
.get("/execute-api/" + apiId + "/test/orders/42")
.then().statusCode(200).extract().asByteArray());
ArgumentCaptor<byte[]> invocation = ArgumentCaptor.forClass(byte[].class);
verify(lambdaService).invoke(eq("us-east-1"), eq(FUNCTION), invocation.capture(), eq(InvocationType.RequestResponse));
JsonNode authorizerContext = MAPPER.readTree(invocation.getValue()).path("requestContext");
for (String field : List.of("requestId", "extendedRequestId", "requestTimeEpoch")) {
assertEquals(authorizerContext.path(field).asText(), response.path("headers").path("x-" + field.toLowerCase(Locale.ROOT)).path(0).asText());
}
}
@ParameterizedTest
@ValueSource(strings = {"HTTP_PROXY", "HTTP"})
void mapsVerifiedIamIdentity(String type) throws Exception {
given().contentType(ContentType.JSON).body(Map.of("authorizationType", "AWS_IAM"))
.put(methodPath + "GET").then().statusCode(201);
Map<String, String> parameters = new LinkedHashMap<>();
for (String field : List.of("accessKey", "accountId", "caller", "user", "userArn")) {
parameters.put("integration.request.header.X-" + field, "context.identity." + field);
}
parameters.put("integration.request.path.principal", "'iam'");
parameters.put("integration.request.path.proxy", "method.request.path.proxy");
configureIntegration(type, "GET", parameters);
deploy();
String path = "/execute-api/" + apiId + "/test/orders/42";
Map<String, String> signed = ExecuteApiRequestSigner.signedHeaders("GET", path, Map.of(),
"localhost:" + RestAssured.port, null, "test", "test", "us-east-1", Instant.now());
JsonNode response = MAPPER.readTree(given().headers(signed).get(path)
.then().statusCode(200).extract().asByteArray());
assertEquals("test", response.path("headers").path("x-accesskey").path(0).asText());
assertEquals("000000000000", response.path("headers").path("x-accountid").path(0).asText());
assertFalse(response.path("headers").path("x-userarn").path(0).asText().isEmpty());
assertEquals(response.path("headers").path("x-caller"), response.path("headers").path("x-user"));
}
@ParameterizedTest
@ValueSource(strings = {"HTTP_PROXY", "HTTP"})
void mapsResolvedApiKey(String type) throws Exception {
given().contentType(ContentType.JSON).body(Map.of("authorizationType", "NONE", "apiKeyRequired", true))
.put(methodPath + "GET").then().statusCode(201);
configureIntegration(type, "GET", Map.of("integration.request.header.X-Key", "context.identity.apiKey",
"integration.request.header.X-Key-Id", "context.identity.apiKeyId",
"integration.request.path.principal", "'key'", "integration.request.path.proxy", "method.request.path.proxy"));
deploy();
JsonNode key = MAPPER.readTree(given().contentType(ContentType.JSON).body(Map.of("name", "mapping-key", "enabled", true))
.post("/apikeys").then().statusCode(201).extract().asByteArray());
String plan = given().contentType(ContentType.JSON).body(Map.of("name", "mapping-plan", "apiStages",
List.of(Map.of("apiId", apiId, "stage", "test"))))
.post("/usageplans").then().statusCode(201).extract().path("id");
try {
given().contentType(ContentType.JSON).body(Map.of("keyId", key.path("id").asText(), "keyType", "API_KEY"))
.post("/usageplans/" + plan + "/keys").then().statusCode(201);
JsonNode response = MAPPER.readTree(given().header("X-Api-Key", key.path("value").asText())
.get("/execute-api/" + apiId + "/test/orders/42")
.then().statusCode(200).extract().asByteArray());
assertEquals(key.path("value").asText(), response.path("headers").path("x-key").path(0).asText());
assertEquals(key.path("id").asText(), response.path("headers").path("x-key-id").path(0).asText());
} finally {
given().delete("/usageplans/" + plan).then().statusCode(202);
given().delete("/apikeys/" + key.path("id").asText()).then().statusCode(202);
}
}
private void assertMappedContext(JsonNode response) {
JsonNode headers = response.path("headers");
assertEquals(MAPPER.valueToTree(List.of("verified-claims")), headers.path("x-user-claims"));
@@ -279,8 +528,12 @@ class ApiGatewayHttpContextMappingIntegrationTest {
}
private void configureAuthorizer(int ttl, Map<String, Object> context) throws Exception {
configureAuthorizer(ttl, context, "TOKEN");
}
private void configureAuthorizer(int ttl, Map<String, Object> context, String type) throws Exception {
String authorizerId = given().contentType(ContentType.JSON)
.body(Map.of("name", "claims", "type", "TOKEN", "authorizerUri", AUTHORIZER_URI,
.body(Map.of("name", "claims", "type", type, "authorizerUri", AUTHORIZER_URI,
"identitySource", "method.request.header.Authorization", "authorizerResultTtlInSeconds", ttl))
.post("/restapis/" + apiId + "/authorizers")
.then().statusCode(201).extract().path("id");
@@ -290,7 +543,7 @@ class ApiGatewayHttpContextMappingIntegrationTest {
when(lambdaService.invoke(eq("us-east-1"), eq(FUNCTION), any(byte[].class), eq(InvocationType.RequestResponse)))
.thenAnswer(invocation -> {
JsonNode event = MAPPER.readTree((byte[]) invocation.getArgument(2));
String effect = "Bearer allowed".equals(event.path("authorizationToken").asText()) ? "Allow" : "Deny";
String effect = "REQUEST".equals(type) || "Bearer allowed".equals(event.path("authorizationToken").asText()) ? "Allow" : "Deny";
byte[] payload = MAPPER.writeValueAsBytes(Map.of("principalId", "verified-user",
"policyDocument", Map.of("Version", "2012-10-17", "Statement", List.of(Map.of(
"Action", "execute-api:Invoke", "Effect", effect, "Resource", "*"))),
@@ -306,6 +559,7 @@ class ApiGatewayHttpContextMappingIntegrationTest {
parameters.put("integration.request.header.X-Number", "context.authorizer.numberKey");
parameters.put("integration.request.header.X-Boolean", "context.authorizer.booleanKey");
parameters.put("integration.request.header.X-Missing", "context.authorizer.missing");
// REST authorizer context rejects objects, so use the identity map to test non-scalar mappings.
parameters.put("integration.request.header.X-Object", "context.identity");
parameters.put("integration.request.header.X-Request-Id", "context.requestId");
parameters.put("integration.request.header.X-Context-Stage", "context.stage");
@@ -9,6 +9,8 @@ import jakarta.ws.rs.core.MultivaluedMap;
import jakarta.ws.rs.core.UriInfo;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;
import java.net.URI;
@@ -77,6 +79,18 @@ class ProxyEventIamIdentityTest {
assertEquals("arn:aws:iam::000000000000:user/alice", identity.get("userArn").asText());
}
@ParameterizedTest
@ValueSource(strings = {"bad_host", "[bad", "", "bad host"})
void invalidHostFallsBackToExecuteApiDomainInRestProxyEvent(String host) throws Exception {
when(headers.getHeaderString("Host")).thenReturn(host);
JsonNode context = MAPPER.readTree(controller.buildProxyEvent(
"us-east-1", "api1", "GET", "/iam", "/iam", "res1", "test", null,
headers, uriInfo, null, "req-1", null, null, null, CALLER))
.path("requestContext");
assertEquals("api1.execute-api.us-east-1.amazonaws.com", context.path("domainName").asText());
assertEquals("api1", context.path("domainPrefix").asText());
}
@Test
void restIdentityStaysExplicitlyNullWithoutIamAuthorization() throws Exception {
JsonNode identity = MAPPER.readTree(controller.buildProxyEvent(