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
"[<path>] '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.
This commit is contained in:
Alessandro Lattao authored and GitHub committed 2026-10-20 17:13:31 -04:00
1 parent 2c6f2118e8
commit 5fa67625c1
9 files changed
+398 -21

No files matched your search

@@ -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<Arguments> 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"));
}
}
@@ -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) {