From 711b216bad1ef1084308dbb83a66b51cc7e9e17c Mon Sep 17 00:00:00 2001 From: Koushik Dutta Date: Sun, 22 Nov 2026 17:49:49 +0530 Subject: [PATCH] fix(cloudformation): resolve Fn::Sub in AWS::Include Location (#8748) Resolve Fn::Sub (both the string and the [template, variableMap] forms) and Ref in an AWS::Include Location against the stack's pseudo parameters, template parameters, mappings and exports before parsing the S3 URI. An unreadable AWS::SSM::Parameter::Value parameter is left out of what the include sees, so only a Location that uses it is rejected, and DescribeChangeSet still succeeds otherwise. Closes #8667 --- .../cloudformation/AwsIncludeProcessor.java | 88 ++++++++--- .../cloudformation/CloudFormationService.java | 80 ++++++++-- .../CloudFormationTemplateEngine.java | 4 + .../AwsIncludeIntegrationTest.java | 117 +++++++++++++++ .../AwsIncludeProcessorTest.java | 140 +++++++++++++++++- 5 files changed, 395 insertions(+), 34 deletions(-) diff --git a/src/main/java/io/floci/aws/services/cloudformation/AwsIncludeProcessor.java b/src/main/java/io/floci/aws/services/cloudformation/AwsIncludeProcessor.java index 6e332bdc83..4e4fe79246 100644 --- a/src/main/java/io/floci/aws/services/cloudformation/AwsIncludeProcessor.java +++ b/src/main/java/io/floci/aws/services/cloudformation/AwsIncludeProcessor.java @@ -9,6 +9,7 @@ import io.floci.aws.services.s3.S3Service; import java.nio.charset.StandardCharsets; import java.util.Iterator; import java.util.Map; +import java.util.function.Function; /** * Expands {@code Fn::Transform} nodes whose {@code Name} is {@code AWS::Include}: splices the @@ -50,26 +51,45 @@ class AwsIncludeProcessor { * treat an untouched template as changed. */ JsonNode mergeIncludes(JsonNode template) { + return mergeIncludes(template, CloudFormationService.resolveDefaultParameters(template, Map.of()), + "", "", "", "", name -> null); + } + + JsonNode mergeIncludes(JsonNode template, Map parameters, String region, + String accountId, String stackName, String stackId) { + return mergeIncludes(template, parameters, region, accountId, stackName, stackId, name -> null); + } + + JsonNode mergeIncludes(JsonNode template, Map parameters, String region, + String accountId, String stackName, String stackId, + Function importValueResolver) { if (!containsAwsInclude(template)) { return template; } JsonNode merged = template.deepCopy(); - merge(merged); + merge(merged, merged, parameters, region, accountId, stackName, stackId, importValueResolver); return merged; } - private void merge(JsonNode node) { + private void merge(JsonNode node, JsonNode root, Map parameters, + String region, String accountId, String stackName, String stackId, + Function importValueResolver) { if (node.isObject()) { - mergeObject((ObjectNode) node); + mergeObject((ObjectNode) node, root, parameters, region, accountId, stackName, stackId, + importValueResolver); } else if (node.isArray()) { - node.forEach(this::merge); + node.forEach(item -> merge(item, root, parameters, region, accountId, stackName, stackId, + importValueResolver)); } } - private void mergeObject(ObjectNode obj) { + private void mergeObject(ObjectNode obj, JsonNode root, Map parameters, + String region, String accountId, String stackName, String stackId, + Function importValueResolver) { JsonNode transform = obj.get(FN_TRANSFORM); if (transform != null && AWS_INCLUDE.equals(transform.path("Name").asText(""))) { - spliceInclude(obj, transform); + spliceInclude(obj, transform, root, parameters, region, accountId, stackName, stackId, + importValueResolver); } // 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 @@ -77,12 +97,21 @@ class AwsIncludeProcessor { // elsewhere in the template. Iterator> fields = obj.fields(); while (fields.hasNext()) { - merge(fields.next().getValue()); + merge(fields.next().getValue(), root, parameters, region, accountId, stackName, stackId, + importValueResolver); } } - private void spliceInclude(ObjectNode obj, JsonNode transform) { - String location = describeLocation(transform); + private void spliceInclude(ObjectNode obj, JsonNode transform, JsonNode root, + Map parameters, String region, + String accountId, String stackName, String stackId, + Function importValueResolver) { + CloudFormationTemplateEngine engine = new CloudFormationTemplateEngine( + accountId, region, stackName, stackId, + parameters, + Map.of(), Map.of(), Map.of(), CloudFormationService.templateMappings(root), + objectMapper, importValueResolver); + String location = describeLocation(transform, engine); S3Location s3Location = parseS3Location(location); JsonNode snippet = fetchSnippet(s3Location, location); @@ -100,19 +129,18 @@ class AwsIncludeProcessor { } /** - * 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 + * Resolves or renders {@code transform.Parameters.Location}. A well-formed {@code Location} is + * a plain string, a {@code Ref}, or an {@code Fn::Sub} expression. An unresolvable mapping + * (such as a {@code Ref} or {@code Fn::Sub} naming an unknown parameter, or another intrinsic) + * 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) { + private String describeLocation(JsonNode transform, CloudFormationTemplateEngine engine) { JsonNode parameters = transform.path("Parameters"); if (!parameters.isObject()) { return transform.toString(); @@ -121,10 +149,32 @@ class AwsIncludeProcessor { if (locationNode.isTextual() && !locationNode.asText().isBlank()) { return locationNode.asText(); } + if (isResolvableLocation(locationNode)) { + String resolved = engine.resolve(locationNode); + if (!engine.hasUnresolvedIntrinsics() && !resolved.isBlank()) { + return resolved; + } + } JsonNode described = locationNode.isMissingNode() || locationNode.isNull() ? parameters : locationNode; return described.toString(); } + private static boolean isResolvableLocation(JsonNode locationNode) { + if (!locationNode.isObject() || locationNode.size() != 1) { + return false; + } + if (locationNode.has("Ref")) { + JsonNode ref = locationNode.get("Ref"); + return ref.isTextual() && !ref.asText().isBlank(); + } + if (!locationNode.has("Fn::Sub")) { + return false; + } + JsonNode sub = locationNode.get("Fn::Sub"); + return sub.isTextual() + || (sub.isArray() && sub.size() == 2 && sub.get(0).isTextual() && sub.get(1).isObject()); + } + /** * 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 diff --git a/src/main/java/io/floci/aws/services/cloudformation/CloudFormationService.java b/src/main/java/io/floci/aws/services/cloudformation/CloudFormationService.java index 540061ab0e..e9fe1af4ca 100644 --- a/src/main/java/io/floci/aws/services/cloudformation/CloudFormationService.java +++ b/src/main/java/io/floci/aws/services/cloudformation/CloudFormationService.java @@ -679,7 +679,8 @@ public class CloudFormationService implements ResourceProvider { // template declaring the SAM transform, whether or not that transform succeeded, so // gating this call on samTransformFailureReason == null duplicates that check for no // effect. - validateGetStackOutputPlacement(resolvedTemplate); + validateGetStackOutputPlacement(resolvedTemplate, parameters, preflightStackName, preflightStackId, + region, accountId); validateResourceDependencies(resolvedTemplate, parameters, preflightStackName, preflightStackId, region, accountId); @@ -857,7 +858,8 @@ public class CloudFormationService implements ResourceProvider { // Compared as execution stores it: AWS::Include fragments read again and merged, then // the SAM transform applied with the stack's parameter values, which it can resolve // into the expansion. A fragment that changed in S3 is a change. - JsonNode template = awsIncludeProcessor.mergeIncludes(submittedTemplate); + JsonNode template = mergeAwsIncludes(submittedTemplate, given, region, ownerAccount(stack), + stack.getStackName(), stack.getStackId()); if (samTransformProcessor.hasSamTransform(template)) { template = samTransformProcessor.expandSamTemplate(template, samTransformParameters(template, given, region)); @@ -1108,7 +1110,8 @@ public class CloudFormationService implements ResourceProvider { 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); + newTemplate = mergeAwsIncludes(newTemplate, cs.getParameters(), region, accountId, + stack.getStackName(), stack.getStackId()); 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 @@ -1728,7 +1731,7 @@ public class CloudFormationService implements ResourceProvider { Map conditions, JsonNode template) { return new CloudFormationTemplateEngine(accountId, region, stack.getStackName(), stack.getStackId(), params, physicalIds, attributes, conditions, templateMappings(template), objectMapper, - name -> exports.get(accountExportKey(accountId, exportKey(region, name))), value -> value); + exportResolver(accountId, region), value -> value); } } @@ -2811,7 +2814,7 @@ public class CloudFormationService implements ResourceProvider { } } - private Map resolveDefaultParameters(JsonNode template, Map callerParams) { + static Map resolveDefaultParameters(JsonNode template, Map callerParams) { Map resolved = new HashMap<>(callerParams != null ? callerParams : Map.of()); JsonNode paramDefs = template.path("Parameters"); if (paramDefs.isObject()) { @@ -2826,6 +2829,48 @@ public class CloudFormationService implements ResourceProvider { return resolved; } + private JsonNode mergeAwsIncludes(JsonNode template, Map params, String region, + String accountId, String stackName, String stackId) { + if (!awsIncludeProcessor.containsAwsInclude(template)) { + return template; + } + return awsIncludeProcessor.mergeIncludes(template, includeParameters(template, params, region), + region, accountId, stackName, stackId, exportResolver(accountId, region)); + } + + /** + * The parameter values {@code AWS::Include} sees: the given ones over each {@code Default}, with + * readable {@code AWS::SSM::Parameter::Value} parameters read from Parameter Store and + * unreadable ones omitted so an include that does not reference them still expands (for example + * during {@code DescribeChangeSet}) while a {@code Location} that does reference one is rejected + * as unresolved. + */ + private Map includeParameters(JsonNode template, Map params, String region) { + Map resolved = resolveDefaultParameters(template, params); + JsonNode paramDefs = template.path("Parameters"); + if (!paramDefs.isObject()) { + return resolved; + } + paramDefs.fields().forEachRemaining(e -> { + if (!"AWS::SSM::Parameter::Value".equals(e.getValue().path("Type").asText())) { + return; + } + String parameterName = resolved.get(e.getKey()); + if (parameterName == null || parameterName.isBlank()) { + resolved.remove(e.getKey()); + return; + } + try { + resolved.put(e.getKey(), ssmService.getParameter(parameterName, false, region).getValue()); + } catch (AwsException ex) { + LOG.debugv("Omitting unreadable SSM parameter {0} from AWS::Include context: {1}", + e.getKey(), ex.getMessage()); + resolved.remove(e.getKey()); + } + }); + return resolved; + } + /** * The parameter values the SAM transform sees: the given ones over each {@code Default}, with * {@code AWS::SSM::Parameter::Value} parameters already read from Parameter Store, as @@ -2917,7 +2962,8 @@ public class CloudFormationService implements ResourceProvider { // 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); + template = mergeAwsIncludes(template, params, region, accountId, + stack.getStackName(), stack.getStackId()); boolean includeMerged = template != beforeInclude; // Apply SAM transform if the template declares AWS::Serverless-2016-10-31 @@ -3201,7 +3247,7 @@ public class CloudFormationService implements ResourceProvider { CloudFormationTemplateEngine finalEngine = new CloudFormationTemplateEngine( accountId, region, stack.getStackName(), stack.getStackId(), resolvedParams, physicalIds, resourceAttrs, conditions, mappings, objectMapper, - name -> exports.get(accountExportKey(accountId, exportKey(region, name))), + exportResolver(accountId, region), value -> dynamicReferences.resolveDynamicReferences(value, region, false), (name, output, outputRegion, roleArn) -> resolveStackOutput(accountId, name, output, outputRegion, roleArn), @@ -4086,7 +4132,7 @@ public class CloudFormationService implements ResourceProvider { } } - private static Map templateMappings(JsonNode template) { + static Map templateMappings(JsonNode template) { Map mappings = new HashMap<>(); if (template != null) { template.path("Mappings").fields().forEachRemaining(e -> mappings.put(e.getKey(), e.getValue())); @@ -4094,6 +4140,10 @@ public class CloudFormationService implements ResourceProvider { return mappings; } + private Function exportResolver(String accountId, String region) { + return name -> exports.get(accountExportKey(accountId, exportKey(region, name))); + } + /** An engine for one deployment's template: its parameters, conditions, mappings and resource types. */ private CloudFormationTemplateEngine deploymentEngine(Stack stack, String region, String accountId, Map params, Map ids, @@ -4104,7 +4154,7 @@ public class CloudFormationService implements ResourceProvider { return new CloudFormationTemplateEngine( accountId, region, stack.getStackName(), stack.getStackId(), params, ids, attributes, conditions, mappings, objectMapper, - name -> exports.get(accountExportKey(accountId, exportKey(region, name))), + exportResolver(accountId, region), value -> dynamicReferences.resolveDynamicReferences(value, region, false), (name, output, outputRegion, roleArn) -> resolveStackOutput(accountId, name, output, outputRegion, roleArn), @@ -5376,9 +5426,11 @@ public class CloudFormationService implements ResourceProvider { // CreateStack or UpdateStack would, before the child is created or changed: a parameter // without a value, or a Fn::GetStackOutput where the child's template may not hold one // (measured: the Child resource fails with the template error, and the parent rolls back). + String childStackId = childCreate ? newStackId(childStackName, region, accountId) : childStack.getStackId(); try { requireParameterValues(childTemplate, childParams); - validateGetStackOutputPlacement(childTemplate); + validateGetStackOutputPlacement(childTemplate, childParams, childStackName, + childStackId, region, accountId); } catch (AwsException e) { resource.setStatus("CREATE_FAILED"); resource.setStatusReason(e.getMessage()); @@ -5386,7 +5438,7 @@ public class CloudFormationService implements ResourceProvider { } if (childCreate) { - childStack = newStack(childStackName, newStackId(childStackName, region, accountId), region, accountId); + childStack = newStack(childStackName, childStackId, region, accountId); childStack.setParentId(parentStack.getStackId()); childStack.setStatus("CREATE_IN_PROGRESS"); stacks.put(stackKey(accountId, childStackName, region), childStack); @@ -5835,7 +5887,9 @@ public class CloudFormationService implements ResourceProvider { * {@code Export.Name}, neither of which may depend on another stack. A nested stack's template * is checked when the child is created, and the child's resource fails with the same message. */ - private void validateGetStackOutputPlacement(String templateBody) { + private void validateGetStackOutputPlacement(String templateBody, Map params, + String stackName, String stackId, String region, + String accountId) { JsonNode parsed; try { parsed = parseTemplate(templateBody); @@ -5849,7 +5903,7 @@ public class CloudFormationService implements ResourceProvider { JsonNode template; try { // The rules hold for the template as processed: an AWS::Include fragment can carry it. - template = awsIncludeProcessor.mergeIncludes(parsed); + template = mergeAwsIncludes(parsed, params, region, accountId, stackName, stackId); } catch (AwsException e) { // A fragment that cannot be read fails the operation as the transform does, where the // includes are processed; the request itself is not refused for it on AWS. diff --git a/src/main/java/io/floci/aws/services/cloudformation/CloudFormationTemplateEngine.java b/src/main/java/io/floci/aws/services/cloudformation/CloudFormationTemplateEngine.java index fc9bfe7bdf..63f8fa2f3f 100644 --- a/src/main/java/io/floci/aws/services/cloudformation/CloudFormationTemplateEngine.java +++ b/src/main/java/io/floci/aws/services/cloudformation/CloudFormationTemplateEngine.java @@ -481,6 +481,10 @@ public class CloudFormationTemplateEngine { return resolved; } + boolean hasUnresolvedIntrinsics() { + return !unresolvedIntrinsics.isEmpty(); + } + private String resolveRef(String name) { // Pseudo-parameters return switch (name) { diff --git a/src/test/java/io/floci/aws/services/cloudformation/AwsIncludeIntegrationTest.java b/src/test/java/io/floci/aws/services/cloudformation/AwsIncludeIntegrationTest.java index b72f7972ab..acc6cf1bb4 100644 --- a/src/test/java/io/floci/aws/services/cloudformation/AwsIncludeIntegrationTest.java +++ b/src/test/java/io/floci/aws/services/cloudformation/AwsIncludeIntegrationTest.java @@ -674,6 +674,123 @@ class AwsIncludeIntegrationTest { .body(containsString("DependentParam")); } + @Test + void fnSubLocationWithPseudoParameterMergesSnippetOnCreateStack() { + String suffix = Long.toString(System.nanoTime(), 36); + String bucketPrefix = "aws-include-sub-" + suffix; + String bucket = bucketPrefix + "-us-east-1"; + String key = "names.yaml"; + String stackName = "aws-include-sub-stack-" + suffix; + String expectedParamName = "/aws-include-it/sub-" + suffix; + stacksToDelete.add(stackName); + + putSnippet(bucket, key, "Params:\n Name: " + expectedParamName + "\n"); + + String template = """ + { + "Mappings": { + "Names": { + "Fn::Transform": { + "Name": "AWS::Include", + "Parameters": { + "Location": { + "Fn::Sub": "s3://%s-${AWS::Region}/%s" + } + } + } + } + }, + "Resources": { + "IncludedParam": { + "Type": "AWS::SSM::Parameter", + "Properties": { + "Name": { "Fn::FindInMap": ["Names", "Params", "Name"] }, + "Type": "String", + "Value": "from-fn-sub-include" + } + } + } + } + """.formatted(bucketPrefix, key); + + given() + .contentType("application/x-www-form-urlencoded") + .formParam("Action", "CreateStack") + .formParam("StackName", stackName) + .formParam("TemplateBody", template) + .when() + .post("/") + .then() + .statusCode(200) + .body(containsString("")); + + CfnStackWaits.awaitStatus(stackName, "CREATE_COMPLETE"); + given() + .contentType("application/x-www-form-urlencoded") + .formParam("Action", "DescribeStackResources") + .formParam("StackName", stackName) + .when() + .post("/") + .then() + .statusCode(200) + .body(containsString("" + expectedParamName + "")); + } + + @Test + void describeChangeSetWithIncludeToleratesUnrelatedMissingSsmParameter() { + String suffix = Long.toString(System.nanoTime(), 36); + String bucket = "aws-include-cs-ssm-" + suffix; + String key = "meta.yaml"; + String stackName = "aws-include-cs-ssm-stack-" + suffix; + String location = putSnippet(bucket, key, "mergedFlag: merged-value\n"); + stacksToDelete.add(stackName); + + String template = """ + Parameters: + IncludeLocation: + Type: String + Default: %s + MissingSsm: + Type: AWS::SSM::Parameter::Value + Default: /aws-include-it/does-not-exist-%s + Resources: + IncludedParam: + Type: AWS::SSM::Parameter + Metadata: + Fn::Transform: + Name: AWS::Include + Parameters: + Location: !Ref IncludeLocation + Properties: + Name: !Ref MissingSsm + Type: String + Value: preview-value + """.formatted(location, suffix); + + given() + .contentType("application/x-www-form-urlencoded") + .formParam("Action", "CreateChangeSet") + .formParam("StackName", stackName) + .formParam("ChangeSetName", "preview-cs") + .formParam("ChangeSetType", "CREATE") + .formParam("TemplateBody", template) + .when() + .post("/") + .then() + .statusCode(200); + + given() + .contentType("application/x-www-form-urlencoded") + .formParam("Action", "DescribeChangeSet") + .formParam("StackName", stackName) + .formParam("ChangeSetName", "preview-cs") + .when() + .post("/") + .then() + .statusCode(200) + .body(containsString("IncludedParam")); + } + private static String stateMachineTemplate(String stateMachineName, String location) { return """ Resources: diff --git a/src/test/java/io/floci/aws/services/cloudformation/AwsIncludeProcessorTest.java b/src/test/java/io/floci/aws/services/cloudformation/AwsIncludeProcessorTest.java index c61f695533..246200d40c 100644 --- a/src/test/java/io/floci/aws/services/cloudformation/AwsIncludeProcessorTest.java +++ b/src/test/java/io/floci/aws/services/cloudformation/AwsIncludeProcessorTest.java @@ -12,6 +12,8 @@ import java.nio.file.Files; import java.nio.file.Path; import java.util.ArrayList; import java.util.List; +import java.util.Map; +import java.util.function.Function; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; @@ -87,8 +89,16 @@ class AwsIncludeProcessorTest { } private JsonNode mergedSubstitutions(String templateYaml) throws Exception { + return mergedSubstitutions(templateYaml, Map.of(), "us-east-1", "000000000000", "", "", name -> null); + } + + private JsonNode mergedSubstitutions(String templateYaml, Map parameters, + String region, String accountId, String stackName, String stackId, + Function importValueResolver) throws Exception { JsonNode template = new CloudFormationYamlParser(mapper).parse(templateYaml); - JsonNode merged = processor.mergeIncludes(template); + JsonNode merged = processor.mergeIncludes(template, + CloudFormationService.resolveDefaultParameters(template, parameters), + region, accountId, stackName, stackId, importValueResolver); return merged.at("/Resources/OrdersStateMachine/Properties/DefinitionSubstitutions"); } @@ -214,10 +224,136 @@ class AwsIncludeProcessorTest { "message does not name the rejected location: " + bare.getMessage()); } + @Test + void fnSubLocationResolvesPseudoParametersAndTemplateParameters() throws Exception { + stubSnippet("snippets-eu-west-1", "prod/names.yaml", "orderTableName: orders-eu\n"); + String template = """ + Parameters: + Env: + Type: String + Default: dev + Resources: + OrdersStateMachine: + Type: AWS::StepFunctions::StateMachine + Properties: + DefinitionSubstitutions: + Fn::Transform: + Name: AWS::Include + Parameters: + Location: !Sub s3://snippets-${AWS::Region}/${Env}/names.yaml + """; + + JsonNode substitutions = mergedSubstitutions(template, Map.of("Env", "prod"), + "eu-west-1", "123456789012", "orders-stack", + "arn:aws:cloudformation:eu-west-1:123456789012:stack/orders-stack/1", name -> null); + + assertEquals("orders-eu", substitutions.get("orderTableName").asText()); + assertFalse(substitutions.has("Fn::Transform")); + } + + @Test + void fnSubArrayLocationResolvesVariableMapAndDefaultParameters() throws Exception { + stubSnippet("snippets-us-east-1", "custom/names.yaml", "orderTableName: orders-custom\n"); + String template = """ + Parameters: + BucketPrefix: + Type: String + Default: snippets + Resources: + OrdersStateMachine: + Type: AWS::StepFunctions::StateMachine + Properties: + DefinitionSubstitutions: + Fn::Transform: + Name: AWS::Include + Parameters: + Location: + Fn::Sub: + - s3://${BucketPrefix}-${AWS::Region}/${Folder}/names.yaml + - Folder: custom + """; + + JsonNode substitutions = mergedSubstitutions(template); + + assertEquals("orders-custom", substitutions.get("orderTableName").asText()); + assertFalse(substitutions.has("Fn::Transform")); + } + + @Test + void fnSubLocationWithUnresolvedVariableIsRejected() { + String template = """ + Resources: + OrdersStateMachine: + Type: AWS::StepFunctions::StateMachine + Properties: + DefinitionSubstitutions: + Fn::Transform: + Name: AWS::Include + Parameters: + Location: !Sub s3://snippets-${Missing}/names.yaml + """; + + AwsException e = assertThrows(AwsException.class, () -> mergedSubstitutions(template)); + assertTrue(e.getMessage().contains("\"Fn::Sub\":\"s3://snippets-${Missing}/names.yaml\""), + "unresolved Fn::Sub variable must reject the Location node rather than substituting the variable name: " + + e.getMessage()); + } + + @Test + void fnSubLocationWithImportValueResolvesExport() throws Exception { + stubSnippet("exported-snippets", "names.yaml", "orderTableName: orders-exported\n"); + String template = """ + Resources: + OrdersStateMachine: + Type: AWS::StepFunctions::StateMachine + Properties: + DefinitionSubstitutions: + Fn::Transform: + Name: AWS::Include + Parameters: + Location: + Fn::Sub: + - s3://${Bucket}/names.yaml + - Bucket: { Fn::ImportValue: SharedSnippetBucket } + """; + + JsonNode substitutions = mergedSubstitutions(template, Map.of(), "us-east-1", "000000000000", "", "", + exportName -> "SharedSnippetBucket".equals(exportName) ? "exported-snippets" : null); + + assertEquals("orders-exported", substitutions.get("orderTableName").asText()); + assertFalse(substitutions.has("Fn::Transform")); + } + + @Test + void refLocationResolvesTemplateParameter() throws Exception { + stubMeasuredFragment(); + String template = """ + Parameters: + InputValue: + Type: String + Default: %s + Resources: + OrdersStateMachine: + Type: AWS::StepFunctions::StateMachine + Properties: + DefinitionSubstitutions: + Fn::Transform: + Name: AWS::Include + Parameters: + Location: { Ref: InputValue } + """.formatted(LOCATION); + + JsonNode substitutions = mergedSubstitutions(template); + + assertEquals(EXPAND_ITEMS, substitutions.path("expandItems").asText()); + assertEquals("orders", substitutions.get("orderTableName").asText()); + assertFalse(substitutions.has("Fn::Transform")); + } + @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. + // AWS::Include example. When InputValue is not declared, the unresolved node is named. String template = """ Resources: OrdersStateMachine: