fix(cloudformation): transform SAM layer versions (#7062)

* fix(cloudformation): transform SAM layer versions

Map packaged layer content to Lambda layers, retain version-specific resource identities, and preserve references and retention behavior. Cover publication, replacement and deletion through CloudFormation.

* fix(cloudformation): preserve typed and inherited SAM layer references

Rewrite captured Globals references, retain typed list references for provisioning, and restrict dependency rewriting to resource attributes. Cover each case in unit regressions and stack creation/update.

* fix(cloudformation): keep Fn::Sub overlay variables out of parameter substitution

A variable map localizes names for the template engine, so resolving a
same-named stack parameter first consumed the placeholder and left the map
dead: Key: !Sub ['${Key}', {Key: 'layer.zip'}] published the parameter's
value instead of the layer package the author named.

* refactor(cloudformation): fold SAM logical-id hashing into one helper

The layer-version and function-version generated ids serialized their hash
input the same way - properties sorted, non-ASCII escaped, DEL escaped, then
the first ten hex digits of the SHA-1 - but as two copies. Extract samHashSuffix
so a generated id is its subject plus one shared suffix. Ids are unchanged.

* fix(cloudformation): deploy SAM layers from original content expressions

The transform resolved ContentUri parameters before copying them onto the
generated AWS::Lambda::LayerVersion, so a parameter value that itself held
a ${...} was published inside a Fn::Sub and CloudFormation substituted it a
second time at deploy. Deploy the bucket and key expressions as written and
let the template engine resolve them once; keep the resolved copy only as
the hash input, so a versioned package still yields a distinct logical id.

* fix(cloudformation): keep Fn::Sub local variables out of layer rewrites

The recursive layer-reference walk re-entered an Fn::Sub node through the
blanket children loop, so it treated a variable map as another expression.
With a local variable literally named Ref whose value was a layer's logical
id, the walk rewrote that literal into the generated id and changed what the
stack deployed. Rewrite only the map's values as intrinsic contexts and skip
the already-handled Fn::Sub node in the walk.

* fix(lambda): read a layer's pinned S3 object version

A SAM layer with a packaged ContentUri.Version, or an
AWS::Lambda::LayerVersion whose Content sets S3ObjectVersion, publishes that
pinned package, but the provisioner fetched the object with a null version
and so read the latest one. If the key changed after publishing, the layer
ended up with different code than the template requested. Pass
S3ObjectVersion through to the S3 read so a pinned package stays pinned.

* fix(cloudformation): resolve a whole ContentUri reference before splitting it

Keeping the original ContentUri expressions on the generated layer means a
ContentUri that is itself a parameter reference arrives as a Ref object with
no Bucket or Key, and the transform rejected the stack. Resolve such a
reference to the location it names and split that, while the object form
keeps its expressions for the template engine to resolve at deploy.
This commit is contained in:
Rashen Anupama authored and GitHub committed 2026-10-31 13:20:11 -04:00
1 parent 9e0bc1b43b
commit 7569a9a8ec
6 files changed
+603 -21

No files matched your search

@@ -121,6 +121,9 @@ class SamTransformProcessor {
}
});
expandServerlessLayers(expanded, expandedResources, globals, parameterValues);
samLogicalIds.removeIf(id -> !expandedResources.has(id));
// Collect implicit-API routes from function Api events before the functions are expanded.
List<ApiRoute> apiRoutes = collectApiRoutes(samLogicalIds, resources);
@@ -206,6 +209,160 @@ class SamTransformProcessor {
}
}
private void expandServerlessLayers(ObjectNode template, ObjectNode resources, JsonNode globals,
Map<String, String> parameterValues) {
Map<String, String> layerIds = new LinkedHashMap<>();
List<String> ids = new ArrayList<>();
resources.fieldNames().forEachRemaining(ids::add);
for (String id : ids) {
JsonNode source = resources.path(id);
if (!"AWS::Serverless::LayerVersion".equals(source.path("Type").asText())) {
continue;
}
JsonNode properties = source.path("Properties");
JsonNode resolvedProperties = resolveParameterRefs(properties, template, parameterValues);
// Deploy with the original ContentUri expressions so CloudFormation resolves parameters
// once, at deploy: a resolved value that itself holds a ${...} would resolve twice. The
// resolved copy is what SAM hashes, so a versioned package still changes the logical id.
JsonNode uri = properties.path("ContentUri");
ObjectNode content = objectMapper.createObjectNode();
if (uri.isObject() && uri.hasNonNull("Bucket") && uri.hasNonNull("Key")) {
copyRenamed(uri, "Bucket", content, "S3Bucket");
copyRenamed(uri, "Key", content, "S3Key");
copyRenamed(uri, "Version", content, "S3ObjectVersion");
} else {
// A plain location is split as written, and a whole ContentUri reference resolves to
// the location itself, so the resolved value is what gets split. The object form
// above keeps its expressions for the template engine to resolve at deploy.
JsonNode resolvedUri = resolvedProperties.path("ContentUri");
String location = null;
if (uri.isTextual()) {
location = uri.asText();
} else if (resolvedUri.isTextual()) {
location = resolvedUri.asText();
}
if (location == null) {
throw invalidResource(id, "'ContentUri' requires Bucket and Key properties to be specified.");
}
Matcher match = S3_DEFINITION_URI.matcher(location);
if (!match.matches()) {
throw invalidResource(id, "'ContentUri' must specify a packaged S3 location.");
}
content.put("S3Bucket", match.group("bucket"));
content.put("S3Key", match.group("key"));
if (match.group("version") != null) {
content.put("S3ObjectVersion", match.group("version"));
}
}
String retention = resolvedProperties.path("RetentionPolicy").asText(null);
if (retention != null && !List.of("Retain", "Delete").contains(retention)) {
throw invalidResource(id, "'RetentionPolicy' must be 'Retain' or 'Delete'.");
}
ObjectNode layer = objectMapper.createObjectNode();
layer.put("Type", "AWS::Lambda::LayerVersion");
copyResourceLevelAttributes(source, layer);
if (retention != null || !layer.has("DeletionPolicy")) {
layer.put("DeletionPolicy", retention == null ? "Retain" : retention);
}
ObjectNode target = layer.putObject("Properties");
target.set("Content", content);
target.set("LayerName", properties.hasNonNull("LayerName")
? properties.get("LayerName").deepCopy() : TextNode.valueOf(id));
for (String key : List.of("Description", "LicenseInfo", "CompatibleRuntimes", "CompatibleArchitectures")) {
copyIfPresent(properties, key, target);
}
ObjectNode hashResource = source.deepCopy();
hashResource.set("Properties", resolvedProperties);
hashResource.remove(List.of("Metadata", "DeletionPolicy", "UpdateReplacePolicy"));
ObjectNode hashInput = objectMapper.createObjectNode();
hashInput.set(id, hashResource);
String generatedId = id + samHashSuffix(hashInput, id);
if (resources.has(generatedId)) {
throw invalidResource(id, "Generated layer logical id conflicts with resource '" + generatedId + "'.");
}
resources.remove(id);
resources.set(generatedId, layer);
layerIds.put(id, generatedId);
}
if (!layerIds.isEmpty()) {
rewriteLayerReferences(template, layerIds);
rewriteLayerReferences(globals, layerIds);
resources.elements().forEachRemaining(resource -> {
if (resource instanceof ObjectNode object) {
rewriteLayerDependencies(object, layerIds);
}
});
}
}
private void rewriteLayerReferences(JsonNode node, Map<String, String> ids) {
if (node instanceof ObjectNode object) {
if (object.path("Ref").isTextual() && ids.containsKey(object.path("Ref").asText())) {
object.put("Ref", ids.get(object.path("Ref").asText()));
}
JsonNode getAtt = object.path("Fn::GetAtt");
if (getAtt instanceof ArrayNode array && !array.isEmpty() && ids.containsKey(array.get(0).asText())) {
array.set(0, TextNode.valueOf(ids.get(array.get(0).asText())));
} else if (getAtt.isTextual()) {
object.put("Fn::GetAtt", rewriteLayerName(getAtt.asText(), ids));
}
JsonNode sub = object.path("Fn::Sub");
if (sub.isTextual()) {
object.put("Fn::Sub", rewriteLayerSub(sub.asText(), ids, objectMapper.createObjectNode()));
} else if (sub instanceof ArrayNode array && array.size() == 2 && array.get(0).isTextual()) {
array.set(0, TextNode.valueOf(rewriteLayerSub(array.get(0).asText(), ids, array.get(1))));
// Only the map's values are intrinsic contexts; its keys are local variable names
// that may themselves be spelled Ref, so walk the values, never the map container.
if (array.get(1) instanceof ObjectNode variables) {
variables.elements().forEachRemaining(value -> rewriteLayerReferences(value, ids));
}
}
// The Fn::Sub node is fully handled above, so skip it here; recursing into its variables
// map would treat a variable literally named Ref as a Ref-intrinsic and rewrite it.
List<String> keys = new ArrayList<>();
object.fieldNames().forEachRemaining(keys::add);
for (String key : keys) {
if (!"Fn::Sub".equals(key)) {
rewriteLayerReferences(object.get(key), ids);
}
}
} else if (node.isArray()) {
node.forEach(child -> rewriteLayerReferences(child, ids));
}
}
private static void rewriteLayerDependencies(ObjectNode object, Map<String, String> ids) {
JsonNode dependsOn = object.path("DependsOn");
if (dependsOn.isTextual() && ids.containsKey(dependsOn.asText())) {
object.put("DependsOn", ids.get(dependsOn.asText()));
} else if (dependsOn instanceof ArrayNode array) {
for (int i = 0; i < array.size(); i++) {
String replacement = ids.get(array.get(i).asText());
if (replacement != null) {
array.set(i, TextNode.valueOf(replacement));
}
}
}
}
private static String rewriteLayerName(String name, Map<String, String> ids) {
int dot = name.indexOf('.');
String id = dot < 0 ? name : name.substring(0, dot);
return ids.getOrDefault(id, id) + (dot < 0 ? "" : name.substring(dot));
}
private static String rewriteLayerSub(String text, Map<String, String> ids, JsonNode variables) {
Matcher matcher = SUB_REFERENCE.matcher(text);
StringBuilder result = new StringBuilder();
while (matcher.find()) {
String name = matcher.group(1);
String replacement = variables.has(name) ? name : rewriteLayerName(name, ids);
matcher.appendReplacement(result, Matcher.quoteReplacement("${" + replacement + "}"));
}
matcher.appendTail(result);
return result.toString();
}
private JsonNode globals(JsonNode template) {
return template.path("Globals");
}
@@ -1204,19 +1361,7 @@ class SamTransformProcessor {
hashed.set("SnapStart", snapStart.deepCopy());
}
}
String hashInput;
try {
hashInput = objectMapper.writer()
.with(JsonNodeFeature.WRITE_PROPERTIES_SORTED)
.with(JsonWriteFeature.ESCAPE_NON_ASCII)
.without(JsonWriteFeature.WRITE_HEX_UPPER_CASE)
.writeValueAsString(hashed)
// ESCAPE_NON_ASCII leaves DEL as it is; SAM's hash input escapes DEL as well.
.replace("\u007f", "\\u007f");
} catch (JsonProcessingException e) {
throw new IllegalStateException("Cannot serialize the version hash input of " + functionLogicalId, e);
}
return functionLogicalId + "Version" + Digests.sha1Hex(hashInput).substring(0, 10);
return functionLogicalId + "Version" + samHashSuffix(hashed, functionLogicalId);
}
/**
@@ -1250,11 +1395,15 @@ class SamTransformProcessor {
JsonNode sub = node.get("Fn::Sub");
ObjectNode resolved = objectMapper.createObjectNode();
if (sub.isTextual()) {
resolved.put("Fn::Sub", substituteParameters(sub.asText(), template, parameterValues));
resolved.put("Fn::Sub", substituteParameters(sub.asText(), template, parameterValues, Set.of()));
} else if (sub.isArray() && !sub.isEmpty() && sub.get(0).isTextual()) {
Set<String> localVariables = new LinkedHashSet<>();
if (sub.size() > 1 && sub.get(1).isObject()) {
sub.get(1).fieldNames().forEachRemaining(localVariables::add);
}
ArrayNode arguments = (ArrayNode) resolveParameterRefs(sub, template, parameterValues);
arguments.set(0, TextNode.valueOf(substituteParameters(sub.get(0).asText(), template,
parameterValues)));
parameterValues, localVariables)));
resolved.set("Fn::Sub", arguments);
} else {
resolved.set("Fn::Sub", resolveParameterRefs(sub, template, parameterValues));
@@ -1275,12 +1424,17 @@ class SamTransformProcessor {
return node;
}
/** {@code text} with each {@code ${Name}} naming a template parameter replaced by its value. */
private static String substituteParameters(String text, JsonNode template, Map<String, String> parameterValues) {
/**
* {@code text} with each {@code ${Name}} naming a template parameter replaced by its value. Names that
* the same {@code Fn::Sub} localizes in its variable map are left for the template engine to resolve.
*/
private static String substituteParameters(String text, JsonNode template, Map<String, String> parameterValues,
Set<String> localVariables) {
Matcher matcher = SUB_REFERENCE.matcher(text);
StringBuilder substituted = new StringBuilder();
while (matcher.find()) {
String value = parameterValue(matcher.group(1), template, parameterValues);
String name = matcher.group(1);
String value = localVariables.contains(name) ? null : parameterValue(name, template, parameterValues);
matcher.appendReplacement(substituted, Matcher.quoteReplacement(value == null ? matcher.group() : value));
}
matcher.appendTail(substituted);
@@ -1552,6 +1706,27 @@ class SamTransformProcessor {
return name;
}
/**
* The first ten hex digits of the SHA-1 of SAM's canonical form of {@code hashInput}: properties
* sorted, non-ASCII escaped, and DEL escaped as well, because ESCAPE_NON_ASCII leaves DEL as it is
* while SAM's hash input escapes it. A generated logical id is its subject plus this suffix, so a
* layer version and a function version hash their input exactly alike.
*/
private String samHashSuffix(JsonNode hashInput, String subject) {
String serialized;
try {
serialized = objectMapper.writer()
.with(JsonNodeFeature.WRITE_PROPERTIES_SORTED)
.with(JsonWriteFeature.ESCAPE_NON_ASCII)
.without(JsonWriteFeature.WRITE_HEX_UPPER_CASE)
.writeValueAsString(hashInput)
.replace("\u007f", "\\u007f");
} catch (JsonProcessingException e) {
throw new IllegalStateException("Cannot serialize the hash input of " + subject, e);
}
return Digests.sha1Hex(serialized).substring(0, 10);
}
/**
* SAM's generated condition name: the name plus the first ten hex digits of the SHA-1 of
* {@code hashInput}, cut to CloudFormation's 255-character limit. SHA-1 is SAM's choice and is
@@ -498,8 +498,9 @@ public class LambdaLayerService {
if (s3Service == null) {
throw new AwsException("ServiceUnavailableException", "S3 service not available", 503);
}
String s3ObjectVersion = (String) content.get("S3ObjectVersion");
try {
return DeploymentPackage.read(s3Service.openObject(s3Bucket, s3Key, null), stagingDir);
return DeploymentPackage.read(s3Service.openObject(s3Bucket, s3Key, s3ObjectVersion), stagingDir);
} catch (Exception e) {
throw new AwsException("InvalidParameterValueException",
"Unable to fetch layer content from s3://" + s3Bucket + "/" + s3Key + ": " + e.getMessage(), 400);