Light, fluffy, and always free - The AWS Local Emulator alternative
fix(cloudformation): drop undeclared OpenAPI authorizer schemes (#6632)
Andre Kuraitf32db4fe4926
diff --git a/docs/services/cloudformation.md b/docs/services/cloudformation.mdindex 2e1c654ef7..4cd5c55fdf 100644--- a/docs/services/cloudformation.md+++ b/docs/services/cloudformation.md@@ -772,9 +772,11 @@ always lists both stages, matching AWS.adds the corresponding security schemes and operation requirements. API Gateway importsthese as `authorizationType: AWS_IAM` and `apiKeyRequired: true`: invocation requires botha valid SigV4 signature and an enabled API key associated with the invoked stage when both-controls are selected. Existing operation requirements and their scheme definitions are-preserved. Defaults are selected by the SAM names `AWS_IAM` and `api_key`; an existing-scheme with another name does not suppress either default.+controls are selected. Existing operation requirements are preserved. When a default applies+to OpenAPI 3, inline custom authorizer schemes are removed unless they also appear in the+SAM `securityDefinitions` map. This matches SAM's removal of undeclared OpenAPI authorizers+before import. Swagger 2 keeps its custom schemes. Defaults are selected by the SAM names+`AWS_IAM` and `api_key`; an existing scheme with another name does not suppress either default.As in SAM, the defaults are added to each operation's own `security`, inside each branch ofan `Fn::If` written around a path or an operation, skipping an `AWS::NoValue` branch. Anested `Fn::If` around an operation is left as written, without the defaults, as SAM leaves@@ -792,9 +794,9 @@ When a default applies, so are unresolved or malformed security requirements, meoverride markers, a nested `Fn::If` around a path item, a body or securityscheme map written as an intrinsic function, an `AWS_IAM` or `api_key` scheme that containsone, and a body that declares both `swagger` and `openapi`. Existing-custom schemes remain subject to API Gateway's importer and invocation support; preserving-them does not implement another authentication protocol. The importer rejects multiple-authorizer or IAM requirements, including a defined custom authorizer alongside the+custom schemes retained by the transform remain subject to API Gateway's importer and+invocation support; preserving them does not implement another authentication protocol. The+importer rejects multiple authorizer or IAM requirements, including a defined custom authorizer alongside thegenerated IAM default, with `BadRequestException`. API-key requirements can accompanyone authorizer or IAM requirement. The transformpreserves integration credentials, Lambda permissions and inline resource policies.diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudformation/SamRestApiAuth.java b/src/main/java/io/github/hectorvent/floci/services/cloudformation/SamRestApiAuth.javaindex 858ed65e58..b770af0ed2 100644--- a/src/main/java/io/github/hectorvent/floci/services/cloudformation/SamRestApiAuth.java+++ b/src/main/java/io/github/hectorvent/floci/services/cloudformation/SamRestApiAuth.java@@ -107,6 +107,22 @@ final class SamRestApiAuth {}}}+ if (!swagger) {+ removeUndeclaredCustomSchemes(document, definitions);+ }+ }++ private void removeUndeclaredCustomSchemes(ObjectNode document, ObjectNode definitions) {+ // SAM builds securityDefinitions first, then replaces OpenAPI securitySchemes with it.+ // Inline OpenAPI authorizers absent from that generated map do not reach the importer.+ Iterator<Map.Entry<String, JsonNode>> schemes = definitions.fields();+ while (schemes.hasNext()) {+ Map.Entry<String, JsonNode> scheme = schemes.next();+ if (scheme.getValue().has("x-amazon-apigateway-authorizer")+ && !document.path("securityDefinitions").has(scheme.getKey())) {+ schemes.remove();+ }+ }}private void applyDefaults(ObjectNode operation, ObjectNode definitions, boolean iam, boolean keyRequired) {diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/SamRestApiAuthIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/SamRestApiAuthIntegrationTest.javaindex e4120dcf71..aef24210e2 100644--- a/src/test/java/io/github/hectorvent/floci/services/cloudformation/SamRestApiAuthIntegrationTest.java+++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/SamRestApiAuthIntegrationTest.java@@ -31,7 +31,7 @@ class SamRestApiAuthIntegrationTest {private final ObjectMapper mapper = new ObjectMapper();@ParameterizedTest- @CsvSource({"false,false", "false,true", "true,false", "true,true"})+ @CsvSource({"false,true", "true,false", "true,true"})void conflictingAuthorizersCannotSilentlyReplaceTheSamIamDefault(boolean swagger, boolean repeated)throws Exception {ObjectNode template = template(swagger);@@ -57,6 +57,34 @@ class SamRestApiAuthIntegrationTest {.body("item.find { it.name == '" + title + "' }", equalTo(null));}+ @ParameterizedTest+ @ValueSource(booleans = {false, true})+ void undeclaredOpenApiCustomAuthorizerDoesNotConflictWithIam(boolean conditional) throws Exception {+ ObjectNode template = template(false);+ ObjectNode body = (ObjectNode) template.at("/Resources/Api/Properties/DefinitionBody");+ body.set("components", mapper.createObjectNode().set("securitySchemes",+ mapper.createObjectNode().set("custom", customAuthorizer())));+ ObjectNode operation = (ObjectNode) body.at("/paths/~1items/post");+ operation.set("security", mapper.readTree("[{\"custom\":[\"read\"]}]"));+ if (conditional) {+ template.set("Conditions", mapper.readTree("{\"Enabled\":{\"Fn::Equals\":[\"on\",\"on\"]}}"));+ ObjectNode choice = mapper.createObjectNode();+ choice.putArray("Fn::If").add("Enabled").add(operation)+ .add(mapper.createObjectNode().put("Ref", "AWS::NoValue"));+ ((ObjectNode) body.at("/paths/~1items")).set("post", choice);+ }+ withDeployedApi(template, "sam-pruned-authorizer-", apiId -> {+ String resourceId = given().get("/restapis/" + apiId + "/resources")+ .then().statusCode(200).extract().path("item.find { it.path == '/items' }.id");+ given().get("/restapis/" + apiId + "/resources/" + resourceId + "/methods/POST")+ .then().statusCode(200)+ .body("authorizationType", equalTo("AWS_IAM"))+ .body("apiKeyRequired", equalTo(true));+ given().get("/restapis/" + apiId + "/authorizers").then().statusCode(200)+ .body("item.size()", equalTo(0));+ });+ }+@ParameterizedTest@CsvSource({"false,none", "false,custom-authentication", "false,awsSigv4","true,none", "true,custom-authentication", "true,awsSigv4"})diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/SamRestApiAuthTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/SamRestApiAuthTest.javaindex d7c7cb973d..c9dd33c232 100644--- a/src/test/java/io/github/hectorvent/floci/services/cloudformation/SamRestApiAuthTest.java+++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/SamRestApiAuthTest.java@@ -77,7 +77,8 @@ class SamRestApiAuthTest {@ParameterizedTest@ValueSource(strings = {- "{\"Authorizers\":{}}", "{\"ResourcePolicy\":{}}", "{\"UsagePlan\":{}}",+ "{\"Authorizers\":{}}", "{\"Authorizers\":{\"custom\":{\"FunctionArn\":\"example\"}}}",+ "{\"ResourcePolicy\":{}}", "{\"UsagePlan\":{}}","{\"InvokeRole\":\"CALLER_CREDENTIALS\"}", "{\"AddDefaultAuthorizerToCorsPreflight\":false}","{\"DefaultAuthorizer\":\"CUSTOM\"}", "{\"DefaultAuthorizer\":null}","{\"ApiKeyRequired\":\"true\"}", "\"AWS_IAM\""@@ -92,7 +93,7 @@ class SamRestApiAuthTest {}@Test- void preservesExistingCustomSecurityAndAddsTheNamedDefault() throws Exception {+ void dropsUndeclaredOpenApiCustomSchemeAndAddsTheNamedDefault() throws Exception {ObjectNode template = template(false);ObjectNode body = (ObjectNode) template.at("/Resources/Api/Properties/DefinitionBody");((ObjectNode) body.at("/paths/~1items/get")).set("security",@@ -104,12 +105,57 @@ class SamRestApiAuthTest {JsonNode original = template.deepCopy();JsonNode expanded = processor.expandSamTemplate(template).at("/Resources/Api/Properties/Body");assertEquals(original, template);- assertEquals(body.at("/components/securitySchemes/custom"),- expanded.at("/components/securitySchemes/custom"));+ assertTrue(expanded.at("/components/securitySchemes/custom").isMissingNode());assertEquals(mapper.readTree("[{\"custom\":[\"read\"]},{\"AWS_IAM\":[]},{\"api_key\":[]}]"),expanded.at("/paths/~1items/get/security"));}+ @ParameterizedTest+ @CsvSource({"false,iam,false", "false,key,false", "false,none,true",+ "true,iam,true", "true,key,true", "true,none,true"})+ void customSchemePruningDependsOnDocumentAndSelectedDefault(boolean swagger, String defaults,+ boolean retained) throws Exception {+ ObjectNode template = template(swagger);+ ObjectNode properties = (ObjectNode) template.at("/Resources/Api/Properties");+ properties.set("Auth", mapper.readTree(switch (defaults) {+ case "iam" -> "{\"DefaultAuthorizer\":\"AWS_IAM\"}";+ case "key" -> "{\"ApiKeyRequired\":true}";+ default -> "{\"ApiKeyRequired\":false}";+ }));+ ObjectNode body = (ObjectNode) properties.get("DefinitionBody");+ JsonNode custom = mapper.readTree("""+ {"type":"apiKey","name":"Authorization","in":"header",+ "x-amazon-apigateway-authorizer":{"type":"request","authorizerUri":"unused"}}+ """);+ setSchemes(body, swagger, mapper.createObjectNode().set("custom", custom));+ JsonNode security = mapper.readTree("[{\"custom\":[\"read\"]},{}]");+ body.set("security", security.deepCopy());+ ((ObjectNode) body.at("/paths/~1items/get")).set("security", security.deepCopy());+ JsonNode original = template.deepCopy();+ JsonNode expanded = processor.expandSamTemplate(template).at("/Resources/Api/Properties/Body");+ JsonNode schemes = swagger ? expanded.path("securityDefinitions")+ : expanded.at("/components/securitySchemes");+ assertEquals(retained, schemes.has("custom"));+ assertEquals(security, expanded.path("security"));+ assertEquals(security.get(0), expanded.at("/paths/~1items/get/security/0"));+ assertEquals(security.get(1), expanded.at("/paths/~1items/get/security/1"));+ assertEquals(original, template);+ }++ @Test+ void keepsCustomSchemeAlsoDeclaredInSamSecurityDefinitions() throws Exception {+ ObjectNode template = template(false);+ ObjectNode body = (ObjectNode) template.at("/Resources/Api/Properties/DefinitionBody");+ JsonNode definitions = mapper.readTree("""+ {"custom":{"type":"apiKey","name":"Authorization","in":"header",+ "x-amazon-apigateway-authorizer":{"type":"request","authorizerUri":"unused"}}}+ """);+ setSchemes(body, false, definitions.deepCopy());+ body.set("securityDefinitions", definitions.deepCopy());+ JsonNode expanded = processor.expandSamTemplate(template).at("/Resources/Api/Properties/Body");+ assertEquals(definitions.get("custom"), expanded.at("/components/securitySchemes/custom"));+ }+@ParameterizedTest@ValueSource(strings = {"custom-authentication", "awsSigv4"})void existingSchemeMetadataDoesNotSuppressTheNamedIamDefault(String authType) throws Exception {