Skip to content

armgit / floci

Public Imported from GitHub
0

Light, fluffy, and always free - The AWS Local Emulator alternative

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

Jackson Price3cb1643d3018
diff --git a/compatibility-tests/sdk-test-awscli/test/cloudformation.bats b/compatibility-tests/sdk-test-awscli/test/cloudformation.bats
index 644e76422b..ace02ed7bf 100644
--- a/compatibility-tests/sdk-test-awscli/test/cloudformation.bats
+++ b/compatibility-tests/sdk-test-awscli/test/cloudformation.bats
@@ -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' ]
+}
diff --git a/docs/services/cloudformation.md b/docs/services/cloudformation.md
index b61d25fea6..7f1da752d1 100644
--- a/docs/services/cloudformation.md
+++ b/docs/services/cloudformation.md
@@ -395,6 +395,27 @@ 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), 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.
+
+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`.
+
## RDS Credential Dynamic References
`AWS::RDS::DBInstance` and `AWS::RDS::DBCluster` resolve CloudFormation dynamic
@@ -639,7 +660,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 |
|---|---|---|
@@ -672,9 +694,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` is honored only by the resource types that delete a displaced resource once
diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudformation/SamTransformProcessor.java b/src/main/java/io/github/hectorvent/floci/services/cloudformation/SamTransformProcessor.java
index f30712ad0f..9167d3a6d6 100644
--- a/src/main/java/io/github/hectorvent/floci/services/cloudformation/SamTransformProcessor.java
+++ b/src/main/java/io/github/hectorvent/floci/services/cloudformation/SamTransformProcessor.java
@@ -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,9 @@ 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 matches one. */
+ private static final Pattern SUB_REFERENCE = Pattern.compile("\\$\\{([A-Za-z0-9.]+|AWS::[A-Z][A-Za-z]*)}");
+
private final ObjectMapper objectMapper;
SamTransformProcessor(ObjectMapper objectMapper) {
@@ -943,7 +950,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 +983,35 @@ 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) {
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.put("DeletionPolicy", "Retain");
+ }
resources.set(versionId, versionDef);
// Alias names may legally contain '-' and '_', neither of which is valid in a
@@ -1008,20 +1024,118 @@ 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;
}
+ /**
+ * The logical id SAM gives 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}, 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.
+ */
+ private String versionLogicalId(String functionLogicalId, JsonNode samProperties, JsonNode functionProperties,
+ JsonNode template, Map<String, String> parameterValues) {
+ 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());
+ }
+ 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);
+ }
+
+ /**
+ * {@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");
@@ -1204,13 +1318,7 @@ class SamTransformProcessor {
private static String destinationType(JsonNode type, JsonNode template, Map<String, String> parameterValues) {
String value = type.isTextual() ? type.asText() : null;
if (type.isObject() && type.size() == 1 && type.path("Ref").isTextual()) {
- String parameter = type.path("Ref").asText();
- JsonNode defaultValue = template.path("Parameters").path(parameter).path("Default");
- if (parameterValues.containsKey(parameter)) {
- value = parameterValues.get(parameter);
- } else if (defaultValue.isTextual()) {
- value = defaultValue.asText();
- }
+ value = parameterValue(type.path("Ref").asText(), template, parameterValues);
}
return value != null && EVENT_INVOKE_DESTINATION_TYPES.contains(value) ? value : null;
}
diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/SamEventInvokeConfigTransformTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/SamEventInvokeConfigTransformTest.java
index 1350ed148a..ccc3e7a595 100644
--- a/src/test/java/io/github/hectorvent/floci/services/cloudformation/SamEventInvokeConfigTransformTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/SamEventInvokeConfigTransformTest.java
@@ -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());
}
}
diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/SamTransformIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/SamTransformIntegrationTest.java
index 2a2e027836..91c44a1aea 100644
--- a/src/test/java/io/github/hectorvent/floci/services/cloudformation/SamTransformIntegrationTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/SamTransformIntegrationTest.java
@@ -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,153 @@ 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"));
+ }
+
+ /**
+ * 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 SAM 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";
diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/SamTransformProcessorTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/SamTransformProcessorTest.java
index a22865171f..f57a1912a3 100644
--- a/src/test/java/io/github/hectorvent/floci/services/cloudformation/SamTransformProcessorTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/SamTransformProcessorTest.java
@@ -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,12 @@ 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 first ten hex digits of the SHA-1 of {"ZipFile": ...} as sorted compact JSON.
+ 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 +144,271 @@ 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 SAM gives the same function. */
+ @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");
+ }
+
+ /**
+ * 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.
+ */
+ @Test
+ void expandSamTemplate_autoPublishAliasVersionIdIncludesAppliedSnapStart() throws Exception {
+ String template = """
+ {
+ "Transform": "AWS::Serverless-2016-10-31",
+ "Resources": {
+ "MyFunc": {
+ "Type": "AWS::Serverless::Function",
+ "Properties": {
+ "Handler": "index.handler", "Runtime": "java21", "AutoPublishAlias": "live",
+ "InlineCode": "exports.handler = async () => ({});"%s
+ }
+ }
+ }
+ }
+ """;
+ String snapStart = ", \"SnapStart\": {\"ApplyOn\": \"PublishedVersions\"}";
+
+ assertEquals("MyFuncVersiona8f283d3fa", publishedVersionId(template.formatted(snapStart)));
+ assertEquals("MyFuncVersion2154246fbb",
+ publishedVersionId(template.formatted(", \"MemorySize\": 256" + snapStart)));
+ assertEquals("MyFuncVersion3c4b5efba5",
+ publishedVersionId(template.formatted(", \"SnapStart\": {\"ApplyOn\": null}")),
+ "a null ApplyOn is not None, so SAM hashes it");
+ for (String off : List.of("", ", \"SnapStart\": {\"ApplyOn\": \"None\"}", ", \"SnapStart\": {}")) {
+ assertEquals("MyFuncVersion102360dfc3", publishedVersionId(template.formatted(off)), off);
+ }
+ }
+
+ /**
+ * SAM hashes the code with every character outside printable ASCII, DEL included, written as a
+ * lowercase hex escape (JSON's short escapes such as a newline's stay short), and a character
+ * beyond the Basic Multilingual Plane as its surrogate pair.
+ */
+ @Test
+ void expandSamTemplate_autoPublishAliasVersionIdEscapesTheCodeAsSamDoes() 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")));
+ }
+
+ /**
+ * SAM retains each version it publishes unless the function sets a {@code DeletionPolicy}, which
+ * the version and alias both take.
+ */
+ @Test
+ void expandSamTemplate_autoPublishAliasVersionIsRetainedUnlessTheFunctionSaysOtherwise() 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\",", "")));
+ }
+
+ 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}, 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.
+ */
+ @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")));
+ assertNotEquals(publishedVersionId(template.formatted(ref, ""), Map.of("Release", "1")),
+ publishedVersionId(template.formatted(ref, ""), 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