Light, fluffy, and always free - The AWS Local Emulator alternative
fix(cloudformation): relocate SAM schemes without auth defaults (#6656)
Andre Kurait07597598b681
diff --git a/docs/services/cloudformation.md b/docs/services/cloudformation.mdindex 2b44ece548..6e68669cc8 100644--- a/docs/services/cloudformation.md+++ b/docs/services/cloudformation.md@@ -785,7 +785,10 @@ nested `Fn::If` around an operation is left as written, without the defaults, asit.Root-level `security` stays in the document as written and is not copied into operations,and an `Auth` that selects no default, such as `ApiKeyRequired: false` alone, leaves the-document unchanged. floci's REST importer still applies root-level `security` to an+operation requirements unchanged. For inline OpenAPI 3 documents, non-empty+`securityDefinitions` replace `components.securitySchemes` and are removed even when+`Auth` is absent, empty, or selects no default. Empty or absent definitions do not replace+existing schemes. Swagger documents retain their definitions. floci's REST importer still applies root-level `security` to anoperation that has none of its own, which API Gateway does not. As in SAM, any non-empty`Auth`, even one that selects no default, needs a Swagger or OpenAPI 3 `DefinitionBody`whose `paths` entries, and the branches of an `Fn::If` around one, are objects, so a body ordiff --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 e1899dad46..c677d76d70 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@@ -29,6 +29,27 @@ final class SamRestApiAuth {}void apply(JsonNode auth, JsonNode body) {+ applyDefaults(auth, body);+ relocateOpenApiSchemes(body);+ }++ private void relocateOpenApiSchemes(JsonNode body) {+ if (!(body instanceof ObjectNode document) || document.hasNonNull("swagger")) {+ return;+ }+ JsonNode version = document.path("openapi");+ JsonNode definitions = document.path("securityDefinitions");+ if (version.isTextual() && OPENAPI_3.matcher(version.asText()).matches()+ && SamTransformProcessor.isTruthy(definitions)) {+ if (!SamTransformProcessor.isTruthy(document.path("components"))) {+ document.set("components", mapper.createObjectNode());+ }+ object(document, "components").set("securitySchemes", definitions);+ document.remove("securityDefinitions");+ }+ }++ private void applyDefaults(JsonNode auth, JsonNode body) {if (auth.isMissingNode() || auth.isNull()) {return;}@@ -57,7 +78,7 @@ final class SamRestApiAuth {}if (!iam && !keyRequired) {// Like SAM, an Auth that selects no default, such as ApiKeyRequired: false alone,- // leaves the document as written once it has checked what SAM checks for any Auth.+ // leaves operation security as written after checking what SAM checks for any Auth.requireSamDocument(document);return;}@@ -108,12 +129,11 @@ final class SamRestApiAuth {}}if (!swagger) {- replaceOpenApiSchemes(document, iam, keyRequired);+ addOpenApiDefaultSchemes(document, iam, keyRequired);}}- private void replaceOpenApiSchemes(ObjectNode document, boolean iam, boolean keyRequired) {- // SAM replaces the whole OpenAPI map with its generated Swagger definitions.+ private void addOpenApiDefaultSchemes(ObjectNode document, boolean iam, boolean keyRequired) {ObjectNode definitions = object(document, "securityDefinitions");if (iam) {addScheme(definitions, "AWS_IAM", true);@@ -121,8 +141,6 @@ final class SamRestApiAuth {if (keyRequired) {addScheme(definitions, "api_key", false);}- object(document, "components").set("securitySchemes", definitions);- document.remove("securityDefinitions");}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 aa1b888fec..37df3ad94d 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@@ -97,6 +97,38 @@ class SamRestApiAuthIntegrationTest {});}+ @ParameterizedTest+ @ValueSource(strings = {"missing", "{}", "{\"ApiKeyRequired\":false}"})+ void importedApiUsesRelocatedSchemesWithoutDefaults(String auth) throws Exception {+ ObjectNode template = template(false);+ ObjectNode properties = (ObjectNode) template.at("/Resources/Api/Properties");+ if ("missing".equals(auth)) {+ properties.remove("Auth");+ } else {+ properties.set("Auth", mapper.readTree(auth));+ }+ ObjectNode body = (ObjectNode) properties.get("DefinitionBody");+ body.set("components", mapper.readTree("{\"securitySchemes\":{}}"));+ body.set("securityDefinitions", mapper.readTree("""+ {"declaredKey":{"type":"apiKey","name":"x-api-key","in":"header"}}+ """));+ ((ObjectNode) body.at("/paths/~1items/post")).set("security",+ mapper.readTree("[{\"declaredKey\":[]}]"));+ try (ApiGatewayClient client = ApiGatewayClient.builder().endpointOverride(endpoint)+ .region(Region.US_EAST_1).httpClientBuilder(UrlConnectionHttpClient.builder())+ .credentialsProvider(StaticCredentialsProvider.create(AwsBasicCredentials.create("test", "test")))+ .build()) {+ withDeployedApi(template, "sam-relocated-key-", apiId -> {+ String resourceId = client.getResources(request -> request.restApiId(apiId)).items().stream()+ .filter(resource -> "/items".equals(resource.path())).findFirst().orElseThrow().id();+ GetMethodResponse method = client.getMethod(request -> request.restApiId(apiId)+ .resourceId(resourceId).httpMethod("POST"));+ assertEquals("NONE", method.authorizationType());+ assertEquals(true, method.apiKeyRequired());+ });+ }+ }+@Testvoid undeclaredInlineApiKeyDoesNotSurviveSamOpenApiPostProcessing() throws Exception {ObjectNode template = template(false);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 aa58519ab2..b7ce34b97f 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@@ -43,6 +43,80 @@ class SamRestApiAuthTest {assertEquals("x-api-key", schemes.path("api_key").path("name").asText());}+ @ParameterizedTest+ @ValueSource(strings = {"missing", "null", "{}", "{\"ApiKeyRequired\":false}"})+ void relocatesDeclaredSchemesWithoutAuthDefaults(String auth) throws Exception {+ ObjectNode template = template(false);+ ObjectNode properties = (ObjectNode) template.at("/Resources/Api/Properties");+ if ("missing".equals(auth)) {+ properties.remove("Auth");+ } else {+ properties.set("Auth", mapper.readTree(auth));+ }+ ObjectNode body = (ObjectNode) properties.get("DefinitionBody");+ body.set("components", mapper.readTree("""+ {"schemas":{"Example":{"type":"string"}},"securitySchemes":{"old":{"type":"apiKey"}}}+ """));+ JsonNode definitions = existingSchemes();+ body.set("securityDefinitions", definitions.deepCopy());+ body.set("security", mapper.readTree("[{\"existingKey\":[]}]"));+ JsonNode original = template.deepCopy();+ JsonNode expanded = processor.expandSamTemplate(template).at("/Resources/Api/Properties/Body");+ assertFalse(expanded.has("securityDefinitions"));+ assertEquals(definitions, expanded.at("/components/securitySchemes"));+ assertEquals(body.at("/components/schemas"), expanded.at("/components/schemas"));+ assertEquals(body.get("security"), expanded.get("security"));+ assertEquals(body.get("paths"), expanded.get("paths"));+ assertEquals(original, template);+ }++ @ParameterizedTest+ @ValueSource(strings = {"3.0.1", "3.1.0", "3.0"})+ void relocatesSchemesIntoAbsentOrNullComponents(String version) throws Exception {+ ObjectNode template = template(false);+ ObjectNode properties = (ObjectNode) template.at("/Resources/Api/Properties");+ properties.remove("Auth");+ ObjectNode body = (ObjectNode) properties.get("DefinitionBody");+ body.put("openapi", version);+ for (boolean nullComponents : new boolean[] {false, true}) {+ if (nullComponents) {+ body.putNull("components");+ } else {+ body.remove("components");+ }+ body.set("securityDefinitions", existingSchemes());+ JsonNode expanded = processor.expandSamTemplate(template).at("/Resources/Api/Properties/Body");+ assertEquals(existingSchemes(), expanded.at("/components/securitySchemes"));+ assertFalse(expanded.has("securityDefinitions"));+ }+ }++ @ParameterizedTest+ @ValueSource(strings = {"swagger", "both", "invalidVersion", "nullVersion", "emptyDefinitions",+ "nullDefinitions", "missingDefinitions", "intrinsic"})+ void leavesDocumentsOutsideRelocationScopeUnchanged(String shape) throws Exception {+ ObjectNode template = template(false);+ ObjectNode properties = (ObjectNode) template.at("/Resources/Api/Properties");+ properties.remove("Auth");+ ObjectNode body = (ObjectNode) properties.get("DefinitionBody");+ body.set("securityDefinitions", existingSchemes());+ switch (shape) {+ case "swagger" -> {+ body.remove("openapi");+ body.put("swagger", "2.0");+ }+ case "both" -> body.put("swagger", "2.0");+ case "invalidVersion" -> body.put("openapi", "3.invalid");+ case "nullVersion" -> body.putNull("openapi");+ case "emptyDefinitions" -> body.set("securityDefinitions", mapper.createObjectNode());+ case "nullDefinitions" -> body.putNull("securityDefinitions");+ case "missingDefinitions" -> body.remove("securityDefinitions");+ default -> properties.set("DefinitionBody", mapper.readTree("{\"Ref\":\"Document\"}"));+ }+ JsonNode expanded = processor.expandSamTemplate(template).at("/Resources/Api/Properties/Body");+ assertEquals(properties.get("DefinitionBody"), expanded);+ }+@Testvoid leavesOperationsAndRootSecurityAsWrittenWhenNoDefaultApplies() throws Exception {ObjectNode template = template(false);