fix(cloudformation): publish content-hashed versions for SAM AutoPublishAlias

Point the alias AutoPublishAlias generates at the Version attribute of
the generated AWS::Lambda::Version, as SAM does, instead of $LATEST,
and name that version as SAM names it: <Function>Version plus the
first ten hex digits of the SHA-1 of the function's code, with
template parameters resolved as a Ref or as ${Name} in an Fn::Sub,
merged with its Environment and MemorySize, as sorted compact JSON
escaped the way Python's json.dumps escapes it. Under
AutoPublishAliasAllProperties the hash covers every property floci
gives the function. A string AutoPublishCodeSha256 takes the hash's
place with its first ten characters. As in SAM, the version is
retained (DeletionPolicy: Retain) unless the function says otherwise,
and version properties of the wrong type are refused.

With the alias on the published version, a template change to the
code names a new version resource, which publishes, and the alias
moves to it, while changes made to $LATEST outside the stack no longer
reach the alias. The $LATEST pin worked around #1987 and #1988: a cold
invoke of a published version timed out, and a warm $LATEST container
served version-qualified invokes. Both are fixed on main.

Signed-off-by: Jackson Price <59149601+jprice8@users.noreply.github.com>
This commit is contained in:
Jackson Price committed 2026-10-15 16:24:28 +00:00
1 parent 17c40cecbd
commit 156d4ecc9b
6 files changed
+905 -45

No files matched your search

@@ -308,3 +308,56 @@ EOF
run aws_cmd s3api head-bucket --bucket "$bucket"
assert_failure
}
# ── SAM AutoPublishAlias (regression: issue #5676) ────────────────────────────
#
# The alias AutoPublishAlias generates must point at the version the stack
# published, not at $LATEST, and a template code change must publish the next
# version and move the alias to it, as AWS SAM does.
# https://github.com/floci-io/floci/issues/5676
sam_alias_template() {
cat << EOF
Transform: AWS::Serverless-2016-10-31
Resources:
Fn:
Type: AWS::Serverless::Function
Properties:
FunctionName: $1
Runtime: nodejs20.x
Handler: index.handler
AutoPublishAlias: live
InlineCode: "exports.handler = async () => ({ release: '$2' });"
EOF
}
@test "CloudFormation: SAM AutoPublishAlias points the alias at the published version (issue #5676)" {
local fn
fn=$(unique_name bats-sam-alias)
sam_alias_template "$fn" first > "$TEMPLATE_FILE"
run aws_cmd cloudformation deploy \
--stack-name "$STACK_NAME" \
--template-file "$TEMPLATE_FILE" \
--capabilities CAPABILITY_IAM CAPABILITY_AUTO_EXPAND
assert_success
run aws_cmd lambda get-alias --function-name "$fn" --name live
assert_success
[ "$(json_get "$output" '.FunctionVersion')" = "1" ]
# A code change publishes the next version and the alias moves to it.
sam_alias_template "$fn" second > "$TEMPLATE_FILE"
run aws_cmd cloudformation deploy \
--stack-name "$STACK_NAME" \
--template-file "$TEMPLATE_FILE" \
--capabilities CAPABILITY_IAM CAPABILITY_AUTO_EXPAND
assert_success
run aws_cmd lambda get-alias --function-name "$fn" --name live
assert_success
[ "$(json_get "$output" '.FunctionVersion')" = "2" ]
run aws_cmd lambda list-versions-by-function --function-name "$fn"
assert_success
[ "$(json_get "$output" '[.Versions[].Version] | join(",")')" = '$LATEST,1,2' ]
}
+27 -4
View File
@@ -354,6 +354,31 @@ set to exactly what the template lists. Removing the property leaves collection
- Hot-reload code (`S3Bucket: hot-reload`) is compared by host path: the same path is a no-op, a different path updates the bind mount in place.
- `Tags` are applied when the function is created, including a replacement function. On `UpdateStack` the template's tags are applied and only the keys the previous template set and the new one drops are removed, so a tag added outside the template is kept, as in AWS.
## SAM published aliases
`AutoPublishAlias` creates a version and points the generated alias at that version's
numeric `Version` attribute. CloudFormation resolves the version before creating the
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), and its `Environment` and `MemorySize` as
written. An update that changes any of them, 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`. `AutoPublishAliasAllProperties`
hashes every property floci gives the function instead, and a string `AutoPublishCodeSha256`
replaces the hash with its first ten characters. A new id publishes only when the function's code
or configuration changed since its last version, so a new `AutoPublishCodeSha256` alone, or a
`Tags` edit under `AutoPublishAliasAllProperties`, leaves the alias where it is. On AWS a new
`AutoPublishCodeSha256` alone also publishes, because SAM appends it to the function's
`Description`; floci's transform sets no `Description` on the function.
The version a new id replaces stays published: like SAM, floci gives the version
`DeletionPolicy: Retain` unless the function sets a `DeletionPolicy` or `VersionDeletionPolicy`
(or a `CapacityProviderConfig`, which makes it `Delete`), 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`.
## RDS Credential Dynamic References
`AWS::RDS::DBInstance` and `AWS::RDS::DBCluster` resolve CloudFormation dynamic
@@ -564,7 +589,8 @@ asked for it, so the window defaults to 30 seconds (see [Configuration](#configu
## Deletion Policies
A resource's [`DeletionPolicy`](https://docs.aws.amazon.com/AWSCloudFormation/latest/TemplateReference/aws-attribute-deletionpolicy.html)
attribute is honored on `DeleteStack` and on the rollback of a failed `CreateStack`:
attribute is honored on `DeleteStack`, on the rollback of a failed `CreateStack`, and when an
update removes the resource from the template, where it applies as on `DeleteStack`:
| Value | `DeleteStack` | Rollback of the create that made the resource |
|---|---|---|
@@ -597,9 +623,6 @@ Deviations from AWS to be aware of:
- Every resource defaults to `Delete`. AWS instead defaults `AWS::RDS::DBCluster`, and
`AWS::RDS::DBInstance` without a `DBClusterIdentifier`, to `Snapshot`.
- Unrecognized values are treated as `Delete`.
- An update that removes a resource from the template does not delete it (or consult its policy);
only the new template's resources are provisioned. AWS applies `DeletionPolicy` to update-time
removals as well.
- After `DeleteStack` completes, a retained resource's `DELETE_SKIPPED` record is only visible
through `DescribeStackEvents` for the deleted stack, not `DescribeStackResources`.
- `UpdateReplacePolicy`, and the `RetainExceptOnCreate` request parameter of `CreateStack` /
@@ -1,9 +1,13 @@
package io.github.hectorvent.floci.services.cloudformation;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.json.JsonWriteFeature;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.cfg.JsonNodeFeature;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.fasterxml.jackson.databind.node.TextNode;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.common.Digests;
import io.github.hectorvent.floci.core.common.ServicePrincipals;
@@ -37,6 +41,12 @@ class SamTransformProcessor {
private static final Pattern S3_DEFINITION_URI = Pattern.compile(
"^s3://(?<bucket>[^/?]+)/(?<key>.+?)(?:\\?versionId=(?<version>.+))?$");
/** A {@code ${Name}} reference in an {@code Fn::Sub} string, as SAM's translator 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) {
@@ -943,7 +953,8 @@ class SamTransformProcessor {
ObjectNode lambdaResource = createLambdaFunction(logicalId, roleLogicalId, properties, hasExplicitRole);
resources.set(logicalId, lambdaResource);
String aliasLogicalId = expandAutoPublishAlias(logicalId, properties, passthrough, resources);
String aliasLogicalId = expandAutoPublishAlias(logicalId, properties,
lambdaResource.path("Properties"), passthrough, template, parameterValues, resources);
List<ObjectNode> eventInvokePolicies = expandEventInvokeConfig(
logicalId, properties, aliasLogicalId, passthrough, template, resources, parameterValues);
@@ -975,27 +986,36 @@ class SamTransformProcessor {
* template engine resolves it at provision time; only the generated logical id needs a
* literal, and it drops the suffix when the value isn't textual.
*
* <p>The {@code Ref}s on {@code FunctionName} give {@code topologicalSort} the edges it needs
* — function → version and function → alias — so no explicit {@code DependsOn} is needed.
* There is no version → alias edge while {@code FunctionVersion} is the literal
* {@code $LATEST}; none is required, since the alias does not reference the version. It
* returns with the {@code Fn::GetAtt} form once #1987 lands.
* <p>The function reference and version attribute establish function → version → alias
* 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.
*/
private String expandAutoPublishAlias(String functionLogicalId, JsonNode properties, ObjectNode passthrough,
ObjectNode resources) {
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())) {
return null;
}
String versionId = uniqueId(functionLogicalId + "Version", resources);
String versionId = uniqueId(
versionLogicalId(functionLogicalId, properties, functionProperties, template, parameterValues),
resources);
ObjectNode versionDef = objectMapper.createObjectNode();
versionDef.put("Type", "AWS::Lambda::Version");
ObjectNode versionProps = objectMapper.createObjectNode();
versionProps.set("FunctionName", ref(functionLogicalId));
versionDef.set("Properties", versionProps);
versionDef.setAll(passthrough.deepCopy());
// 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.set("DeletionPolicy", defaultVersionDeletionPolicy(properties));
}
resources.set(versionId, versionDef);
// Alias names may legally contain '-' and '_', neither of which is valid in a
@@ -1008,20 +1028,194 @@ class SamTransformProcessor {
ObjectNode aliasProps = objectMapper.createObjectNode();
aliasProps.set("FunctionName", ref(functionLogicalId));
aliasProps.set("Name", aliasName.deepCopy());
// Real SAM points the alias at the published version (Fn::GetAtt <Version>.Version).
// Floci cannot invoke a published version: the snapshot carries no code path, so a
// version-qualified invoke times out on a cold start (#1987) and silently runs $LATEST's
// code when a warm container happens to exist (#1988). Aiming the alias there would break
// the alias-qualified invoke this expansion exists to enable, so point it at $LATEST — the
// alias resolves and runs the function's code, which is the behavior callers depend on.
// Switch to the GetAtt form once #1987 lands.
aliasProps.put("FunctionVersion", "$LATEST");
aliasProps.set("FunctionVersion", getAtt(versionId, "Version"));
aliasDef.set("Properties", aliasProps);
aliasDef.setAll(passthrough.deepCopy());
resources.set(aliasId, aliasDef);
return aliasId;
}
/**
* 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 samtranslator makes on every function's version properties before it transforms
* them: the types it declares for each, and that {@code VersionDeletionPolicy} comes with an
* {@code AutoPublishAlias}. Like SAM's property validation, 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;
}
/**
* SAM's logical id for the version it publishes: {@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} and {@code MemorySize}, or of all its properties
* under {@code AutoPublishAliasAllProperties}, as sorted compact JSON. A string
* {@code AutoPublishCodeSha256} takes the hash's place with its own first ten characters, as
* SAM's {@code LogicalIdGenerator} does with a given hash. 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. Like Python's {@code json.dumps} by default, the JSON escapes every character
* outside printable ASCII, in lowercase hex.
*/
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 (samProperties.path("AutoPublishAliasAllProperties").asBoolean(false)) {
hashed.setAll((ObjectNode) functionProperties.deepCopy());
if (code.isObject()) {
hashed.set("Code", code);
}
} 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());
}
}
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; Python escapes it too.
.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);
}
/**
* 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
* {@code ${Name}} in the string of an {@code Fn::Sub}. Any other reference is left as written.
*/
private JsonNode resolveParameterRefs(JsonNode node, JsonNode template, Map<String, String> parameterValues) {
if (node.isObject() && node.size() == 1 && node.path("Ref").isTextual()) {
String value = parameterValue(node.path("Ref").asText(), template, parameterValues);
return value == null ? node : TextNode.valueOf(value);
}
if (node.isObject() && node.size() == 1 && node.has("Fn::Sub")) {
JsonNode sub = node.get("Fn::Sub");
ObjectNode resolved = objectMapper.createObjectNode();
if (sub.isTextual()) {
resolved.put("Fn::Sub", substituteParameters(sub.asText(), template, parameterValues));
} else if (sub.isArray() && !sub.isEmpty() && sub.get(0).isTextual()) {
ArrayNode arguments = (ArrayNode) resolveParameterRefs(sub, template, parameterValues);
arguments.set(0, TextNode.valueOf(substituteParameters(sub.get(0).asText(), template,
parameterValues)));
resolved.set("Fn::Sub", arguments);
} else {
resolved.set("Fn::Sub", resolveParameterRefs(sub, template, parameterValues));
}
return resolved;
}
if (node.isObject()) {
ObjectNode resolved = objectMapper.createObjectNode();
node.properties().forEach(entry ->
resolved.set(entry.getKey(), resolveParameterRefs(entry.getValue(), template, parameterValues)));
return resolved;
}
if (node.isArray()) {
ArrayNode resolved = objectMapper.createArrayNode();
node.forEach(element -> resolved.add(resolveParameterRefs(element, template, parameterValues)));
return resolved;
}
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) {
Matcher matcher = SUB_REFERENCE.matcher(text);
StringBuilder substituted = new StringBuilder();
while (matcher.find()) {
String value = parameterValue(matcher.group(1), template, parameterValues);
matcher.appendReplacement(substituted, Matcher.quoteReplacement(value == null ? matcher.group() : value));
}
matcher.appendTail(substituted);
return substituted.toString();
}
/** The stack's value for a template parameter, else its {@code Default}, or null for any other name. */
private static String parameterValue(String name, JsonNode template, Map<String, String> parameterValues) {
if (parameterValues.containsKey(name)) {
return parameterValues.get(name);
}
JsonNode defaultValue = template.path("Parameters").path(name).path("Default");
return defaultValue.isValueNode() ? defaultValue.asText() : null;
}
private static final List<String> EVENT_INVOKE_DESTINATION_TYPES =
List.of("SQS", "SNS", "EventBridge", "Lambda", "S3Bucket");
@@ -100,10 +100,8 @@ class SamEventInvokeConfigTransformTest {
}
// SAM passes the function's Condition, DeletionPolicy and UpdateReplacePolicy to the alias
// and version AutoPublishAlias generates as well. Only what the function declares is
// checked: SAM also retains every published version on its own (DeletionPolicy: Retain),
// which floci's AutoPublishAlias expansion has never done and this change does not touch.
JsonNode function = input.path("Resources").path("Fn");
// and version AutoPublishAlias generates as well, and retains the version
// (DeletionPolicy: Retain) when the function declares no DeletionPolicy.
for (Map.Entry<String, JsonNode> byType : fixture.path("expectedAttributesByType").properties()) {
JsonNode generatedResource = null;
for (Map.Entry<String, JsonNode> resource : resources.properties()) {
@@ -112,10 +110,8 @@ class SamEventInvokeConfigTransformTest {
}
}
for (Map.Entry<String, JsonNode> attribute : byType.getValue().properties()) {
if (function.has(attribute.getKey())) {
assertEquals(attribute.getValue(), generatedResource.path(attribute.getKey()),
byType.getKey() + " " + attribute.getKey());
}
assertEquals(attribute.getValue(), generatedResource.path(attribute.getKey()),
byType.getKey() + " " + attribute.getKey());
}
}
@@ -1,14 +1,19 @@
package io.github.hectorvent.floci.services.cloudformation;
import io.github.hectorvent.floci.core.common.XmlParser;
import io.github.hectorvent.floci.testing.RestAssuredJsonUtils;
import io.quarkus.test.junit.QuarkusTest;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Tag;
import org.junit.jupiter.api.Test;
import java.io.ByteArrayOutputStream;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Base64;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
import static io.restassured.RestAssured.given;
@@ -103,7 +108,8 @@ class SamTransformIntegrationTest {
}
@Test
void samFunction_withAutoPublishAlias_createsVersionAndAlias() {
@Tag("docker")
void samFunction_withAutoPublishAlias_createsVersionAndAlias() throws Exception {
String stackName = "sam-alias-stack";
stacksToDelete.add(stackName);
@@ -143,15 +149,10 @@ class SamTransformIntegrationTest {
.then()
.statusCode(200)
.body("Name", equalTo("production"))
// $LATEST rather than the published version real SAM targets — see #1987/#1988 and the
// comment in expandAutoPublishAlias. The invoke below is what actually matters.
.body("FunctionVersion", equalTo("$LATEST"))
.body("FunctionVersion", equalTo("1"))
.body("AliasArn", containsString(":function:sam-alias-func:production"));
// The behavior the whole expansion exists for: an alias-qualified invoke runs the function.
// Asserting only that the alias *record* exists is not enough — an alias pointing at a
// published version satisfies that and still times out on invoke (#1987), which is how an
// earlier revision of this change shipped a broken alias past its own tests.
// Exercise the published code through the generated alias, not only its metadata.
given()
.contentType("application/json")
.body("{}")
@@ -160,6 +161,44 @@ class SamTransformIntegrationTest {
.then()
.statusCode(200)
.header("X-Amz-Function-Error", nullValue())
.header("X-Amz-Executed-Version", equalTo("1"))
.body("ok", equalTo(true));
ByteArrayOutputStream changedCode = new ByteArrayOutputStream();
try (ZipOutputStream zip = new ZipOutputStream(changedCode)) {
zip.putNextEntry(new ZipEntry("index.js"));
zip.write("exports.handler = async () => ({ ok: false });".getBytes(StandardCharsets.UTF_8));
zip.closeEntry();
}
given()
.contentType("application/json")
.body("{\"ZipFile\":\"" + Base64.getEncoder().encodeToString(changedCode.toByteArray()) + "\"}")
.when()
.put("/2015-03-31/functions/sam-alias-func/code")
.then()
.statusCode(200);
given()
.contentType("application/json")
.body("{}")
.when()
.post("/2015-03-31/functions/sam-alias-func/invocations")
.then()
.statusCode(200)
.header("X-Amz-Function-Error", nullValue())
.header("X-Amz-Executed-Version", equalTo("$LATEST"))
.body("ok", equalTo(false));
// Updating $LATEST must neither repoint the SAM alias nor replace its published code.
given()
.contentType("application/json")
.body("{}")
.when()
.post("/2015-03-31/functions/sam-alias-func:production/invocations")
.then()
.statusCode(200)
.header("X-Amz-Function-Error", nullValue())
.header("X-Amz-Executed-Version", equalTo("1"))
.body("ok", equalTo(true));
given()
@@ -185,6 +224,200 @@ class SamTransformIntegrationTest {
assertThat(resourcesXml, containsString("<LogicalResourceId>AliasFunctionAliasProduction</LogicalResourceId>"));
}
@Test
@Tag("docker")
void samAutoPublishAliasFollowsATemplateCodeChangeToANewVersion() {
String stackName = "sam-alias-update-stack";
stacksToDelete.add(stackName);
String template = """
Transform: AWS::Serverless-2016-10-31
Resources:
Function:
Type: AWS::Serverless::Function
Properties:
FunctionName: sam-alias-update-func
Handler: index.handler
Runtime: nodejs20.x
AutoPublishAlias: production
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");
// The changed code names a new version resource, which publishes version 2, and the alias follows it.
given().when().get("/2015-03-31/functions/sam-alias-update-func/aliases/production")
.then().statusCode(200).body("FunctionVersion", equalTo("2"));
given().contentType("application/json").body("{}")
.when().post("/2015-03-31/functions/sam-alias-update-func:production/invocations")
.then()
.statusCode(200)
.header("X-Amz-Function-Error", nullValue())
.header("X-Amz-Executed-Version", equalTo("2"))
.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")));
}
/**
* 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.
*/
@Test
void samAutoPublishAliasCodeChangeSetSwapsTheVersionResource() {
String stackName = "sam-alias-changeset-stack";
String function = "sam-alias-changeset-func";
stacksToDelete.add(stackName);
String template = """
Transform: AWS::Serverless-2016-10-31
Resources:
Function:
Type: AWS::Serverless::Function
Properties:
FunctionName: sam-alias-changeset-func
Handler: index.handler
Runtime: nodejs20.x
AutoPublishAlias: live
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", "CreateChangeSet").formParam("StackName", stackName)
.formParam("ChangeSetName", "second").formParam("ChangeSetType", "UPDATE")
.formParam("TemplateBody", template.formatted("second")).formParam("Capabilities.member.1", "CAPABILITY_IAM")
.when().post("/").then().statusCode(200);
String changeSet = given().contentType("application/x-www-form-urlencoded")
.formParam("Action", "DescribeChangeSet").formParam("StackName", stackName)
.formParam("ChangeSetName", "second")
.when().post("/").then().statusCode(200).extract().asString();
// The ids samtranslator gives the two InlineCode values.
List<String> changes = XmlParser.extractGroups(changeSet, "ResourceChange").stream()
.map(change -> change.get("Action") + " " + change.get("LogicalResourceId"))
.toList();
assertThat(changes, hasItems("Add FunctionVersion7ce4e6a12f", "Remove FunctionVersion6a52d0f87f",
"Modify FunctionAliasLive", "Modify Function"));
given().contentType("application/x-www-form-urlencoded")
.formParam("Action", "ExecuteChangeSet").formParam("StackName", stackName)
.formParam("ChangeSetName", "second")
.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")));
String events = given().contentType("application/x-www-form-urlencoded")
.formParam("Action", "DescribeStackEvents").formParam("StackName", stackName)
.when().post("/").then().statusCode(200).extract().asString();
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_SKIPPED"));
assertThat(oldVersionStatuses, not(hasItem("DELETE_COMPLETE")));
}
@Test
void samAutoPublishAliasKeepsPublishedConfiguration() {
String stackName = "sam-published-config-stack";
String function = "sam-published-config-func";
stacksToDelete.add(stackName);
String template = """
Transform: AWS::Serverless-2016-10-31
Resources:
Function:
Type: AWS::Serverless::Function
Properties:
FunctionName: sam-published-config-func
Handler: index.handler
Runtime: nodejs20.x
MemorySize: 128
AutoPublishAlias: production
Environment:
Variables:
MARKER: original
InlineCode: exports.handler = async () => ({ ok:true });
""";
given().contentType("application/x-www-form-urlencoded")
.formParam("Action", "CreateStack").formParam("StackName", stackName)
.formParam("TemplateBody", template).formParam("Capabilities.member.1", "CAPABILITY_IAM")
.when().post("/").then().statusCode(200);
waitForStackStatus(stackName, "CREATE_COMPLETE");
given().when().get("/2015-03-31/functions/" + function + "/aliases/production")
.then().statusCode(200).body("FunctionVersion", equalTo("1"));
given().contentType("application/json")
.body("{\"MemorySize\":256,\"Environment\":{\"Variables\":{\"MARKER\":\"changed\"}}}")
.when().put("/2015-03-31/functions/" + function + "/configuration")
.then().statusCode(200);
given().when().get("/2015-03-31/functions/" + function + "/configuration")
.then().statusCode(200).body("MemorySize", equalTo(256))
.body("Environment.Variables.MARKER", equalTo("changed"));
given().queryParam("Qualifier", "production")
.when().get("/2015-03-31/functions/" + function + "/configuration")
.then().statusCode(200).body("Version", equalTo("1"))
.body("MemorySize", equalTo(128)).body("Environment.Variables.MARKER", equalTo("original"));
}
@Test
void samFunction_withoutAutoPublishAlias_createsNoAlias() {
String stackName = "sam-no-alias-stack";
@@ -7,6 +7,7 @@ import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import static org.junit.jupiter.api.Assertions.*;
@@ -127,10 +128,13 @@ class SamTransformProcessorTest {
JsonNode resources = processor.expandSamTemplate(template).path("Resources");
assertTrue(resources.has("MyFuncVersion"));
assertEquals("AWS::Lambda::Version", resources.path("MyFuncVersion").path("Type").asText());
// SAM's id: the SHA-1 of {"ZipFile": ...} as sorted compact JSON, the value Python's
// json.dumps(separators=(",", ":"), sort_keys=True) and hashlib.sha1 give.
String versionId = "MyFuncVersion102360dfc3";
assertTrue(resources.has(versionId), resources.toString());
assertEquals("AWS::Lambda::Version", resources.path(versionId).path("Type").asText());
assertEquals("MyFunc",
resources.path("MyFuncVersion").path("Properties").path("FunctionName").path("Ref").asText());
resources.path(versionId).path("Properties").path("FunctionName").path("Ref").asText());
// Suffix is sanitize()d, so the logical id stays alphanumeric — see the alias-name case
// below, where the raw name would otherwise leak a '-' into it.
@@ -141,11 +145,368 @@ class SamTransformProcessorTest {
assertEquals("production", aliasProps.path("Name").asText());
assertEquals("MyFunc", aliasProps.path("FunctionName").path("Ref").asText());
// The alias deliberately targets $LATEST rather than the published version real SAM points
// at: Floci cannot invoke a published version (#1987 cold-start timeout, #1988 warm-pool
// keying), so the faithful form would break the alias-qualified invoke this expansion
// exists to enable.
assertEquals("$LATEST", aliasProps.path("FunctionVersion").asText());
assertEquals(objectMapper.readTree("[\"" + versionId + "\",\"Version\"]"),
aliasProps.path("FunctionVersion").path("Fn::GetAtt"));
}
/** The ids are the ones samtranslator gives for the same input, as recomputed in Python. */
@Test
void expandSamTemplate_autoPublishAliasVersionIdFollowsSamsHashInput() 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"%s
}
}
}
}
""";
String code = "exports.handler = async () => ({});";
assertEquals("MyFuncVersion102360dfc3", publishedVersionId(template.formatted(code, "")));
assertEquals("MyFuncVersion102360dfc3", publishedVersionId(template.formatted(code, ", \"Timeout\": 9")),
"Timeout is outside SAM's hash input, so changing it publishes no version");
assertEquals("MyFuncVersion390d0d3f1c",
publishedVersionId(template.formatted("exports.handler = async () => ({ changed: true });", "")));
assertEquals("MyFuncVersion450730da1b", publishedVersionId(template.formatted(code,
", \"MemorySize\": 256, \"Environment\": {\"Variables\": {\"STAGE\": \"dev\"}}")));
assertEquals("MyFuncVersionccaa7bd288", publishedVersionId(template.formatted(code,
", \"Environment\": {\"Variables\": {\"STAGE\": \"dev\", \"APP\": \"orders\"}}")),
"nested keys are sorted too");
}
/**
* Python's {@code json.dumps} escapes everything outside printable ASCII, DEL included, in
* lowercase hex, and a character beyond the Basic Multilingual Plane as its surrogate pair.
*/
@Test
void expandSamTemplate_autoPublishAliasVersionIdEscapesTheCodeAsPythonDoes() 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"
}
}
}
}
""";
assertEquals("MyFuncVersion307c99f964", publishedVersionId(template.formatted(
"exports.handler = async () => ({ msg: 'caf\u00e9 \u2192 ok' });")));
assertEquals("MyFuncVersion3bd79f6f3e", publishedVersionId(template.formatted("a\u007fb\\u001fc")));
assertEquals("MyFuncVersion3d3709555d", publishedVersionId(template.formatted("x \uD83D\uDE00")));
}
/**
* SAM resolves parameters only in the code: one that only {@code Environment} or
* {@code MemorySize} uses is hashed as the {@code Ref}, so changing its value publishes nothing.
*/
@Test
void expandSamTemplate_autoPublishAliasVersionIdIgnoresParametersOutsideTheCode() throws Exception {
String template = """
{
"Transform": "AWS::Serverless-2016-10-31",
"Parameters": {"Release": {"Type": "String"}, "Memory": {"Type": "Number"}},
"Resources": {
"MyFunc": {
"Type": "AWS::Serverless::Function",
"Properties": {
"Handler": "index.handler", "Runtime": "nodejs20.x", "AutoPublishAlias": "live",
"CodeUri": "s3://artifacts/app.zip", "MemorySize": {"Ref": "Memory"},
"Environment": {"Variables": {"RELEASE": {"Ref": "Release"}}}
}
}
}
}
""";
assertEquals(publishedVersionId(template, Map.of("Release", "1", "Memory", "128")),
publishedVersionId(template, Map.of("Release", "2", "Memory", "256")));
}
/**
* A given {@code AutoPublishCodeSha256} is the hash: samtranslator's {@code LogicalIdGenerator}
* returns its first ten characters and hashes nothing else, so the code alone no longer names
* the version.
*/
@Test
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 passed on for CloudFormation to resolve");
}
/**
* 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",
"Resources": {
"MyFunc": {
"Type": "AWS::Serverless::Function",%s
"Properties": {
"Handler": "index.handler", "Runtime": "nodejs20.x", "AutoPublishAlias": "live",
"InlineCode": "exports.handler = async () => ({});"%s
}
}
}
}
""";
JsonNode retained = processor.expandSamTemplate(objectMapper.readTree(template.formatted("", "")))
.path("Resources");
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\",", ", \"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 {
return processor.expandSamTemplate(objectMapper.readTree(template)).path("Resources")
.path("MyFuncVersion102360dfc3").path("DeletionPolicy").asText();
}
@Test
void expandSamTemplate_autoPublishAliasVersionIdResolvesParameterReferencesInTheCode() throws Exception {
JsonNode template = objectMapper.readTree("""
{
"Transform": "AWS::Serverless-2016-10-31",
"Parameters": {"CodeKey": {"Type": "String", "Default": "v1/code.zip"}},
"Resources": {
"MyFunc": {
"Type": "AWS::Serverless::Function",
"Properties": {
"Handler": "index.handler", "Runtime": "nodejs20.x", "AutoPublishAlias": "live",
"CodeUri": {"Bucket": "artifacts", "Key": {"Ref": "CodeKey"}}
}
}
}
}
""");
JsonNode resources = processor.expandSamTemplate(template, Map.of("CodeKey", "v2/code.zip"))
.path("Resources");
assertEquals("[\"MyFuncVersionf3ad9caea0\",\"Version\"]",
resources.path("MyFuncAliasLive").path("Properties").path("FunctionVersion")
.path("Fn::GetAtt").toString());
// SAM writes the resolved value into the function's Code; floci keeps the Ref, which
// CloudFormation resolves to the same value. Resolving for the hash must not rewrite it.
assertEquals("CodeKey", resources.path("MyFunc").path("Properties").path("Code").path("S3Key")
.path("Ref").asText());
}
/**
* 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 {
String template = """
{
"Transform": "AWS::Serverless-2016-10-31",
"Parameters": {"Release": {"Type": "String"}},
"Resources": {
"MyFunc": {
"Type": "AWS::Serverless::Function",
"Properties": {
"Handler": "index.handler", "Runtime": "nodejs20.x", "AutoPublishAlias": "live",
"CodeUri": {"Bucket": "artifacts", "Key": %s}%s
}
}
}
}
""";
String sub = "{\"Fn::Sub\": \"app-${Release}.zip\"}";
String ref = "{\"Ref\": \"Release\"}";
assertEquals(publishedVersionId(template.formatted("{\"Fn::Sub\": \"app-2.zip\"}", ""), Map.of()),
publishedVersionId(template.formatted(sub, ""), Map.of("Release", "2")),
"a substituted parameter hashes as its value");
assertNotEquals(publishedVersionId(template.formatted(sub, ""), Map.of("Release", "1")),
publishedVersionId(template.formatted(sub, ""), 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")));
}
private String publishedVersionId(String template) throws Exception {
return publishedVersionId(template, Map.of());
}
private String publishedVersionId(String template, Map<String, String> parameterValues) throws Exception {
JsonNode resources = processor.expandSamTemplate(objectMapper.readTree(template), parameterValues)
.path("Resources");
return resources.path("MyFuncAliasLive").path("Properties").path("FunctionVersion")
.path("Fn::GetAtt").get(0).asText();
}
/**
* SAM itself refuses a template that already declares an id it generates; floci has always
* renamed its generated resource instead, and the alias must still follow the generated version.
*/
@Test
void expandSamTemplate_autoPublishAliasUsesGeneratedVersionWhenLogicalIdCollides() throws Exception {
JsonNode template = objectMapper.readTree("""
{
"Transform": "AWS::Serverless-2016-10-31",
"Resources": {
"MyFuncVersion102360dfc3": {"Type": "AWS::S3::Bucket"},
"MyFunc": {
"Type": "AWS::Serverless::Function",
"Properties": {
"Handler": "index.handler", "Runtime": "nodejs20.x",
"AutoPublishAlias": {"Ref": "StageName"},
"InlineCode": "exports.handler = async () => ({});"
}
}
}
}
""");
JsonNode resources = processor.expandSamTemplate(template).path("Resources");
JsonNode versionRef = resources.path("MyFuncAlias").path("Properties")
.path("FunctionVersion").path("Fn::GetAtt");
String generatedVersion = versionRef.get(0).asText();
assertEquals("MyFuncVersion102360dfc32", generatedVersion);
assertEquals("AWS::S3::Bucket", resources.path("MyFuncVersion102360dfc3").path("Type").asText());
assertEquals("AWS::Lambda::Version", resources.path(generatedVersion).path("Type").asText());
assertEquals("Version", versionRef.get(1).asText());
assertEquals("StageName", resources.path("MyFuncAlias").path("Properties")
.path("Name").path("Ref").asText());
}
@Test