feat(cloudformation): support SAM's optional AutoPublishAlias version properties (#5823)

* feat(cloudformation): support SAM's optional AutoPublishAlias version properties

With AutoPublishAlias, read the three function properties SAM uses to
shape the version it publishes:

- AutoPublishCodeSha256: a string names the version by its first ten
  characters instead of the hash, so new code under the same value
  publishes nothing. A Ref to a parameter resolves first.
- AutoPublishAliasAllProperties: the hash covers every property the
  transform gives the function, plus its SnapStart.
- VersionDeletionPolicy: the version's DeletionPolicy when the
  function sets none; a function with a CapacityProviderConfig
  defaults to Delete, any other to Retain. An intrinsic value is
  copied unresolved, as SAM copies it.

Each gets SAM's type checks and messages: AutoPublishCodeSha256 must
be a string and make an alphanumeric id, AutoPublishAliasAllProperties
a boolean, and VersionDeletionPolicy Delete or Retain, only with
AutoPublishAlias.

Signed-off-by: Jackson Price <59149601+jprice8@users.noreply.github.com>

* test(cloudformation): pin the default Ref hash and AutoPublishAliasAllProperties coverage

Keep the check that a Ref in the code changes the version id without
AutoPublishAliasAllProperties, and show that with it a Timeout change
names a new version and false hashes as if the property were absent.
Pin that an AutoPublishCodeSha256 Ref resolving to an empty value
leaves the hash in place. The docs say that ids under
AutoPublishAliasAllProperties are floci's own and that a Ref to a
parameter works for AutoPublishCodeSha256.

Signed-off-by: Jackson Price <59149601+jprice8@users.noreply.github.com>

* fix(cloudformation): refuse AutoPublishCodeSha256 in SAM Globals

SAM refuses a Globals property it does not list for a section, and
Globals.Function does not list AutoPublishCodeSha256. Now that the
property names the version, merging it from Globals would give every
function the same version id, so a code change would never publish.
Refuse the template with SAM's message, without the list of supported
properties that SAM appends.

Signed-off-by: Jackson Price <59149601+jprice8@users.noreply.github.com>

* test(cloudformation): pin the AutoPublishAliasAllProperties ids and SAM version updates

Pin two version ids under AutoPublishAliasAllProperties to the SHA-1 of
the generated function's properties, worked out by hand, and that a
given AutoPublishCodeSha256 still names the version there. Show that
Globals.Function carries AutoPublishAliasAllProperties and
VersionDeletionPolicy. On a stack, a Timeout change under
AutoPublishAliasAllProperties publishes version 2 with the new timeout,
and VersionDeletionPolicy: Delete reports the replaced version
DELETE_COMPLETE instead of DELETE_SKIPPED. An intrinsic
VersionDeletionPolicy is copied unresolved, which the assertion now
says.

Signed-off-by: Jackson Price <59149601+jprice8@users.noreply.github.com>

* docs(cloudformation): say when a new SAM version id publishes

Say which statements about the version id hold by default, that
AutoPublishCodeSha256 outranks AutoPublishAliasAllProperties and cannot
come from Globals, and when a new id publishes nothing: SnapStart, a new
AutoPublishCodeSha256 alone, or, under AutoPublishAliasAllProperties, a
Tags or ReservedConcurrentExecutions change, which AWS fails with "A
version for this Lambda function exists". A hot-reloaded function
publishes for every new id. State the DeletionPolicy order, and that
CloudFormation takes intrinsic functions only in resource properties,
outputs, metadata and update policies. The javadocs of the version id
and of AutoPublishAlias say the same.

Signed-off-by: Jackson Price <59149601+jprice8@users.noreply.github.com>

* docs(cloudformation): note IgnoreGlobals and LanguageExtensions for SAM versions

Say that floci does not honour IgnoreGlobals, so a function cannot opt
out of a VersionDeletionPolicy in Globals, and that an intrinsic
VersionDeletionPolicy reaches CloudFormation only through a transform
such as AWS::LanguageExtensions, which floci does not implement. Under
AutoPublishAliasAllProperties the code's parameter references are still
resolved, and any SnapStart change publishes nothing.

Signed-off-by: Jackson Price <59149601+jprice8@users.noreply.github.com>

* test(cloudformation): pin the SnapStart id under AutoPublishAliasAllProperties

Pin the id a SnapStart with ApplyOn None gives under
AutoPublishAliasAllProperties, worked out by hand like the others, and
show that a version VersionDeletionPolicy: Delete reports deleted is
still listed, as the docs say floci keeps every version it publishes.

Signed-off-by: Jackson Price <59149601+jprice8@users.noreply.github.com>

* docs(cloudformation): say that IgnoreGlobals is the opt-out floci ignores

A function can still clear a Globals VersionDeletionPolicy with a null
of its own; what floci does not honour is IgnoreGlobals.

Signed-off-by: Jackson Price <59149601+jprice8@users.noreply.github.com>

---------

Signed-off-by: Jackson Price <59149601+jprice8@users.noreply.github.com>
This commit is contained in:
Jackson Price authored and GitHub committed 2026-10-17 14:04:04 -04:00
1 parent c33823bd48
commit f22c2a4db1
4 files changed
+527 -41

No files matched your search

+45 -12
View File
@@ -436,19 +436,52 @@ numeric `Version` attribute. CloudFormation resolves the version before creating
alias. As in SAM, the version's logical id is `<Function>Version` followed by ten hex digits of a
SHA-1 over the function's code, with its template parameter references resolved (pseudo
parameters such as `${AWS::Region}` stay as written), its `Environment` and `MemorySize` as
written, and its `SnapStart` when it sets an `ApplyOn` other than `None`. An update that changes the
code, `Environment` or `MemorySize`, or a parameter the code uses, publishes a new version and
moves the alias to it. A parameter used only in `Environment` or `MemorySize` does not, and neither
does a property outside the hash, such as `Timeout`. A new id publishes only when the function's
code or configuration changed since its last version. floci does not give the function
`SnapStart`, so turning it on changes the id but publishes nothing: the alias stays where it is.
written, and its `SnapStart` when it sets an `ApplyOn` other than `None`. By default, then, an
update that changes the code, `Environment` or `MemorySize`, or a parameter the code uses, publishes
a new version and moves the alias to it. A parameter used only in `Environment` or `MemorySize` does
not, and neither does a property outside the hash, such as `Timeout`.
The version a new id replaces stays published: like SAM, floci gives the version
`DeletionPolicy: Retain` unless the function sets a `DeletionPolicy`, and the update reports it
`DELETE_SKIPPED`. With `Delete` floci reports the old version `DELETE_COMPLETE` but never deletes
it, where AWS does. Changes made to `$LATEST` outside the stack, including Lambda's reactive S3
sync, do not reach the alias until an update publishes a new version. Event sources and API
integrations still invoke the function rather than the alias, so they run `$LATEST`.
Two optional function properties change the id. Under `AutoPublishAliasAllProperties: true` the
hash covers every property floci gives the function, its code's parameter references resolved as
above, plus its `SnapStart`; those properties differ from the ones SAM generates, so these ids are
floci's own rather than SAM's. An `AutoPublishCodeSha256` that is a string, or a `Ref` to a
parameter holding one, replaces the hash with its first ten characters, under
`AutoPublishAliasAllProperties` too; an empty value leaves the hash in place. `Globals` can set
`AutoPublishAliasAllProperties` and `VersionDeletionPolicy`, but as in SAM not
`AutoPublishCodeSha256`, which fails the transform there. floci does not honour a resource's
`IgnoreGlobals`, so no function can opt out of a `VersionDeletionPolicy` in `Globals` with it: one
without `AutoPublishAlias` fails the transform with
`'VersionDeletionPolicy' requires 'AutoPublishAlias'.`, as it does in SAM when it does not ignore
that global.
A new id publishes a version, and moves the alias to it, only when the function's code or
configuration changed since its last version. Otherwise the new version resource takes the last
version and the alias stays where it is, as when an update changes only one of these:
- A change to `SnapStart`: floci does not give the function `SnapStart`.
- A new `AutoPublishCodeSha256` alone: on AWS this publishes, because SAM appends it to the
function's `Description`, but floci's transform sets no `Description` on the function.
- Under `AutoPublishAliasAllProperties`, a change to `Tags` or `ReservedConcurrentExecutions`
only: AWS fails that update with
`A version for this Lambda function exists ( N ). Modify the function to create a new version.`,
where floci completes it.
A function whose code is hot-reloaded publishes a version for every new id.
Like SAM, floci gives the version the function's `DeletionPolicy`, else its `VersionDeletionPolicy`
(`Delete` or `Retain`), else `Delete` for a function with a `CapacityProviderConfig` and `Retain`
for any other. So by default the version a new id replaces stays published, and the update reports
it `DELETE_SKIPPED`. With `Delete` floci reports the old version `DELETE_COMPLETE` but never deletes
it, where AWS does. A `VersionDeletionPolicy` written as an intrinsic function, such as a `Ref` to
a parameter, is copied onto the version unresolved, as SAM copies it. CloudFormation takes
intrinsic functions only in resource properties, outputs, metadata attributes and update policy
attributes, unless a transform such as `AWS::LanguageExtensions` resolves them first, and floci
implements no such transform: it reads any `DeletionPolicy` that is not a plain string as `Delete`
(see [Deletion Policies](#deletion-policies)).
Changes made to `$LATEST` outside the stack, including Lambda's reactive S3 sync, do not reach the
alias until an update publishes a new version. Event sources and API integrations still invoke the
function rather than the alias, so they run `$LATEST`.
## RDS Credential Dynamic References
@@ -44,6 +44,9 @@ class SamTransformProcessor {
/** A {@code ${Name}} reference in an {@code Fn::Sub} string, as SAM matches one. */
private static final Pattern SUB_REFERENCE = Pattern.compile("\\$\\{([A-Za-z0-9.]+|AWS::[A-Z][A-Za-z]*)}");
/** What SAM accepts as a logical id. */
private static final Pattern ALPHANUMERIC = Pattern.compile("[A-Za-z0-9]+");
private final ObjectMapper objectMapper;
SamTransformProcessor(ObjectMapper objectMapper) {
@@ -91,6 +94,12 @@ class SamTransformProcessor {
// (including the early return below when Resources is absent or not an object).
JsonNode globals = expanded.path("Globals");
expanded.remove("Globals");
// SAM refuses any Globals property it does not list for a section. AutoPublishCodeSha256 is
// one of them: one value there would name every function's version.
if (globals.path("Function").has("AutoPublishCodeSha256")) {
throw new AwsException("ValidationError", "'Globals' section is invalid. 'AutoPublishCodeSha256' "
+ "is not a supported property of 'Function'.", 400);
}
JsonNode resources = expanded.path("Resources");
if (!resources.isObject()) {
@@ -987,11 +996,13 @@ class SamTransformProcessor {
* dependencies, so the alias selects the immutable version published by this stack. The
* version's logical id carries a hash of what a new version publishes (see
* {@link #versionLogicalId}), so an update that changes the code names a new version resource,
* which publishes, and the alias follows it.
* which publishes, and the alias follows it; a given {@code AutoPublishCodeSha256} fixes the id
* instead.
*/
private String expandAutoPublishAlias(String functionLogicalId, JsonNode properties, JsonNode functionProperties,
ObjectNode passthrough, JsonNode template,
Map<String, String> parameterValues, ObjectNode resources) {
validateVersionProperties(functionLogicalId, properties);
JsonNode aliasName = properties.path("AutoPublishAlias");
if (aliasName.isMissingNode() || aliasName.isNull()
|| (aliasName.isTextual() && aliasName.asText().isBlank())) {
@@ -1010,7 +1021,7 @@ class SamTransformProcessor {
// The version a new hash replaces leaves the template on that update; like SAM, keep it
// published unless the template says otherwise, so the update reports it DELETE_SKIPPED.
if (!versionDef.has("DeletionPolicy")) {
versionDef.put("DeletionPolicy", "Retain");
versionDef.set("DeletionPolicy", defaultVersionDeletionPolicy(properties));
}
resources.set(versionId, versionDef);
@@ -1032,34 +1043,105 @@ class SamTransformProcessor {
}
/**
* The logical id SAM gives the version it publishes: {@code <Function>Version} and the first ten
* SAM's {@code DeletionPolicy} for the version when the function declares none: the function's
* {@code VersionDeletionPolicy}, else {@code Delete} for a function on a capacity provider and
* {@code Retain} for any other.
*/
private JsonNode defaultVersionDeletionPolicy(JsonNode properties) {
JsonNode versionDeletionPolicy = properties.path("VersionDeletionPolicy");
if (isPropertyPresent(versionDeletionPolicy)) {
return versionDeletionPolicy.deepCopy();
}
return TextNode.valueOf(isPropertyPresent(properties.path("CapacityProviderConfig")) ? "Delete" : "Retain");
}
/**
* The checks SAM makes on every function's version properties before it transforms them: the
* type each must have, and that {@code VersionDeletionPolicy} comes with an
* {@code AutoPublishAlias}. Like SAM, it takes any one-key object for an intrinsic function where
* the property allows one.
*/
private void validateVersionProperties(String functionLogicalId, JsonNode properties) {
JsonNode codeSha256 = properties.path("AutoPublishCodeSha256");
if (isPropertyPresent(codeSha256) && !codeSha256.isTextual() && !isOneKeyObject(codeSha256)) {
throw invalidResource(functionLogicalId, "Type of property 'AutoPublishCodeSha256' is invalid.");
}
JsonNode allProperties = properties.path("AutoPublishAliasAllProperties");
if (isPropertyPresent(allProperties) && !allProperties.isBoolean()) {
throw invalidResource(functionLogicalId, "Type of property 'AutoPublishAliasAllProperties' is invalid.");
}
JsonNode versionDeletionPolicy = properties.path("VersionDeletionPolicy");
if (!isPropertyPresent(versionDeletionPolicy)) {
return;
}
boolean allowed = versionDeletionPolicy.isTextual()
&& List.of("Delete", "Retain").contains(versionDeletionPolicy.asText());
if (!allowed && !isOneKeyObject(versionDeletionPolicy)) {
throw invalidResource(functionLogicalId,
"Property 'VersionDeletionPolicy' should be a one of the strings: 'Delete' or 'Retain'.");
}
if (!isPropertyPresent(properties.path("AutoPublishAlias"))) {
throw invalidResource(functionLogicalId, "'VersionDeletionPolicy' requires 'AutoPublishAlias'.");
}
}
private static boolean isOneKeyObject(JsonNode node) {
return node.isObject() && node.size() == 1;
}
/**
* The logical id of the version the alias points at: {@code <Function>Version} and the first ten
* hex digits of the SHA-1 of the function's {@code Code}, with references to template parameters
* resolved, merged with its {@code Environment}, its {@code MemorySize} and a {@code SnapStart}
* that applies, as sorted compact JSON with characters outside printable ASCII as lowercase hex
* escapes, apart from JSON's short escapes such as a newline's. A change to the hashed input is a new logical id: the update publishes a new version and the alias moves
* to it. Unchanged, the id and the version it published stay, since the version provisioner never
* republishes under the same id.
* escapes, apart from JSON's short escapes such as a newline's; that is the id SAM gives. Under
* {@code AutoPublishAliasAllProperties} the hash covers all the properties this transform gives
* the function, the code's parameter references still resolved, plus its {@code SnapStart},
* which makes the id floci's own. A string
* {@code AutoPublishCodeSha256} names the version itself, by its first ten characters. A change
* to the hashed input is a new logical id, so a new version resource, which publishes when the
* function's code or configuration changed since its last version. Unchanged, the id and the
* version it published stay, since the version provisioner never republishes under the same id.
*/
private String versionLogicalId(String functionLogicalId, JsonNode samProperties, JsonNode functionProperties,
JsonNode template, Map<String, String> parameterValues) {
String codeSha256 = autoPublishCodeSha256(functionLogicalId, samProperties, template, parameterValues);
if (codeSha256 != null && !codeSha256.isEmpty()) {
String given = codeSha256.substring(0, Math.min(10, codeSha256.length()));
if (!ALPHANUMERIC.matcher(given).matches()) {
throw invalidResource(functionLogicalId + "Version" + given, "Logical ids must be alphanumeric.");
}
return functionLogicalId + "Version" + given;
}
// SAM resolves the code in place, so the all-properties hash sees it resolved as well.
JsonNode code = resolveParameterRefs(functionProperties.path("Code"), template, parameterValues);
ObjectNode hashed = objectMapper.createObjectNode();
if (code.isObject()) {
hashed.setAll((ObjectNode) code);
}
JsonNode environment = functionProperties.path("Environment");
if (environment.isObject()) {
hashed.setAll((ObjectNode) environment.deepCopy());
}
if (functionProperties.has("MemorySize")) {
hashed.set("MemorySize", functionProperties.get("MemorySize").deepCopy());
}
// SAM hashes a SnapStart that applies, so the id matches the one SAM gives. A missing
// ApplyOn means None; a null one does not.
JsonNode snapStart = samProperties.path("SnapStart");
JsonNode applyOn = snapStart.path("ApplyOn");
if (snapStart.isObject() && !applyOn.isMissingNode() && !"None".equals(applyOn.asText(null))) {
hashed.set("SnapStart", snapStart.deepCopy());
if (samProperties.path("AutoPublishAliasAllProperties").asBoolean(false)) {
hashed.setAll((ObjectNode) functionProperties.deepCopy());
if (code.isObject()) {
hashed.set("Code", code);
}
if (isPropertyPresent(snapStart)) {
hashed.set("SnapStart", snapStart.deepCopy());
}
} else {
if (code.isObject()) {
hashed.setAll((ObjectNode) code);
}
JsonNode environment = functionProperties.path("Environment");
if (environment.isObject()) {
hashed.setAll((ObjectNode) environment.deepCopy());
}
if (functionProperties.has("MemorySize")) {
hashed.set("MemorySize", functionProperties.get("MemorySize").deepCopy());
}
// SAM hashes a SnapStart that applies, so the id matches the one SAM gives. A missing
// ApplyOn means None; a null one does not.
JsonNode applyOn = snapStart.path("ApplyOn");
if (snapStart.isObject() && !applyOn.isMissingNode() && !"None".equals(applyOn.asText(null))) {
hashed.set("SnapStart", snapStart.deepCopy());
}
}
String hashInput;
try {
@@ -1076,6 +1158,23 @@ class SamTransformProcessor {
return functionLogicalId + "Version" + Digests.sha1Hex(hashInput).substring(0, 10);
}
/**
* The function's {@code AutoPublishCodeSha256} with template parameters resolved, or null when it
* declares none. As in SAM, an intrinsic function that does not resolve to a string is refused.
*/
private String autoPublishCodeSha256(String functionLogicalId, JsonNode samProperties, JsonNode template,
Map<String, String> parameterValues) {
JsonNode given = samProperties.path("AutoPublishCodeSha256");
if (!isPropertyPresent(given)) {
return null;
}
JsonNode resolved = resolveParameterRefs(given, template, parameterValues);
if (!resolved.isTextual()) {
throw invalidResource(functionLogicalId, "AutoPublishCodeSha256 must be a string");
}
return resolved.asText();
}
/**
* {@code node} with each reference to a template parameter replaced by the stack's value for it,
* or else its {@code Default}, as SAM resolves the code before hashing it: a {@code Ref}, and a
@@ -265,6 +265,140 @@ class SamTransformIntegrationTest {
.body("release", equalTo("second"));
}
@Test
void samAutoPublishCodeSha256DecidesWhenANewVersionPublishes() {
String stackName = "sam-code-sha-stack";
String function = "sam-code-sha-func";
stacksToDelete.add(stackName);
String template = """
Transform: AWS::Serverless-2016-10-31
Resources:
Function:
Type: AWS::Serverless::Function
Properties:
FunctionName: sam-code-sha-func
Handler: index.handler
Runtime: nodejs20.x
AutoPublishAlias: live
AutoPublishCodeSha256: "%s"
InlineCode: "exports.handler = async () => ({ release: '%s' });"
""";
given().contentType("application/x-www-form-urlencoded")
.formParam("Action", "CreateStack").formParam("StackName", stackName)
.formParam("TemplateBody", template.formatted("aaaaaaaaaa", "first"))
.formParam("Capabilities.member.1", "CAPABILITY_IAM")
.when().post("/").then().statusCode(200);
waitForStackStatus(stackName, "CREATE_COMPLETE");
// As in SAM, the given hash names the version, so new code under the same value is not published.
given().contentType("application/x-www-form-urlencoded")
.formParam("Action", "UpdateStack").formParam("StackName", stackName)
.formParam("TemplateBody", template.formatted("aaaaaaaaaa", "second"))
.formParam("Capabilities.member.1", "CAPABILITY_IAM")
.when().post("/").then().statusCode(200);
waitForStackStatus(stackName, "UPDATE_COMPLETE");
given().when().get("/2015-03-31/functions/" + function + "/aliases/live")
.then().statusCode(200).body("FunctionVersion", equalTo("1"));
given().contentType("application/x-www-form-urlencoded")
.formParam("Action", "UpdateStack").formParam("StackName", stackName)
.formParam("TemplateBody", template.formatted("bbbbbbbbbb", "second"))
.formParam("Capabilities.member.1", "CAPABILITY_IAM")
.when().post("/").then().statusCode(200);
waitForStackStatus(stackName, "UPDATE_COMPLETE");
given().when().get("/2015-03-31/functions/" + function + "/aliases/live")
.then().statusCode(200).body("FunctionVersion", equalTo("2"));
given().when().get("/2015-03-31/functions/" + function + "/versions")
.then().statusCode(200).body("Versions.Version", equalTo(List.of("$LATEST", "1", "2")));
}
/** Under AutoPublishAliasAllProperties a property outside the default hash, here Timeout, publishes. */
@Test
void samAutoPublishAliasAllPropertiesPublishesATimeoutChange() {
String stackName = "sam-all-properties-stack";
String function = "sam-all-properties-func";
stacksToDelete.add(stackName);
String template = """
Transform: AWS::Serverless-2016-10-31
Resources:
Function:
Type: AWS::Serverless::Function
Properties:
FunctionName: sam-all-properties-func
Handler: index.handler
Runtime: nodejs20.x
Timeout: %d
AutoPublishAlias: live
AutoPublishAliasAllProperties: true
InlineCode: "exports.handler = async () => ({});"
""";
given().contentType("application/x-www-form-urlencoded")
.formParam("Action", "CreateStack").formParam("StackName", stackName)
.formParam("TemplateBody", template.formatted(3)).formParam("Capabilities.member.1", "CAPABILITY_IAM")
.when().post("/").then().statusCode(200);
waitForStackStatus(stackName, "CREATE_COMPLETE");
given().contentType("application/x-www-form-urlencoded")
.formParam("Action", "UpdateStack").formParam("StackName", stackName)
.formParam("TemplateBody", template.formatted(9)).formParam("Capabilities.member.1", "CAPABILITY_IAM")
.when().post("/").then().statusCode(200);
waitForStackStatus(stackName, "UPDATE_COMPLETE");
given().when().get("/2015-03-31/functions/" + function + "/aliases/live")
.then().statusCode(200).body("FunctionVersion", equalTo("2"));
given().queryParam("Qualifier", "live")
.when().get("/2015-03-31/functions/" + function + "/configuration")
.then().statusCode(200).body("Version", equalTo("2")).body("Timeout", equalTo(9));
}
/** With VersionDeletionPolicy: Delete, the version a code change replaces is reported deleted. */
@Test
void samVersionDeletionPolicyDeleteAppliesToTheReplacedVersion() {
String stackName = "sam-version-delete-stack";
String function = "sam-version-delete-func";
stacksToDelete.add(stackName);
String template = """
Transform: AWS::Serverless-2016-10-31
Resources:
Function:
Type: AWS::Serverless::Function
Properties:
FunctionName: sam-version-delete-func
Handler: index.handler
Runtime: nodejs20.x
AutoPublishAlias: live
VersionDeletionPolicy: Delete
InlineCode: "exports.handler = async () => ({ release: '%s' });"
""";
given().contentType("application/x-www-form-urlencoded")
.formParam("Action", "CreateStack").formParam("StackName", stackName)
.formParam("TemplateBody", template.formatted("first")).formParam("Capabilities.member.1", "CAPABILITY_IAM")
.when().post("/").then().statusCode(200);
waitForStackStatus(stackName, "CREATE_COMPLETE");
given().contentType("application/x-www-form-urlencoded")
.formParam("Action", "UpdateStack").formParam("StackName", stackName)
.formParam("TemplateBody", template.formatted("second")).formParam("Capabilities.member.1", "CAPABILITY_IAM")
.when().post("/").then().statusCode(200);
waitForStackStatus(stackName, "UPDATE_COMPLETE");
given().when().get("/2015-03-31/functions/" + function + "/aliases/live")
.then().statusCode(200).body("FunctionVersion", equalTo("2"));
String events = given().contentType("application/x-www-form-urlencoded")
.formParam("Action", "DescribeStackEvents").formParam("StackName", stackName)
.when().post("/").then().statusCode(200).extract().asString();
// FunctionVersion6a52d0f87f is the id SAM gives the first InlineCode.
List<String> oldVersionStatuses = XmlParser.extractGroups(events, "member").stream()
.filter(event -> "FunctionVersion6a52d0f87f".equals(event.get("LogicalResourceId")))
.map(event -> event.get("ResourceStatus"))
.toList();
assertThat(oldVersionStatuses, hasItem("DELETE_COMPLETE"));
assertThat(oldVersionStatuses, not(hasItem("DELETE_SKIPPED")));
// floci reports the version deleted but keeps every version it publishes; AWS deletes it.
given().when().get("/2015-03-31/functions/" + function + "/versions")
.then().statusCode(200).body("Versions.Version", equalTo(List.of("$LATEST", "1", "2")));
}
/**
* A code change names a new version resource: the change set adds it, modifies the alias and
* removes the old version, which, retained as SAM retains it, stays published.
@@ -181,7 +181,8 @@ class SamTransformProcessorTest {
/**
* SAM also hashes a function's SnapStart when its ApplyOn is anything but "None", so turning
* SnapStart on names a new version; absent, empty or "None" leaves the id unchanged.
* SnapStart on names a new version; absent, empty or "None" leaves the id unchanged. With
* AutoPublishAliasAllProperties it is hashed like every other property.
*/
@Test
void expandSamTemplate_autoPublishAliasVersionIdIncludesAppliedSnapStart() throws Exception {
@@ -210,6 +211,20 @@ class SamTransformProcessorTest {
for (String off : List.of("", ", \"SnapStart\": {\"ApplyOn\": \"None\"}", ", \"SnapStart\": {}")) {
assertEquals("MyFuncVersion102360dfc3", publishedVersionId(template.formatted(off)), off);
}
String allProperties = ", \"AutoPublishAliasAllProperties\": true";
// The SHA-1 of the properties the transform gives the function, as sorted compact JSON:
// {"Code":{"ZipFile":"..."},"Handler":"index.handler","Role":{"Fn::GetAtt":["MyFuncRole","Arn"]},
// "Runtime":"java21"}
assertEquals("MyFuncVersionef5795a086", publishedVersionId(template.formatted(allProperties)));
assertEquals("MyFuncVersion60f02511cd",
publishedVersionId(template.formatted(allProperties + ", \"Timeout\": 9")),
"every property is hashed, Timeout included");
assertEquals("MyFuncVersion6c94e3ab8d",
publishedVersionId(template.formatted(allProperties + ", \"SnapStart\": {\"ApplyOn\": \"None\"}")),
"SnapStart is hashed whatever its ApplyOn");
assertEquals("MyFuncVersion102360dfc3",
publishedVersionId(template.formatted(", \"AutoPublishAliasAllProperties\": false")),
"false hashes as if the property were absent");
}
/**
@@ -268,11 +283,197 @@ class SamTransformProcessorTest {
}
/**
* SAM retains each version it publishes unless the function sets a {@code DeletionPolicy}, which
* the version and alias both take.
* A given {@code AutoPublishCodeSha256} names the version: SAM takes its first ten characters
* and hashes nothing else, so the code alone no longer names the version.
*/
@Test
void expandSamTemplate_autoPublishAliasVersionIsRetainedUnlessTheFunctionSaysOtherwise() throws Exception {
void expandSamTemplate_autoPublishCodeSha256TakesTheHashesPlace() throws Exception {
String template = """
{
"Transform": "AWS::Serverless-2016-10-31",
"Resources": {
"MyFunc": {
"Type": "AWS::Serverless::Function",
"Properties": {
"Handler": "index.handler", "Runtime": "nodejs20.x", "AutoPublishAlias": "live",
"InlineCode": "%s", "AutoPublishCodeSha256": "%s"
}
}
}
}
""";
String code = "exports.handler = async () => ({});";
String sha = "6b86b273ff34fce19d6b804eff5a3f5747ada4eaa22f1d49c01e52ddb7875b4b";
assertEquals("MyFuncVersion6b86b273ff", publishedVersionId(template.formatted(code, sha)));
assertEquals("MyFuncVersion6b86b273ff",
publishedVersionId(template.formatted("exports.handler = async () => ({ changed: true });", sha)),
"a code change under the same AutoPublishCodeSha256 keeps the version");
assertEquals("MyFuncVersionabc", publishedVersionId(template.formatted(code, "abc")));
assertEquals("MyFuncVersion102360dfc3", publishedVersionId(template.formatted(code, "")),
"an empty AutoPublishCodeSha256 gives no hash, so the code is hashed");
}
/**
* SAM refuses an AutoPublishCodeSha256 that is not a string: on any function when it is neither a
* string nor a one-key object, and with AutoPublishAlias when it does not resolve to a string.
*/
@Test
void expandSamTemplate_autoPublishCodeSha256MustBeAString() throws Exception {
String template = """
{
"Transform": "AWS::Serverless-2016-10-31",
"Resources": {
"Bucket": {"Type": "AWS::S3::Bucket"},
"MyFunc": {
"Type": "AWS::Serverless::Function",
"Properties": {
"Handler": "index.handler", "Runtime": "nodejs20.x",%s
"InlineCode": "exports.handler = async () => ({});", "AutoPublishCodeSha256": %s
}
}
}
}
""";
String alias = " \"AutoPublishAlias\": \"live\",";
AwsException number = assertThrows(AwsException.class,
() -> processor.expandSamTemplate(objectMapper.readTree(template.formatted("", "12"))));
assertEquals("ValidationError", number.getErrorCode());
assertEquals("Resource with id [MyFunc] is invalid. Type of property 'AutoPublishCodeSha256' is invalid.",
number.getMessage(), "checked whether or not the function publishes a version");
assertEquals("Resource with id [MyFunc] is invalid. Type of property 'AutoPublishCodeSha256' is invalid.",
assertThrows(AwsException.class, () -> publishedVersionId(template.formatted(alias,
"{\"Fn::Sub\": \"a\", \"Fn::Join\": [\"\", []]}"))).getMessage());
for (String unresolved : List.of("{\"Fn::GetAtt\": [\"Bucket\", \"Arn\"]}", "{\"Sha\": \"abc\"}")) {
assertEquals("Resource with id [MyFunc] is invalid. AutoPublishCodeSha256 must be a string",
assertThrows(AwsException.class, () -> publishedVersionId(template.formatted(alias, unresolved)))
.getMessage(), unresolved);
}
assertEquals("Resource with id [MyFuncVersion1.2.3-rc] is invalid. Logical ids must be alphanumeric.",
assertThrows(AwsException.class, () -> publishedVersionId(template.formatted(alias, "\"1.2.3-rc\"")))
.getMessage());
assertEquals("MyFuncVersionabcdefghij", publishedVersionId(template.formatted(alias, "\"abcdefghij-x\"")),
"only the first ten characters name the version");
}
/** SAM's types for the other version properties, and VersionDeletionPolicy needs AutoPublishAlias. */
@Test
void expandSamTemplate_versionPropertiesHaveSamsTypes() throws Exception {
String template = """
{
"Transform": "AWS::Serverless-2016-10-31",
"Parameters": {"Policy": {"Type": "String", "Default": "Retain"}},
"Resources": {
"MyFunc": {
"Type": "AWS::Serverless::Function",
"Properties": {
"Handler": "index.handler", "Runtime": "nodejs20.x",
"InlineCode": "exports.handler = async () => ({});"%s
}
}
}
}
""";
String alias = ", \"AutoPublishAlias\": \"live\"";
for (String allProperties : List.of("\"true\"", "1", "{\"Ref\": \"HashAll\"}")) {
assertEquals("Resource with id [MyFunc] is invalid. Type of property 'AutoPublishAliasAllProperties' "
+ "is invalid.",
assertThrows(AwsException.class, () -> processor.expandSamTemplate(objectMapper.readTree(
template.formatted(alias + ", \"AutoPublishAliasAllProperties\": " + allProperties))))
.getMessage(), allProperties);
}
assertEquals("Resource with id [MyFunc] is invalid. Property 'VersionDeletionPolicy' should be a one of the "
+ "strings: 'Delete' or 'Retain'.",
assertThrows(AwsException.class, () -> processor.expandSamTemplate(objectMapper.readTree(
template.formatted(alias + ", \"VersionDeletionPolicy\": \"retain\"")))).getMessage());
assertEquals("Resource with id [MyFunc] is invalid. 'VersionDeletionPolicy' requires 'AutoPublishAlias'.",
assertThrows(AwsException.class, () -> processor.expandSamTemplate(objectMapper.readTree(
template.formatted(", \"VersionDeletionPolicy\": \"Retain\"")))).getMessage());
assertEquals("{\"Ref\":\"Policy\"}", processor.expandSamTemplate(objectMapper.readTree(
template.formatted(alias + ", \"VersionDeletionPolicy\": {\"Ref\": \"Policy\"}")))
.path("Resources").path("MyFuncVersion102360dfc3").path("DeletionPolicy").toString(),
"an intrinsic function is copied unresolved, as SAM copies it");
}
/** As in SAM, a given AutoPublishCodeSha256 names the version under AutoPublishAliasAllProperties too. */
@Test
void expandSamTemplate_autoPublishCodeSha256OutranksAutoPublishAliasAllProperties() throws Exception {
String template = """
{
"Transform": "AWS::Serverless-2016-10-31",
"Resources": {
"MyFunc": {
"Type": "AWS::Serverless::Function",
"Properties": {
"Handler": "index.handler", "Runtime": "nodejs20.x", "AutoPublishAlias": "live",
"AutoPublishAliasAllProperties": true, "AutoPublishCodeSha256": "abc123",
"InlineCode": "exports.handler = async () => ({});", "Timeout": %d
}
}
}
}
""";
assertEquals("MyFuncVersionabc123", publishedVersionId(template.formatted(3)));
assertEquals("MyFuncVersionabc123", publishedVersionId(template.formatted(9)));
}
/** Globals.Function carries AutoPublishAliasAllProperties and VersionDeletionPolicy, as SAM's do. */
@Test
void expandSamTemplate_versionPropertiesComeFromGlobals() throws Exception {
JsonNode resources = processor.expandSamTemplate(objectMapper.readTree("""
{
"Transform": "AWS::Serverless-2016-10-31",
"Globals": {"Function": {"AutoPublishAlias": "live", "AutoPublishAliasAllProperties": true,
"VersionDeletionPolicy": "Delete"}},
"Resources": {
"MyFunc": {
"Type": "AWS::Serverless::Function",
"Properties": {"Handler": "index.handler", "Runtime": "nodejs20.x",
"InlineCode": "exports.handler = async () => ({});"}
}
}
}
""")).path("Resources");
// Without AutoPublishAliasAllProperties the id is MyFuncVersion102360dfc3.
assertEquals("[\"MyFuncVersionb6788accf2\",\"Version\"]", resources.path("MyFuncAliasLive")
.path("Properties").path("FunctionVersion").path("Fn::GetAtt").toString());
assertEquals("Delete", resources.path("MyFuncVersionb6788accf2").path("DeletionPolicy").asText());
}
/** SAM's Globals do not take AutoPublishCodeSha256, which would name every function's version. */
@Test
void expandSamTemplate_globalsRefuseAutoPublishCodeSha256() throws Exception {
JsonNode template = objectMapper.readTree("""
{
"Transform": "AWS::Serverless-2016-10-31",
"Globals": {"Function": {"AutoPublishAlias": "live", "AutoPublishCodeSha256": "release1234"}},
"Resources": {
"MyFunc": {
"Type": "AWS::Serverless::Function",
"Properties": {"Handler": "index.handler", "Runtime": "nodejs20.x",
"InlineCode": "exports.handler = async () => ({});"}
}
}
}
""");
AwsException refused = assertThrows(AwsException.class, () -> processor.expandSamTemplate(template));
assertEquals("ValidationError", refused.getErrorCode());
assertEquals("'Globals' section is invalid. 'AutoPublishCodeSha256' is not a supported property of "
+ "'Function'.", refused.getMessage());
}
/**
* SAM retains each version it publishes unless the function sets a {@code DeletionPolicy}, which
* the version and alias both take, or a {@code VersionDeletionPolicy}; a function on a capacity
* provider defaults to {@code Delete}.
*/
@Test
void expandSamTemplate_autoPublishAliasVersionDeletionPolicyFollowsSam() throws Exception {
String template = """
{
"Transform": "AWS::Serverless-2016-10-31",
@@ -293,7 +494,16 @@ class SamTransformProcessorTest {
assertEquals("Retain", retained.path("MyFuncVersion102360dfc3").path("DeletionPolicy").asText());
assertTrue(retained.path("MyFuncAliasLive").path("DeletionPolicy").isMissingNode(),
"the alias takes only what the function declares");
assertEquals("Delete", versionDeletionPolicy(template.formatted(" \"DeletionPolicy\": \"Delete\",", "")));
assertEquals("Delete", versionDeletionPolicy(template.formatted(
" \"DeletionPolicy\": \"Delete\",", ", \"VersionDeletionPolicy\": \"Retain\"")));
assertEquals("Delete", versionDeletionPolicy(template.formatted(
"", ", \"VersionDeletionPolicy\": \"Delete\"")));
assertEquals("Retain", versionDeletionPolicy(template.formatted(
"", ", \"VersionDeletionPolicy\": \"Retain\"")));
assertEquals("Delete", versionDeletionPolicy(template.formatted(
"", ", \"CapacityProviderConfig\": {\"Arn\": \"capacity-provider-arn\"}")));
assertEquals("Retain", versionDeletionPolicy(template.formatted("", ", \"VersionDeletionPolicy\": \"Retain\", "
+ "\"CapacityProviderConfig\": {\"Arn\": \"capacity-provider-arn\"}")));
}
private String versionDeletionPolicy(String template) throws Exception {
@@ -332,9 +542,10 @@ class SamTransformProcessorTest {
}
/**
* A parameter reaches the hash the way SAM resolves it: as a {@code Ref}, and as a
* {@code ${Name}} in an {@code Fn::Sub}. Otherwise a parameter-only update changes the function
* but publishes no version, and the alias keeps the old code.
* A parameter reaches the hash the way SAM resolves it: as a {@code Ref}, as a {@code ${Name}}
* in an {@code Fn::Sub}, under {@code AutoPublishAliasAllProperties} too, and in
* {@code AutoPublishCodeSha256}. Otherwise a parameter-only update changes the function but
* publishes no version, and the alias keeps the old code.
*/
@Test
void expandSamTemplate_autoPublishAliasVersionIdFollowsParametersInEveryForm() throws Exception {
@@ -363,6 +574,15 @@ class SamTransformProcessorTest {
publishedVersionId(template.formatted(sub, ""), Map.of("Release", "2")));
assertNotEquals(publishedVersionId(template.formatted(ref, ""), Map.of("Release", "1")),
publishedVersionId(template.formatted(ref, ""), Map.of("Release", "2")));
String allProperties = ", \"AutoPublishAliasAllProperties\": true";
assertNotEquals(publishedVersionId(template.formatted(ref, allProperties), Map.of("Release", "1")),
publishedVersionId(template.formatted(ref, allProperties), Map.of("Release", "2")));
String codeSha = ", \"AutoPublishCodeSha256\": {\"Ref\": \"Release\"}";
assertEquals("MyFuncVersion2",
publishedVersionId(template.formatted("\"app.zip\"", codeSha), Map.of("Release", "2")));
assertEquals(publishedVersionId(template.formatted("\"app.zip\"", ""), Map.of()),
publishedVersionId(template.formatted("\"app.zip\"", codeSha), Map.of("Release", "")),
"a Ref resolving to an empty value leaves the hash in place");
}
private String publishedVersionId(String template) throws Exception {