diff --git a/docs/services/cloudformation.md b/docs/services/cloudformation.md index 993303026e..1c5eb93da7 100644 --- a/docs/services/cloudformation.md +++ b/docs/services/cloudformation.md @@ -433,6 +433,20 @@ status, named with its stack or by its ARN alone; a `StackName` that names no st - 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 layers + +`AWS::Serverless::LayerVersion` expands into `AWS::Lambda::LayerVersion`. Packaged +`ContentUri` values accept an S3 URI (including `?versionId=`) or a `Bucket`/`Key`/ +optional `Version` object. Local directories must first be packaged with the SAM CLI. +The transform preserves layer metadata, runtime and architecture compatibility, and +license information. `Ref` returns the published layer version ARN. + +As in SAM, the generated logical id changes with the layer definition, while the +default layer name remains the original logical id. References and dependencies +follow the generated resource. Layers default to `DeletionPolicy: Retain`; +`RetentionPolicy: Delete` deletes the published version when the stack is deleted. +An explicit resource `DeletionPolicy` is preserved unless `RetentionPolicy` overrides it. + ## SAM published aliases `AutoPublishAlias` creates a version and points the generated alias at that version's 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 fc81c708a8..87cd148856 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 @@ -121,6 +121,9 @@ class SamTransformProcessor { } }); + expandServerlessLayers(expanded, expandedResources, globals, parameterValues); + samLogicalIds.removeIf(id -> !expandedResources.has(id)); + // Collect implicit-API routes from function Api events before the functions are expanded. List apiRoutes = collectApiRoutes(samLogicalIds, resources); @@ -206,6 +209,160 @@ class SamTransformProcessor { } } + private void expandServerlessLayers(ObjectNode template, ObjectNode resources, JsonNode globals, + Map parameterValues) { + Map layerIds = new LinkedHashMap<>(); + List ids = new ArrayList<>(); + resources.fieldNames().forEachRemaining(ids::add); + for (String id : ids) { + JsonNode source = resources.path(id); + if (!"AWS::Serverless::LayerVersion".equals(source.path("Type").asText())) { + continue; + } + JsonNode properties = source.path("Properties"); + JsonNode resolvedProperties = resolveParameterRefs(properties, template, parameterValues); + // Deploy with the original ContentUri expressions so CloudFormation resolves parameters + // once, at deploy: a resolved value that itself holds a ${...} would resolve twice. The + // resolved copy is what SAM hashes, so a versioned package still changes the logical id. + JsonNode uri = properties.path("ContentUri"); + ObjectNode content = objectMapper.createObjectNode(); + if (uri.isObject() && uri.hasNonNull("Bucket") && uri.hasNonNull("Key")) { + copyRenamed(uri, "Bucket", content, "S3Bucket"); + copyRenamed(uri, "Key", content, "S3Key"); + copyRenamed(uri, "Version", content, "S3ObjectVersion"); + } else { + // A plain location is split as written, and a whole ContentUri reference resolves to + // the location itself, so the resolved value is what gets split. The object form + // above keeps its expressions for the template engine to resolve at deploy. + JsonNode resolvedUri = resolvedProperties.path("ContentUri"); + String location = null; + if (uri.isTextual()) { + location = uri.asText(); + } else if (resolvedUri.isTextual()) { + location = resolvedUri.asText(); + } + if (location == null) { + throw invalidResource(id, "'ContentUri' requires Bucket and Key properties to be specified."); + } + Matcher match = S3_DEFINITION_URI.matcher(location); + if (!match.matches()) { + throw invalidResource(id, "'ContentUri' must specify a packaged S3 location."); + } + content.put("S3Bucket", match.group("bucket")); + content.put("S3Key", match.group("key")); + if (match.group("version") != null) { + content.put("S3ObjectVersion", match.group("version")); + } + } + String retention = resolvedProperties.path("RetentionPolicy").asText(null); + if (retention != null && !List.of("Retain", "Delete").contains(retention)) { + throw invalidResource(id, "'RetentionPolicy' must be 'Retain' or 'Delete'."); + } + ObjectNode layer = objectMapper.createObjectNode(); + layer.put("Type", "AWS::Lambda::LayerVersion"); + copyResourceLevelAttributes(source, layer); + if (retention != null || !layer.has("DeletionPolicy")) { + layer.put("DeletionPolicy", retention == null ? "Retain" : retention); + } + ObjectNode target = layer.putObject("Properties"); + target.set("Content", content); + target.set("LayerName", properties.hasNonNull("LayerName") + ? properties.get("LayerName").deepCopy() : TextNode.valueOf(id)); + for (String key : List.of("Description", "LicenseInfo", "CompatibleRuntimes", "CompatibleArchitectures")) { + copyIfPresent(properties, key, target); + } + ObjectNode hashResource = source.deepCopy(); + hashResource.set("Properties", resolvedProperties); + hashResource.remove(List.of("Metadata", "DeletionPolicy", "UpdateReplacePolicy")); + ObjectNode hashInput = objectMapper.createObjectNode(); + hashInput.set(id, hashResource); + String generatedId = id + samHashSuffix(hashInput, id); + if (resources.has(generatedId)) { + throw invalidResource(id, "Generated layer logical id conflicts with resource '" + generatedId + "'."); + } + resources.remove(id); + resources.set(generatedId, layer); + layerIds.put(id, generatedId); + } + if (!layerIds.isEmpty()) { + rewriteLayerReferences(template, layerIds); + rewriteLayerReferences(globals, layerIds); + resources.elements().forEachRemaining(resource -> { + if (resource instanceof ObjectNode object) { + rewriteLayerDependencies(object, layerIds); + } + }); + } + } + + private void rewriteLayerReferences(JsonNode node, Map ids) { + if (node instanceof ObjectNode object) { + if (object.path("Ref").isTextual() && ids.containsKey(object.path("Ref").asText())) { + object.put("Ref", ids.get(object.path("Ref").asText())); + } + JsonNode getAtt = object.path("Fn::GetAtt"); + if (getAtt instanceof ArrayNode array && !array.isEmpty() && ids.containsKey(array.get(0).asText())) { + array.set(0, TextNode.valueOf(ids.get(array.get(0).asText()))); + } else if (getAtt.isTextual()) { + object.put("Fn::GetAtt", rewriteLayerName(getAtt.asText(), ids)); + } + JsonNode sub = object.path("Fn::Sub"); + if (sub.isTextual()) { + object.put("Fn::Sub", rewriteLayerSub(sub.asText(), ids, objectMapper.createObjectNode())); + } else if (sub instanceof ArrayNode array && array.size() == 2 && array.get(0).isTextual()) { + array.set(0, TextNode.valueOf(rewriteLayerSub(array.get(0).asText(), ids, array.get(1)))); + // Only the map's values are intrinsic contexts; its keys are local variable names + // that may themselves be spelled Ref, so walk the values, never the map container. + if (array.get(1) instanceof ObjectNode variables) { + variables.elements().forEachRemaining(value -> rewriteLayerReferences(value, ids)); + } + } + // The Fn::Sub node is fully handled above, so skip it here; recursing into its variables + // map would treat a variable literally named Ref as a Ref-intrinsic and rewrite it. + List keys = new ArrayList<>(); + object.fieldNames().forEachRemaining(keys::add); + for (String key : keys) { + if (!"Fn::Sub".equals(key)) { + rewriteLayerReferences(object.get(key), ids); + } + } + } else if (node.isArray()) { + node.forEach(child -> rewriteLayerReferences(child, ids)); + } + } + + private static void rewriteLayerDependencies(ObjectNode object, Map ids) { + JsonNode dependsOn = object.path("DependsOn"); + if (dependsOn.isTextual() && ids.containsKey(dependsOn.asText())) { + object.put("DependsOn", ids.get(dependsOn.asText())); + } else if (dependsOn instanceof ArrayNode array) { + for (int i = 0; i < array.size(); i++) { + String replacement = ids.get(array.get(i).asText()); + if (replacement != null) { + array.set(i, TextNode.valueOf(replacement)); + } + } + } + } + + private static String rewriteLayerName(String name, Map ids) { + int dot = name.indexOf('.'); + String id = dot < 0 ? name : name.substring(0, dot); + return ids.getOrDefault(id, id) + (dot < 0 ? "" : name.substring(dot)); + } + + private static String rewriteLayerSub(String text, Map ids, JsonNode variables) { + Matcher matcher = SUB_REFERENCE.matcher(text); + StringBuilder result = new StringBuilder(); + while (matcher.find()) { + String name = matcher.group(1); + String replacement = variables.has(name) ? name : rewriteLayerName(name, ids); + matcher.appendReplacement(result, Matcher.quoteReplacement("${" + replacement + "}")); + } + matcher.appendTail(result); + return result.toString(); + } + private JsonNode globals(JsonNode template) { return template.path("Globals"); } @@ -1204,19 +1361,7 @@ class SamTransformProcessor { 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); + return functionLogicalId + "Version" + samHashSuffix(hashed, functionLogicalId); } /** @@ -1250,11 +1395,15 @@ class SamTransformProcessor { JsonNode sub = node.get("Fn::Sub"); ObjectNode resolved = objectMapper.createObjectNode(); if (sub.isTextual()) { - resolved.put("Fn::Sub", substituteParameters(sub.asText(), template, parameterValues)); + resolved.put("Fn::Sub", substituteParameters(sub.asText(), template, parameterValues, Set.of())); } else if (sub.isArray() && !sub.isEmpty() && sub.get(0).isTextual()) { + Set localVariables = new LinkedHashSet<>(); + if (sub.size() > 1 && sub.get(1).isObject()) { + sub.get(1).fieldNames().forEachRemaining(localVariables::add); + } ArrayNode arguments = (ArrayNode) resolveParameterRefs(sub, template, parameterValues); arguments.set(0, TextNode.valueOf(substituteParameters(sub.get(0).asText(), template, - parameterValues))); + parameterValues, localVariables))); resolved.set("Fn::Sub", arguments); } else { resolved.set("Fn::Sub", resolveParameterRefs(sub, template, parameterValues)); @@ -1275,12 +1424,17 @@ class SamTransformProcessor { 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 parameterValues) { + /** + * {@code text} with each {@code ${Name}} naming a template parameter replaced by its value. Names that + * the same {@code Fn::Sub} localizes in its variable map are left for the template engine to resolve. + */ + private static String substituteParameters(String text, JsonNode template, Map parameterValues, + Set localVariables) { Matcher matcher = SUB_REFERENCE.matcher(text); StringBuilder substituted = new StringBuilder(); while (matcher.find()) { - String value = parameterValue(matcher.group(1), template, parameterValues); + String name = matcher.group(1); + String value = localVariables.contains(name) ? null : parameterValue(name, template, parameterValues); matcher.appendReplacement(substituted, Matcher.quoteReplacement(value == null ? matcher.group() : value)); } matcher.appendTail(substituted); @@ -1552,6 +1706,27 @@ class SamTransformProcessor { return name; } + /** + * The first ten hex digits of the SHA-1 of SAM's canonical form of {@code hashInput}: properties + * sorted, non-ASCII escaped, and DEL escaped as well, because ESCAPE_NON_ASCII leaves DEL as it is + * while SAM's hash input escapes it. A generated logical id is its subject plus this suffix, so a + * layer version and a function version hash their input exactly alike. + */ + private String samHashSuffix(JsonNode hashInput, String subject) { + String serialized; + try { + serialized = objectMapper.writer() + .with(JsonNodeFeature.WRITE_PROPERTIES_SORTED) + .with(JsonWriteFeature.ESCAPE_NON_ASCII) + .without(JsonWriteFeature.WRITE_HEX_UPPER_CASE) + .writeValueAsString(hashInput) + .replace("\u007f", "\\u007f"); + } catch (JsonProcessingException e) { + throw new IllegalStateException("Cannot serialize the hash input of " + subject, e); + } + return Digests.sha1Hex(serialized).substring(0, 10); + } + /** * SAM's generated condition name: the name plus the first ten hex digits of the SHA-1 of * {@code hashInput}, cut to CloudFormation's 255-character limit. SHA-1 is SAM's choice and is diff --git a/src/main/java/io/github/hectorvent/floci/services/lambda/LambdaLayerService.java b/src/main/java/io/github/hectorvent/floci/services/lambda/LambdaLayerService.java index c0ac679c2f..bc550bc750 100644 --- a/src/main/java/io/github/hectorvent/floci/services/lambda/LambdaLayerService.java +++ b/src/main/java/io/github/hectorvent/floci/services/lambda/LambdaLayerService.java @@ -498,8 +498,9 @@ public class LambdaLayerService { if (s3Service == null) { throw new AwsException("ServiceUnavailableException", "S3 service not available", 503); } + String s3ObjectVersion = (String) content.get("S3ObjectVersion"); try { - return DeploymentPackage.read(s3Service.openObject(s3Bucket, s3Key, null), stagingDir); + return DeploymentPackage.read(s3Service.openObject(s3Bucket, s3Key, s3ObjectVersion), stagingDir); } catch (Exception e) { throw new AwsException("InvalidParameterValueException", "Unable to fetch layer content from s3://" + s3Bucket + "/" + s3Key + ": " + e.getMessage(), 400); diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/SamLayerVersionTransformTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/SamLayerVersionTransformTest.java new file mode 100644 index 0000000000..3bd5e17ca9 --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/SamLayerVersionTransformTest.java @@ -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)); + } + } +} 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 2c95c328e6..cac561b9c7 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 @@ -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 + "")[1] diff --git a/src/test/java/io/github/hectorvent/floci/services/lambda/LambdaLayerCodePathIsolationTest.java b/src/test/java/io/github/hectorvent/floci/services/lambda/LambdaLayerCodePathIsolationTest.java index b105d99976..456e5c92a0 100644 --- a/src/test/java/io/github/hectorvent/floci/services/lambda/LambdaLayerCodePathIsolationTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/lambda/LambdaLayerCodePathIsolationTest.java @@ -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 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 {