fix(apigateway): send x-amzn-ErrorType on REST gateway responses (#6687)

* fix(apigateway): send x-amzn-ErrorType on the API key 403

* fix(apigateway): send x-amzn-ErrorType on every REST gateway response

Authorizer, validation, media-type, configuration and Lambda proxy
failures now carry the error type AWS pairs with their gateway response
type, customised or not, measured on a REST API in eu-west-1.

* fix(apigateway): keep a gateway response's own x-amzn-ErrorType where AWS does

A gateway response that maps gatewayresponse.header.x-amzn-ErrorType sends
only that value for the validation, media type, configuration and
integration types, and sends it ahead of the default for the authorizer
and API key types, as measured on AWS.
This commit is contained in:
Mario Toffia authored and GitHub committed 2026-10-27 10:28:34 -04:00
1 parent 64069f9ccd
commit 3f294c3529
9 files changed
+162 -35

No files matched your search

@@ -15,6 +15,7 @@ import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.equalTo;
/**
* Integration tests for {@code AWS::ApiGateway::Method.ApiKeyRequired} enforcement on the
@@ -36,6 +37,7 @@ class ApiGatewayApiKeyRequiredIntegrationTest {
private static String protectedResourceId;
private static String openResourceId;
private static String keyValue;
private static String planId;
@Test @Order(1)
void createEchoLambda() throws Exception {
@@ -143,7 +145,7 @@ class ApiGatewayApiKeyRequiredIntegrationTest {
.then().statusCode(200)
.extract().path("value");
String planId = given()
planId = given()
.contentType(ContentType.JSON)
.body("""
{"name":"apikeyrequired-plan","apiStages":[{"apiId":"%s","stage":"prod"}]}
@@ -166,6 +168,7 @@ class ApiGatewayApiKeyRequiredIntegrationTest {
given()
.when().get("/execute-api/" + apiId + "/prod/secret")
.then().statusCode(403)
.header("x-amzn-ErrorType", equalTo("ForbiddenException"))
.body("message", org.hamcrest.Matchers.is("Forbidden"));
}
@@ -175,6 +178,7 @@ class ApiGatewayApiKeyRequiredIntegrationTest {
.header("x-api-key", "not-a-real-key")
.when().get("/execute-api/" + apiId + "/prod/secret")
.then().statusCode(403)
.header("x-amzn-ErrorType", equalTo("ForbiddenException"))
.body("message", org.hamcrest.Matchers.is("Forbidden"));
}
@@ -254,6 +258,40 @@ class ApiGatewayApiKeyRequiredIntegrationTest {
.body("apiKeyRequired", org.hamcrest.Matchers.is(true));
}
@Test @Order(11)
void protectedMethodRejectsDisabledAndUnboundApiKeys() {
String disabledKeyId = given()
.contentType(ContentType.JSON)
.body("{\"name\":\"apikeyrequired-disabled\",\"enabled\":false}")
.when().post("/apikeys")
.then().statusCode(201)
.extract().path("id");
given()
.contentType(ContentType.JSON)
.body("{\"keyId\":\"%s\",\"keyType\":\"API_KEY\"}".formatted(disabledKeyId))
.when().post("/usageplans/" + planId + "/keys")
.then().statusCode(201);
String unboundKeyId = given()
.contentType(ContentType.JSON)
.body("{\"name\":\"apikeyrequired-unbound\",\"enabled\":true}")
.when().post("/apikeys")
.then().statusCode(201)
.extract().path("id");
for (String keyId : new String[] {disabledKeyId, unboundKeyId}) {
String value = given()
.when().get("/apikeys/" + keyId + "?includeValue=true")
.then().statusCode(200)
.extract().path("value");
given()
.header("x-api-key", value)
.when().get("/execute-api/" + apiId + "/prod/secret")
.then().statusCode(403)
.header("x-amzn-ErrorType", equalTo("ForbiddenException"))
.body("message", equalTo("Forbidden"));
}
}
private static byte[] zipEntries(Map<String, String> entries) throws Exception {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
try (ZipOutputStream zos = new ZipOutputStream(baos)) {
@@ -74,6 +74,7 @@ class ApiGatewayCognitoAuthorizerIntegrationTest {
.when().get(base + "secured").then().statusCode(401);
given().header("X-Id-Token", "Bearer " + idToken)
.when().get(base + "secured").then().statusCode(401)
.header("x-amzn-ErrorType", equalTo("UnauthorizedException"))
.body("message", equalTo("Unauthorized"));
given().header("X-Id-Token", "Bearer " + accessToken)
.when().get(base + "missing-scope").then().statusCode(401)
@@ -13,6 +13,8 @@ import java.time.temporal.ChronoUnit;
import java.util.Map;
import static io.restassured.RestAssured.given;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.contains;
import static org.hamcrest.Matchers.containsInAnyOrder;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.hasKey;
@@ -377,6 +379,7 @@ class ApiGatewayGatewayResponseIntegrationTest {
.when().get("/execute-api/" + apiId + "/api/validated")
.then().statusCode(400)
.header("Access-Control-Allow-Origin", equalTo("*"))
.header("x-amzn-ErrorType", equalTo("BadRequestException"))
.body("type", equalTo("BAD_REQUEST_PARAMETERS"))
.body("message", equalTo("Missing required request parameter in QUERY_STRING: 'q'"));
@@ -398,6 +401,7 @@ class ApiGatewayGatewayResponseIntegrationTest {
.when().get("/execute-api/" + apiId + "/api/keyed")
.then().statusCode(401)
.header("Access-Control-Allow-Origin", nullValue())
.header("x-amzn-ErrorType", equalTo("ForbiddenException"))
.body("type", equalTo("INVALID_API_KEY"))
.body("message", equalTo("Forbidden"));
}
@@ -468,9 +472,31 @@ class ApiGatewayGatewayResponseIntegrationTest {
.when().get("/execute-api/" + apiId + "/api/broken")
.then().statusCode(500)
.header("Access-Control-Allow-Origin", equalTo("*"))
.header("x-amzn-ErrorType", equalTo("InternalServerErrorException"))
.body("message", equalTo("Internal server error"));
}
@Test
void aMappedErrorTypeReplacesTheDefaultOnlyWhereAwsDoes() {
deployMockApi();
putGatewayResponse("DEFAULT_4XX", "{\"responseParameters\":{"
+ "\"gatewayresponse.header.x-amzn-ErrorType\":\"'Mapped4xx'\"}}");
putGatewayResponse("DEFAULT_5XX", "{\"responseParameters\":{"
+ "\"gatewayresponse.header.x-amzn-ErrorType\":\"'Mapped5xx'\"}}");
// Measured (eu-west-1, 2026-10-26): validation and configuration failures send only the
// mapped value, an API key rejection sends it ahead of its own.
assertThat(given().when().get("/execute-api/" + apiId + "/api/validated")
.then().statusCode(400).extract().headers().getValues("x-amzn-ErrorType"),
contains("Mapped4xx"));
assertThat(given().when().get("/execute-api/" + apiId + "/api/broken")
.then().statusCode(500).extract().headers().getValues("x-amzn-ErrorType"),
contains("Mapped5xx"));
assertThat(given().when().get("/execute-api/" + apiId + "/api/keyed")
.then().statusCode(403).extract().headers().getValues("x-amzn-ErrorType"),
contains("Mapped4xx", "ForbiddenException"));
}
// ──────────────────────────── fixtures ────────────────────────────
private void putGatewayResponse(String responseType, String body) {
@@ -276,7 +276,8 @@ class ApiGatewayHttpNonProxyIntegrationTest {
given().contentType(ContentType.JSON).body("{}")
.when().post("/execute-api/" + apiId + "/test/widget")
.then().statusCode(415);
.then().statusCode(415)
.header("x-amzn-ErrorType", equalTo("BadRequestException"));
}
@Test
@@ -99,6 +99,7 @@ class ApiGatewayMockAuthorizerIntegrationTest {
given().header("Authorization", "Bearer denied")
.get("/execute-api/" + apiId + "/test/claims")
.then().statusCode(403)
.header("x-amzn-ErrorType", equalTo("AccessDeniedException"))
.body(equalTo("{\"message\":\"User is not authorized to access this resource\"}"));
}
@@ -1272,7 +1272,8 @@ class ApiGatewayOpenApiImportTest {
AtomicInteger integrationCalls) {
int calls = integrationCalls.get();
given().spec(request).contentType(ContentType.JSON).body(body).post(endpoint)
.then().statusCode(400).body("message", equalTo("Invalid request body"));
.then().statusCode(400).body("message", equalTo("Invalid request body"))
.header("x-amzn-ErrorType", equalTo("BadRequestException"));
assertEquals(calls, integrationCalls.get(), "Rejected requests must not reach the integration");
}
@@ -97,7 +97,8 @@ class RestLambdaAuthorizerIntegrationTest {
default -> output.put("policyDocument", Map.of("Statement", List.of(Map.of("Effect", "Allow"))));
}
respond(output);
given().header("Authorization", "token").get(execute("allowed")).then().statusCode(500);
given().header("Authorization", "token").get(execute("allowed")).then().statusCode(500)
.header("x-amzn-ErrorType", equalTo("AuthorizerConfigurationException"));
}
@ParameterizedTest
@@ -182,7 +183,8 @@ class RestLambdaAuthorizerIntegrationTest {
void missingTokenIsUnauthorizedWithoutInvokingLambda() throws Exception {
configure("TOKEN", 0, "method.request.header.Authorization");
allowAll();
given().get(execute("allowed")).then().statusCode(401);
given().get(execute("allowed")).then().statusCode(401)
.header("x-amzn-ErrorType", equalTo("UnauthorizedException"));
verifyInvocation(0);
}
@@ -312,11 +314,33 @@ class RestLambdaAuthorizerIntegrationTest {
.thenReturn(new InvokeResult(200, "Unhandled", payload, null, "lambda-error"));
for (int i = 0; i < 2; i++) {
given().header("Authorization", "token").get(execute("allowed"))
.then().statusCode("Unauthorized".equals(message) ? 401 : 500);
.then().statusCode("Unauthorized".equals(message) ? 401 : 500)
.header("x-amzn-ErrorType", equalTo("Unauthorized".equals(message)
? "UnauthorizedException" : "AuthorizerConfigurationException"));
}
verifyInvocation(2);
}
@Test
void lambdaProxyFunctionErrorIsAnInternalServerError() throws Exception {
configure("TOKEN", 0, "method.request.header.Authorization");
allowAll();
String resourceId = given().get("/restapis/" + apiId + "/resources").then().extract()
.path("item.find { it.path == '/allowed' }.id");
given().contentType(ContentType.JSON).body(Map.of("type", "AWS_PROXY", "httpMethod", "POST",
"uri", AUTHORIZER_URI.replace(FUNCTION, "failing-proxy")))
.put(methodPath(resourceId) + "/integration").then().statusCode(201);
when(lambdaService.invokeTarget(eq("us-east-1"), eq("arn:aws:lambda:us-east-1:000000000000:function:failing-proxy"),
any(byte[].class), eq(InvocationType.RequestResponse)))
.thenReturn(new InvokeResult(200, "Unhandled",
new ObjectMapper().writeValueAsBytes(Map.of("errorMessage", "boom")), null, "proxy-error"));
deploy("test");
given().header("Authorization", "token").get(execute("allowed"))
.then().statusCode(502)
.header("x-amzn-ErrorType", equalTo("InternalServerErrorException"));
}
private void configure(String type, int ttl, String identitySource) {
Map<String, Object> request = new LinkedHashMap<>(Map.of("name", "contract", "type", type,
"authorizerUri", AUTHORIZER_URI, "authorizerResultTtlInSeconds", ttl));