mirror of
https://github.com/floci-io/floci.git
synced 2026-12-01 01:12:48 -05:00
fix(cloudformation): publish content-hashed versions for SAM AutoPublishAlias (#5744)
* 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>
* fix(cloudformation): hash an applied SnapStart into the SAM version id
SAM adds a function's SnapStart to the hash behind the AutoPublishAlias
version's logical id when its ApplyOn is anything but None, so turning
SnapStart on names a new version, which publishes and gets its
snapshot. Without it a SnapStart function got a different id than SAM
gives it, and changing SnapStart published nothing. Under
AutoPublishAliasAllProperties SnapStart is hashed like the other
properties.
Signed-off-by: Jackson Price <59149601+jprice8@users.noreply.github.com>
* refactor(cloudformation): resolve SAM destination types with parameterValue
destinationType repeated the parameter lookup parameterValue already
does for the version hash: the stack's value, else the Default. Use the
one helper. A non-string Default still names no destination type.
Signed-off-by: Jackson Price <59149601+jprice8@users.noreply.github.com>
* docs(cloudformation): describe the SAM version hash in SAM terms
Reword the comments and test names around the AutoPublishAlias version
id to state what SAM and CloudFormation do, rather than how another
project or language implements it.
Signed-off-by: Jackson Price <59149601+jprice8@users.noreply.github.com>
* fix(cloudformation): hash a null SnapStart ApplyOn and state what it changes
SAM leaves SnapStart out of the version hash only when ApplyOn is
missing or "None"; a null ApplyOn is hashed. The check read a null as
"None".
floci does not pass SnapStart to the function, so turning it on
changes the version's logical id but publishes no new version, and
no snapshot is taken. 44eae301d said it publishes; the docs and the
comment now say what happens.
Signed-off-by: Jackson Price <59149601+jprice8@users.noreply.github.com>
* docs(cloudformation): say which characters the SAM version hash escapes
Characters outside printable ASCII are hex escapes except where JSON
has a short escape, such as a newline's, and SnapStart is hashed only
when it sets an ApplyOn other than None.
Signed-off-by: Jackson Price <59149601+jprice8@users.noreply.github.com>
* refactor(cloudformation): leave the optional SAM version properties to their own change
Take AutoPublishCodeSha256, AutoPublishAliasAllProperties and
VersionDeletionPolicy, with their validation, docs and tests, out of
the AutoPublishAlias fix so they can follow as their own change. The
transform no longer reads them, as on main: each is ignored, never
refused, and none changes the version's logical id or its
DeletionPolicy. The CapacityProviderConfig default goes with
VersionDeletionPolicy.
The fix keeps the alias on Fn::GetAtt of the version's Version, the
hashed version id over the code, Environment, MemorySize and an
applied SnapStart, and the version's default DeletionPolicy: Retain.
Signed-off-by: Jackson Price <59149601+jprice8@users.noreply.github.com>
---------
Signed-off-by: Jackson Price <59149601+jprice8@users.noreply.github.com>
This commit is contained in:
1 parent
a2d02ef967
commit
3cb1643d30
6 files changed
+677
-52
No files matched your search
+4
-8
@@ -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());
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+194
-8
@@ -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";
|
||||
|
||||
+271
-8
@@ -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
|
||||
|
||||
Reference in new issue
Block a user