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

* fix(cloudformation): transform SAM layer versions

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

No files matched your search

@@ -0,0 +1,239 @@
package io.github.hectorvent.floci.services.cloudformation;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import io.github.hectorvent.floci.core.common.AwsException;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
class SamLayerVersionTransformTest {
private final ObjectMapper mapper = new ObjectMapper();
private final SamTransformProcessor processor = new SamTransformProcessor(mapper);
private JsonNode template(String properties) throws Exception {
return mapper.readTree("""
{"Transform":"AWS::Serverless-2016-10-31","Resources":{
"Layer":{"Type":"AWS::Serverless::LayerVersion","Properties":%s}},
"Outputs":{"LayerArn":{"Value":{"Ref":"Layer"}}}}
""".formatted(properties));
}
@Test
void packagedLayerIsTransformedAndReferencesFollowItsVersion() throws Exception {
JsonNode result = processor.expandSamTemplate(template("""
{"ContentUri":{"Bucket":{"Ref":"Bucket"},"Key":"layer.zip","Version":"v1"},
"CompatibleRuntimes":["nodejs22.x"],"CompatibleArchitectures":["arm64"],
"Description":"shared code","LicenseInfo":"MIT","RetentionPolicy":"Delete"}
"""));
String id = result.path("Resources").fieldNames().next();
JsonNode layer = result.path("Resources").path(id);
assertEquals("AWS::Lambda::LayerVersion", layer.path("Type").asText());
assertTrue(id.matches("Layer[0-9a-f]{10}"));
assertEquals(id, result.at("/Outputs/LayerArn/Value/Ref").asText());
assertEquals("Layer", layer.at("/Properties/LayerName").asText());
assertEquals("Bucket", layer.at("/Properties/Content/S3Bucket/Ref").asText());
assertEquals("layer.zip", layer.at("/Properties/Content/S3Key").asText());
assertEquals("v1", layer.at("/Properties/Content/S3ObjectVersion").asText());
assertEquals("arm64", layer.at("/Properties/CompatibleArchitectures/0").asText());
assertEquals("nodejs22.x", layer.at("/Properties/CompatibleRuntimes/0").asText());
assertEquals("MIT", layer.at("/Properties/LicenseInfo").asText());
assertEquals("Delete", layer.path("DeletionPolicy").asText());
}
@Test
void stringContentUriAndDefaultRetentionAreSupported() throws Exception {
JsonNode result = processor.expandSamTemplate(template("{\"ContentUri\":\"s3://layers/code.zip?versionId=abc\"}"));
JsonNode layer = result.path("Resources").elements().next();
assertEquals("AWS::Lambda::LayerVersion", layer.path("Type").asText());
assertEquals("layers", layer.at("/Properties/Content/S3Bucket").asText());
assertEquals("abc", layer.at("/Properties/Content/S3ObjectVersion").asText());
assertEquals("Retain", layer.path("DeletionPolicy").asText());
}
@Test
void wholeContentUriParameterReferenceIsResolvedBeforeSplitting() throws Exception {
ObjectNode input = (ObjectNode) template("{\"ContentUri\":{\"Ref\":\"PackageUri\"}}");
input.putObject("Parameters").putObject("PackageUri").put("Type", "String")
.put("Default", "s3://layers/code.zip?versionId=v9");
JsonNode content = processor.expandSamTemplate(input).path("Resources").elements().next()
.path("Properties").path("Content");
assertEquals("layers", content.path("S3Bucket").asText());
assertEquals("code.zip", content.path("S3Key").asText());
assertEquals("v9", content.path("S3ObjectVersion").asText());
}
@Test
void changedContentProducesANewLogicalId() throws Exception {
JsonNode first = processor.expandSamTemplate(template("{\"ContentUri\":\"s3://layers/one.zip\"}"));
JsonNode second = processor.expandSamTemplate(template("{\"ContentUri\":\"s3://layers/two.zip\"}"));
assertNotEquals(first.path("Resources").fieldNames().next(), second.path("Resources").fieldNames().next());
}
@Test
void referencesDependenciesAndSubstitutionVariablesArePreserved() throws Exception {
JsonNode input = mapper.readTree("""
{"Transform":"AWS::Serverless-2016-10-31","Resources":{
"Layer":{"Type":"AWS::Serverless::LayerVersion","Condition":"UseLayer",
"Metadata":{"purpose":"shared"},"DeletionPolicy":"Delete",
"Properties":{"ContentUri":"s3://layers/code.zip"}},
"Consumer":{"Type":"AWS::Lambda::Function","DependsOn":["Layer"],
"Properties":{"Layers":[{"Ref":"Layer"}]}},
"Other":{"Type":"AWS::S3::Bucket","DependsOn":"Layer"}},
"Outputs":{
"Direct":{"Value":{"Fn::Sub":"${Layer}-${Layer.Arn}-${!Layer}"}},
"Shadowed":{"Value":{"Fn::Sub":["${Layer}-${Layer.Arn}",{"Layer":"literal"}]}},
"Attribute":{"Value":{"Fn::GetAtt":["Layer","Arn"]}},
"Dotted":{"Value":{"Fn::GetAtt":"Layer.Arn"}}}}
""");
JsonNode result = processor.expandSamTemplate(input);
String id = result.path("Resources").properties().stream()
.filter(entry -> "AWS::Lambda::LayerVersion".equals(entry.getValue().path("Type").asText()))
.findFirst().orElseThrow().getKey();
assertEquals("Layer", input.at("/Resources/Consumer/DependsOn/0").asText());
assertEquals(id, result.at("/Resources/Consumer/DependsOn/0").asText());
assertEquals(id, result.at("/Resources/Other/DependsOn").asText());
assertEquals(id, result.at("/Resources/Consumer/Properties/Layers/0/Ref").asText());
assertEquals("${" + id + "}-${" + id + ".Arn}-${!Layer}", result.at("/Outputs/Direct/Value/Fn::Sub").asText());
assertEquals("${Layer}-${" + id + ".Arn}", result.at("/Outputs/Shadowed/Value/Fn::Sub/0").asText());
assertEquals(id, result.at("/Outputs/Attribute/Value/Fn::GetAtt/0").asText());
assertEquals(id + ".Arn", result.at("/Outputs/Dotted/Value/Fn::GetAtt").asText());
assertEquals("UseLayer", result.path("Resources").path(id).path("Condition").asText());
assertEquals("Delete", result.path("Resources").path(id).path("DeletionPolicy").asText());
}
@Test
void metadataAndResourceRetentionDoNotChangeVersionIdentity() throws Exception {
JsonNode first = template("{\"ContentUri\":\"s3://layers/code.zip\"}");
JsonNode second = first.deepCopy();
((ObjectNode) second.at("/Resources/Layer"))
.putObject("Metadata").put("note", "updated documentation");
((ObjectNode) second.at("/Resources/Layer"))
.put("DeletionPolicy", "Delete");
assertEquals(processor.expandSamTemplate(first).path("Resources").fieldNames().next(),
processor.expandSamTemplate(second).path("Resources").fieldNames().next());
}
@Test
void inheritedGlobalLayersFollowTheGeneratedLayer() throws Exception {
ObjectNode input = (ObjectNode) template("{\"ContentUri\":\"s3://layers/code.zip\"}");
input.putObject("Globals").putObject("Function").putArray("Layers").addObject().put("Ref", "Layer");
ObjectNode function = ((ObjectNode) input.path("Resources")).putObject("Function");
function.put("Type", "AWS::Serverless::Function");
function.putObject("Properties").put("Runtime", "nodejs22.x").put("Handler", "index.handler")
.put("InlineCode", "exports.handler=async()=>({})");
JsonNode result = processor.expandSamTemplate(input);
String id = result.at("/Outputs/LayerArn/Value/Ref").asText();
assertEquals(id, result.at("/Resources/Function/Properties/Layers/0/Ref").asText());
}
@Test
void listParameterReferencesRemainTypedForTheProvisioner() throws Exception {
ObjectNode input = (ObjectNode) template("""
{"ContentUri":"s3://layers/code.zip","CompatibleRuntimes":{"Ref":"Runtimes"},
"CompatibleArchitectures":{"Ref":"Architectures"}}
""");
input.putObject("Parameters").putObject("Runtimes").put("Type", "CommaDelimitedList")
.put("Default", "nodejs22.x,python3.14");
((ObjectNode) input.path("Parameters")).putObject("Architectures").put("Type", "CommaDelimitedList")
.put("Default", "arm64");
JsonNode layer = processor.expandSamTemplate(input).path("Resources").elements().next();
assertEquals("Runtimes", layer.at("/Properties/CompatibleRuntimes/Ref").asText());
assertEquals("Architectures", layer.at("/Properties/CompatibleArchitectures/Ref").asText());
}
@Test
void subOverlayVariablesWinOverSameNamedParameters() throws Exception {
ObjectNode input = (ObjectNode) template("""
{"ContentUri":{"Bucket":{"Fn::Sub":["${Bucket}-${Env}",{"Bucket":"layers"}]},
"Key":{"Fn::Sub":["${Env}/${Key}.zip",{"Key":"layer"}]}}}
""");
input.putObject("Parameters").putObject("Bucket").put("Type", "String").put("Default", "other-bucket");
((ObjectNode) input.path("Parameters")).putObject("Env").put("Type", "String").put("Default", "staging");
JsonNode content = processor.expandSamTemplate(input).path("Resources").elements().next()
.path("Properties").path("Content");
// The deployed Content keeps the original !Sub expressions, so CloudFormation resolves the
// parameter once at deploy and names the same !Sub declares locally stay local.
assertEquals("${Bucket}-${Env}", content.at("/S3Bucket/Fn::Sub/0").asText());
assertEquals("layers", content.at("/S3Bucket/Fn::Sub/1/Bucket").asText());
assertEquals("${Env}/${Key}.zip", content.at("/S3Key/Fn::Sub/0").asText());
assertEquals("layer", content.at("/S3Key/Fn::Sub/1/Key").asText());
}
@Test
void deployedContentKeepsOriginalSubExpressionsForTheTemplateEngine() throws Exception {
// A parameter whose text itself contains ${Env} must not be re-substituted at deploy:
// CloudFormation resolves ${PackageKey} once, so the literal stays intact for the engine.
ObjectNode input = (ObjectNode) template("""
{"ContentUri":{"Bucket":"layers","Key":{"Fn::Sub":"${PackageKey}"}}}
""");
input.putObject("Parameters").putObject("PackageKey").put("Type", "String").put("Default", "layers/${Env}.zip");
((ObjectNode) input.path("Parameters")).putObject("Env").put("Type", "String").put("Default", "staging");
JsonNode content = processor.expandSamTemplate(input).path("Resources").elements().next()
.path("Properties").path("Content");
assertEquals("${PackageKey}", content.at("/S3Key/Fn::Sub").asText());
// The deployed bucket and key keep their !Sub forms, but the generated logical id hashes the
// resolved copy, so two parameter values that select different packages get two distinct ids.
ObjectNode first = (ObjectNode) template("""
{"ContentUri":{"Bucket":{"Fn::Sub":"${Bucket}"},"Key":{"Fn::Sub":"${Key}"}}}
""");
addSubParams(first, "layers", "one.zip");
ObjectNode second = (ObjectNode) template("""
{"ContentUri":{"Bucket":{"Fn::Sub":"${Bucket}"},"Key":{"Fn::Sub":"${Key}"}}}
""");
addSubParams(second, "layers", "two.zip");
assertNotEquals(processor.expandSamTemplate(first).path("Resources").fieldNames().next(),
processor.expandSamTemplate(second).path("Resources").fieldNames().next());
}
private static void addSubParams(ObjectNode input, String bucket, String key) {
input.putObject("Parameters").putObject("Bucket").put("Type", "String").put("Default", bucket);
((ObjectNode) input.path("Parameters")).putObject("Key").put("Type", "String").put("Default", key);
}
@Test
void subLocalVariableNamedRefIsNotTreatedAsAResourceReference() throws Exception {
ObjectNode input = (ObjectNode) mapper.readTree("""
{"Transform":"AWS::Serverless-2016-10-31","Resources":{
"Consumer":{"Type":"AWS::Lambda::Function",
"Properties":{"Layers":[{"Ref":"Layer"}],
"Environment":{"Variables":{"Url":{"Fn::Sub":["${Name}-${Layer}-${Ref}",{"Name":"n","Ref":"Layer"}]}}}}},
"Layer":{"Type":"AWS::Serverless::LayerVersion",
"Properties":{"ContentUri":"s3://layers/code.zip"}}}}
""");
JsonNode result = processor.expandSamTemplate(input);
String id = result.at("/Resources/Consumer/Properties/Layers/0/Ref").asText();
assertTrue(id.startsWith("Layer") && id.length() > "Layer".length());
JsonNode url = result.at("/Resources/Consumer/Properties/Environment/Variables/Url");
// The real ${Layer} use follows the renamed layer, while ${Name} and ${Ref} stay local and
// the map value under the variable named Ref remains the literal Layer, never the hashed id.
assertEquals("${Name}-${" + id + "}-${Ref}", url.at("/Fn::Sub/0").asText());
assertEquals("n", url.at("/Fn::Sub/1/Name").asText());
assertEquals("Layer", url.at("/Fn::Sub/1/Ref").asText());
}
@Test
void literalDependsOnValuesAreNotResourceDependencies() throws Exception {
ObjectNode input = (ObjectNode) template("{\"ContentUri\":\"s3://layers/code.zip\"}");
ObjectNode function = ((ObjectNode) input.path("Resources")).putObject("Function");
function.put("Type", "AWS::Serverless::Function");
ObjectNode properties = function.putObject("Properties");
properties.put("Runtime", "nodejs22.x").put("Handler", "index.handler")
.put("InlineCode", "exports.handler=async()=>({})");
properties.putObject("Environment").putObject("Variables").put("DependsOn", "Layer");
JsonNode result = processor.expandSamTemplate(input);
assertEquals("Layer", result.at("/Resources/Function/Properties/Environment/Variables/DependsOn").asText());
}
@Test
void unpackagedOrIncompleteContentIsRejectedBeforeProvisioning() throws Exception {
for (String props : new String[]{"{}", "{\"ContentUri\":\"./layer\"}",
"{\"ContentUri\":{\"Bucket\":\"layers\"}}",
"{\"ContentUri\":\"s3://layers/code.zip\",\"RetentionPolicy\":\"invalid\"}"}) {
JsonNode input = template(props);
assertThrows(AwsException.class, () -> processor.expandSamTemplate(input));
}
}
}
@@ -20,6 +20,7 @@ import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
import static io.restassured.RestAssured.given;
import static org.awaitility.Awaitility.await;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.emptyOrNullString;
@@ -2213,6 +2214,109 @@ class SamTransformIntegrationTest {
.body("definition", not(containsString("${TableName}")));
}
@Test
void samLayerVersionPublishesPackagedCodeAndReturnsItsArn() {
String stack = "sam-layer-stack";
String bucket = "sam-layer-code";
stacksToDelete.add(stack);
given().when().put("/" + bucket).then().statusCode(200);
given().contentType("application/zip").body(buildHandlerZip())
.when().put("/" + bucket + "/layer.zip").then().statusCode(200);
String template = """
Transform: AWS::Serverless-2016-10-31
Parameters:
Bucket: {Type: String}
Runtimes: {Type: CommaDelimitedList, Default: 'nodejs22.x,python3.14'}
Architectures: {Type: CommaDelimitedList, Default: arm64}
Globals:
Function:
Runtime: nodejs22.x
Architectures: [arm64]
Handler: index.handler
Layers: [!Ref Layer]
Resources:
Layer:
Type: AWS::Serverless::LayerVersion
Properties:
LayerName: sam-shared-layer
ContentUri:
Bucket: !Ref Bucket
Key: layer.zip
CompatibleRuntimes: !Ref Runtimes
CompatibleArchitectures: !Ref Architectures
LicenseInfo: MIT
RetentionPolicy: Delete
Function:
Type: AWS::Serverless::Function
Properties:
FunctionName: sam-layer-consumer
InlineCode: 'exports.handler=async()=>({})'
Environment:
Variables:
DependsOn: Layer
Outputs:
LayerArn:
Value: !Ref Layer
LayerSub:
Value: !Sub '${Layer}'
""";
try {
given().contentType("application/x-www-form-urlencoded")
.formParam("Action", "CreateStack").formParam("StackName", stack)
.formParam("Capabilities.member.1", "CAPABILITY_IAM")
.formParam("TemplateBody", template)
.formParam("Parameters.member.1.ParameterKey", "Bucket")
.formParam("Parameters.member.1.ParameterValue", bucket)
.when().post("/").then().statusCode(200);
waitForStackStatus(stack, "CREATE_COMPLETE");
String description = given().contentType("application/x-www-form-urlencoded")
.formParam("Action", "DescribeStacks").formParam("StackName", stack)
.when().post("/").then().statusCode(200).extract().asString();
String arn = stackOutputValue(description, "LayerArn");
assertThat(arn, containsString(":layer:sam-shared-layer:1"));
assertThat(stackOutputValue(description, "LayerSub"), equalTo(arn));
given().when().get("/2018-10-31/layers/sam-shared-layer/versions/1")
.then().statusCode(200).body("LayerVersionArn", equalTo(arn))
.body("CompatibleRuntimes", hasItems("nodejs22.x", "python3.14"))
.body("CompatibleArchitectures", hasItem("arm64"))
.body("LicenseInfo", equalTo("MIT"))
.body("Content.CodeSize", equalTo(buildHandlerZip().length));
given().when().get("/2015-03-31/functions/sam-layer-consumer")
.then().statusCode(200).body("Configuration.Layers[0].Arn", equalTo(arn))
.body("Configuration.Environment.Variables.DependsOn", equalTo("Layer"));
given().contentType("application/zip").body(buildHandlerZip())
.when().put("/" + bucket + "/updated.zip").then().statusCode(200);
given().contentType("application/x-www-form-urlencoded")
.formParam("Action", "UpdateStack").formParam("StackName", stack)
.formParam("Capabilities.member.1", "CAPABILITY_IAM")
.formParam("TemplateBody", template.replace("Key: layer.zip", "Key: updated.zip"))
.formParam("Parameters.member.1.ParameterKey", "Bucket")
.formParam("Parameters.member.1.ParameterValue", bucket)
.when().post("/").then().statusCode(200);
waitForStackStatus(stack, "UPDATE_COMPLETE");
String updated = given().contentType("application/x-www-form-urlencoded")
.formParam("Action", "DescribeStacks").formParam("StackName", stack)
.when().post("/").then().statusCode(200).extract().asString();
assertThat(stackOutputValue(updated, "LayerArn"), containsString(":layer:sam-shared-layer:2"));
given().when().get("/2015-03-31/functions/sam-layer-consumer")
.then().statusCode(200)
.body("Configuration.Layers[0].Arn", equalTo(stackOutputValue(updated, "LayerArn")))
.body("Configuration.Environment.Variables.DependsOn", equalTo("Layer"));
given().when().get("/2018-10-31/layers/sam-shared-layer/versions/1")
.then().statusCode(404);
given().contentType("application/x-www-form-urlencoded")
.formParam("Action", "DeleteStack").formParam("StackName", stack)
.when().post("/").then().statusCode(200);
await().atMost(Duration.ofSeconds(5)).untilAsserted(() ->
given().when().get("/2018-10-31/layers/sam-shared-layer/versions/2")
.then().statusCode(404));
} finally {
given().when().delete("/" + bucket + "/updated.zip");
given().when().delete("/" + bucket + "/layer.zip");
given().when().delete("/" + bucket);
}
}
private static String stackOutputValue(String describeStacksXml, String outputKey) {
return describeStacksXml
.split("<OutputKey>" + outputKey + "</OutputKey>")[1]
@@ -6,10 +6,13 @@ import io.github.hectorvent.floci.core.common.RegionResolver;
import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend;
import io.github.hectorvent.floci.services.lambda.model.LambdaLayerVersion;
import io.github.hectorvent.floci.services.lambda.zip.ZipExtractor;
import io.github.hectorvent.floci.services.s3.S3Service;
import io.github.hectorvent.floci.services.s3.model.S3Object;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
import org.mockito.Answers;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.nio.file.Files;
import java.nio.file.Path;
@@ -24,6 +27,7 @@ import static org.junit.jupiter.api.Assertions.assertNotEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
class LambdaLayerCodePathIsolationTest {
@@ -157,13 +161,54 @@ class LambdaLayerCodePathIsolationTest {
+ "Member must have length less than or equal to 512", error.getMessage());
}
@Test
void pinnedS3ObjectVersionIsReadInsteadOfTheLatest(@TempDir Path baseDir) throws Exception {
// Catches: resolveLayerContent ignoring S3ObjectVersion and fetching the latest object.
S3Service s3Service = mock(S3Service.class);
byte[] zip = zipBytes("pinned");
S3Service.ObjectRead read = new S3Service.ObjectRead(inMemoryObject(zip), new ByteArrayInputStream(zip));
when(s3Service.openObject("layers", "code.zip", "v1")).thenReturn(read);
LambdaLayerService service = serviceFor(baseDir, "111111111111",
new LambdaLayerStore(AccountAwareStorageBackend.inMemory("111111111111")), s3Service);
service.publishLayerVersion("us-east-1", LAYER_NAME, Map.of("Content",
Map.of("S3Bucket", "layers", "S3Key", "code.zip", "S3ObjectVersion", "v1")));
verify(s3Service).openObject("layers", "code.zip", "v1");
}
@Test
void unpinnedS3ContentReadsTheLatestObjectVersion(@TempDir Path baseDir) throws Exception {
S3Service s3Service = mock(S3Service.class);
byte[] zip = zipBytes("latest");
S3Service.ObjectRead read = new S3Service.ObjectRead(inMemoryObject(zip), new ByteArrayInputStream(zip));
when(s3Service.openObject("layers", "code.zip", null)).thenReturn(read);
LambdaLayerService service = serviceFor(baseDir, "111111111111",
new LambdaLayerStore(AccountAwareStorageBackend.inMemory("111111111111")), s3Service);
service.publishLayerVersion("us-east-1", LAYER_NAME, Map.of("Content",
Map.of("S3Bucket", "layers", "S3Key", "code.zip")));
verify(s3Service).openObject("layers", "code.zip", null);
}
private static LambdaLayerService serviceFor(Path baseDir, String account, LambdaLayerStore store) {
return serviceFor(baseDir, account, store, null);
}
private static LambdaLayerService serviceFor(Path baseDir, String account, LambdaLayerStore store, S3Service s3Service) {
EmulatorConfig config = mock(EmulatorConfig.class, Answers.RETURNS_DEEP_STUBS);
when(config.services().lambda().codePath()).thenReturn(baseDir.toString());
when(config.services().lambda().zipMaxEntries()).thenReturn(100_000);
when(config.services().lambda().executor()).thenReturn("docker");
return new LambdaLayerService(store, new ZipExtractor(), config,
new RegionResolver("us-east-1", account), null);
new RegionResolver("us-east-1", account), s3Service);
}
private static S3Object inMemoryObject(byte[] data) {
S3Object object = mock(S3Object.class);
when(object.getData()).thenReturn(data);
return object;
}
private static Map<String, Object> request(String content) throws Exception {
@@ -171,13 +216,17 @@ class LambdaLayerCodePathIsolationTest {
}
private static String zipBase64(String content) throws Exception {
return Base64.getEncoder().encodeToString(zipBytes(content));
}
private static byte[] zipBytes(String content) throws Exception {
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
try (ZipOutputStream zip = new ZipOutputStream(bytes)) {
zip.putNextEntry(new ZipEntry("index.js"));
zip.write(content.getBytes());
zip.closeEntry();
}
return Base64.getEncoder().encodeToString(bytes.toByteArray());
return bytes.toByteArray();
}
private static void assertEqualsContent(String path, String expected) throws Exception {