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

@@ -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) {