fix(apigateway): enforce ApiKeyRequired on REST API methods (#3537)

* fix(apigateway): enforce ApiKeyRequired on REST API methods

A method with ApiKeyRequired=true accepted requests missing or using an
unrecognized x-api-key header instead of rejecting them with 403, since the
property was never read from PutMethod, the AWS::ApiGateway::Method
CloudFormation resource, or the execute-api data plane.

MethodConfig now carries apiKeyRequired (wired through putMethod, the PATCH
/apiKeyRequired path, and CloudFormation's ApiKeyRequired property), and
ApiGatewayExecuteController rejects the request with 403 {"message":"Forbidden"}
when the method requires a key and none resolves via the existing usage-plan
lookup.

Fixes #3507 (ApiKeyRequired half; the resource Policy gap remains open).

* fix(apigateway): validate patch operation and boolean value for /apiKeyRequired in UpdateMethod (#3507)
This commit is contained in:
Vũ Thế Huy authored and GitHub committed 2026-09-13 18:20:01 -04:00
1 parent 3c6568bac5
commit 3b31c5a663
7 files changed
+304 -6

No files matched your search

@@ -1963,6 +1963,7 @@ public class ApiGatewayController {
ObjectNode node = objectMapper.createObjectNode();
node.put("httpMethod", m.getHttpMethod());
node.put("authorizationType", m.getAuthorizationType());
node.put("apiKeyRequired", m.isApiKeyRequired());
if (m.getAuthorizerId() != null) node.put("authorizerId", m.getAuthorizerId());
if (m.getRequestValidatorId() != null) node.put("requestValidatorId", m.getRequestValidatorId());
if (m.getRequestModels() != null && !m.getRequestModels().isEmpty()) {
@@ -386,6 +386,15 @@ public class ApiGatewayExecuteController {
AuthorizerResult authorizerResult = invokeAuthorizer(region, apiId, stageName, httpMethod, path, matched.getPath(), matched.getId(), stage, method, headers, uriInfo, resolvedApiKey);
if (authorizerResult.errorResponse() != null) return authorizerResult.errorResponse();
// API Gateway checks the API key requirement after authorization but before request
// validation and throttling. resolvedApiKey is null when the header is missing or matches
// no enabled key linked to this (apiId, stage) through a usage plan.
if (method.isApiKeyRequired() && resolvedApiKey == null) {
return Response.status(403)
.entity(jsonMessage("Forbidden"))
.type(MediaType.APPLICATION_JSON).build();
}
// 2. Request validation
Response validationResponse = validateRequest(region, apiId, method, headers, uriInfo, body);
if (validationResponse != null) return validationResponse;
@@ -378,6 +378,7 @@ public class ApiGatewayService {
method.setAuthorizationType((String) request.getOrDefault("authorizationType", "NONE"));
method.setAuthorizerId((String) request.get("authorizerId"));
method.setRequestValidatorId((String) request.get("requestValidatorId"));
method.setApiKeyRequired(Boolean.TRUE.equals(request.get("apiKeyRequired")));
@SuppressWarnings("unchecked")
Map<String, Boolean> reqParams = (Map<String, Boolean>) request.get("requestParameters");
@@ -1943,11 +1944,25 @@ public class ApiGatewayService {
MethodConfig method = getMethod(region, apiId, resourceId, httpMethod);
if (patchOperations != null) {
for (Map<String, String> op : patchOperations) {
if (!"replace" .equals(op.get("op"))) continue;
String path = op.getOrDefault("path", "");
String opType = op.get("op");
String value = op.get("value");
if ("/apiKeyRequired".equals(path)) {
if (!"replace".equals(opType)) {
throw new AwsException("BadRequestException", "Invalid patch operation '" + opType + "' for path '" + path + "'. Supported operation is: replace", 400);
}
if (value == null || (!"true".equalsIgnoreCase(value) && !"false".equalsIgnoreCase(value))) {
throw new AwsException("BadRequestException", "Invalid boolean value '" + value + "' for apiKeyRequired. Must be 'true' or 'false'", 400);
}
}
}
for (Map<String, String> op : patchOperations) {
if (!"replace".equals(op.get("op"))) continue;
String path = op.getOrDefault("path", "");
String value = op.get("value");
if ("/authorizationType" .equals(path)) method.setAuthorizationType(value);
else if ("/authorizerId" .equals(path)) method.setAuthorizerId(value);
if ("/authorizationType".equals(path)) method.setAuthorizationType(value);
else if ("/authorizerId".equals(path)) method.setAuthorizerId(value);
else if ("/apiKeyRequired".equals(path)) method.setApiKeyRequired(Boolean.parseBoolean(value));
}
}
resourceStore.put(resourceKey(region, apiId, resourceId), getResource(region, apiId, resourceId));
@@ -15,6 +15,7 @@ public class MethodConfig {
private String authorizationType;
private String authorizerId;
private String requestValidatorId;
private boolean apiKeyRequired;
private Map<String, Boolean> requestParameters = new HashMap<>();
private Map<String, String> requestModels = new HashMap<>();
private Map<String, MethodResponse> methodResponses = new HashMap<>();
@@ -32,6 +33,9 @@ public class MethodConfig {
public String getRequestValidatorId() { return requestValidatorId; }
public void setRequestValidatorId(String requestValidatorId) { this.requestValidatorId = requestValidatorId; }
public boolean isApiKeyRequired() { return apiKeyRequired; }
public void setApiKeyRequired(boolean apiKeyRequired) { this.apiKeyRequired = apiKeyRequired; }
public Map<String, String> getRequestModels() { return requestModels; }
public void setRequestModels(Map<String, String> requestModels) {
this.requestModels = requestModels != null ? requestModels : new HashMap<>();
@@ -3319,6 +3319,7 @@ public class CloudFormationResourceProvisioner {
if (authorizerId != null) {
req.put("authorizerId", authorizerId);
}
req.put("apiKeyRequired", Boolean.parseBoolean(resolveOrDefault(props, "ApiKeyRequired", engine, "false")));
apiGatewayService.putMethod(region, apiId, resourceId, httpMethod, req);
r.setPhysicalId(apiId + "-" + resourceId + "-" + httpMethod);
@@ -0,0 +1,268 @@
package io.github.hectorvent.floci.services.apigateway;
import io.quarkus.test.junit.QuarkusTest;
import io.restassured.http.ContentType;
import org.junit.jupiter.api.MethodOrderer;
import org.junit.jupiter.api.Order;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestMethodOrder;
import java.io.ByteArrayOutputStream;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
import java.util.Map;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
import static io.restassured.RestAssured.given;
/**
* Integration tests for {@code AWS::ApiGateway::Method.ApiKeyRequired} enforcement on the
* execute-api data plane. A method with {@code apiKeyRequired=true} must reject requests whose
* {@code x-api-key} header does not resolve to an enabled key linked to the invoked stage through
* a usage plan, and must not affect a method that leaves it at the default {@code false}.
*/
@QuarkusTest
@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
class ApiGatewayApiKeyRequiredIntegrationTest {
private static final String LAMBDA_BASE_PATH = "/2015-03-31/functions";
private static final String ECHO_FUNCTION = "apigw-apikeyrequired-echo";
private static final String ROLE_ARN = "arn:aws:iam::000000000000:role/lambda-role";
private static final String REGION = "us-east-1";
private static final String ACCOUNT = "000000000000";
private static String apiId;
private static String protectedResourceId;
private static String openResourceId;
private static String keyValue;
@Test @Order(1)
void createEchoLambda() throws Exception {
String zipBase64 = Base64.getEncoder().encodeToString(zipEntries(Map.of("index.js", """
exports.handler = async () => ({ statusCode: 200, body: JSON.stringify({ ok: true }) });
""")));
given()
.contentType(ContentType.JSON)
.body("""
{
"FunctionName": "%s",
"Runtime": "nodejs20.x",
"Role": "%s",
"Handler": "index.handler",
"Timeout": 30,
"Code": {"ZipFile": "%s"}
}
""".formatted(ECHO_FUNCTION, ROLE_ARN, zipBase64))
.when().post(LAMBDA_BASE_PATH)
.then()
.statusCode(201);
}
@Test @Order(2)
void setupApiWithProtectedAndOpenMethods() {
apiId = given()
.contentType(ContentType.JSON)
.body("{\"name\":\"apikeyrequired-api\"}")
.when().post("/restapis")
.then().statusCode(201)
.extract().path("id");
String rootId = given()
.when().get("/restapis/" + apiId + "/resources")
.then().statusCode(200)
.extract().path("item[0].id");
protectedResourceId = given()
.contentType(ContentType.JSON)
.body("{\"pathPart\":\"secret\"}")
.when().post("/restapis/" + apiId + "/resources/" + rootId)
.then().statusCode(201)
.extract().path("id");
openResourceId = given()
.contentType(ContentType.JSON)
.body("{\"pathPart\":\"public\"}")
.when().post("/restapis/" + apiId + "/resources/" + rootId)
.then().statusCode(201)
.extract().path("id");
given()
.contentType(ContentType.JSON)
.body("{\"authorizationType\":\"NONE\",\"apiKeyRequired\":true}")
.when().put("/restapis/" + apiId + "/resources/" + protectedResourceId + "/methods/GET")
.then().statusCode(201)
.body("apiKeyRequired", org.hamcrest.Matchers.is(true));
given()
.contentType(ContentType.JSON)
.body("{\"authorizationType\":\"NONE\"}")
.when().put("/restapis/" + apiId + "/resources/" + openResourceId + "/methods/GET")
.then().statusCode(201)
.body("apiKeyRequired", org.hamcrest.Matchers.is(false));
String uri = "arn:aws:apigateway:" + REGION + ":lambda:path/2015-03-31/functions/"
+ "arn:aws:lambda:" + REGION + ":" + ACCOUNT + ":function:" + ECHO_FUNCTION + "/invocations";
for (String resourceId : new String[] {protectedResourceId, openResourceId}) {
given()
.contentType(ContentType.JSON)
.body("""
{"type":"AWS_PROXY","httpMethod":"POST","uri":"%s"}
""".formatted(uri))
.when().put("/restapis/" + apiId + "/resources/" + resourceId + "/methods/GET/integration")
.then().statusCode(201);
}
String depId = given()
.contentType(ContentType.JSON)
.body("{\"description\":\"apikeyrequired\"}")
.when().post("/restapis/" + apiId + "/deployments")
.then().statusCode(201)
.extract().path("id");
given()
.contentType(ContentType.JSON)
.body("""
{"stageName":"prod","deploymentId":"%s"}
""".formatted(depId))
.when().post("/restapis/" + apiId + "/stages")
.then().statusCode(201);
}
@Test @Order(3)
void createKeyAndAttachToUsagePlan() {
String keyId = given()
.contentType(ContentType.JSON)
.body("{\"name\":\"apikeyrequired-key\",\"enabled\":true,\"generateDistinctId\":true}")
.when().post("/apikeys")
.then().statusCode(201)
.extract().path("id");
keyValue = given()
.when().get("/apikeys/" + keyId + "?includeValue=true")
.then().statusCode(200)
.extract().path("value");
String planId = given()
.contentType(ContentType.JSON)
.body("""
{"name":"apikeyrequired-plan","apiStages":[{"apiId":"%s","stage":"prod"}]}
""".formatted(apiId))
.when().post("/usageplans")
.then().statusCode(201)
.extract().path("id");
given()
.contentType(ContentType.JSON)
.body("""
{"keyId":"%s","keyType":"API_KEY"}
""".formatted(keyId))
.when().post("/usageplans/" + planId + "/keys")
.then().statusCode(201);
}
@Test @Order(4)
void protectedMethodRejectsRequestWithoutApiKey() {
given()
.when().get("/execute-api/" + apiId + "/prod/secret")
.then().statusCode(403)
.body("message", org.hamcrest.Matchers.is("Forbidden"));
}
@Test @Order(5)
void protectedMethodRejectsRequestWithUnknownApiKey() {
given()
.header("x-api-key", "not-a-real-key")
.when().get("/execute-api/" + apiId + "/prod/secret")
.then().statusCode(403)
.body("message", org.hamcrest.Matchers.is("Forbidden"));
}
@Test @Order(6)
void protectedMethodAcceptsRequestWithValidApiKey() {
given()
.header("x-api-key", keyValue)
.when().get("/execute-api/" + apiId + "/prod/secret")
.then().statusCode(200)
.body("ok", org.hamcrest.Matchers.is(true));
}
@Test @Order(7)
void openMethodDoesNotRequireApiKey() {
given()
.when().get("/execute-api/" + apiId + "/prod/public")
.then().statusCode(200)
.body("ok", org.hamcrest.Matchers.is(true));
}
@Test @Order(8)
void updateMethodRejectsUnsupportedPatchOperationOnApiKeyRequired() {
given()
.contentType(ContentType.JSON)
.body("""
{
"patchOperations": [
{"op": "remove", "path": "/apiKeyRequired"}
]
}
""")
.when().patch("/restapis/" + apiId + "/resources/" + protectedResourceId + "/methods/GET")
.then().statusCode(400);
}
@Test @Order(9)
void updateMethodRejectsInvalidBooleanValueOnApiKeyRequired() {
given()
.contentType(ContentType.JSON)
.body("""
{
"patchOperations": [
{"op": "replace", "path": "/apiKeyRequired", "value": "garbage"}
]
}
""")
.when().patch("/restapis/" + apiId + "/resources/" + protectedResourceId + "/methods/GET")
.then().statusCode(400);
}
@Test @Order(10)
void updateMethodSuccessfullyUpdatesApiKeyRequired() {
given()
.contentType(ContentType.JSON)
.body("""
{
"patchOperations": [
{"op": "replace", "path": "/apiKeyRequired", "value": "false"}
]
}
""")
.when().patch("/restapis/" + apiId + "/resources/" + protectedResourceId + "/methods/GET")
.then().statusCode(200)
.body("apiKeyRequired", org.hamcrest.Matchers.is(false));
given()
.contentType(ContentType.JSON)
.body("""
{
"patchOperations": [
{"op": "replace", "path": "/apiKeyRequired", "value": "true"}
]
}
""")
.when().patch("/restapis/" + apiId + "/resources/" + protectedResourceId + "/methods/GET")
.then().statusCode(200)
.body("apiKeyRequired", org.hamcrest.Matchers.is(true));
}
private static byte[] zipEntries(Map<String, String> entries) throws Exception {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
try (ZipOutputStream zos = new ZipOutputStream(baos)) {
for (Map.Entry<String, String> entry : entries.entrySet()) {
zos.putNextEntry(new ZipEntry(entry.getKey()));
zos.write(entry.getValue().getBytes(StandardCharsets.UTF_8));
zos.closeEntry();
}
}
return baos.toByteArray();
}
}
@@ -28,9 +28,9 @@ import static org.junit.jupiter.api.Assertions.*;
* {@code DeleteApiKey} must therefore stop the value being recognised, otherwise a revoked credential
* keeps identifying requests.
*
* <p>Floci does not implement the {@code apiKeyRequired} gate, so a revoked key produces a request
* whose {@code identity.apiKey} is null rather than a 403. These tests assert the resolution
* behaviour that exists today.
* <p>This suite's method does not set {@code apiKeyRequired}, so a revoked key produces a request
* whose {@code identity.apiKey} is null rather than a 403; enforcement of the gate itself is
* covered separately by {@link ApiGatewayApiKeyRequiredIntegrationTest}.
*/
@QuarkusTest
@TestMethodOrder(MethodOrderer.OrderAnnotation.class)