diff --git a/src/main/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayController.java b/src/main/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayController.java index e4b2bce706..ba1cfabda9 100644 --- a/src/main/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayController.java +++ b/src/main/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayController.java @@ -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()) { diff --git a/src/main/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayExecuteController.java b/src/main/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayExecuteController.java index 60665cd16f..ac02838d1d 100644 --- a/src/main/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayExecuteController.java +++ b/src/main/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayExecuteController.java @@ -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; diff --git a/src/main/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayService.java b/src/main/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayService.java index 906188b018..ec2579664e 100644 --- a/src/main/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayService.java +++ b/src/main/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayService.java @@ -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 reqParams = (Map) request.get("requestParameters"); @@ -1943,11 +1944,25 @@ public class ApiGatewayService { MethodConfig method = getMethod(region, apiId, resourceId, httpMethod); if (patchOperations != null) { for (Map 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 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)); diff --git a/src/main/java/io/github/hectorvent/floci/services/apigateway/model/MethodConfig.java b/src/main/java/io/github/hectorvent/floci/services/apigateway/model/MethodConfig.java index 8ca668ec42..ac6457d6c6 100644 --- a/src/main/java/io/github/hectorvent/floci/services/apigateway/model/MethodConfig.java +++ b/src/main/java/io/github/hectorvent/floci/services/apigateway/model/MethodConfig.java @@ -15,6 +15,7 @@ public class MethodConfig { private String authorizationType; private String authorizerId; private String requestValidatorId; + private boolean apiKeyRequired; private Map requestParameters = new HashMap<>(); private Map requestModels = new HashMap<>(); private Map 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 getRequestModels() { return requestModels; } public void setRequestModels(Map requestModels) { this.requestModels = requestModels != null ? requestModels : new HashMap<>(); diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationResourceProvisioner.java b/src/main/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationResourceProvisioner.java index 655b962f1c..5ad75ac239 100644 --- a/src/main/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationResourceProvisioner.java +++ b/src/main/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationResourceProvisioner.java @@ -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); diff --git a/src/test/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayApiKeyRequiredIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayApiKeyRequiredIntegrationTest.java new file mode 100644 index 0000000000..6d1f20e3be --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayApiKeyRequiredIntegrationTest.java @@ -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 entries) throws Exception { + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + try (ZipOutputStream zos = new ZipOutputStream(baos)) { + for (Map.Entry entry : entries.entrySet()) { + zos.putNextEntry(new ZipEntry(entry.getKey())); + zos.write(entry.getValue().getBytes(StandardCharsets.UTF_8)); + zos.closeEntry(); + } + } + return baos.toByteArray(); + } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayApiKeyRevocationIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayApiKeyRevocationIntegrationTest.java index ac1fc2c1e1..72c2e04d98 100644 --- a/src/test/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayApiKeyRevocationIntegrationTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayApiKeyRevocationIntegrationTest.java @@ -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. * - *

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. + *

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)