mirror of
https://github.com/floci-io/floci.git
synced 2026-12-01 01:12:48 -05:00
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<String> 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
This commit is contained in:
1 parent
2250972578
commit
711b216bad
5 files changed
+395
-34
No files matched your search
@@ -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<String, String> parameters, String region,
|
||||
String accountId, String stackName, String stackId) {
|
||||
return mergeIncludes(template, parameters, region, accountId, stackName, stackId, name -> null);
|
||||
}
|
||||
|
||||
JsonNode mergeIncludes(JsonNode template, Map<String, String> parameters, String region,
|
||||
String accountId, String stackName, String stackId,
|
||||
Function<String, String> 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<String, String> parameters,
|
||||
String region, String accountId, String stackName, String stackId,
|
||||
Function<String, String> 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<String, String> parameters,
|
||||
String region, String accountId, String stackName, String stackId,
|
||||
Function<String, String> 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<Map.Entry<String, JsonNode>> 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<String, String> parameters, String region,
|
||||
String accountId, String stackName, String stackId,
|
||||
Function<String, String> 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
|
||||
|
||||
@@ -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<String, Boolean> 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<String, String> resolveDefaultParameters(JsonNode template, Map<String, String> callerParams) {
|
||||
static Map<String, String> resolveDefaultParameters(JsonNode template, Map<String, String> callerParams) {
|
||||
Map<String, String> 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<String, String> 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<String>} 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<String, String> includeParameters(JsonNode template, Map<String, String> params, String region) {
|
||||
Map<String, String> resolved = resolveDefaultParameters(template, params);
|
||||
JsonNode paramDefs = template.path("Parameters");
|
||||
if (!paramDefs.isObject()) {
|
||||
return resolved;
|
||||
}
|
||||
paramDefs.fields().forEachRemaining(e -> {
|
||||
if (!"AWS::SSM::Parameter::Value<String>".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<String>} 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<String, JsonNode> templateMappings(JsonNode template) {
|
||||
static Map<String, JsonNode> templateMappings(JsonNode template) {
|
||||
Map<String, JsonNode> 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<String, String> 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<String, String> params, Map<String, String> 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<String, String> 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.
|
||||
|
||||
@@ -481,6 +481,10 @@ public class CloudFormationTemplateEngine {
|
||||
return resolved;
|
||||
}
|
||||
|
||||
boolean hasUnresolvedIntrinsics() {
|
||||
return !unresolvedIntrinsics.isEmpty();
|
||||
}
|
||||
|
||||
private String resolveRef(String name) {
|
||||
// Pseudo-parameters
|
||||
return switch (name) {
|
||||
|
||||
Reference in new issue
Block a user