Light, fluffy, and always free - The AWS Local Emulator alternative
fix(apigateway): require API keys for imported methods (#5450)
Som Samantray77113c7f8521
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.javaindex 7573de8919..f9b2e1b025 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@@ -3390,6 +3390,7 @@ public class ApiGatewayService implements ResourceProvider {// Lambda authorizer land as authorizationType=NONE and are silently open at runtime.Map<String, String> schemeToAuthorizerId = new HashMap<>();Map<String, String> schemeToAuthType = new HashMap<>();+ Set<String> apiKeySchemes = new HashSet<>();Map<String, String> authorizerNameToId = new HashMap<>();for (Authorizer authorizer : getAuthorizers(region, apiId)) {if (authorizer.getName() != null) {@@ -3407,6 +3408,12 @@ public class ApiGatewayService implements ResourceProvider {SecurityScheme scheme = schemeEntry.getValue();String authtype = importedAuthorizationType(scheme, schemeName);Map<String, Object> authDef = importedAuthorizerDefinition(scheme, schemeName);+ if (authDef == null && scheme != null+ && SecurityScheme.Type.APIKEY.equals(scheme.getType())+ && scheme.getIn() != null && "header".equalsIgnoreCase(scheme.getIn().toString())+ && scheme.getName() != null && "x-api-key".equalsIgnoreCase(scheme.getName())) {+ apiKeySchemes.add(schemeName);+ }if (authDef != null) {String t = importedAuthorizerType(authDef, schemeName); // token | request | cognito_user_poolsMap<String, Object> req = new HashMap<>();@@ -3501,7 +3508,8 @@ public class ApiGatewayService implements ResourceProvider {String httpMethod = opEntry.getKey().name().toUpperCase();try {applyOperation(region, apiId, resourceId, httpMethod, opEntry.getValue(), openAPI,- schemeToAuthorizerId, schemeToAuthType, validatorNameToId, defaultValidatorId);+ schemeToAuthorizerId, schemeToAuthType, apiKeySchemes,+ validatorNameToId, defaultValidatorId);} catch (AwsException e) {if (PARAMETER_NAME_ERROR.equals(e.getMessage())) {throw importParameterNameFailure(httpMethod, path, e);@@ -3522,7 +3530,8 @@ public class ApiGatewayService implements ResourceProvider {Operation anyOperation = parseAnyMethodOperation(path, anyMethodExt);try {applyOperation(region, apiId, resourceId, "ANY", anyOperation, openAPI,- schemeToAuthorizerId, schemeToAuthType, validatorNameToId, defaultValidatorId);+ schemeToAuthorizerId, schemeToAuthType, apiKeySchemes,+ validatorNameToId, defaultValidatorId);} catch (AwsException e) {if (PARAMETER_NAME_ERROR.equals(e.getMessage())) {throw importParameterNameFailure("ANY", path, e);@@ -3583,7 +3592,8 @@ public class ApiGatewayService implements ResourceProvider {private void applyOperation(String region, String apiId, String resourceId, String httpMethod,Operation operation, OpenAPI openAPI, Map<String, String> schemeToAuthorizerId,- Map<String, String> schemeToAuthType, Map<String, String> validatorNameToId,+ Map<String, String> schemeToAuthType, Set<String> apiKeySchemes,+ Map<String, String> validatorNameToId,String defaultValidatorId) {// Create the methodMap<String, Object> methodRequest = new HashMap<>();@@ -3591,12 +3601,14 @@ public class ApiGatewayService implements ResourceProvider {// to a method authorizationType (CUSTOM/AWS_IAM/COGNITO_USER_POOLS) + authorizerId.List<SecurityRequirement> secReqs = operation.getSecurity() != null? operation.getSecurity() : openAPI.getSecurity();+ boolean apiKeyRequired = secReqs != null && !secReqs.isEmpty()+ && secReqs.stream().allMatch(requirement -> requirement.keySet().stream()+ .anyMatch(apiKeySchemes::contains));String authType = "NONE";String authorizerId = null;List<String> authorizationScopes = List.of();if (secReqs != null) {- // AWS resolves the OR-list of security requirements to the first declared- // authorizer scheme (a method has exactly one authorizer), so stop at the first match.+ // An API Gateway method can reference only one authorizer, so preserve the first match.resolveAuth:for (SecurityRequirement secReq : secReqs) {for (String schemeName : secReq.keySet()) {@@ -3615,6 +3627,7 @@ public class ApiGatewayService implements ResourceProvider {}}methodRequest.put("authorizationType", authType);+ methodRequest.put("apiKeyRequired", apiKeyRequired);if (authorizerId != null) {methodRequest.put("authorizerId", authorizerId);}diff --git a/src/test/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayPutRestApiMergeAuthorizationTest.java b/src/test/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayPutRestApiMergeAuthorizationTest.javaindex 2e5b2bba18..59dc602b5c 100644--- a/src/test/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayPutRestApiMergeAuthorizationTest.java+++ b/src/test/java/io/github/hectorvent/floci/services/apigateway/ApiGatewayPutRestApiMergeAuthorizationTest.java@@ -19,6 +19,7 @@ import java.util.Map;import static io.restassured.RestAssured.given;import static org.junit.jupiter.api.Assertions.assertAll;import static org.junit.jupiter.api.Assertions.assertEquals;+import static org.junit.jupiter.api.Assertions.assertFalse;import static org.junit.jupiter.api.Assertions.assertTrue;import static org.mockito.ArgumentMatchers.any;import static org.mockito.ArgumentMatchers.eq;@@ -130,6 +131,35 @@ class ApiGatewayPutRestApiMergeAuthorizationTest {}}}}""";+ private static final String API_KEY_SPEC = """+ {+ "openapi": "3.0.1",+ "info": {"title": "ApiKeyProtected", "version": "1"},+ "components": {"securitySchemes": {+ "client_key": {"type": "apiKey", "name": "x-api-key", "in": "header"}+ }},+ "paths": {"/protected": {"get": {+ "security": [{"client_key": []}],+ "x-amazon-apigateway-integration": {"type": "MOCK"}+ }}}+ }+ """;+ private static final String ROOT_API_KEY_SPEC = """+ {+ "openapi": "3.0.1",+ "info": {"title": "RootApiKeyProtected", "version": "1"},+ "security": [{"client_key": []}],+ "components": {"securitySchemes": {+ "client_key": {+ "type": "apiKey", "name": "x-api-key", "in": "header",+ "x-amazon-apigateway-authtype": "apiKey"+ }+ }},+ "paths": {"/protected": {"get": {+ "x-amazon-apigateway-integration": {"type": "MOCK"}+ }}}+ }+ """;private static final String EMPTY_SECURITY_SPEC = """{"openapi": "3.0.1",@@ -402,6 +432,204 @@ class ApiGatewayPutRestApiMergeAuthorizationTest {}}+ @Test+ void importedPlainApiKeySecurityRequiresApiKeyForOperationAndRootSecurity() throws Exception {+ for (String spec : List.of(API_KEY_SPEC, ROOT_API_KEY_SPEC)) {+ String apiId = importApi(spec);+ try {+ JsonNode method = getJson(methodPath(apiId));+ assertAll(+ () -> assertEquals("NONE", method.path("authorizationType").asText()),+ () -> assertTrue(method.path("apiKeyRequired").asBoolean()));+ } finally {+ given().delete("/restapis/" + apiId).then().statusCode(202);+ }+ }+ }++ @Test+ void importedNonHeaderApiKeySchemesDoNotRequireApiKey() throws Exception {+ List<String> nonApiGatewayKeySpecs = List.of(+ API_KEY_SPEC.replace("\"name\": \"x-api-key\", \"in\": \"header\"",+ "\"name\": \"x-api-key\", \"in\": \"query\""),+ API_KEY_SPEC.replace("\"name\": \"x-api-key\", \"in\": \"header\"",+ "\"name\": \"X-Custom-Key\", \"in\": \"header\""));+ for (String spec : nonApiGatewayKeySpecs) {+ String apiId = importApi(spec);+ try {+ JsonNode method = getJson(methodPath(apiId));+ assertFalse(method.path("apiKeyRequired").asBoolean());+ } finally {+ given().delete("/restapis/" + apiId).then().statusCode(202);+ }+ }++ String mixedCaseHeaderSpec = API_KEY_SPEC.replace("\"name\": \"x-api-key\", \"in\": \"header\"",+ "\"name\": \"X-API-KEY\", \"in\": \"header\"");+ String apiId = importApi(mixedCaseHeaderSpec);+ try {+ JsonNode method = getJson(methodPath(apiId));+ assertTrue(method.path("apiKeyRequired").asBoolean());+ } finally {+ given().delete("/restapis/" + apiId).then().statusCode(202);+ }++ String authorizerApiKeySpec = API_KEY_SPEC.replace(+ "\"client_key\": {\"type\": \"apiKey\", \"name\": \"x-api-key\", \"in\": \"header\"}",+ "\"client_key\": {\"type\": \"apiKey\", \"name\": \"x-api-key\", \"in\": \"header\", "+ + "\"x-amazon-apigateway-authorizer\": {\"type\": \"token\", "+ + "\"authorizerUri\": \"" + AUTHORIZER_URI + "\"}}");+ String authorizerApiId = importApi(authorizerApiKeySpec);+ try {+ JsonNode method = getJson(methodPath(authorizerApiId));+ assertAll(+ () -> assertFalse(method.path("apiKeyRequired").asBoolean()),+ () -> assertEquals("CUSTOM", method.path("authorizationType").asText()));+ } finally {+ given().delete("/restapis/" + authorizerApiId).then().statusCode(202);+ }+ }++ @Test+ void importedApiKeysAreEnforcedForImportAndPutRestApi() throws Exception {+ List<String> apiKeySpecs = List.of(API_KEY_SPEC, ROOT_API_KEY_SPEC);+ List<String> modes = List.of("import", "merge", "overwrite");+ int scenario = 0;+ for (String mode : modes) {+ for (String spec : apiKeySpecs) {+ String apiId = "import".equals(mode) ? importApi(spec) : importApi();+ String keyId = null;+ String planId = null;+ try {+ if (!"import".equals(mode)) {+ putSpec(apiId, mode, spec);+ }+ String stageName = "apikey-" + scenario++;+ deploy(apiId, stageName);++ keyId = given().contentType(ContentType.JSON)+ .body("{\"name\":\"imported-key-" + scenario + "\",\"enabled\":true}")+ .post("/apikeys").then().statusCode(201).extract().path("id");+ String keyValue = given().get("/apikeys/" + keyId + "?includeValue=true")+ .then().statusCode(200).extract().path("value");+ planId = given().contentType(ContentType.JSON)+ .body("{\"name\":\"imported-plan-" + scenario+ + "\",\"apiStages\":[{\"apiId\":\"" + apiId+ + "\",\"stage\":\"" + stageName + "\"}]}")+ .post("/usageplans").then().statusCode(201).extract().path("id");+ given().contentType(ContentType.JSON)+ .body("{\"keyId\":\"" + keyId + "\",\"keyType\":\"API_KEY\"}")+ .post("/usageplans/" + planId + "/keys").then().statusCode(201);++ assertAll(+ () -> assertEquals(403, invokeWithoutApiKey(apiId, stageName)),+ () -> assertEquals(403, invokeWithApiKey(apiId, stageName, "invalid-api-key")),+ () -> assertEquals(200, invokeWithApiKey(apiId, stageName, keyValue)));+ } finally {+ if (planId != null) {+ given().delete("/usageplans/" + planId).then().statusCode(202);+ }+ if (keyId != null) {+ given().delete("/apikeys/" + keyId).then().statusCode(202);+ }+ given().delete("/restapis/" + apiId).then().statusCode(202);+ }+ }+ }+ }++ @Test+ void emptySecurityAlternativeKeepsImportedMethodPublic() throws Exception {+ String optionalOperationSecurity = API_KEY_SPEC.replace(+ "\"security\": [{\"client_key\": []}]",+ "\"security\": [{\"client_key\": []}, {}]");+ String optionalRootSecurity = ROOT_API_KEY_SPEC.replace(+ "\"security\": [{\"client_key\": []}]",+ "\"security\": [{\"client_key\": []}, {}]");+ for (String spec : List.of(optionalOperationSecurity, optionalRootSecurity)) {+ String apiId = importApi(spec);+ try {+ JsonNode method = getJson(methodPath(apiId));+ deploy(apiId, "optional-security");+ assertAll(+ () -> assertFalse(method.path("apiKeyRequired").asBoolean()),+ () -> assertEquals("NONE", method.path("authorizationType").asText()),+ () -> assertEquals(200, invokeWithoutApiKey(apiId, "optional-security")));+ } finally {+ given().delete("/restapis/" + apiId).then().statusCode(202);+ }+ }++ String optionalAuthorizerSecurity = COGNITO_SPEC.replace(+ "\"security\": [{\"Guard\": []}]",+ "\"security\": [{\"Guard\": []}, {}]");+ String apiId = importApi(optionalAuthorizerSecurity);+ try {+ JsonNode method = getJson(methodPath(apiId));+ assertAll(+ () -> assertFalse(method.path("apiKeyRequired").asBoolean()),+ () -> assertEquals("COGNITO_USER_POOLS", method.path("authorizationType").asText()),+ () -> assertTrue(method.hasNonNull("authorizerId")));+ } finally {+ given().delete("/restapis/" + apiId).then().statusCode(202);+ }+ }++ @Test+ void apiKeyAndAuthorizerAlternativesDoNotRequireAnApiKeyAndKeepAuthorizer() throws Exception {+ String apiKeyAndAuthorizerSpec = """+ {+ "openapi": "3.0.1",+ "info": {"title": "IncompatibleSecurity", "version": "1"},+ "components": {"securitySchemes": {+ "client_key": {"type": "apiKey", "name": "x-api-key", "in": "header"},+ "Guard": {+ "type": "apiKey", "name": "Authorization", "in": "header",+ "x-amazon-apigateway-authorizer": {+ "type": "token", "authorizerUri": "%s"+ }+ }+ }},+ "paths": {"/protected": {"get": {+ "security": [{"client_key": []}, {"Guard": []}],+ "x-amazon-apigateway-integration": {"type": "MOCK"}+ }}}+ }+ """.formatted(AUTHORIZER_URI);+ String apiId = importApi(apiKeyAndAuthorizerSpec);+ try {+ denyAuthorizerRequests();+ JsonNode method = getJson(methodPath(apiId));+ deploy(apiId, "mixed-security");+ assertAll(+ () -> assertFalse(method.path("apiKeyRequired").asBoolean()),+ () -> assertEquals("CUSTOM", method.path("authorizationType").asText()),+ () -> assertTrue(method.hasNonNull("authorizerId")),+ () -> assertEquals(403, invoke(apiId, "mixed-security")),+ () -> verifyDenyInvocations(1));+ } finally {+ given().delete("/restapis/" + apiId).then().statusCode(202);+ }+ }++ @Test+ void putRestApiPlainApiKeySecurityRequiresApiKeyForMergeAndOverwrite() throws Exception {+ for (String mode : List.of("merge", "overwrite")) {+ for (String spec : List.of(API_KEY_SPEC, ROOT_API_KEY_SPEC)) {+ String apiId = importApi();+ try {+ putSpec(apiId, mode, spec);+ JsonNode method = getJson(methodPath(apiId));+ assertAll(+ () -> assertEquals("NONE", method.path("authorizationType").asText()),+ () -> assertTrue(method.path("apiKeyRequired").asBoolean()));+ } finally {+ given().delete("/restapis/" + apiId).then().statusCode(202);+ }+ }+ }+ }+@Testvoid retainedCognitoSchemeKeepsItsAuthorizationType() throws Exception {String apiId = importApi(COGNITO_SPEC);@@ -621,6 +849,15 @@ class ApiGatewayPutRestApiMergeAuthorizationTest {return given().get("/execute-api/" + apiId + "/" + stageName + "/protected").statusCode();}+ private static int invokeWithoutApiKey(String apiId, String stageName) {+ return given().get("/execute-api/" + apiId + "/" + stageName + "/protected").statusCode();+ }++ private static int invokeWithApiKey(String apiId, String stageName, String keyValue) {+ return given().header("x-api-key", keyValue)+ .get("/execute-api/" + apiId + "/" + stageName + "/protected").statusCode();+ }+private static JsonNode getJson(String path) throws Exception {String body = given().get(path).then().statusCode(200).extract().asString();return MAPPER.readTree(body);