fix(cloudformation): merge Fn::Transform AWS::Include before provisioning, and honour GetTemplate TemplateStage (#2886)

* test(cloudformation): pin Fn::Transform AWS::Include merging against the deployed template

The expected values come from a deployed stack's original and processed templates,
read with get-template, and from get-template-summary probes against real AWS.
Every assertion states its expected value as a literal, including the spliced
multi-line Fn::Sub value with its line breaks intact.

* fix(cloudformation): merge Fn::Transform AWS::Include before provisioning

The template engine evaluated ten intrinsics and Fn::Transform was not among them,
so an AWS::Include node was neither expanded nor rejected: it reached provisioning
as an ordinary key. A state machine whose DefinitionSubstitutions came from a
snippet therefore reached CreateStateMachine with a key literally named
Fn::Transform and without any of the snippet's keys, leaving every ${placeholder}
unsubstituted in the stored definition. The stack still reported CREATE_COMPLETE.

Measured against a deployed stack: 41 Fn::Transform nodes in the original template,
all Name AWS::Include, all with the same s3:// Location, all at
Resources.<id>.Properties.DefinitionSubstitutions; 0 in the processed template. At
one of those positions the six sibling keys keep their original order and the five
snippet keys are appended after them, and the spliced multi-line Fn::Sub value keeps
its line breaks: nothing is folded or re-serialized.

Three controlled get-template-summary probes settle the summary contract. A template
with no transform reports DeclaredTransforms null and its ResourceTypes; the same
template with an embedded Fn::Transform, and one with a top-level Transform, both
report DeclaredTransforms AWS::Include. GetTemplate keeps returning the body as
submitted, matching AWS's TemplateStage=Original default, while the change-set
baseline uses the merged body so a byte-identical resubmission reports no change.

* test(cloudformation): pin Fn::Transform AWS::Include rejection when Parameters is absent entirely

* test(cloudformation): pin Fn::Transform AWS::Include rejection when Location is present but blank

* fix(cloudformation): name the Fn::Transform node when AWS::Include Parameters is absent or Location is blank

* test(cfn-transform): pin AWS::Include Location error message for blank and null-Parameters shapes

Renames the existing empty-string test to name the shape it actually feeds,
adds coverage for a whitespace-only Location (which today leaks its raw
value with no quoting) and for an explicit null Parameters (which already
renders the Fn::Transform node, with no test pinning that literal).

* fix(cfn-transform): reject whitespace-only Location and stop leaking non-object Parameters

describeLocation checked isEmpty() where its own javadoc promised blank, so a
whitespace-only Location leaked its raw unquoted value into the rejection
message instead of a quoted string. It also enumerated missing and null as
the only non-mapping Parameters shapes, so a scalar or a list Parameters fell
through to Location's MissingNode and the message rendered Parameters itself
as if it were the rejected Location. Both guards now ask a single question
each: isBlank() for the Location text, and isObject() for the Parameters
shape, dropping the OR out of the second guard.

* test(cfn-transform): pin AWS::Include Location error message for scalar and list Parameters

Closes the coverage gap for defect 2: before the isObject() guard, a scalar
or list Parameters fell through to Location's MissingNode and the rejection
message rendered Parameters itself as if it were the Location, which a
reader could mistake for a valid rejected URI. Both templates go red against
the pre-hunk isMissingNode()||isNull() guard and green against isObject().

* test(cloudformation): pin GetTemplate TemplateStage selecting Processed vs Original

Processed must return the SAM-expanded, AWS::Include-merged body with no
AWS::Serverless::Function or Fn::Transform node left; Original and the
no-stage default must return the caller's raw YAML byte for byte; an
invalid stage must reject with the AWS enum ValidationError; and a plain
stack with no transform must return identical bodies for both stages and
advertise StagesAvailable on every GetTemplate call.

* fix(cloudformation): honor GetTemplate TemplateStage instead of always returning Original

GetTemplate accepted no TemplateStage, so a caller asking for Processed was
silently answered with Original. It now validates the parameter against
AWS's Original/Processed enum, returns stack.templateBody (the SAM- and
AWS::Include-merged body) for Processed and stack.originalTemplateBody
(the caller's raw submission, also the default) otherwise, and reports
StagesAvailable on every response, matching real AWS.

* test(cloudformation): pin GetTemplate TemplateStage validation ordering and empty-string rejection

Pins two AWS-measured behaviors GetTemplate does not have yet: TemplateStage
Bogus is rejected with the enum ValidationError even when the named stack was
never created, proving AWS validates the request shape before the stack
lookup; and TemplateStage="" (present but empty) is rejected the same as any
other value outside the enum, distinct from the omitted case which defaults
to Original.

* fix(cloudformation): validate GetTemplate TemplateStage before the stack lookup and reject an empty value

Two ordering and parsing gaps measured against a real account: an invalid
TemplateStage was rejected with "Stack ... does not exist" instead of the
enum ValidationError when the stack was absent, because the lookup ran
first; and TemplateStage="" (present but empty) was silently accepted as
Original instead of rejected, because isBlank() treated it the same as the
omitted case. Both are hoisted/tightened to match AWS. The two stage names
are also named once as constants instead of retyped across the enum list,
the StagesAvailable list, the stage-selection check and the default, and the
rollback comment and docs are rewritten to describe today's two-stage
behavior instead of the pre-TemplateStage one.

* docs(cloudformation): correct GetTemplate Processed-stage claim, drop a self-evident comment

The GetTemplate doc claimed AWS::LanguageExtensions, a third-party macro, and the
top-level Transform AWS::Include short form always leave Processed unexpanded.
SamTransformProcessor removes the whole Transform section unconditionally when the
template also declares the SAM transform, so any of those three shapes co-declared
with SAM is gone from Processed too; the sentence now states that condition.

Also drops the block comment above STAGE_PROCESSED/STAGE_ORIGINAL: it restated what
the constant names already show.

* docs(cloudformation): drop the CAPABILITY_AUTO_EXPAND deviation, measured as parity

A CreateChangeSet carrying an embedded Fn::Transform/AWS::Include was
accepted against a real account with CAPABILITY_IAM alone, so requiring
no capability for AWS::Include matches AWS rather than deviating from
it. The known-deviation count drops from three to two, and the
unmeasured CreateStack path is named as unmeasured.

---------

Co-authored-by: Facundo Paredes <25681464+facuparedes@users.noreply.github.com>
This commit is contained in:
Facundo ParedesandFacundo Paredes authored and GitHub committed 2026-09-01 23:05:26 -05:00
1 parent f2b4c08481
commit 77b4881fe4
7 files changed
+1490 -14

No files matched your search

@@ -0,0 +1,688 @@
package io.github.hectorvent.floci.services.cloudformation;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.github.hectorvent.floci.services.s3.S3Service;
import io.github.hectorvent.floci.testing.RestAssuredJsonUtils;
import io.quarkus.test.junit.QuarkusTest;
import jakarta.inject.Inject;
import org.jboss.logging.Logger;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import static io.restassured.RestAssured.given;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.not;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
/**
* The deployed outcome of {@code Fn::Transform}/{@code AWS::Include}: a {@code
* DefinitionSubstitutions} mapping written as an include reaches the state machine's actual
* definition, closing the symptom in "Request": 23 of 67 state machines in one repository
* deploying with a literal {@code ${expandItems}}. The state machine is declared as
* {@code AWS::StepFunctions::StateMachine}, not the SAM {@code AWS::Serverless::StateMachine} form
* ({@code fix/sam-serverless-statemachine}'s subject); this test does not depend on that transform.
*/
@QuarkusTest
class AwsIncludeIntegrationTest {
private static final Logger LOG = Logger.getLogger(AwsIncludeIntegrationTest.class);
private static final String SFN_CONTENT_TYPE = "application/x-amz-json-1.0";
@Inject
S3Service s3Service;
private final ObjectMapper mapper = new ObjectMapper();
private final List<String> stacksToDelete = new ArrayList<>();
private final Map<String, List<String>> objectsToDelete = new LinkedHashMap<>();
@BeforeAll
static void configureRestAssured() {
RestAssuredJsonUtils.configureAwsContentTypes();
}
@AfterEach
void cleanUp() {
for (String stackName : stacksToDelete) {
given()
.contentType("application/x-www-form-urlencoded")
.formParam("Action", "DeleteStack")
.formParam("StackName", stackName)
.when()
.post("/");
}
stacksToDelete.clear();
objectsToDelete.forEach((bucket, keys) -> {
try {
for (String key : keys) {
s3Service.deleteObject(bucket, key);
}
s3Service.deleteBucket(bucket);
} catch (RuntimeException e) {
// A bucket that a test (or a resource it provisioned) left with an object this
// test never tracked throws BucketNotEmpty here. Left unguarded, that throw used
// to abort the forEach before objectsToDelete.clear() ran, so the next @AfterEach
// retried the same stale bucket/key pairs on top of its own, cascading one failed
// delete into every test that ran afterward. Catching per-bucket keeps the loop
// going for the buckets that follow and lets clear() below always run.
LOG.warnv(e, "AwsIncludeIntegrationTest cleanup could not remove bucket {0}", bucket);
}
});
objectsToDelete.clear();
}
private String putSnippet(String bucket, String key, String content) {
s3Service.createBucket(bucket, "us-east-1");
s3Service.putObject(bucket, key, content.getBytes(StandardCharsets.UTF_8), "text/yaml", Map.of());
objectsToDelete.computeIfAbsent(bucket, b -> new ArrayList<>()).add(key);
return "s3://" + bucket + "/" + key;
}
@Test
void includedSubstitutionsReachTheStateMachineDefinition() throws Exception {
String suffix = Long.toString(System.nanoTime(), 36);
String bucket = "aws-include-it-" + suffix;
String key = "definition-substitutions.yaml";
String stackName = "aws-include-stack-" + suffix;
String stateMachineName = "aws-include-sm-" + suffix;
String stateMachineArn = "arn:aws:states:us-east-1:000000000000:stateMachine:" + stateMachineName;
stacksToDelete.add(stackName);
String location = putSnippet(bucket, key, "expandItems: substituted-value\n");
String template = stateMachineTemplate(stateMachineName, location);
given()
.contentType("application/x-www-form-urlencoded")
.formParam("Action", "CreateStack")
.formParam("StackName", stackName)
.formParam("TemplateBody", template)
.when()
.post("/")
.then()
.statusCode(200)
.body(containsString("<StackId>"));
given()
.contentType("application/x-www-form-urlencoded")
.formParam("Action", "DescribeStacks")
.formParam("StackName", stackName)
.when()
.post("/")
.then()
.statusCode(200)
.body(containsString("<StackStatus>CREATE_COMPLETE</StackStatus>"));
String definition = given()
.header("X-Amz-Target", "AWSStepFunctions.DescribeStateMachine")
.contentType(SFN_CONTENT_TYPE)
.body("{\"stateMachineArn\":\"" + stateMachineArn + "\"}")
.when()
.post("/")
.then()
.statusCode(200)
.body("definition", containsString("substituted-value"))
.body("definition", not(containsString("${expandItems}")))
.extract().path("definition");
assertDoesNotThrow(() -> mapper.readTree(definition),
"the deployed definition does not parse as JSON: " + definition);
}
@Test
void stackWithUnreadableSnippetFailsCreation() {
// No bucket is created for this location: AWS::Include fails the same way any other
// unreadable AWS resource reference does, before any resource in the stack is attempted:
// the same class of pre-provisioning failure CloudFormationSsmParameterIntegrationTest pins
// for a missing SSM parameter, and CREATE_FAILED (not a rollback) is what that class of
// failure produces today: CloudFormationService's create-path exception handler sets
// CREATE_FAILED directly, and only a resource that reached the provisioning loop drives the
// ROLLBACK_IN_PROGRESS/ROLLBACK_COMPLETE transition.
String suffix = Long.toString(System.nanoTime(), 36);
String stackName = "aws-include-missing-stack-" + suffix;
String stateMachineName = "aws-include-missing-sm-" + suffix;
String location = "s3://aws-include-it-missing-bucket-" + suffix + "/definition-substitutions.yaml";
stacksToDelete.add(stackName);
String template = stateMachineTemplate(stateMachineName, location);
given()
.contentType("application/x-www-form-urlencoded")
.formParam("Action", "CreateStack")
.formParam("StackName", stackName)
.formParam("TemplateBody", template)
.when()
.post("/")
.then()
.statusCode(200);
given()
.contentType("application/x-www-form-urlencoded")
.formParam("Action", "DescribeStacks")
.formParam("StackName", stackName)
.when()
.post("/")
.then()
.statusCode(200)
.body(containsString("<StackStatus>CREATE_FAILED</StackStatus>"))
.body(containsString(location))
.body(not(containsString("CREATE_COMPLETE")));
String resourcesXml = given()
.contentType("application/x-www-form-urlencoded")
.formParam("Action", "DescribeStackResources")
.formParam("StackName", stackName)
.when()
.post("/")
.then()
.statusCode(200)
.extract().asString();
// The merge fails before the resource loop starts, so the state machine was never attempted:
// it never even reaches CREATE_FAILED as a tracked resource, unlike a resource that fails
// during provisioning itself.
assertThat(resourcesXml, not(containsString("AWS::StepFunctions::StateMachine")));
}
@Test
void getTemplateSummaryDoesNotExpandTheInclude() {
// Same unreachable location as the unhappy path above, but through GetTemplateSummary:
// AWS answers this with the transform declared and the snippet never fetched (measured
// against us-east-1). Reusing the merge seam for GetTemplateSummary would instead fail the
// summary on an unreachable location, which is the receipt this test exists to catch on a
// future refactor.
String suffix = Long.toString(System.nanoTime(), 36);
String stateMachineName = "aws-include-summary-sm-" + suffix;
String location = "s3://aws-include-it-missing-bucket-" + suffix + "/definition-substitutions.yaml";
String template = stateMachineTemplate(stateMachineName, location);
given()
.contentType("application/x-www-form-urlencoded")
.formParam("Action", "GetTemplateSummary")
.formParam("TemplateBody", template)
.when()
.post("/")
.then()
.statusCode(200)
.body(containsString("<member>AWS::StepFunctions::StateMachine</member>"))
// Anchored to the enclosing element, not just to a bare <member>: TemplateSummary
// also renders ResourceTypes and Capabilities as <member> lists, so an unanchored
// containsString cannot tell DeclaredTransforms apart from either of them and would
// stay green even if AWS::Include regressed into the wrong list.
// Measured against us-east-1: AWS reports AWS::Include in DeclaredTransforms for the
// embedded Fn::Transform form too, with no top-level Transform section and no fetch of
// the (here unreachable) snippet.
.body(containsString("<DeclaredTransforms><member>AWS::Include</member></DeclaredTransforms>"));
}
@Test
void getTemplateReturnsTheSubmittedYamlWhileTheChangeSetBaselineStaysMerged() {
// Superseded assertions, and why they were wrong: this test used to assert that GetTemplate
// returned the MERGED body ("merged-value" present, "Fn::Transform" absent). That pinned a
// real fix (a live Fn::Transform node was leaking into the deployed template because the
// re-serialize sat inside the SAM-only branch) but overshot it: real CloudFormation's
// GetTemplate defaults to TemplateStage=Original and returns the template exactly as the
// caller submitted it, not the SAM/Include-expanded form (GetTemplateSummary already reads
// stack.getOriginalTemplateBody() for the same reason). So GetTemplate must return the
// caller's raw YAML, Fn::Transform node and all, while CreateChangeSet's baseline diff
// keeps comparing against the merged body (stack.getTemplateBody()) so a resubmit of the
// identical template still reports zero changes instead of a spurious Modify.
String suffix = Long.toString(System.nanoTime(), 36);
String bucket = "aws-include-it-persist-" + suffix;
String key = "definition-substitutions.yaml";
String stackName = "aws-include-persist-stack-" + suffix;
String parameterName = "/aws-include-it/persist-" + suffix;
stacksToDelete.add(stackName);
String location = putSnippet(bucket, key, "mergedFlag: merged-value\n");
String template = """
Resources:
IncludeParam:
Type: AWS::SSM::Parameter
Metadata:
Fn::Transform:
Name: AWS::Include
Parameters:
Location: %s
Properties:
Name: %s
Type: String
Value: unmerged-value
""".formatted(location, parameterName);
given()
.contentType("application/x-www-form-urlencoded")
.formParam("Action", "CreateStack")
.formParam("StackName", stackName)
.formParam("TemplateBody", template)
.when()
.post("/")
.then()
.statusCode(200);
given()
.contentType("application/x-www-form-urlencoded")
.formParam("Action", "DescribeStacks")
.formParam("StackName", stackName)
.when()
.post("/")
.then()
.statusCode(200)
.body(containsString("<StackStatus>CREATE_COMPLETE</StackStatus>"));
given()
.contentType("application/x-www-form-urlencoded")
.formParam("Action", "GetTemplate")
.formParam("StackName", stackName)
.when()
.post("/")
.then()
.statusCode(200)
// The submitted YAML, verbatim: the Fn::Transform node survives (Original stage, not
// merged) and the YAML key syntax ("Value: unmerged-value", no quotes around either
// side) rules out a reserialized JSON pretty-print of the merged tree. "mergedFlag" is
// the snippet's own key, so its presence would mean the merge ran despite Original.
.body(containsString("Fn::Transform"))
.body(containsString("Value: unmerged-value"))
.body(not(containsString("mergedFlag")));
given()
.contentType("application/x-www-form-urlencoded")
.formParam("Action", "CreateChangeSet")
.formParam("StackName", stackName)
.formParam("ChangeSetName", "identical-resubmit-cs")
.formParam("ChangeSetType", "UPDATE")
.formParam("TemplateBody", template)
.when()
.post("/")
.then()
.statusCode(200);
given()
.contentType("application/x-www-form-urlencoded")
.formParam("Action", "DescribeChangeSet")
.formParam("StackName", stackName)
.formParam("ChangeSetName", "identical-resubmit-cs")
.when()
.post("/")
.then()
.statusCode(200)
// The baseline diff still uses the merged body (stack.getTemplateBody(), untouched by
// this fix): resubmitting the identical template must not report a spurious Modify.
.body(not(containsString("<Action>Modify</Action>")));
}
@Test
void getTemplateStageSelectsBetweenTheMergedBodyAndTheSubmittedBody() {
// One stack carrying both a SAM resource and an embedded AWS::Include, so TemplateStage
// exercises both processors at once: Processed is the merged/SAM-expanded body
// (stack.getTemplateBody()) with AWS::Serverless::Function expanded away and the include
// merged in, Original is the caller's raw YAML (stack.getOriginalTemplateBody()), and no
// TemplateStage at all still defaults to Original, byte for byte.
String suffix = Long.toString(System.nanoTime(), 36);
String bucket = "aws-include-it-stage-" + suffix;
String key = "stage-definition.yaml";
String stackName = "aws-include-stage-stack-" + suffix;
String functionName = "aws-include-stage-func-" + suffix;
String parameterName = "/aws-include-it/stage-" + suffix;
stacksToDelete.add(stackName);
String location = putSnippet(bucket, key, "mergedFlag: merged-value\n");
String template = """
AWSTemplateFormatVersion: '2010-09-09'
Transform: AWS::Serverless-2016-10-31
Resources:
StageFunction:
Type: AWS::Serverless::Function
Properties:
FunctionName: %s
Handler: index.handler
Runtime: nodejs22.x
InlineCode: |
exports.handler = async () => ({ statusCode: 200, body: 'ok' });
IncludeParam:
Type: AWS::SSM::Parameter
Metadata:
Fn::Transform:
Name: AWS::Include
Parameters:
Location: %s
Properties:
Name: %s
Type: String
Value: unmerged-value
""".formatted(functionName, location, parameterName);
given()
.contentType("application/x-www-form-urlencoded")
.formParam("Action", "CreateStack")
.formParam("StackName", stackName)
.formParam("TemplateBody", template)
.formParam("Capabilities.member.1", "CAPABILITY_IAM")
.when()
.post("/")
.then()
.statusCode(200);
given()
.contentType("application/x-www-form-urlencoded")
.formParam("Action", "DescribeStacks")
.formParam("StackName", stackName)
.when()
.post("/")
.then()
.statusCode(200)
.body(containsString("<StackStatus>CREATE_COMPLETE</StackStatus>"));
given()
.contentType("application/x-www-form-urlencoded")
.formParam("Action", "GetTemplate")
.formParam("StackName", stackName)
.formParam("TemplateStage", "Processed")
.when()
.post("/")
.then()
.statusCode(200)
.body(containsString("AWS::Lambda::Function"))
.body(containsString("mergedFlag"))
.body(not(containsString("AWS::Serverless::Function")))
.body(not(containsString("Fn::Transform")));
String originalBody = given()
.contentType("application/x-www-form-urlencoded")
.formParam("Action", "GetTemplate")
.formParam("StackName", stackName)
.formParam("TemplateStage", "Original")
.when()
.post("/")
.then()
.statusCode(200)
.body(containsString("AWS::Serverless::Function"))
.body(containsString("Fn::Transform"))
.body(not(containsString("mergedFlag")))
.extract().path("GetTemplateResponse.GetTemplateResult.TemplateBody");
String defaultStageBody = given()
.contentType("application/x-www-form-urlencoded")
.formParam("Action", "GetTemplate")
.formParam("StackName", stackName)
.when()
.post("/")
.then()
.statusCode(200)
.extract().path("GetTemplateResponse.GetTemplateResult.TemplateBody");
assertThat(defaultStageBody, equalTo(originalBody));
}
@Test
void getTemplateWithInvalidStageRejectsWithTheAwsEnumValidationError() {
// Verbatim against real AWS (measured on us-east-1): an invalid TemplateStage value is
// rejected with ValidationError naming the enum, on any existing stack.
String suffix = Long.toString(System.nanoTime(), 36);
String stackName = "aws-include-stage-bogus-stack-" + suffix;
String parameterName = "/aws-include-it/stage-bogus-" + suffix;
stacksToDelete.add(stackName);
String template = """
Resources:
BogusStageParam:
Type: AWS::SSM::Parameter
Properties:
Name: %s
Type: String
Value: plain-value
""".formatted(parameterName);
given()
.contentType("application/x-www-form-urlencoded")
.formParam("Action", "CreateStack")
.formParam("StackName", stackName)
.formParam("TemplateBody", template)
.when()
.post("/")
.then()
.statusCode(200);
given()
.contentType("application/x-www-form-urlencoded")
.formParam("Action", "GetTemplate")
.formParam("StackName", stackName)
.formParam("TemplateStage", "Bogus")
.when()
.post("/")
.then()
.statusCode(400)
.body(containsString("<Code>ValidationError</Code>"))
.body(containsString("Value &apos;Bogus&apos; at &apos;templateStage&apos; failed to satisfy "
+ "constraint: Member must satisfy enum value set: [Processed, Original]"));
}
@Test
void getTemplateWithInvalidStageValidatesBeforeCheckingWhetherTheStackExists() {
// Verbatim against real AWS (measured on us-east-1): `--template-stage Bogus` against a
// stack name that was never created still answers with the enum ValidationError, not
// "Stack with id ... does not exist", proving AWS validates the request shape before it
// looks the stack up. This stack name is never created here, on purpose: a test that
// creates the stack first (like the one above) cannot tell this ordering apart from
// floci validating after a successful lookup.
String suffix = Long.toString(System.nanoTime(), 36);
String stackName = "aws-include-stage-bogus-no-stack-" + suffix;
given()
.contentType("application/x-www-form-urlencoded")
.formParam("Action", "GetTemplate")
.formParam("StackName", stackName)
.formParam("TemplateStage", "Bogus")
.when()
.post("/")
.then()
.statusCode(400)
.body(containsString("<Code>ValidationError</Code>"))
.body(containsString("Value &apos;Bogus&apos; at &apos;templateStage&apos; failed to satisfy "
+ "constraint: Member must satisfy enum value set: [Processed, Original]"))
.body(not(containsString("does not exist")));
}
@Test
void getTemplateWithEmptyStringStageRejectsWithTheAwsEnumValidationError() {
// Verbatim against real AWS (measured on us-east-1): `--template-stage ""` is rejected the
// same as any other value outside the enum. params.getFirst("TemplateStage") returns "" for
// this request, distinct from the omitted case (null), which defaults to Original.
String suffix = Long.toString(System.nanoTime(), 36);
String stackName = "aws-include-stage-empty-stack-" + suffix;
String parameterName = "/aws-include-it/stage-empty-" + suffix;
stacksToDelete.add(stackName);
String template = """
Resources:
EmptyStageParam:
Type: AWS::SSM::Parameter
Properties:
Name: %s
Type: String
Value: plain-value
""".formatted(parameterName);
given()
.contentType("application/x-www-form-urlencoded")
.formParam("Action", "CreateStack")
.formParam("StackName", stackName)
.formParam("TemplateBody", template)
.when()
.post("/")
.then()
.statusCode(200);
given()
.contentType("application/x-www-form-urlencoded")
.formParam("Action", "GetTemplate")
.formParam("StackName", stackName)
.formParam("TemplateStage", "")
.when()
.post("/")
.then()
.statusCode(400)
.body(containsString("<Code>ValidationError</Code>"))
.body(containsString("Value &apos;&apos; at &apos;templateStage&apos; failed to satisfy "
+ "constraint: Member must satisfy enum value set: [Processed, Original]"));
}
@Test
void getTemplateOnAPlainStackReturnsIdenticalBodiesAcrossStagesAndAdvertisesBothInStagesAvailable() {
// No transform at all: real AWS still accepts TemplateStage on a plain stack and returns
// the identical body for both stages (measured md5-identical on us-east-1), and
// StagesAvailable lists both stages on every GetTemplate call, including one with no
// stage requested, which floci never returned before this change.
String suffix = Long.toString(System.nanoTime(), 36);
String stackName = "aws-include-stage-plain-stack-" + suffix;
String parameterName = "/aws-include-it/stage-plain-" + suffix;
stacksToDelete.add(stackName);
String template = """
Resources:
PlainStageParam:
Type: AWS::SSM::Parameter
Properties:
Name: %s
Type: String
Value: plain-value
""".formatted(parameterName);
given()
.contentType("application/x-www-form-urlencoded")
.formParam("Action", "CreateStack")
.formParam("StackName", stackName)
.formParam("TemplateBody", template)
.when()
.post("/")
.then()
.statusCode(200);
String processedBody = given()
.contentType("application/x-www-form-urlencoded")
.formParam("Action", "GetTemplate")
.formParam("StackName", stackName)
.formParam("TemplateStage", "Processed")
.when()
.post("/")
.then()
.statusCode(200)
.extract().path("GetTemplateResponse.GetTemplateResult.TemplateBody");
given()
.contentType("application/x-www-form-urlencoded")
.formParam("Action", "GetTemplate")
.formParam("StackName", stackName)
.when()
.post("/")
.then()
.statusCode(200)
.body("GetTemplateResponse.GetTemplateResult.TemplateBody", equalTo(processedBody))
.body(containsString(
"<StagesAvailable><member>Original</member><member>Processed</member></StagesAvailable>"));
}
@Test
void conditionsFromTheIncludedSnippetReachProvisioningInsteadOfBeingRejected() {
// validateConditionDependencies used to preflight the RAW, unmerged body: a Conditions
// section spliced in from a snippet was invisible there, so a resource conditioned on it
// defaulted to excluded and a dependent resource failed CreateStack synchronously with a
// spurious "Unresolved resource dependencies" error, even though the merge that runs later
// in executeTemplate would have resolved the condition to true.
String suffix = Long.toString(System.nanoTime(), 36);
String bucket = "aws-include-it-cond-" + suffix;
String key = "conditions.yaml";
String stackName = "aws-include-cond-stack-" + suffix;
String conditionedParamName = "/aws-include-it/conditioned-" + suffix;
String dependentParamName = "/aws-include-it/dependent-" + suffix;
stacksToDelete.add(stackName);
String location = putSnippet(bucket, key, "Conditions:\n FeatureEnabled: true\n");
String template = """
Fn::Transform:
Name: AWS::Include
Parameters:
Location: %s
Resources:
ConditionedParam:
Type: AWS::SSM::Parameter
Condition: FeatureEnabled
Properties:
Name: %s
Type: String
Value: conditioned-value
DependentParam:
Type: AWS::SSM::Parameter
DependsOn: ConditionedParam
Properties:
Name: %s
Type: String
Value: dependent-value
""".formatted(location, conditionedParamName, dependentParamName);
given()
.contentType("application/x-www-form-urlencoded")
.formParam("Action", "CreateStack")
.formParam("StackName", stackName)
.formParam("TemplateBody", template)
.when()
.post("/")
.then()
.statusCode(200);
given()
.contentType("application/x-www-form-urlencoded")
.formParam("Action", "DescribeStacks")
.formParam("StackName", stackName)
.when()
.post("/")
.then()
.statusCode(200)
.body(containsString("<StackStatus>CREATE_COMPLETE</StackStatus>"))
.body(not(containsString("Unresolved resource dependencies")));
given()
.contentType("application/x-www-form-urlencoded")
.formParam("Action", "DescribeStackResources")
.formParam("StackName", stackName)
.when()
.post("/")
.then()
.statusCode(200)
.body(containsString("<LogicalResourceId>ConditionedParam</LogicalResourceId>"))
.body(containsString("<LogicalResourceId>DependentParam</LogicalResourceId>"));
}
private static String stateMachineTemplate(String stateMachineName, String location) {
return """
Resources:
QueryPool:
Type: AWS::StepFunctions::StateMachine
Properties:
StateMachineName: %s
RoleArn: arn:aws:iam::000000000000:role/aws-include-it-role
DefinitionString: |-
{"StartAt":"Done","States":{"Done":{"Type":"Pass","Result":"${expandItems}","End":true}}}
DefinitionSubstitutions:
Fn::Transform:
Name: AWS::Include
Parameters:
Location: %s
""".formatted(stateMachineName, location);
}
}
@@ -0,0 +1,460 @@
package io.github.hectorvent.floci.services.cloudformation;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.services.s3.S3Service;
import io.github.hectorvent.floci.services.s3.model.S3Object;
import org.junit.jupiter.api.Test;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotSame;
import static org.junit.jupiter.api.Assertions.assertSame;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
/**
* {@code Fn::Transform} with {@code Name: AWS::Include} splices the S3 snippet a
* {@code DefinitionSubstitutions} mapping points at into the template before any other intrinsic
* resolves, so the fragment's keys land in the enclosing mapping and {@code Fn::Transform} itself
* does not survive into it. {@code Location} accepts only an {@code s3://} URI: the template
* CloudFormation itself receives always carries one, because {@code aws cloudformation package}
* rewrites every local path before a stack ever sees it.
*/
class AwsIncludeProcessorTest {
private static final String BUCKET = "cfn-snippets";
private static final String KEY = "substitutions.yaml";
private static final String LOCATION = "s3://" + BUCKET + "/" + KEY;
private static final Path FRAGMENT_PATH =
Path.of("src/test/resources/cloudformation/aws-include/definition-substitutions.yaml");
// The exact value SnakeYAML 2.6 parses out of the fragment's folded (>-) block scalar: three
// line breaks preserved, because its continuation lines are more indented than the first, and
// AWS::Include's merge does not fold them (it splices the parsed node, unmodified).
private static final String EXPAND_ITEMS =
"{% (\n"
+ " $c := function($v) { $exists($v.S) ? $v.S : $exists($v.N) ? $number($v.N) : $v };\n"
+ " $map($states.result.Items, function($i) { $merge($map($keys($i), function($k) { {$k: $c($lookup($i, $k))} })) })\n"
+ ") %}";
private final ObjectMapper mapper = new ObjectMapper();
private final S3Service s3Service = mock(S3Service.class);
private final AwsIncludeProcessor processor = new AwsIncludeProcessor(mapper, s3Service);
private void stubSnippet(String bucket, String key, String content) {
S3Object object = new S3Object();
object.setData(content.getBytes(StandardCharsets.UTF_8));
when(s3Service.getObject(bucket, key)).thenReturn(object);
}
private void stubMeasuredFragment() throws Exception {
stubSnippet(BUCKET, KEY, Files.readString(FRAGMENT_PATH));
}
private static String blockForm() {
return """
Resources:
OrdersStateMachine:
Type: AWS::StepFunctions::StateMachine
Properties:
DefinitionSubstitutions:
Fn::Transform:
Name: AWS::Include
Parameters:
Location: %s
""".formatted(LOCATION);
}
private static String flowForm() {
return """
Resources:
OrdersStateMachine:
Type: AWS::StepFunctions::StateMachine
Properties:
DefinitionSubstitutions:
Fn::Transform: { Name: AWS::Include, Parameters: { Location: %s } }
""".formatted(LOCATION);
}
private JsonNode mergedSubstitutions(String templateYaml) throws Exception {
JsonNode template = new CloudFormationYamlParser(mapper).parse(templateYaml);
JsonNode merged = processor.mergeIncludes(template);
return merged.at("/Resources/OrdersStateMachine/Properties/DefinitionSubstitutions");
}
@Test
void blockFormIncludeMergesSnippetKeysIntoSubstitutions() throws Exception {
stubMeasuredFragment();
JsonNode substitutions = mergedSubstitutions(blockForm());
assertEquals(EXPAND_ITEMS, substitutions.path("expandItems").asText(),
"AWS::Include did not merge the snippet's scalar verbatim; substitutions are " + substitutions);
assertEquals("orders", substitutions.get("orderTableName").asText());
assertFalse(substitutions.has("Fn::Transform"),
"the Fn::Transform node survived the merge");
}
@Test
void flowFormIncludeMergesSnippetKeysIntoSubstitutions() throws Exception {
stubMeasuredFragment();
JsonNode substitutions = mergedSubstitutions(flowForm());
assertEquals(EXPAND_ITEMS, substitutions.path("expandItems").asText(),
"AWS::Include did not merge the snippet's scalar verbatim; substitutions are " + substitutions);
assertEquals("orders", substitutions.get("orderTableName").asText());
assertFalse(substitutions.has("Fn::Transform"),
"the Fn::Transform node survived the merge");
}
@Test
void mergeIncludesReturnsTheSameReferenceWhenTemplateCarriesNoInclude() throws Exception {
JsonNode template = new CloudFormationYamlParser(mapper).parse("""
Resources:
Bucket:
Type: AWS::S3::Bucket
""");
JsonNode merged = processor.mergeIncludes(template);
// CloudFormationService.executeTemplate tells a real merge apart from a no-op one by
// comparing this return value's reference against the one it passed in; a copy here, even
// an unmodified one, would make every executeTemplate call reserialize the submitted body.
assertSame(template, merged,
"a template with no AWS::Include must come back as the exact same JsonNode instance");
}
@Test
void mergeIncludesReturnsADifferentReferenceWhenTemplateCarriesAnInclude() throws Exception {
stubMeasuredFragment();
JsonNode template = new CloudFormationYamlParser(mapper).parse(blockForm());
JsonNode merged = processor.mergeIncludes(template);
assertNotSame(template, merged,
"a template whose Fn::Transform/AWS::Include was actually merged must not come back "
+ "as the caller's own unmodified reference");
}
@Test
void includeKeepsSiblingKeysOfTheTransformAndAppendsSnippetKeysAfterThem() throws Exception {
stubMeasuredFragment();
String template = """
Resources:
OrdersStateMachine:
Type: AWS::StepFunctions::StateMachine
Properties:
DefinitionSubstitutions:
alreadyWrittenKey: alreadyWrittenValue
Fn::Transform:
Name: AWS::Include
Parameters:
Location: %s
""".formatted(LOCATION);
JsonNode substitutions = mergedSubstitutions(template);
assertEquals("alreadyWrittenValue", substitutions.get("alreadyWrittenKey").asText(),
"a key already written beside Fn::Transform did not survive the merge");
assertEquals(EXPAND_ITEMS, substitutions.path("expandItems").asText());
assertEquals("orders", substitutions.get("orderTableName").asText());
// Matches the shape read back from a deployed stack's processed template:
// the sibling keys already written beside Fn::Transform keep their original order, and the
// snippet's own keys are appended after them, not interleaved or reordered.
List<String> fieldOrder = new ArrayList<>();
substitutions.fieldNames().forEachRemaining(fieldOrder::add);
assertEquals(List.of("alreadyWrittenKey", "expandItems", "orderTableName"), fieldOrder,
"sibling keys must precede the snippet's keys, both in their original order: " + fieldOrder);
}
@Test
void includeWithNonS3LocationIsRejected() {
String blockFormLocalPath = """
Resources:
OrdersStateMachine:
Type: AWS::StepFunctions::StateMachine
Properties:
DefinitionSubstitutions:
Fn::Transform:
Name: AWS::Include
Parameters:
Location: ./src/shared/substitutions.yaml
""";
AwsException relative = assertThrows(AwsException.class,
() -> mergedSubstitutions(blockFormLocalPath));
assertTrue(relative.getMessage().contains("./src/shared/substitutions.yaml"),
"message does not name the rejected location: " + relative.getMessage());
String blockFormBareName = """
Resources:
OrdersStateMachine:
Type: AWS::StepFunctions::StateMachine
Properties:
DefinitionSubstitutions:
Fn::Transform:
Name: AWS::Include
Parameters:
Location: swagger.yaml
""";
AwsException bare = assertThrows(AwsException.class,
() -> mergedSubstitutions(blockFormBareName));
assertTrue(bare.getMessage().contains("swagger.yaml"),
"message does not name the rejected location: " + bare.getMessage());
}
@Test
void locationAsAMappingNamesTheNodeInTheRejectionMessage() {
// Location: {Ref: InputValue} is the form AWS's own Fn::Transform documentation uses in its
// only AWS::Include example. Ref resolution is not implemented; the node must still be named.
String template = """
Resources:
OrdersStateMachine:
Type: AWS::StepFunctions::StateMachine
Properties:
DefinitionSubstitutions:
Fn::Transform:
Name: AWS::Include
Parameters:
Location: { Ref: InputValue }
""";
AwsException e = assertThrows(AwsException.class, () -> mergedSubstitutions(template));
assertTrue(e.getMessage().contains("\"Ref\":\"InputValue\""),
"message does not name the rejected Location node: " + e.getMessage());
}
@Test
void includeWithUnreadableSnippetFailsTheStack() {
when(s3Service.getObject(BUCKET, KEY))
.thenThrow(new AwsException("NoSuchKey", "The specified key does not exist.", 404));
AwsException e = assertThrows(AwsException.class, () -> mergedSubstitutions(blockForm()));
assertTrue(e.getMessage().contains(LOCATION),
"message does not name the unreadable location: " + e.getMessage());
// A well-formed s3:// Location that cannot be read surfaces S3's own error, not a generic
// ValidationError: S3 already reports the precise cause and floci has nothing more specific
// to say.
assertEquals("NoSuchKey", e.getErrorCode());
assertEquals(404, e.getHttpStatus());
}
@Test
void nestedIncludeInsideASnippetIsRejected() {
String innerLocation = "s3://" + BUCKET + "/inner-fragment";
stubSnippet(BUCKET, KEY, """
expandItems:
Fn::Transform:
Name: AWS::Include
Parameters:
Location: %s
""".formatted(innerLocation));
assertThrows(AwsException.class, () -> mergedSubstitutions(blockForm()));
}
@Test
void snippetContainingAForeignTransformIsNotRejected() throws Exception {
// AWS's own considerations bullet is narrow: "You can't use AWS::Include to reference a
// template snippet that also uses AWS::Include." A snippet carrying an unrelated macro under
// Fn::Transform must pass through untouched, not fail the whole merge.
stubSnippet(BUCKET, KEY, """
someResource:
Fn::Transform:
Name: SomeOtherMacro
Parameters:
Foo: bar
orderTableName: orders
""");
JsonNode substitutions = mergedSubstitutions(blockForm());
assertEquals("SomeOtherMacro", substitutions.at("/someResource/Fn::Transform/Name").asText(),
"the foreign transform node did not survive the merge untouched");
assertEquals("bar", substitutions.at("/someResource/Fn::Transform/Parameters/Foo").asText());
assertEquals("orders", substitutions.get("orderTableName").asText());
}
@Test
void missingLocationNamesTheParametersObjectInsteadOfLeavingAnEmptyTail() {
String template = """
Resources:
OrdersStateMachine:
Type: AWS::StepFunctions::StateMachine
Properties:
DefinitionSubstitutions:
Fn::Transform:
Name: AWS::Include
Parameters: {}
""";
AwsException e = assertThrows(AwsException.class, () -> mergedSubstitutions(template));
assertTrue(e.getMessage().endsWith("got {}"),
"an absent Location must name the empty Parameters mapping, not leave an empty tail: "
+ e.getMessage());
}
@Test
void parametersAbsentEntirelyNamesTheTransformNodeInsteadOfLeavingAnEmptyTail() {
String template = """
Resources:
OrdersStateMachine:
Type: AWS::StepFunctions::StateMachine
Properties:
DefinitionSubstitutions:
Fn::Transform:
Name: AWS::Include
""";
AwsException e = assertThrows(AwsException.class, () -> mergedSubstitutions(template));
assertEquals("Fn::Transform AWS::Include Location must be an s3://bucket/key URI, "
+ "got {\"Name\":\"AWS::Include\"}", e.getMessage());
}
@Test
void twoResourcesEachWithTheirOwnFnTransformBothMerge() throws Exception {
// The measured corpus carries 41 Fn::Transform nodes in one template, one per resource's
// own Resources.<id>.Properties.DefinitionSubstitutions - never a single node shared across
// resources. A regression that merges the first one found and stops before walking the
// rest of the template would pass every single-resource test above and still ship broken.
stubMeasuredFragment();
String secondBucket = "second-fragment-bucket";
String secondKey = "second-fragment";
String secondLocation = "s3://" + secondBucket + "/" + secondKey;
stubSnippet(secondBucket, secondKey, "secondOrderTableName: second-orders\n");
String template = """
Resources:
OrdersStateMachine:
Type: AWS::StepFunctions::StateMachine
Properties:
DefinitionSubstitutions:
Fn::Transform:
Name: AWS::Include
Parameters:
Location: %s
InventoryStateMachine:
Type: AWS::StepFunctions::StateMachine
Properties:
DefinitionSubstitutions:
Fn::Transform:
Name: AWS::Include
Parameters:
Location: %s
""".formatted(LOCATION, secondLocation);
JsonNode merged = processor.mergeIncludes(new CloudFormationYamlParser(mapper).parse(template));
JsonNode first = merged.at("/Resources/OrdersStateMachine/Properties/DefinitionSubstitutions");
JsonNode second = merged.at("/Resources/InventoryStateMachine/Properties/DefinitionSubstitutions");
assertEquals("orders", first.path("orderTableName").asText(),
"the first resource's Fn::Transform did not merge; substitutions are " + first);
assertFalse(first.has("Fn::Transform"));
assertEquals("second-orders", second.path("secondOrderTableName").asText(),
"the second resource's Fn::Transform did not merge; a regression that splices the "
+ "first include and stops would leave this unset: substitutions are " + second);
assertFalse(second.has("Fn::Transform"));
}
@Test
void emptyStringLocationRendersItsQuotedEmptyStringInsteadOfLeavingAnEmptyTail() {
String template = """
Resources:
OrdersStateMachine:
Type: AWS::StepFunctions::StateMachine
Properties:
DefinitionSubstitutions:
Fn::Transform:
Name: AWS::Include
Parameters:
Location: ""
""";
AwsException e = assertThrows(AwsException.class, () -> mergedSubstitutions(template));
assertEquals("Fn::Transform AWS::Include Location must be an s3://bucket/key URI, "
+ "got \"\"", e.getMessage());
}
@Test
void whitespaceOnlyLocationRendersItsQuotedStringInsteadOfLeavingAnEmptyTail() {
String template = """
Resources:
OrdersStateMachine:
Type: AWS::StepFunctions::StateMachine
Properties:
DefinitionSubstitutions:
Fn::Transform:
Name: AWS::Include
Parameters:
Location: " "
""";
AwsException e = assertThrows(AwsException.class, () -> mergedSubstitutions(template));
assertEquals("Fn::Transform AWS::Include Location must be an s3://bucket/key URI, "
+ "got \" \"", e.getMessage());
}
@Test
void explicitNullParametersNamesTheTransformNodeInsteadOfLeavingAnEmptyTail() {
String template = """
Resources:
OrdersStateMachine:
Type: AWS::StepFunctions::StateMachine
Properties:
DefinitionSubstitutions:
Fn::Transform:
Name: AWS::Include
Parameters:
""";
AwsException e = assertThrows(AwsException.class, () -> mergedSubstitutions(template));
assertEquals("Fn::Transform AWS::Include Location must be an s3://bucket/key URI, "
+ "got {\"Name\":\"AWS::Include\",\"Parameters\":null}", e.getMessage());
}
@Test
void stringParametersNamesTheTransformNodeInsteadOfLeakingItselfAsTheLocation() {
String template = """
Resources:
OrdersStateMachine:
Type: AWS::StepFunctions::StateMachine
Properties:
DefinitionSubstitutions:
Fn::Transform:
Name: AWS::Include
Parameters: "s3://b/k"
""";
AwsException e = assertThrows(AwsException.class, () -> mergedSubstitutions(template));
assertEquals("Fn::Transform AWS::Include Location must be an s3://bucket/key URI, "
+ "got {\"Name\":\"AWS::Include\",\"Parameters\":\"s3://b/k\"}", e.getMessage());
}
@Test
void listParametersNamesTheTransformNodeInsteadOfLeakingItselfAsTheLocation() {
String template = """
Resources:
OrdersStateMachine:
Type: AWS::StepFunctions::StateMachine
Properties:
DefinitionSubstitutions:
Fn::Transform:
Name: AWS::Include
Parameters: [1, 2]
""";
AwsException e = assertThrows(AwsException.class, () -> mergedSubstitutions(template));
assertEquals("Fn::Transform AWS::Include Location must be an s3://bucket/key URI, "
+ "got {\"Name\":\"AWS::Include\",\"Parameters\":[1,2]}", e.getMessage());
}
}