From 5fa67625c11a4ea0ca619cb57d186be4ea94b97f Mon Sep 17 00:00:00 2001 From: Alessandro Lattao Date: Tue, 20 Oct 2026 23:13:31 +0200 Subject: [PATCH] fix(cloudformation): refuse a template that holds a null value (#6071) * fix(cloudformation): refuse a template that holds a null value CloudFormation refuses a template with a null anywhere in it when ValidateTemplate, CreateStack, UpdateStack or CreateChangeSet is requested, before anything is created: 400 ValidationError "[] 'null' values are not allowed in templates". Floci accepted such a template and provisioned it, so a template AWS rejects deployed locally, and ValidateTemplate answered success without reading it. The check runs where a change set is created, which CreateStack, UpdateStack and CreateChangeSet share, and in ValidateTemplate. The path is the one AWS names, measured on eu-west-1 on 2026-10-20: the first null in document order, Type in place of a resource's Properties below them, a null Properties named as is, list entries by index and an intrinsic's arguments included. JSON null, YAML ~ and a YAML key with no value are all null there. A template that does not parse is left to the parser's error where it is processed, as the other request-time checks do. CognitoResourceServerCfnIntegrationTest's null Scopes cases sent such a template and expected the resource to fail. They now expect the request refused, as on AWS, and keep what they checked: no server is created, and a refused update leaves the server as it was. * fix(cloudformation): refuse null templates in stack sets and answer missing template objects A review of the null-value check found four gaps, each measured on CloudFormation (eu-west-1, 2026-10-20) before the fix. - A template that is null as a whole ("null", "~", "---", a comment alone) parsed to no root and the check failed with a 500. AWS answers "Template format error: At least one Resources member must be defined.", which it does now. - CreateStackSet and UpdateStackSet stored a null-valued template and only each instance's deployment refused it. AWS refuses the request and keeps the previous template, with CloudFormation's message followed by the service exception's details. Both now check the template they would keep before storing it or reserving an operation. - ValidateTemplate reading TemplateURL reached the shared S3 fetch, whose failures were a 500, as they already were for CreateStack and GetTemplateSummary. A missing object or bucket now answers AWS's ValidationError texts for all three. AWS also refuses a URL that is not an S3 one; Floci keeps reading any host as S3, so a local URL can name Floci by whatever host reaches it. - The compatibility test's cleanup swallowed every exception; DeleteStack of a stack that does not exist succeeds, so it no longer catches any. CloudFormationS3VectorsTest and CloudFormationCognitoResourceServerTest in sdk-test-java sent null values and expected them to reach the resource. AWS refuses those templates when the operation is requested, so the S3 Vectors cases that cannot be deployed there are dropped and the Cognito update case now expects the request refused, with the server left as it was. * refactor(cloudformation): build the stack-set null refusal with sdkErrorMessage A review pointed out that the suffix StackSets adds to CloudFormation's message was built by hand while CloudFormationTemplateEngine.sdkErrorMessage already builds it for this package, and that updateStackSet wrote the template it would keep twice. The refusal now uses sdkErrorMessage, and the kept template is one local both checks read; the answers are the same. --- ...oudFormationCognitoResourceServerTest.java | 13 +- .../test/CloudFormationNullValuesTest.java | 70 +++++++ .../test/CloudFormationS3VectorsTest.java | 3 +- docs/services/cloudformation.md | 25 ++- .../CloudFormationQueryHandler.java | 5 + .../cloudformation/CloudFormationService.java | 75 +++++++ .../cloudformation/StackSetService.java | 20 +- ...oudFormationNullValuesIntegrationTest.java | 186 ++++++++++++++++++ ...gnitoResourceServerCfnIntegrationTest.java | 22 +-- 9 files changed, 398 insertions(+), 21 deletions(-) create mode 100644 compatibility-tests/sdk-test-java/src/test/java/com/floci/test/CloudFormationNullValuesTest.java create mode 100644 src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationNullValuesIntegrationTest.java diff --git a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/CloudFormationCognitoResourceServerTest.java b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/CloudFormationCognitoResourceServerTest.java index 14b18eafbb..51a5263639 100644 --- a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/CloudFormationCognitoResourceServerTest.java +++ b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/CloudFormationCognitoResourceServerTest.java @@ -274,18 +274,21 @@ class CloudFormationCognitoResourceServerTest { @ParameterizedTest @ValueSource(booleans = {false, true}) - @DisplayName("Explicit and resolved null Scopes fail without clearing the existing server") + @DisplayName("Explicit and resolved null Scopes are refused without touching the existing server") void nullScopesUpdatesPreserveTheExistingConfiguration(boolean conditional) throws Exception { String identifier = stackName + "-api"; List original = parameters(identifier, p1, "Original API", "read", "Read access", true, false, false); createStack(original); String invalidTemplate = nullScopesTemplate(conditional); + String path = conditional ? "/Resources/Server/Type/Scopes/Fn::If/1" : "/Resources/Server/Type/Scopes"; - cfn.updateStack(r -> r.stackName(stackName).templateBody(invalidTemplate) - .parameters(parameters(identifier, p1, "Changed API", "write", "Write access", true, false, false))); - awaitStatus("UPDATE_ROLLBACK_COMPLETE"); + // As on AWS, a template holding a null is refused when the update is requested. + assertThatThrownBy(() -> cfn.updateStack(r -> r.stackName(stackName).templateBody(invalidTemplate) + .parameters(parameters(identifier, p1, "Changed API", "write", "Write access", true, false, false)))) + .isInstanceOfSatisfying(CloudFormationException.class, e -> assertThat(e.awsErrorDetails().errorMessage()) + .isEqualTo("[" + path + "] 'null' values are not allowed in templates")); + awaitStatus("CREATE_COMPLETE"); - assertThat(failedEvents()).contains("Scopes must be a list"); assertIdentity(identifier); assertServer(p1, identifier, "Original API", "read", "Read access"); updateStack(parameters(identifier, p1, "Recovered API", "write", "Write access", true, false, false), diff --git a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/CloudFormationNullValuesTest.java b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/CloudFormationNullValuesTest.java new file mode 100644 index 0000000000..fa85641fa9 --- /dev/null +++ b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/CloudFormationNullValuesTest.java @@ -0,0 +1,70 @@ +package com.floci.test; + +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; +import software.amazon.awssdk.services.cloudformation.CloudFormationClient; +import software.amazon.awssdk.services.cloudformation.model.CloudFormationException; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +@DisplayName("CloudFormation templates holding a null value") +class CloudFormationNullValuesTest { + + private static CloudFormationClient cfn; + private String stackName; + + @BeforeAll + static void clients() { + cfn = TestFixtures.cloudFormationClient(); + } + + @BeforeEach + void setup() { + stackName = TestFixtures.uniqueName("compat-cfn-null"); + } + + /** The stack is never created, and DeleteStack of a stack that does not exist succeeds; this covers a regression. */ + @AfterEach + void cleanup() { + cfn.deleteStack(r -> r.stackName(stackName)); + } + + @AfterAll + static void closeClients() { + cfn.close(); + } + + @Test + @DisplayName("ValidateTemplate and CreateStack name the first null, and nothing is created") + void aNullValueIsRefused() { + String template = """ + Resources: + Queue: + Type: AWS::SQS::Queue + Properties: + QueueName: + DelaySeconds: ~ + """; + String message = "[/Resources/Queue/Type/QueueName] 'null' values are not allowed in templates"; + + assertThatThrownBy(() -> cfn.validateTemplate(r -> r.templateBody(template))) + .isInstanceOfSatisfying(CloudFormationException.class, e -> { + assertThat(e.awsErrorDetails().errorCode()).isEqualTo("ValidationError"); + assertThat(e.awsErrorDetails().errorMessage()).isEqualTo(message); + }); + assertThatThrownBy(() -> cfn.createStack(r -> r.stackName(stackName).templateBody(template))) + .isInstanceOfSatisfying(CloudFormationException.class, e -> { + assertThat(e.awsErrorDetails().errorCode()).isEqualTo("ValidationError"); + assertThat(e.awsErrorDetails().errorMessage()).isEqualTo(message); + }); + + assertThatThrownBy(() -> cfn.describeStacks(r -> r.stackName(stackName))) + .isInstanceOf(CloudFormationException.class) + .hasMessageContaining("does not exist"); + } +} diff --git a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/CloudFormationS3VectorsTest.java b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/CloudFormationS3VectorsTest.java index 6eba8e4ad2..23a8f0aaf3 100644 --- a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/CloudFormationS3VectorsTest.java +++ b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/CloudFormationS3VectorsTest.java @@ -212,7 +212,6 @@ class CloudFormationS3VectorsTest { Arguments.of("float32", "manhattan", List.of(), "distanceMetric"), Arguments.of("float32", "cosine", List.of(""), "NonFilterableMetadataKeys"), Arguments.of("float32", "cosine", List.of(" "), "NonFilterableMetadataKeys"), - Arguments.of("float32", "cosine", Collections.singletonList(null), "NonFilterableMetadataKeys"), Arguments.of("float32", "cosine", List.of("a".repeat(64)), "NonFilterableMetadataKeys"), Arguments.of("float32", "cosine", Collections.nCopies(11, "key"), "NonFilterableMetadataKeys")); } @@ -418,7 +417,7 @@ class CloudFormationS3VectorsTest { } @ParameterizedTest - @ValueSource(strings = {"absent", "null", "{}", "{\"SseType\":null}", "{\"SseType\":\"AES256\"}"}) + @ValueSource(strings = {"absent", "{}", "{\"SseType\":\"AES256\"}"}) void indexesInheritBucketEncryptionUnlessExplicitlyOverridden(String configuration) throws Exception { String name = TestFixtures.uniqueName("cfn-vectors-inherit"); ObjectNode template = (ObjectNode) MAPPER.readTree(TEMPLATE); diff --git a/docs/services/cloudformation.md b/docs/services/cloudformation.md index 584783270e..f0394ceddf 100644 --- a/docs/services/cloudformation.md +++ b/docs/services/cloudformation.md @@ -24,7 +24,7 @@ | `ListStackResources` | List resource summaries | | `GetTemplate` | Retrieve the template body | | `GetTemplateSummary` | Summarize a template's Parameters, Resources and Transform sections, by StackName, TemplateBody or TemplateURL | -| `ValidateTemplate` | Accepted; returns success without validating (stub) | +| `ValidateTemplate` | Refuses a template holding a `null` value (see [Null values](#null-values)); otherwise returns success without validating further | | `ListStacks` | List stacks by status | | `ListExports` | - | | `SetStackPolicy` | Accepted; no-op (stub — stack policies are not enforced) | @@ -631,6 +631,29 @@ intrinsic's reference page: or Fn::GetAZs.` In a nested stack's template the same rules fail the child's resource with the same message when the child is created, and the parent rolls back. +## Null values + +As on AWS, a template holding a `null` anywhere (JSON `null`, YAML `~` or a key with no value) is +refused when `ValidateTemplate`, `CreateStack`, `UpdateStack` or `CreateChangeSet` is requested, +before anything is created, with `ValidationError` `[] 'null' values are not allowed in +templates`. The path names the first `null` in document order, as AWS's does: below a resource's +`Properties` it says `Type` where `Properties` would be (`[/Resources/Queue/Type/QueueName]`), a +`null` `Properties` is `[/Resources/Queue/Properties]`, list entries are numbered from 0, and an +intrinsic's arguments are part of the path (`[/Resources/Queue/Type/QueueName/Fn::Join/1/1]`). +A template that is null as a whole (`null`, `~`) is refused with `Template format error: At least +one Resources member must be defined.` `CreateStackSet` and `UpdateStackSet` refuse a template +holding a `null` before the stack set keeps it, with the same message followed by the service +exception's details, as on AWS. + +## Template URLs + +A `TemplateURL` names an object in Floci's S3, virtual-hosted or path-style. As on AWS, one whose +bucket or object does not exist is refused by `ValidateTemplate`, `CreateStack` and +`GetTemplateSummary` alike, with `ValidationError` `S3 error: The specified bucket does not exist` +or `S3 object does not exist. Bucket: , Key: . Error: NoSuchKey`. AWS also refuses a +URL that is not an S3 one (`TemplateURL must be a supported URL.`); Floci reads any host as S3, so +the URL can name Floci by whatever host reaches it. + ## Template Parameters Parameters passed to `CreateStack` / `UpdateStack` (and echoed back by `DescribeStacks`) are resolved diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationQueryHandler.java b/src/main/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationQueryHandler.java index 5257268059..34daa043d0 100644 --- a/src/main/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationQueryHandler.java +++ b/src/main/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationQueryHandler.java @@ -581,6 +581,11 @@ public class CloudFormationQueryHandler { // ── ValidateTemplate ────────────────────────────────────────────────────── private Response validateTemplate(MultivaluedMap params) { + try { + cfnService.validateTemplate(params.getFirst("TemplateBody"), params.getFirst("TemplateURL")); + } catch (AwsException e) { + return xmlError(e.getErrorCode(), e.getMessage(), e.getHttpStatus()); + } String xml = new XmlBuilder() .start("ValidateTemplateResponse", CF_NS) .start("ValidateTemplateResult") diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationService.java b/src/main/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationService.java index 3afc5c2635..c322aa71ad 100644 --- a/src/main/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationService.java +++ b/src/main/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationService.java @@ -401,6 +401,7 @@ public class CloudFormationService implements ResourceProvider { Map tags, String region, String accountId, boolean attachToReviewInProgressStack, boolean fromPreviousTemplate) { String resolvedTemplate = resolveTemplate(templateBody, templateUrl); + requireNoNullValues(resolvedTemplate); boolean isCreateType = "CREATE".equalsIgnoreCase(changeSetType); // An update names its stack by name or stack ID; the map is keyed by name. One that names no // live stack is keyed as given, so it lands in the missing-stack branch below. @@ -3974,6 +3975,18 @@ public class CloudFormationService implements ResourceProvider { try { S3Object obj = s3Service.getObject(ref.bucket(), ref.key()); return new String(obj.getData()); + } catch (AwsException e) { + // Measured (eu-west-1, 2026-10-20), alike for ValidateTemplate, CreateStack and GetTemplateSummary. + if ("NoSuchBucket".equals(e.getErrorCode())) { + throw new AwsException("ValidationError", "S3 error: The specified bucket does not exist\nFor more" + + " information check http://docs.aws.amazon.com/AmazonS3/latest/API/ErrorResponses.html", 400); + } + if ("NoSuchKey".equals(e.getErrorCode())) { + throw new AwsException("ValidationError", "S3 object does not exist. Bucket: " + ref.bucket() + + ", Key: " + ref.key() + ". Error: NoSuchKey", 400); + } + LOG.errorv("Failed to fetch CloudFormation template from {0}: {1}", url, e.getMessage()); + throw new RuntimeException("Failed to fetch CloudFormation template from " + url + ": " + e.getMessage(), e); } catch (Exception e) { LOG.errorv("Failed to fetch CloudFormation template from {0}: {1}", url, e.getMessage()); throw new RuntimeException("Failed to fetch CloudFormation template from " + url + ": " + e.getMessage(), e); @@ -4480,6 +4493,68 @@ public class CloudFormationService implements ResourceProvider { return value; } + /** ValidateTemplate's check of a template: the null values AWS refuses there. */ + public void validateTemplate(String templateBody, String templateUrl) { + String resolvedBody = resolveTemplateBody(templateBody, templateUrl); + if (resolvedBody != null) { + requireNoNullValues(resolvedBody); + } + } + + /** + * Refuses a template that holds a null value anywhere, as AWS does when ValidateTemplate, + * CreateStack, UpdateStack or CreateChangeSet is requested, before anything is created + * (measured, eu-west-1, 2026-10-20): ValidationError "[path] 'null' values are not allowed in + * templates", naming the first null in document order. Below a resource's Properties the path + * says Type where Properties would be, as AWS's does; a null Properties is named as it is. + */ + void requireNoNullValues(String templateBody) { + JsonNode parsed; + try { + parsed = parseTemplate(templateBody); + } catch (Exception e) { + // As validateResourceDependencies: a template that does not parse fails where it is + // processed, with the parser's error. + LOG.debugv("Skipping null value validation; template did not parse: {0}", e.getMessage()); + return; + } + if (parsed == null || parsed.isNull()) { + // Measured: a template that is null as a whole ("null", "~") lacks its resources first. + throw new AwsException("ValidationError", + "Template format error: At least one Resources member must be defined.", 400); + } + String path = firstNullPath(parsed, "", false); + if (path != null) { + throw new AwsException("ValidationError", + "[" + path + "] 'null' values are not allowed in templates", 400); + } + } + + private static String firstNullPath(JsonNode node, String path, boolean isResource) { + if (node.isNull()) { + return path; + } + if (node.isObject()) { + boolean childIsResource = "/Resources".equals(path); + for (Map.Entry member : node.properties()) { + String name = isResource && "Properties".equals(member.getKey()) && !member.getValue().isNull() + ? "Type" : member.getKey(); + String found = firstNullPath(member.getValue(), path + "/" + name, childIsResource); + if (found != null) { + return found; + } + } + } else if (node.isArray()) { + for (int i = 0; i < node.size(); i++) { + String found = firstNullPath(node.get(i), path + "/" + i, false); + if (found != null) { + return found; + } + } + } + return null; + } + /** * The places AWS refuses {@code Fn::GetStackOutput} when the stack operation is requested, * before anything runs (measured, eu-west-1, 2026-10-04 and 2026-10-17): anywhere in the diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudformation/StackSetService.java b/src/main/java/io/github/hectorvent/floci/services/cloudformation/StackSetService.java index 7bb8a230e9..d295d9850b 100644 --- a/src/main/java/io/github/hectorvent/floci/services/cloudformation/StackSetService.java +++ b/src/main/java/io/github/hectorvent/floci/services/cloudformation/StackSetService.java @@ -133,6 +133,7 @@ public class StackSetService implements PassedRoleLookup { if ("SELF_MANAGED".equals(resolvedPermissionModel) && (autoDeploymentEnabled || retainStacksOnAccountRemoval)) { throw new AwsException("ValidationError", "AutoDeployment is valid only for SERVICE_MANAGED StackSets.", 400); } + requireNoNullValues(templateBody); // Every instance is deployed with these parameters, so a template parameter left without a // value would fail each one; refuse the stack set instead. cfnService.requireParameterValues(templateBody, parameters); @@ -210,8 +211,9 @@ public class StackSetService implements PassedRoleLookup { StackSet ss = getStackSetOrThrow(name); // Checked against the template and parameters the update leaves the stack set with, before // either is changed or an operation is recorded. - cfnService.requireParameterValues( - templateBody != null && !templateBody.isBlank() ? templateBody : ss.getTemplateBody(), + String keptTemplate = templateBody != null && !templateBody.isBlank() ? templateBody : ss.getTemplateBody(); + requireNoNullValues(keptTemplate); + cfnService.requireParameterValues(keptTemplate, parameters != null && !parameters.isEmpty() ? parameters : ss.getParameters()); String operationId = reserveOperation(name, "UPDATE", requestedOperationId).getOperationId(); if (templateBody != null && !templateBody.isBlank()) { @@ -721,6 +723,20 @@ public class StackSetService implements PassedRoleLookup { return anyFailed ? "FAILED" : "SUCCEEDED"; } + /** + * Refuses a template holding a null value before the stack set stores it, as CreateStackSet and + * UpdateStackSet do (measured, eu-west-1, 2026-10-20). StackSets passes CloudFormation's message + * on with the details of the service exception it came in. + */ + private void requireNoNullValues(String templateBody) { + try { + cfnService.requireNoNullValues(templateBody); + } catch (AwsException e) { + throw new AwsException(e.getErrorCode(), CloudFormationTemplateEngine.sdkErrorMessage( + e.getMessage(), "AmazonCloudFormation", e.getHttpStatus(), e.getErrorCode()), e.getHttpStatus()); + } + } + private StackSet getStackSetOrThrow(String name) { return stackSets.get(name) .orElseThrow(() -> new AwsException("StackSetNotFoundException", diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationNullValuesIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationNullValuesIntegrationTest.java new file mode 100644 index 0000000000..26fa02994e --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationNullValuesIntegrationTest.java @@ -0,0 +1,186 @@ +package io.github.hectorvent.floci.services.cloudformation; + +import io.quarkus.test.junit.QuarkusTest; +import io.restassured.response.Response; +import io.restassured.specification.RequestSpecification; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; +import org.junit.jupiter.params.provider.ValueSource; + +import java.util.List; +import java.util.stream.Stream; + +import static io.restassured.RestAssured.given; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.allOf; +import static org.hamcrest.Matchers.endsWith; +import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.startsWith; +import static org.junit.jupiter.api.Assertions.assertEquals; + +/** + * A template holding a null value is refused when the operation is requested, before anything is + * created. Measured on CloudFormation (eu-west-1, 2026-10-20): ValidateTemplate, CreateStack, + * UpdateStack and CreateChangeSet answer 400 ValidationError "[path] 'null' values are not allowed + * in templates", the path naming the first null in document order, with Type where a resource's + * Properties would be. + */ +@QuarkusTest +class CloudFormationNullValuesIntegrationTest { + + private static final String AUTH = + "AWS4-HMAC-SHA256 Credential=test/20261020/us-east-1/cloudformation/aws4_request"; + + @ParameterizedTest(name = "{0}") + @MethodSource("nullValues") + void aNullValueIsRefusedWhereAwsNamesIt(String where, String template, String path) { + String message = "[" + path + "] 'null' values are not allowed in templates"; + String name = "cfn-null-" + System.nanoTime(); + + assertRefused(request("ValidateTemplate", null, template), message); + assertRefused(request("CreateStack", name, template), message); + given().contentType("application/x-www-form-urlencoded").header("Authorization", AUTH) + .formParam("Action", "DescribeStacks").formParam("StackName", name) + .when().post("/").then().statusCode(400); + } + + static Stream nullValues() { + return Stream.of( + Arguments.of("a property", queue("{\"QueueName\": null}"), "/Resources/Q/Type/QueueName"), + Arguments.of("a nested member", queue("{\"RedrivePolicy\": {\"deadLetterTargetArn\": null, \"maxReceiveCount\": 3}}"), + "/Resources/Q/Type/RedrivePolicy/deadLetterTargetArn"), + Arguments.of("a list item's member", queue("{\"Tags\": [{\"Key\": \"k\", \"Value\": null}]}"), + "/Resources/Q/Type/Tags/0/Value"), + Arguments.of("a list entry", "{\"Resources\": {\"T\": {\"Type\": \"AWS::SNS::Topic\", \"Properties\": {\"Subscription\": [null]}}}}", + "/Resources/T/Type/Subscription/0"), + Arguments.of("Properties", "{\"Resources\": {\"Q\": {\"Type\": \"AWS::SQS::Queue\", \"Properties\": null}}}", + "/Resources/Q/Properties"), + Arguments.of("Type", "{\"Resources\": {\"Q\": {\"Type\": null}}}", "/Resources/Q/Type"), + Arguments.of("Resources", "{\"Resources\": null}", "/Resources"), + Arguments.of("an intrinsic's argument", queue("{\"QueueName\": {\"Fn::Join\": [\"-\", [\"a\", null]]}}"), + "/Resources/Q/Type/QueueName/Fn::Join/1/1"), + Arguments.of("an output's value", "{\"Resources\": {\"H\": {\"Type\": \"AWS::CloudFormation::WaitConditionHandle\"}}," + + " \"Outputs\": {\"O\": {\"Value\": null}}}", "/Outputs/O/Value"), + Arguments.of("a parameter's default", "{\"Parameters\": {\"P\": {\"Type\": \"String\", \"Default\": null}}," + + " \"Resources\": {\"H\": {\"Type\": \"AWS::CloudFormation::WaitConditionHandle\"}}}", "/Parameters/P/Default"), + Arguments.of("a resource's metadata", "{\"Resources\": {\"H\": {\"Type\": \"AWS::CloudFormation::WaitConditionHandle\"," + + " \"Metadata\": {\"m\": null}}}}", "/Resources/H/Metadata/m"), + Arguments.of("two nulls", queue("{\"QueueName\": null, \"DelaySeconds\": null}"), "/Resources/Q/Type/QueueName"), + Arguments.of("YAML, empty and ~", "Resources:\n Q:\n Type: AWS::SQS::Queue\n Properties:\n" + + " QueueName:\n DelaySeconds: ~\n", "/Resources/Q/Type/QueueName")); + } + + @Test + void anUpdateAndAChangeSetAreRefusedToo() { + String name = "cfn-null-update-" + System.nanoTime(); + given().contentType("application/x-www-form-urlencoded").header("Authorization", AUTH) + .formParam("Action", "CreateStack").formParam("StackName", name) + .formParam("TemplateBody", "{\"Resources\": {\"H\": {\"Type\": \"AWS::CloudFormation::WaitConditionHandle\"}}}") + .when().post("/").then().statusCode(200); + assertEquals("CREATE_COMPLETE", CfnStackWaits.awaitTerminal(name).status()); + String message = "[/Resources/Q/Type/QueueName] 'null' values are not allowed in templates"; + String template = queue("{\"QueueName\": null}"); + + assertRefused(request("UpdateStack", name, template), message); + assertRefused(given().contentType("application/x-www-form-urlencoded").header("Authorization", AUTH) + .formParam("Action", "CreateChangeSet").formParam("StackName", name) + .formParam("ChangeSetName", "with-null").formParam("TemplateBody", template) + .when().post("/"), message); + + given().contentType("application/x-www-form-urlencoded").header("Authorization", AUTH) + .formParam("Action", "DeleteStack").formParam("StackName", name) + .when().post("/").then().statusCode(200); + CfnStackWaits.awaitStackDeleted(name); + } + + /** Measured: a template that is null as a whole, or holds only a comment, is refused for lacking its resources. */ + @ParameterizedTest + @ValueSource(strings = {"null", "~", "---\n~\n", "---\n", "# only a comment"}) + void aTemplateThatIsNullAsAWholeLacksItsResources(String template) { + String message = "Template format error: At least one Resources member must be defined."; + + assertRefused(request("ValidateTemplate", null, template), message); + assertRefused(request("CreateStack", "cfn-null-whole-" + System.nanoTime(), template), message); + } + + /** + * Measured: CreateStackSet and UpdateStackSet refuse the template before the stack set keeps it, + * passing CloudFormation's message on with the service exception's details. + */ + @Test + void aStackSetRefusesATemplateWithANullValueBeforeKeepingIt() { + String name = "cfn-null-set-" + System.nanoTime(); + String good = "{\"Resources\": {\"H\": {\"Type\": \"AWS::CloudFormation::WaitConditionHandle\"}}}"; + String prefix = "[/Resources/Q/Type/QueueName] 'null' values are not allowed in templates (Service:" + + " AmazonCloudFormation; Status Code: 400; Error Code: ValidationError; Request ID: "; + + Response create = stackSet("CreateStackSet", name + "-refused", queue("{\"QueueName\": null}")); + create.then().statusCode(400); + assertThat(create.xmlPath().getString("ErrorResponse.Error.Message"), + allOf(startsWith(prefix), endsWith("; Proxy: null)"))); + stackSet("CreateStackSet", name, good).then().statusCode(200); + Response update = stackSet("UpdateStackSet", name, queue("{\"QueueName\": null}")); + update.then().statusCode(400); + assertThat(update.xmlPath().getString("ErrorResponse.Error.Message"), startsWith(prefix)); + + given().contentType("application/x-www-form-urlencoded").header("Authorization", AUTH) + .formParam("Action", "DescribeStackSet").formParam("StackSetName", name) + .when().post("/").then().statusCode(200) + .body("DescribeStackSetResponse.DescribeStackSetResult.StackSet.TemplateBody", equalTo(good)); + given().contentType("application/x-www-form-urlencoded").header("Authorization", AUTH) + .formParam("Action", "DeleteStackSet").formParam("StackSetName", name) + .when().post("/").then().statusCode(200); + } + + /** Measured: a template URL whose object or bucket does not exist, alike for the three calls that read one. */ + @Test + void aTemplateUrlOfNothingIsRefused() { + String bucket = "cfn-null-tpl-" + System.nanoTime(); + given().header("Authorization", AUTH.replace("cloudformation", "s3")).when().put("/" + bucket) + .then().statusCode(200); + String missingKey = "S3 object does not exist. Bucket: " + bucket + ", Key: missing.json. Error: NoSuchKey"; + String missingBucket = "S3 error: The specified bucket does not exist\nFor more information check" + + " http://docs.aws.amazon.com/AmazonS3/latest/API/ErrorResponses.html"; + + for (String action : List.of("ValidateTemplate", "CreateStack", "GetTemplateSummary")) { + assertRefused(templateUrl(action, "http://localhost:4566/" + bucket + "/missing.json"), missingKey); + assertRefused(templateUrl(action, "http://localhost:4566/" + bucket + "-gone/t.json"), missingBucket); + } + } + + private static Response templateUrl(String action, String url) { + RequestSpecification request = given().contentType("application/x-www-form-urlencoded") + .header("Authorization", AUTH).formParam("Action", action).formParam("TemplateURL", url); + if ("CreateStack".equals(action)) { + request.formParam("StackName", "cfn-null-url-" + System.nanoTime()); + } + return request.when().post("/"); + } + + private static Response stackSet(String action, String name, String template) { + return given().contentType("application/x-www-form-urlencoded").header("Authorization", AUTH) + .formParam("Action", action).formParam("StackSetName", name).formParam("TemplateBody", template) + .when().post("/"); + } + + private static String queue(String properties) { + return "{\"Resources\": {\"Q\": {\"Type\": \"AWS::SQS::Queue\", \"Properties\": " + properties + "}}}"; + } + + private static Response request(String action, String stackName, String template) { + RequestSpecification request = given().contentType("application/x-www-form-urlencoded").header("Authorization", AUTH) + .formParam("Action", action).formParam("TemplateBody", template); + if (stackName != null) { + request.formParam("StackName", stackName); + } + return request.when().post("/"); + } + + private static void assertRefused(Response response, String message) { + response.then().statusCode(400); + assertEquals("ValidationError", response.xmlPath().getString("ErrorResponse.Error.Code")); + assertEquals(message, response.xmlPath().getString("ErrorResponse.Error.Message")); + } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/CognitoResourceServerCfnIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CognitoResourceServerCfnIntegrationTest.java index d719840692..96eeb570fe 100644 --- a/src/test/java/io/github/hectorvent/floci/services/cloudformation/CognitoResourceServerCfnIntegrationTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CognitoResourceServerCfnIntegrationTest.java @@ -181,11 +181,8 @@ class CognitoResourceServerCfnIntegrationTest { @ValueSource(booleans = {false, true}) void nullScopesFailCreationWithoutCreatingABackingServer(boolean conditional) throws Exception { String pool = createPool(); - cloudFormation("CreateStack", nullScopesTemplate(pool, "Invalid API", conditional)); - createdStack = true; - assertEquals("ROLLBACK_COMPLETE", CfnStackWaits.awaitTerminal(stack).status()); - assertScopeValidationFailure(); + assertNullScopesRefused("CreateStack", nullScopesTemplate(pool, "Invalid API", conditional), conditional); assertServerGone(pool, IDENTIFIER); } @@ -195,9 +192,9 @@ class CognitoResourceServerCfnIntegrationTest { String pool = createPool(); createStack(template(pool, IDENTIFIER, "Original API", "read")); - updateStack(nullScopesTemplate(pool, "Changed API", conditional), "UPDATE_ROLLBACK_COMPLETE"); + assertNullScopesRefused("UpdateStack", nullScopesTemplate(pool, "Changed API", conditional), conditional); - assertScopeValidationFailure(); + assertEquals("CREATE_COMPLETE", CfnStackWaits.awaitTerminal(stack).status()); assertEquals(IDENTIFIER, output("ServerRef")); assertServer(pool, IDENTIFIER, "Original API", "read"); updateStack(template(pool, IDENTIFIER, "Recovered API", "write"), "UPDATE_COMPLETE"); @@ -823,11 +820,14 @@ class CognitoResourceServerCfnIntegrationTest { return template; } - private void assertScopeValidationFailure() { - String events = given().contentType("application/x-www-form-urlencoded") - .header("Authorization", CFN_AUTH).formParam("Action", "DescribeStackEvents") - .formParam("StackName", stack).post("/").then().statusCode(200).extract().asString(); - assertTrue(events.contains("Scopes must be a list")); + /** As on AWS, a template holding a null is refused when the operation is requested. */ + private void assertNullScopesRefused(String action, ObjectNode template, boolean conditional) { + String path = conditional ? "/Resources/Server/Type/Scopes/Fn::If/1" : "/Resources/Server/Type/Scopes"; + given().contentType("application/x-www-form-urlencoded") + .header("Authorization", CFN_AUTH).formParam("Action", action) + .formParam("StackName", stack).formParam("TemplateBody", template.toString()) + .post("/").then().statusCode(400) + .body("ErrorResponse.Error.Message", equalTo("[" + path + "] 'null' values are not allowed in templates")); } private static void addFailingDependentResource(ObjectNode template) {