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,180 @@
package io.github.hectorvent.floci.services.cloudformation;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.services.s3.S3Service;
import java.nio.charset.StandardCharsets;
import java.util.Iterator;
import java.util.Map;
/**
* Expands {@code Fn::Transform} nodes whose {@code Name} is {@code AWS::Include}: splices the
* YAML/JSON snippet the node's {@code Location} points at into the enclosing mapping, in place of
* the {@code Fn::Transform} key, before any other intrinsic resolves, mirroring
* {@link SamTransformProcessor}, which runs on the same parsed template ahead of provisioning.
*
* <p>{@code Location} accepts only an {@code s3://} URI. The template CloudFormation itself
* receives always carries one: {@code aws cloudformation package} rewrites every local path before
* a stack ever sees it, so a local path never reaches this processor in practice, and floci does
* not read one on the caller's behalf (the CloudFormation package performs no filesystem access,
* and a containerised floci sees none of the caller's paths regardless).
*/
class AwsIncludeProcessor {
static final String AWS_INCLUDE = "AWS::Include";
private static final String FN_TRANSFORM = "Fn::Transform";
private static final String S3_SCHEME = "s3://";
private final ObjectMapper objectMapper;
private final S3Service s3Service;
AwsIncludeProcessor(ObjectMapper objectMapper, S3Service s3Service) {
this.objectMapper = objectMapper;
this.s3Service = s3Service;
}
/**
* Returns a copy of {@code template} with every {@code Fn::Transform}/{@code AWS::Include}
* node replaced by the keys of the snippet it names, merged into the node's enclosing mapping
* alongside any keys already written there.
*
* <p>Reference identity is part of this method's contract, not an incidental optimization: a
* template carrying no {@code AWS::Include} is returned as the exact same {@code JsonNode}
* instance passed in, unmodified, on every {@code executeTemplate} and every
* {@code DescribeChangeSet} - the overwhelming majority of templates. Callers rely on that:
* they compare the reference this method returns against the one they passed in to tell a real
* merge apart from a no-op one, and a copy here even for a no-op merge would make every caller
* treat an untouched template as changed.
*/
JsonNode mergeIncludes(JsonNode template) {
if (!containsAwsInclude(template)) {
return template;
}
JsonNode merged = template.deepCopy();
merge(merged);
return merged;
}
private void merge(JsonNode node) {
if (node.isObject()) {
mergeObject((ObjectNode) node);
} else if (node.isArray()) {
node.forEach(this::merge);
}
}
private void mergeObject(ObjectNode obj) {
JsonNode transform = obj.get(FN_TRANSFORM);
if (transform != null && AWS_INCLUDE.equals(transform.path("Name").asText(""))) {
spliceInclude(obj, transform);
}
// Walk every remaining field, including the snippet's own keys just merged in above:
// spliceInclude already rejects a snippet carrying its own AWS::Include, so revisiting
// them here cannot re-trigger a merge - it only reaches unrelated Fn::Transform nodes
// elsewhere in the template.
Iterator<Map.Entry<String, JsonNode>> fields = obj.fields();
while (fields.hasNext()) {
merge(fields.next().getValue());
}
}
private void spliceInclude(ObjectNode obj, JsonNode transform) {
String location = describeLocation(transform);
S3Location s3Location = parseS3Location(location);
JsonNode snippet = fetchSnippet(s3Location, location);
if (!snippet.isObject()) {
throw new AwsException("ValidationError",
"AWS::Include snippet at " + location + " must be a YAML/JSON mapping", 400);
}
if (containsAwsInclude(snippet)) {
throw new AwsException("ValidationError",
"AWS::Include snippet at " + location + " may not itself use AWS::Include", 400);
}
obj.remove(FN_TRANSFORM);
obj.setAll((ObjectNode) snippet);
}
/**
* Renders {@code transform.Parameters.Location} for an error message. A well-formed
* {@code Location} is a plain string, but a node such as {@code {Ref: InputValue}}, the form
* AWS's own {@code Fn::Transform} documentation uses in its {@code AWS::Include} example, is a
* mapping. {@code Ref} resolution is not implemented here, so that mapping is serialized
* instead, and the rejection message names it. A {@code Parameters} that is not an object
* (missing, explicitly {@code null}, a scalar, or a list) names the whole {@code Fn::Transform}
* node instead, so the message never presents an unrelated value as the rejected
* {@code Location}. A {@code Location} missing from an object {@code Parameters} names the
* enclosing {@code Parameters} mapping. A {@code Location} present but blank, including
* whitespace only, is rendered as its quoted string, not elided, so the message never leaves an
* empty tail.
*/
private String describeLocation(JsonNode transform) {
JsonNode parameters = transform.path("Parameters");
if (!parameters.isObject()) {
return transform.toString();
}
JsonNode locationNode = parameters.path("Location");
if (locationNode.isTextual() && !locationNode.asText().isBlank()) {
return locationNode.asText();
}
JsonNode described = locationNode.isMissingNode() || locationNode.isNull() ? parameters : locationNode;
return described.toString();
}
/**
* Returns whether {@code node} contains an unexpanded {@code Fn::Transform} whose {@code Name}
* is {@code AWS::Include}, at any depth. A foreign macro under a different {@code Name} does not
* count: AWS documents that a snippet may not itself use {@code AWS::Include}, not that it may
* carry no other transform. Package-private: also used by {@code CloudFormationService} to
* report {@code AWS::Include} in {@code GetTemplateSummary}'s {@code DeclaredTransforms} and to
* skip {@code validateConditionDependencies} for a template the merge has not run against yet.
*/
boolean containsAwsInclude(JsonNode node) {
if (node.isObject()) {
JsonNode transform = node.get(FN_TRANSFORM);
if (transform != null && AWS_INCLUDE.equals(transform.path("Name").asText(""))) {
return true;
}
}
if (node.isContainerNode()) {
for (JsonNode child : node) {
if (containsAwsInclude(child)) {
return true;
}
}
}
return false;
}
private JsonNode fetchSnippet(S3Location location, String rawLocation) {
try {
byte[] data = s3Service.getObject(location.bucket(), location.key()).getData();
return new CloudFormationYamlParser(objectMapper).parse(new String(data, StandardCharsets.UTF_8));
} catch (AwsException e) {
throw new AwsException(e.getErrorCode(),
"Unable to read AWS::Include snippet at " + rawLocation + ": " + e.getMessage(),
e.getHttpStatus());
} catch (Exception e) {
throw new AwsException("ValidationError",
"Unable to read AWS::Include snippet at " + rawLocation + ": " + e.getMessage(), 400);
}
}
private record S3Location(String bucket, String key) {}
private S3Location parseS3Location(String location) {
if (location.startsWith(S3_SCHEME)) {
String withoutScheme = location.substring(S3_SCHEME.length());
int slash = withoutScheme.indexOf('/');
if (slash > 0 && slash < withoutScheme.length() - 1) {
return new S3Location(withoutScheme.substring(0, slash), withoutScheme.substring(slash + 1));
}
}
throw new AwsException("ValidationError",
"Fn::Transform AWS::Include Location must be an s3://bucket/key URI, got " + location, 400);
}
}
@@ -443,17 +443,24 @@ public class CloudFormationQueryHandler {
private Response getTemplate(MultivaluedMap<String, String> params, String region) {
String stackName = params.getFirst("StackName");
String templateStage = params.getFirst("TemplateStage");
try {
String template = cfnService.getTemplate(stackName, region);
String xml = new XmlBuilder()
String template = cfnService.getTemplate(stackName, templateStage, region);
var xml = new XmlBuilder()
.start("GetTemplateResponse", CF_NS)
.start("GetTemplateResult")
.elem("TemplateBody", template)
.end("GetTemplateResult")
.raw(AwsQueryResponse.responseMetadata())
.end("GetTemplateResponse")
.build();
return Response.ok(xml).type("text/xml").build();
.elem("TemplateBody", template);
xml.start("StagesAvailable");
for (String stage : cfnService.templateStagesAvailable()) {
xml.elem("member", stage);
}
xml.end("StagesAvailable");
xml.end("GetTemplateResult")
.raw(AwsQueryResponse.responseMetadata())
.end("GetTemplateResponse");
return Response.ok(xml.build()).type("text/xml").build();
} catch (AwsException e) {
return xmlError(e.getErrorCode(), e.getMessage(), e.getHttpStatus());
}
@@ -68,6 +68,7 @@ public class CloudFormationService implements ResourceProvider {
private final EmulatorConfig config;
private final RegionResolver regionResolver;
private final SamTransformProcessor samTransformProcessor;
private final AwsIncludeProcessor awsIncludeProcessor;
private final Clock clock;
// Persisted state so stacks survive a restart (criteria #10, #11). The in-memory maps above are
@@ -90,6 +91,7 @@ public class CloudFormationService implements ResourceProvider {
this.config = config;
this.regionResolver = regionResolver;
this.samTransformProcessor = new SamTransformProcessor(objectMapper);
this.awsIncludeProcessor = new AwsIncludeProcessor(objectMapper, s3Service);
this.clock = clock;
this.storageAccount = config.defaultAccountId();
this.stackBackend = storageFactory.create(
@@ -386,6 +388,9 @@ public class CloudFormationService implements ResourceProvider {
Stack stack = getStackOrThrow(cs.getStackName(), region);
try {
JsonNode newTemplate = parseTemplate(cs.getTemplateBody());
// Merge Fn::Transform/AWS::Include snippets before SAM expansion, matching AWS order:
// an included fragment may itself carry SAM resources.
newTemplate = awsIncludeProcessor.mergeIncludes(newTemplate);
if (samTransformProcessor.hasSamTransform(newTemplate)) {
// The deployed stack's template is always the SAM-expanded form (see
// executeTemplate); comparing the change set's raw SAM source against it would
@@ -674,9 +679,50 @@ public class CloudFormationService implements ResourceProvider {
// ── GetTemplate ───────────────────────────────────────────────────────────
public String getTemplate(String stackName, String region) {
private static final String STAGE_PROCESSED = "Processed";
private static final String STAGE_ORIGINAL = "Original";
// AWS's own enum order for the ValidationError message (measured against a real account).
private static final List<String> TEMPLATE_STAGE_ENUM = List.of(STAGE_PROCESSED, STAGE_ORIGINAL);
// AWS's own StagesAvailable order (Original first), which every GetTemplate call reports.
private static final List<String> TEMPLATE_STAGES_AVAILABLE = List.of(STAGE_ORIGINAL, STAGE_PROCESSED);
public String getTemplate(String stackName, String templateStage, String region) {
// AWS validates TemplateStage before it looks the stack up (measured against a real
// account: an invalid stage is rejected the same way whether or not the stack exists), so
// this must run before getStackOrThrow.
String stage = validateTemplateStage(templateStage);
Stack stack = getStackOrThrow(stackName, region);
return stack.getTemplateBody() != null ? stack.getTemplateBody() : "{}";
// Processed is the SAM/AWS::Include-expanded form templateBody holds after executeTemplate.
// Original (also the default, matching real AWS) is the template exactly as the caller
// submitted it. originalTemplateBody is only absent for stacks persisted by a floci version
// predating this field, hence the fallback to templateBody; getTemplateSummary reads the
// same field for the same reason.
String body = STAGE_PROCESSED.equals(stage) ? stack.getTemplateBody() : stack.getOriginalTemplateBody();
if (body == null) {
body = stack.getTemplateBody();
}
return body != null ? body : "{}";
}
private String validateTemplateStage(String templateStage) {
// null means the caller omitted TemplateStage; "" means the caller sent it present and
// empty. AWS rejects the latter (measured against a real account) and only defaults the
// former, so this must not treat blank the same as absent.
if (templateStage == null) {
return STAGE_ORIGINAL;
}
if (!TEMPLATE_STAGE_ENUM.contains(templateStage)) {
throw new AwsException("ValidationError",
"1 validation error detected: Value '" + templateStage + "' at 'templateStage' failed to "
+ "satisfy constraint: Member must satisfy enum value set: ["
+ String.join(", ", TEMPLATE_STAGE_ENUM) + "]", 400);
}
return templateStage;
}
public List<String> templateStagesAvailable() {
return TEMPLATE_STAGES_AVAILABLE;
}
// ── GetTemplateSummary ────────────────────────────────────────────────────
@@ -780,6 +826,12 @@ public class CloudFormationService implements ResourceProvider {
}
});
}
// AWS reports AWS::Include in DeclaredTransforms for the embedded Fn::Transform form too,
// even with no top-level Transform section (measured against us-east-1).
if (!declaredTransforms.contains(AwsIncludeProcessor.AWS_INCLUDE)
&& awsIncludeProcessor.containsAwsInclude(template)) {
declaredTransforms.add(AwsIncludeProcessor.AWS_INCLUDE);
}
List<String> iamResourceTypes = resourceTypes.stream()
.filter(t -> t.startsWith("AWS::IAM::"))
@@ -931,14 +983,28 @@ public class CloudFormationService implements ResourceProvider {
JsonNode template = parseTemplate(templateBody);
stack.setOriginalTemplateBody(templateBody);
// Merge Fn::Transform/AWS::Include snippets before SAM expansion, matching AWS order:
// an included fragment may itself carry SAM resources. mergeIncludes returns the same
// reference, unchanged, when the template carries no AWS::Include, which is what lets
// the check below tell a real merge apart from a no-op one.
JsonNode beforeInclude = template;
template = awsIncludeProcessor.mergeIncludes(template);
boolean includeMerged = template != beforeInclude;
// Apply SAM transform if the template declares AWS::Serverless-2016-10-31
if (samTransformProcessor.hasSamTransform(template)) {
boolean hasSamTransform = samTransformProcessor.hasSamTransform(template);
if (hasSamTransform) {
LOG.infov("Applying SAM transform for stack {0}", stack.getStackName());
template = samTransformProcessor.expandSamTemplate(template);
// Store the expanded template so GetTemplate returns the transformed version
templateBody = objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(template);
}
// Persist the merged/expanded tree, not the raw submitted body, whenever either
// processor actually changed it, so the change-set baseline diffs against it instead of
// against a stale Fn::Transform node. A template neither processor touched keeps its
// submitted body byte for byte.
if (includeMerged || hasSamTransform) {
templateBody = objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(template);
}
stack.setTemplateBody(templateBody);
// Merge default parameter values from the template with caller-supplied params
@@ -1376,6 +1442,12 @@ public class CloudFormationService implements ResourceProvider {
stack.getResolvedParameters().putAll(previousState.resolvedParameters());
if (rollbackFailures.isEmpty()) {
stack.setTemplateBody(previousState.templateBody());
// GetTemplate reads originalTemplateBody for TemplateStage=Original and templateBody
// for TemplateStage=Processed: without restoring originalTemplateBody here too, a
// rolled-back update would keep serving the failed attempt's submitted body under
// Original even though every other piece of state (resources, parameters, outputs)
// was restored.
stack.setOriginalTemplateBody(previousState.originalTemplateBody());
}
try {
restoreOutputAndExportState(stack, region, previousState);
@@ -1519,6 +1591,7 @@ public class CloudFormationService implements ResourceProvider {
private StackUpdateSnapshot snapshotForUpdate(Stack stack) {
return new StackUpdateSnapshot(
stack.getTemplateBody(),
stack.getOriginalTemplateBody(),
new LinkedHashMap<>(stack.getParameters()),
new LinkedHashMap<>(stack.getResolvedParameters()),
new LinkedHashMap<>(stack.getOutputs()),
@@ -1551,6 +1624,7 @@ public class CloudFormationService implements ResourceProvider {
private record StackUpdateSnapshot(
String templateBody,
String originalTemplateBody,
Map<String, String> parameters,
Map<String, String> resolvedParameters,
Map<String, String> outputs,
@@ -1808,6 +1882,10 @@ public class CloudFormationService implements ResourceProvider {
* template synchronously ("Template format error: Unresolved resource dependencies [...]")
* rather than silently skipping the dependent, so mirror that instead of dropping the resource.
* Malformed or SAM templates are left for the execution path, which surfaces their own errors.
* A template carrying an unexpanded {@code Fn::Transform}/{@code AWS::Include} is left for the
* same reason: a {@code Conditions} section spliced in from a snippet is invisible here, since
* the merge has not run yet, and treating it as absent would fail a template whose dependency
* graph the execution path resolves correctly.
*/
private void validateConditionDependencies(String templateBody, Map<String, String> params,
String region, String accountId) {
@@ -1819,7 +1897,7 @@ public class CloudFormationService implements ResourceProvider {
e.getMessage());
return;
}
if (samTransformProcessor.hasSamTransform(template)) {
if (samTransformProcessor.hasSamTransform(template) || awsIncludeProcessor.containsAwsInclude(template)) {
return;
}
JsonNode resources = template.path("Resources");