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 939bd58da5..fc81c708a8 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 @@ -128,6 +128,7 @@ class SamTransformProcessor { // AWS::Serverless::HttpApi via ApiId: {Ref: }) before either side is expanded, // so expansion order between the Function and the HttpApi resource doesn't matter. List httpApiRoutes = collectHttpApiRoutes(samLogicalIds, resources); + Map generatedReferences = new LinkedHashMap<>(); for (String logicalId : samLogicalIds) { JsonNode resDef = resources.get(logicalId); @@ -141,8 +142,11 @@ class SamTransformProcessor { // copyResourceLevelAttributes runs once per arm, right after that arm builds its node. switch (type) { case "AWS::Serverless::Function" -> { - expandServerlessFunction(logicalId, mergeGlobals(globals, "Function", properties), + String aliasId = expandServerlessFunction(logicalId, mergeGlobals(globals, "Function", properties), resDef, expanded, expandedResources, parameterValues); + if (aliasId != null) { + generatedReferences.put(logicalId + ".Alias", aliasId); + } copyResourceLevelAttributes(resDef, (ObjectNode) expandedResources.path(logicalId)); } case "AWS::Serverless::SimpleTable" -> { @@ -180,9 +184,28 @@ class SamTransformProcessor { generateImplicitApi(apiRoutes, globals(template), expandedResources); } + rewriteGeneratedReferences(expanded, generatedReferences); return expanded; } + private void rewriteGeneratedReferences(JsonNode node, Map generatedReferences) { + if (node.isObject()) { + ObjectNode object = (ObjectNode) node; + if (object.size() == 1 && object.path("Ref").isTextual()) { + String generatedId = generatedReferences.get(object.path("Ref").asText()); + if (generatedId != null) { + object.put("Ref", generatedId); + } + return; + } + object.elements().forEachRemaining(child -> rewriteGeneratedReferences(child, generatedReferences)); + } else if (node.isArray()) { + for (JsonNode child : node) { + rewriteGeneratedReferences(child, generatedReferences); + } + } + } + private JsonNode globals(JsonNode template) { return template.path("Globals"); } @@ -952,7 +975,7 @@ class SamTransformProcessor { return base; } - private void expandServerlessFunction(String logicalId, JsonNode properties, JsonNode source, + private String expandServerlessFunction(String logicalId, JsonNode properties, JsonNode source, ObjectNode template, ObjectNode resources, Map parameterValues) { resources.remove(logicalId); @@ -984,6 +1007,7 @@ class SamTransformProcessor { expandFunctionEvent(logicalId, entry.getKey(), entry.getValue(), resources); } } + return aliasLogicalId; } /** 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 c343c4beba..2c95c328e6 100644 --- a/src/test/java/io/github/hectorvent/floci/services/cloudformation/SamTransformIntegrationTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/SamTransformIntegrationTest.java @@ -1,5 +1,7 @@ package io.github.hectorvent.floci.services.cloudformation; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; import io.github.hectorvent.floci.core.common.XmlParser; import io.github.hectorvent.floci.testing.RestAssuredJsonUtils; import io.quarkus.test.junit.QuarkusTest; @@ -28,6 +30,7 @@ import static org.hamcrest.Matchers.not; import static org.hamcrest.Matchers.notNullValue; import static org.hamcrest.Matchers.nullValue; import static org.hamcrest.Matchers.startsWith; +import static org.junit.jupiter.api.Assertions.assertEquals; @QuarkusTest class SamTransformIntegrationTest { @@ -109,6 +112,73 @@ class SamTransformIntegrationTest { assertThat(resourcesXml, not(containsString("AWS::Serverless::Function"))); } + @Test + void samAutoPublishAliasReferenceCreatesLambdaPermission() throws Exception { + String stackName = "sam-ref-alias-" + Long.toString(System.nanoTime(), 36); + String functionName = stackName + "-fn"; + stacksToDelete.add(stackName); + + String template = """ + Transform: AWS::Serverless-2016-10-31 + Resources: + Fn: + Type: AWS::Serverless::Function + Properties: + FunctionName: %s + Runtime: nodejs22.x + Handler: index.handler + InlineCode: "exports.handler = async () => ({ ok: true });" + AutoPublishAlias: live + FnPermission: + Type: AWS::Lambda::Permission + Properties: + Action: lambda:InvokeFunction + FunctionName: !Ref Fn.Alias + Principal: events.amazonaws.com + Outputs: + AliasArn: + Value: !Ref Fn.Alias + """.formatted(functionName); + + 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"); + String stackXml = given() + .contentType("application/x-www-form-urlencoded") + .formParam("Action", "DescribeStacks") + .formParam("StackName", stackName) + .when() + .post("/") + .then() + .statusCode(200) + .extract().asString(); + assertThat(stackXml, containsString(":function:" + functionName + ":live")); + + String functionArn = given().when().get("/2015-03-31/functions/" + functionName) + .then().statusCode(200).extract().path("Configuration.FunctionArn"); + String policyJson = given() + .when() + .get("/2015-03-31/functions/" + functionName + "/policy?Qualifier=live") + .then() + .statusCode(200) + .extract().path("Policy"); + JsonNode statements = new ObjectMapper().readTree(policyJson).path("Statement"); + assertEquals(1, statements.size()); + JsonNode statement = statements.get(0); + assertEquals("lambda:InvokeFunction", statement.path("Action").asText()); + assertEquals("events.amazonaws.com", statement.path("Principal").path("Service").asText()); + assertEquals(functionArn + ":live", statement.path("Resource").asText()); + } + @Test @Tag("docker") void samFunction_withAutoPublishAlias_createsVersionAndAlias() throws Exception { diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/SamTransformProcessorTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/SamTransformProcessorTest.java index a113584bbb..f309299fc4 100644 --- a/src/test/java/io/github/hectorvent/floci/services/cloudformation/SamTransformProcessorTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/SamTransformProcessorTest.java @@ -154,6 +154,77 @@ class SamTransformProcessorTest { aliasProps.path("FunctionVersion").path("Fn::GetAtt")); } + @Test + void expandSamTemplate_autoPublishAliasResolvesReferenceableProperty() throws Exception { + JsonNode template = objectMapper.readTree(""" + { + "Transform": "AWS::Serverless-2016-10-31", + "Resources": { + "FnPermission": { + "Type": "AWS::Lambda::Permission", + "Properties": { + "Action": "lambda:InvokeFunction", + "FunctionName": {"Ref": "Fn.Alias"}, + "Principal": "events.amazonaws.com" + } + }, + "Fn": { + "Type": "AWS::Serverless::Function", + "Properties": { + "Handler": "index.handler", + "Runtime": "nodejs22.x", + "AutoPublishAlias": "live", + "InlineCode": "exports.handler = async () => ({});" + } + } + }, + "Outputs": { + "AliasArn": {"Value": {"Ref": "Fn.Alias"}}, + "FunctionName": {"Value": {"Ref": "Fn"}} + } + } + """); + + JsonNode expanded = processor.expandSamTemplate(template); + assertEquals("FnAliasLive", expanded.path("Resources").path("FnPermission") + .path("Properties").path("FunctionName").path("Ref").asText()); + assertEquals("FnAliasLive", expanded.path("Outputs").path("AliasArn") + .path("Value").path("Ref").asText()); + assertEquals("Fn", expanded.path("Outputs").path("FunctionName") + .path("Value").path("Ref").asText()); + } + + @Test + void expandSamTemplate_autoPublishAliasReferenceUsesGeneratedIdAfterCollision() throws Exception { + JsonNode template = objectMapper.readTree(""" + { + "Transform": "AWS::Serverless-2016-10-31", + "Resources": { + "FnAliasLive": {"Type": "AWS::S3::Bucket"}, + "Fn": { + "Type": "AWS::Serverless::Function", + "Properties": { + "Handler": "index.handler", + "Runtime": "nodejs22.x", + "AutoPublishAlias": "live", + "InlineCode": "exports.handler = async () => ({});" + } + }, + "FnPermission": { + "Type": "AWS::Lambda::Permission", + "Properties": {"FunctionName": {"Ref": "Fn.Alias"}} + } + } + } + """); + + JsonNode resources = processor.expandSamTemplate(template).path("Resources"); + assertEquals("AWS::S3::Bucket", resources.path("FnAliasLive").path("Type").asText()); + assertEquals("AWS::Lambda::Alias", resources.path("FnAliasLive2").path("Type").asText()); + assertEquals("FnAliasLive2", resources.path("FnPermission").path("Properties") + .path("FunctionName").path("Ref").asText()); + } + /** The ids are the ones SAM gives the same function. */ @Test void expandSamTemplate_autoPublishAliasVersionIdFollowsSamsHashInput() throws Exception {