fix(apigateway): build shared $context values in one helper and match HTTP API extendedRequestId to requestId (#8191)

This commit is contained in:
Tyler Webb authored and GitHub committed 2026-11-16 19:37:45 -04:00
1 parent b07c49082e
commit 39e9cd9d1e
6 files changed
+174 -44

No files matched your search

+4 -2
View File
@@ -930,8 +930,10 @@ expressions are `$request.body`, `$request.body.<JSONPath>`, `$request.header.<n
`$context` variables: `accountId`, `apiId`, `domainName`, `domainPrefix`, `extendedRequestId`,
`httpMethod`, `path`, `protocol`, `requestTime`, `requestTimeEpoch`, `routeKey`, `stage`,
`requestId`, `identity.sourceIp`, `authorizer.<key>` and `authorizer.claims.<claim>`. `requestId`
and `domainName` are the values the rest of the gateway reports for the request, and `path`
starts with the stage name, as in `/test/send`, except on the `$default` stage. An expression
and `domainName` are the values the rest of the gateway reports for the request,
`extendedRequestId` is the same value as `requestId`, as AWS documents for HTTP APIs and as
`HTTP_PROXY` mappings also resolve it (an `HTTP_PROXY` response returns that id as `x-amzn-RequestId`,
in place of any the backend sent, and a valid UUID sent in `x-amzn-RequestId` replaces it), and `path` starts with the stage name, as in `/test/send`, except on the `$default` stage. An expression
with any other source is rejected with `400 BadRequestException` on create, update and import,
including one embedded as `${...}` or inside a JSON parameter's string values. A `$` inside static
text without braces, as in `price $5`, stays literal. A `$context` variable outside the list
@@ -1399,8 +1399,9 @@ public class ApiGatewayExecuteController {
Map<String, String> stageVars = stage != null ? stage.getVariables() : null;
putStageVariables(node, stageVars);
GatewayContextValues values = gatewayContextValues(apiId, region, headers);
ObjectNode ctx = node.putObject("requestContext");
ctx.put("accountId", regionResolver.getAccountId());
ctx.put("accountId", values.accountId());
ctx.put("apiId", apiId);
ctx.put("resourceId", resourceId != null ? resourceId : "");
ctx.put("resourcePath", resourcePath);
@@ -1408,12 +1409,11 @@ public class ApiGatewayExecuteController {
ctx.put("httpMethod", httpMethod);
ctx.put("stage", stageName);
ctx.put("requestId", routeContext.requestId(headers));
ctx.put("requestTimeEpoch", routeContext.requestTime().toEpochMilli());
ctx.put("requestTime", GATEWAY_REQUEST_TIME.format(routeContext.requestTime().atZone(ZoneOffset.UTC)));
ctx.put("extendedRequestId", routeContext.extendedRequestId());
String domain = restDomainName(apiId, region, headers);
ctx.put("domainName", domain);
ctx.put("domainPrefix", domain != null ? domain.split("\\.")[0] : null);
ctx.put("requestTimeEpoch", values.requestTimeEpoch());
ctx.put("requestTime", values.requestTime());
ctx.put("extendedRequestId", values.extendedRequestId());
ctx.put("domainName", values.domainName());
ctx.put("domainPrefix", values.domainPrefix());
ctx.put("protocol", "HTTP/1.1");
// identity.apiKey / identity.apiKeyId: resolve from usage plans linked to this (apiId, stage)
@@ -1526,22 +1526,20 @@ public class ApiGatewayExecuteController {
putStageVariables(event, stageVars);
String arnRegion = region != null ? region : regionResolver.getDefaultRegion();
String domainName = restDomainName(apiId, arnRegion, headers);
long nowMillis = routeContext.requestTime().toEpochMilli();
String requestTime = GATEWAY_REQUEST_TIME.format(routeContext.requestTime().atZone(ZoneOffset.UTC));
GatewayContextValues values = gatewayContextValues(apiId, arnRegion, headers);
ObjectNode ctx = event.putObject("requestContext");
ctx.put("accountId", regionResolver.getAccountId());
ctx.put("accountId", values.accountId());
ctx.put("apiId", apiId);
ctx.put("domainName", domainName);
ctx.put("domainPrefix", domainName.split("\\.")[0]);
ctx.put("extendedRequestId", routeContext.extendedRequestId());
ctx.put("domainName", values.domainName());
ctx.put("domainPrefix", values.domainPrefix());
ctx.put("extendedRequestId", values.extendedRequestId());
ctx.put("httpMethod", httpMethod);
ctx.put("path", requestPath);
ctx.put("protocol", "HTTP/1.1");
ctx.put("requestId", requestId);
ctx.put("requestTime", requestTime);
ctx.put("requestTimeEpoch", nowMillis);
ctx.put("requestTime", values.requestTime());
ctx.put("requestTimeEpoch", values.requestTimeEpoch());
ctx.put("resourceId", resourceId != null ? resourceId : "");
ctx.put("resourcePath", resourcePath);
ctx.put("stage", stageName);
@@ -2306,20 +2304,20 @@ public class ApiGatewayExecuteController {
private Map<String, Object> restRequestContext(GatewayResponseScope scope, String requestId) {
String region = scope.region() != null ? scope.region() : regionResolver.getDefaultRegion();
String domain = restDomainName(scope.apiId(), region, scope.headers());
GatewayContextValues values = gatewayContextValues(scope.apiId(), region, scope.headers());
Map<String, Object> context = new LinkedHashMap<>();
context.put("accountId", regionResolver.getAccountId());
context.put("accountId", values.accountId());
context.put("apiId", scope.apiId());
context.put("deploymentId", scope.stage() != null ? scope.stage().getDeploymentId() : null);
context.put("domainName", domain);
context.put("domainPrefix", domain != null ? domain.split("\\.")[0] : null);
context.put("extendedRequestId", routeContext.extendedRequestId());
context.put("domainName", values.domainName());
context.put("domainPrefix", values.domainPrefix());
context.put("extendedRequestId", values.extendedRequestId());
context.put("httpMethod", scope.httpMethod());
context.put("path", "/" + scope.stageName() + scope.path());
context.put("protocol", "HTTP/1.1");
context.put("requestId", requestId);
context.put("requestTime", GATEWAY_REQUEST_TIME.format(routeContext.requestTime().atZone(ZoneOffset.UTC)));
context.put("requestTimeEpoch", routeContext.requestTime().toEpochMilli());
context.put("requestTime", values.requestTime());
context.put("requestTimeEpoch", values.requestTimeEpoch());
context.put("resourceId", scope.resource() != null ? scope.resource().getId() : "");
context.put("resourcePath", scope.resource() != null ? scope.resource().getPath() : "");
context.put("stage", scope.stageName());
@@ -2327,6 +2325,22 @@ public class ApiGatewayExecuteController {
return context;
}
/**
* The {@code $context} values REST and HTTP APIs build the same way: the account, the domain the caller
* addressed, the gateway-generated request id and the request time. An HTTP API reports its request id as
* {@code extendedRequestId} instead.
*/
private record GatewayContextValues(String accountId, String domainName, String domainPrefix,
String extendedRequestId, String requestTime, long requestTimeEpoch) {}
private GatewayContextValues gatewayContextValues(String apiId, String region, HttpHeaders headers) {
Instant requestTime = routeContext.requestTime();
String domain = restDomainName(apiId, region, headers);
return new GatewayContextValues(regionResolver.getAccountId(), domain, domain.split("\\.")[0],
routeContext.extendedRequestId(), GATEWAY_REQUEST_TIME.format(requestTime.atZone(ZoneOffset.UTC)),
requestTime.toEpochMilli());
}
private String restDomainName(String apiId, String region, HttpHeaders headers) {
String host = headers != null ? headers.getHeaderString("Host") : null;
if (host != null) {
@@ -3018,7 +3032,7 @@ public class ApiGatewayExecuteController {
String hostRegion = region != null ? region : regionResolver.getDefaultRegion();
Map<String, String> contextVariables =
httpApiContextVariables(apiId, stageName, httpMethod, path, route, hostRegion, headers);
httpApiContextVariables(apiId, stageName, httpMethod, path, route, requestId, hostRegion, headers);
LOG.debugv("execute-api v2: {0} {1}/{2}{3} → {4}", httpMethod, apiId, stageName, path,
subtype.subtypeName());
@@ -3049,21 +3063,20 @@ public class ApiGatewayExecuteController {
/** The {@code $context.<name>} values an HTTP API parameter mapping can read for this request. */
private Map<String, String> httpApiContextVariables(String apiId, String stageName, String httpMethod,
String path, Route route, String region,
HttpHeaders headers) {
Instant requestTime = routeContext.requestTime();
String domain = restDomainName(apiId, region, headers);
String path, Route route, String requestId,
String region, HttpHeaders headers) {
GatewayContextValues values = gatewayContextValues(apiId, region, headers);
Map<String, String> contextVariables = new LinkedHashMap<>();
contextVariables.put("accountId", regionResolver.getAccountId());
contextVariables.put("accountId", values.accountId());
contextVariables.put("apiId", apiId);
contextVariables.put("domainName", domain);
contextVariables.put("domainPrefix", domain.split("\\.")[0]);
contextVariables.put("extendedRequestId", routeContext.extendedRequestId());
contextVariables.put("domainName", values.domainName());
contextVariables.put("domainPrefix", values.domainPrefix());
contextVariables.put("extendedRequestId", requestId);
contextVariables.put("httpMethod", httpMethod);
contextVariables.put("path", ("$default".equals(stageName) ? "" : "/" + stageName) + path);
contextVariables.put("protocol", "HTTP/1.1");
contextVariables.put("requestTime", GATEWAY_REQUEST_TIME.format(requestTime.atZone(ZoneOffset.UTC)));
contextVariables.put("requestTimeEpoch", Long.toString(requestTime.toEpochMilli()));
contextVariables.put("requestTime", values.requestTime());
contextVariables.put("requestTimeEpoch", Long.toString(values.requestTimeEpoch()));
contextVariables.put("routeKey", route.getRouteKey());
contextVariables.put("stage", stageName);
return contextVariables;
@@ -3176,15 +3189,17 @@ public class ApiGatewayExecuteController {
// $request.header.* mappings keep the caller's values; only what reaches the backend changes.
Map<String, List<String>> backendHeaders = HttpApiForwardedHeaders.apply(multiValueHeaders, sourceIp,
routeContext.localIp(), headers.getHeaderString("Host"), isSecureTransport(uriInfo) ? "https" : "http");
String requestId = routeContext.requestId(headers);
io.floci.aws.services.apigatewayv2.proxy.RequestContext ctx =
new io.floci.aws.services.apigatewayv2.proxy.RequestContext(
apiId, stageName, httpMethod, path,
pathParams.getOrDefault("proxy", ""), route.getRouteKey(),
UUID.randomUUID().toString(), sourceIp,
requestId, sourceIp,
requestHeaders, queryParams, pathParams, body,
claims, authorizerContext, backendHeaders, multiValueQueryParams, rawPathParams)
.withVariables(stageVariables, httpApiContextVariables(apiId, stageName, httpMethod, path,
route, region != null ? region : regionResolver.getDefaultRegion(), headers));
route, requestId, region != null ? region : regionResolver.getDefaultRegion(),
headers));
LOG.debugv("execute-api v2: {0} {1}/{2}{3} → HTTP_PROXY {4}",
httpMethod, apiId, stageName, path, effective.getIntegrationUri());
@@ -3196,12 +3211,15 @@ public class ApiGatewayExecuteController {
if (result.body() != null) rb.entity(result.body());
if (result.headers() != null) {
for (Map.Entry<String, List<String>> e : result.headers().entrySet()) {
if ("x-amzn-RequestId".equalsIgnoreCase(e.getKey())) {
continue;
}
for (String value : e.getValue()) {
rb.header(e.getKey(), value);
}
}
}
return rb.build();
return rb.header("x-amzn-RequestId", requestId).build();
}
private static boolean isCloudMapIntegration(
@@ -369,6 +369,34 @@ class ApiGatewayHttpContextMappingIntegrationTest {
}
}
@Test
void requestTemplateReadsTheSameContextValuesAsParameterMappings() throws Exception {
configureAuthorizer(0);
Map<String, String> parameters = new LinkedHashMap<>();
parameters.put("integration.request.header.X-Extended", "context.extendedRequestId");
parameters.put("integration.request.header.X-Epoch", "context.requestTimeEpoch");
parameters.put("integration.request.path.principal", "context.authorizer.principalId");
parameters.put("integration.request.path.proxy", "method.request.path.proxy");
configureIntegration("HTTP", "GET", parameters, "{\"accountId\":\"$context.accountId\","
+ "\"domainName\":\"$context.domainName\",\"domainPrefix\":\"$context.domainPrefix\","
+ "\"extendedRequestId\":\"$context.extendedRequestId\",\"requestTime\":\"$context.requestTime\","
+ "\"requestTimeEpoch\":\"$context.requestTimeEpoch\"}");
deploy();
Response response = given().header("Authorization", "Bearer allowed")
.get("/execute-api/" + apiId + "/test/orders/42").then().statusCode(200).extract().response();
JsonNode echoed = MAPPER.readTree(response.asByteArray());
JsonNode rendered = MAPPER.readTree(echoed.path("body").asText());
assertEquals("000000000000", rendered.path("accountId").asText());
assertEquals("localhost", rendered.path("domainName").asText());
assertEquals("localhost", rendered.path("domainPrefix").asText());
assertEquals(response.header("x-amz-apigw-id"), rendered.path("extendedRequestId").asText());
assertEquals(echoed.path("headers").path("x-extended").path(0).asText(),
rendered.path("extendedRequestId").asText());
assertEquals(echoed.path("headers").path("x-epoch").path(0).asText(),
rendered.path("requestTimeEpoch").asText());
assertFalse(rendered.path("requestTime").asText().isEmpty());
}
@ParameterizedTest
@ValueSource(strings = {"bad_host", "bad_host:8080"})
void malformedHostDoesNotBreakMappingOrGatewayErrors(String host) throws Exception {
@@ -631,13 +659,18 @@ class ApiGatewayHttpContextMappingIntegrationTest {
}
private void configureIntegration(String type, String method, Map<String, String> parameters) {
configureIntegration(type, method, parameters, "{\"requestId\":\"$context.requestId\"}");
}
private void configureIntegration(String type, String method, Map<String, String> parameters,
String requestTemplate) {
// POST makes the HTTP integration's rendered request body observable at the echo backend.
String integrationMethod = "HTTP".equals(type) && "GET".equals(method) ? "POST" : method;
given().contentType(ContentType.JSON)
.body(Map.of("type", type, "httpMethod", integrationMethod,
"uri", "http://127.0.0.1:" + backend.getAddress().getPort() + "/users/{principal}/{proxy}",
"requestParameters", parameters, "requestTemplates", Map.of("application/json",
"{\"requestId\":\"$context.requestId\"}")))
requestTemplate)))
.put(methodPath + method + "/integration").then().statusCode(201);
}
@@ -292,6 +292,13 @@ class ApiGatewayRequestAuthorizerIntegrationTest {
String resourceId = ctx.path("resourceId").asText(null);
assertNotNull(resourceId, "requestContext.resourceId must be non-null");
assertFalse(resourceId.isEmpty(), "requestContext.resourceId must be non-empty");
assertEquals("localhost", ctx.path("domainName").asText(null));
assertEquals("localhost", ctx.path("domainPrefix").asText(null));
assertFalse(ctx.path("extendedRequestId").asText("").isEmpty(),
"requestContext.extendedRequestId must be non-empty");
assertFalse(ctx.path("requestTime").asText("").isEmpty(), "requestContext.requestTime must be non-empty");
assertTrue(ctx.path("requestTimeEpoch").asLong() > 0, "requestContext.requestTimeEpoch must be set");
}
@Test
@@ -28,7 +28,9 @@ import static io.restassured.RestAssured.given;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.greaterThanOrEqualTo;
import static org.hamcrest.Matchers.hasSize;
import static org.hamcrest.Matchers.matchesPattern;
import static org.hamcrest.Matchers.notNullValue;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
@@ -472,6 +474,33 @@ class ApiGatewayV2SqsSendMessageIntegrationTest {
});
}
@Test
void invokeResolvesAccountDomainRequestIdAndRequestTimeContextVariables() {
String attributes = "{\"Account\":{\"DataType\":\"String\",\"StringValue\":\"${context.accountId}\"},"
+ "\"Domain\":{\"DataType\":\"String\",\"StringValue\":\"${context.domainName}\"},"
+ "\"Prefix\":{\"DataType\":\"String\",\"StringValue\":\"${context.domainPrefix}\"},"
+ "\"Request\":{\"DataType\":\"String\",\"StringValue\":\"${context.requestId}\"},"
+ "\"Extended\":{\"DataType\":\"String\",\"StringValue\":\"${context.extendedRequestId}\"},"
+ "\"Time\":{\"DataType\":\"String\",\"StringValue\":\"${context.requestTime}\"}}";
withSendMessageRoute("sqs-invoke-context-host",
queueUrl -> Map.of("QueueUrl", queueUrl, "MessageBody", "$context.requestTimeEpoch",
"MessageAttributes", attributes),
(sqs, queueUrl, api) -> {
long before = System.currentTimeMillis();
given().post("/execute-api/" + api + "/test/send").then().statusCode(200);
Message message = onlyMessage(sqs, queueUrl);
assertThat(Long.parseLong(message.body()), greaterThanOrEqualTo(before - 1000));
assertThat(message.messageAttributes().get("Account").stringValue(), equalTo("000000000000"));
assertThat(message.messageAttributes().get("Domain").stringValue(), equalTo("localhost"));
assertThat(message.messageAttributes().get("Prefix").stringValue(), equalTo("localhost"));
String requestId = message.messageAttributes().get("Request").stringValue();
assertThat(requestId, matchesPattern(".+"));
assertThat(message.messageAttributes().get("Extended").stringValue(), equalTo(requestId));
assertThat(message.messageAttributes().get("Time").stringValue(),
matchesPattern("\\d{2}/[A-Z][a-z]{2}/\\d{4}:\\d{2}:\\d{2}:\\d{2} \\+0000"));
});
}
private interface RouteCheck {
void run(SqsClient sqs, String queueUrl, String apiId);
}
@@ -14,11 +14,13 @@ import java.net.InetSocketAddress;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.Map;
import java.util.UUID;
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.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
@@ -27,7 +29,7 @@ import static org.junit.jupiter.api.Assertions.assertTrue;
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");
"x-account", "x-path", "x-epoch", "x-missing", "x-missing-stage", "x-request-id", "x-extended-request-id");
private final AtomicReference<JsonNode> received = new AtomicReference<>();
private HttpServer backend;
private String apiId;
@@ -85,6 +87,42 @@ class HttpProxyRequestSourceMappingIntegrationTest {
assertEquals("order=o-42", request.path("query").asText());
}
@Test
void extendedRequestIdMatchesRequestIdAndResponseRequestId() {
configureApi();
String responseRequestId = invoke("{}");
JsonNode request = received.get();
String requestId = request.path("x-request-id").asText();
assertFalse(requestId.isEmpty());
assertEquals(requestId, request.path("x-extended-request-id").asText());
assertEquals(requestId, responseRequestId);
}
@Test
void requestIdOverrideReachesMappingsAndResponse() {
configureApi();
String override = UUID.randomUUID().toString();
String responseRequestId = given().contentType(ContentType.JSON).header("x-amzn-RequestId", override)
.body("{}").post("/execute-api/" + apiId + "/test/orders")
.then().statusCode(200).extract().header("x-amzn-RequestId");
JsonNode request = received.get();
assertEquals(override, request.path("x-request-id").asText());
assertEquals(override, request.path("x-extended-request-id").asText());
assertEquals(override, responseRequestId);
}
@Test
void invalidRequestIdOverrideIsReplacedInMappingsAndResponse() {
configureApi();
String responseRequestId = given().contentType(ContentType.JSON).header("x-amzn-RequestId", "not-a-uuid")
.body("{}").post("/execute-api/" + apiId + "/test/orders")
.then().statusCode(200).extract().header("x-amzn-RequestId");
JsonNode request = received.get();
assertTrue(responseRequestId.endsWith("_REPLACED_INVALID_REQUEST_ID"));
assertEquals(responseRequestId, request.path("x-request-id").asText());
assertEquals(responseRequestId, request.path("x-extended-request-id").asText());
}
@Test
void bodyThatIsNotJsonSkipsBodyMappings() {
configureApi();
@@ -125,6 +163,8 @@ class HttpProxyRequestSourceMappingIntegrationTest {
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-request-id", "$context.requestId"),
Map.entry("overwrite:header.x-extended-request-id", "$context.extendedRequestId"),
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"),
@@ -141,9 +181,10 @@ class HttpProxyRequestSourceMappingIntegrationTest {
.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 String invoke(String body) {
return given().contentType(ContentType.JSON).body(body)
.post("/execute-api/" + apiId + "/test/orders").then().statusCode(200)
.extract().header("x-amzn-RequestId");
}
private void invokeExpectingRejectedHeader(String body, String header) {