From 7d66bf087aa585012ccdd397305eb4353813a4e8 Mon Sep 17 00:00:00 2001 From: Bill DeMoss Date: Fri, 14 Aug 2026 14:43:42 -0400 Subject: [PATCH] fix(cloudformation): expand SAM AutoPublishAlias into Version + Alias (#1961) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * fix(cloudformation): expand SAM AutoPublishAlias AutoPublishAlias was read nowhere in the codebase, so the SAM transform silently dropped it: the stack reached CREATE_COMPLETE, the function deployed with only $LATEST, and an alias-qualified invoke then failed with "Alias not found" far from the deploy that caused it. The "Unsupported SAM resource type" debug arm only covers unknown resource types, not unknown properties, so nothing was logged either. Expand it into the AWS::Lambda::Version + AWS::Lambda::Alias pair real SAM generates, and provision those two types. Both halves are needed: the transform alone emits resources the provisioner ignores, and the provisioner alone is unreachable from a SAM template. The Lambda service already implements publishVersion and the alias APIs, so this is plumbing rather than new service behavior. The new types go through CfnResourceProvisioner rather than the legacy switch, following the registry migration. Ref/GetAtt on the emitted properties give the function -> version -> alias ordering that topologicalSort already follows, so no explicit DependsOn is needed. An intrinsic alias name (e.g. !Ref StageName) is passed through to Name for the engine to resolve at provision time; only the generated logical id needs a literal and drops the suffix in that case. * test(cloudformation): cover Version/Alias provisioner directly The SAM integration test drives provisioning end to end but cannot reach two paths: the already-exists fallback (createAlias conflicting with an alias that outlived a stack delete) and delete(), which its @AfterEach invokes but never asserts on — a broken delete was silent. Add LambdaVersionAliasCfnProvisionerTest alongside the existing Sqs and Rds provisioner tests: attribute wiring for both types, the conflict fallback, non-conflict failures still propagating, alias delete parsed out of the ARN, delete idempotency when the alias is already gone, version delete as a no-op, and a physical id that is not an alias ARN (the generic fallback's shape on stacks predating this provisioner). Also stop pinning the alias's FunctionVersion to a literal "1" in the integration test: assert it is a number and not $LATEST, which is what the assertion is actually for. Pinning the first version fails confusingly when an earlier run leaks the function and its counter. * fix(cloudformation): point the SAM alias at $LATEST Real SAM points AutoPublishAlias at the published version, and the first revision of this change did the same. Floci cannot invoke a published version: the snapshot carries no code path, so a version-qualified invoke times out on a cold start (#1987), and silently runs $LATEST's code when a warm container happens to exist (#1988). Emitting the faithful form therefore broke the alias-qualified invoke this expansion exists to enable — strictly worse than not expanding the property. Point the alias at $LATEST instead. The Version resource is still emitted, so the resource set and GetAtt still match SAM; only the alias target differs, and it flips back to the version in one line once #1987 lands. The integration test asserted the alias record existed with a numeric FunctionVersion, which the broken form satisfied — so it passed while the behavior was broken. It now invokes through the alias and asserts the function actually runs, which fails against the version-pointing form (verified by reverting it with the record assertion relaxed). * fix(cloudformation): point the SAM alias at $LATEST Restores the change d753187e was supposed to carry. That commit landed only its unit-test half — the main-code change and the integration test's invoke assertion were lost to a `git checkout --` used to undo a verification experiment, leaving a test asserting $LATEST against code still emitting the version pointer. Real SAM points AutoPublishAlias at the published version. Floci cannot invoke a published version: the snapshot carries no code path, so a version-qualified invoke times out on a cold start (#1987) and silently runs $LATEST's code when a warm container happens to exist (#1988). Emitting the faithful form broke the alias-qualified invoke this expansion exists to enable. The Version resource is still emitted, so the resource set and GetAtt match SAM; only the alias target differs, and it flips back in one line once #1987 lands. The integration test now invokes through the alias instead of only asserting the alias record exists — the record assertion was satisfied by the broken form. Verified load-bearing by re-applying the version pointer with the record assertion relaxed: the invoke fails at the function timeout. * fix(cloudformation): sanitize the generated alias logical id The AutoPublishAlias expansion built the alias resource's logical id by concatenating the alias name raw. Lambda alias names may contain '-' and '_', neither of which is valid in a CloudFormation logical id, so `AutoPublishAlias: blue-green` emitted `MyFuncAliasblue-green`. Route the suffix through the sanitize() helper this file already uses for every other derived logical id. The alias name sent to Lambda is untouched -- only the logical id changes. Also corrects the expandAutoPublishAlias javadoc: with FunctionVersion a literal $LATEST there is no version -> alias ordering edge, only function -> version and function -> alias. None is needed, since the alias does not reference the version; the edge returns with the GetAtt form once #1987 lands. --- docs/services/cloudformation.md | 2 +- .../cloudformation/SamTransformProcessor.java | 57 ++++++ .../LambdaVersionAliasCfnProvisioner.java | 125 ++++++++++++ .../SamTransformIntegrationTest.java | 137 +++++++++++++ .../SamTransformProcessorTest.java | 145 ++++++++++++++ .../LambdaVersionAliasCfnProvisionerTest.java | 187 ++++++++++++++++++ 6 files changed, 652 insertions(+), 1 deletion(-) create mode 100644 src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/LambdaVersionAliasCfnProvisioner.java create mode 100644 src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/LambdaVersionAliasCfnProvisionerTest.java diff --git a/docs/services/cloudformation.md b/docs/services/cloudformation.md index 4fa96738b9..e880bb9f88 100644 --- a/docs/services/cloudformation.md +++ b/docs/services/cloudformation.md @@ -58,7 +58,7 @@ cross-resource references. | SQS | `Queue`, `QueuePolicy` (accepted; policy not enforced) | | SNS | `Topic`, `Subscription` | | DynamoDB | `Table`, `GlobalTable` | -| Lambda | `Function` (Zip via S3/inline `ZipFile`, and Image), `LayerVersion`, `EventSourceMapping` (SQS, Kinesis, DynamoDB Streams) | +| Lambda | `Function` (Zip via S3/inline `ZipFile`, and Image), `LayerVersion`, `EventSourceMapping` (SQS, Kinesis, DynamoDB Streams), `Version`, `Alias` (also what SAM's `AutoPublishAlias` expands into) | | IAM | `Role`, `User`, `AccessKey`, `Policy`, `ManagedPolicy`, `InstanceProfile` | | SSM | `Parameter` | | KMS | `Key`, `Alias` | 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 c7cd9caae5..524ffcb4ea 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 @@ -361,6 +361,8 @@ class SamTransformProcessor { ObjectNode lambdaResource = createLambdaFunction(logicalId, roleLogicalId, properties, hasExplicitRole); resources.set(logicalId, lambdaResource); + expandAutoPublishAlias(logicalId, properties, resources); + JsonNode events = properties.path("Events"); if (events.isObject()) { Iterator> eventFields = events.fields(); @@ -371,6 +373,61 @@ class SamTransformProcessor { } } + /** + * Expands {@code AutoPublishAlias} into the {@code AWS::Lambda::Version} + + * {@code AWS::Lambda::Alias} pair real SAM generates, so an alias-qualified invoke + * ({@code :production}) resolves instead of failing with "Alias not found". + * Without this the property is silently dropped and the deploy still reports + * CREATE_COMPLETE, so the failure only surfaces later, at invoke time. + * + *

The alias name is normally a literal, but SAM also allows an intrinsic (e.g. + * {@code !Ref StageName}). The node is passed through to {@code Name} either way so the + * template engine resolves it at provision time; only the generated logical id needs a + * literal, and it drops the suffix when the value isn't textual. + * + *

The {@code Ref}s on {@code FunctionName} give {@code topologicalSort} the edges it needs + * — function → version and function → alias — so no explicit {@code DependsOn} is needed. + * There is no version → alias edge while {@code FunctionVersion} is the literal + * {@code $LATEST}; none is required, since the alias does not reference the version. It + * returns with the {@code Fn::GetAtt} form once #1987 lands. + */ + private void expandAutoPublishAlias(String functionLogicalId, JsonNode properties, ObjectNode resources) { + JsonNode aliasName = properties.path("AutoPublishAlias"); + if (aliasName.isMissingNode() || aliasName.isNull() + || (aliasName.isTextual() && aliasName.asText().isBlank())) { + return; + } + + String versionId = uniqueId(functionLogicalId + "Version", resources); + ObjectNode versionDef = objectMapper.createObjectNode(); + versionDef.put("Type", "AWS::Lambda::Version"); + ObjectNode versionProps = objectMapper.createObjectNode(); + versionProps.set("FunctionName", ref(functionLogicalId)); + versionDef.set("Properties", versionProps); + resources.set(versionId, versionDef); + + // Alias names may legally contain '-' and '_', neither of which is valid in a + // CloudFormation logical id, so the suffix goes through the same sanitize() every other + // derived id in this file uses. + String aliasSuffix = aliasName.isTextual() ? sanitize(aliasName.asText()) : ""; + String aliasId = uniqueId(functionLogicalId + "Alias" + aliasSuffix, resources); + ObjectNode aliasDef = objectMapper.createObjectNode(); + aliasDef.put("Type", "AWS::Lambda::Alias"); + ObjectNode aliasProps = objectMapper.createObjectNode(); + aliasProps.set("FunctionName", ref(functionLogicalId)); + aliasProps.set("Name", aliasName.deepCopy()); + // Real SAM points the alias at the published version (Fn::GetAtt .Version). + // Floci cannot invoke a published version: the snapshot carries no code path, so a + // version-qualified invoke times out on a cold start (#1987) and silently runs $LATEST's + // code when a warm container happens to exist (#1988). Aiming the alias there would break + // the alias-qualified invoke this expansion exists to enable, so point it at $LATEST — the + // alias resolves and runs the function's code, which is the behavior callers depend on. + // Switch to the GetAtt form once #1987 lands. + aliasProps.put("FunctionVersion", "$LATEST"); + aliasDef.set("Properties", aliasProps); + resources.set(aliasId, aliasDef); + } + private ObjectNode createExecutionRole(JsonNode properties) { ObjectNode roleDef = objectMapper.createObjectNode(); roleDef.put("Type", "AWS::IAM::Role"); diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/LambdaVersionAliasCfnProvisioner.java b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/LambdaVersionAliasCfnProvisioner.java new file mode 100644 index 0000000000..462d85a886 --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/LambdaVersionAliasCfnProvisioner.java @@ -0,0 +1,125 @@ +package io.github.hectorvent.floci.services.cloudformation.provisioners; + +import com.fasterxml.jackson.databind.JsonNode; +import io.github.hectorvent.floci.core.common.AwsException; +import io.github.hectorvent.floci.services.cloudformation.model.StackResource; +import io.github.hectorvent.floci.services.lambda.LambdaArnUtils; +import io.github.hectorvent.floci.services.lambda.LambdaService; +import io.github.hectorvent.floci.services.lambda.model.LambdaAlias; +import io.github.hectorvent.floci.services.lambda.model.LambdaFunction; +import jakarta.enterprise.context.ApplicationScoped; +import jakarta.inject.Inject; +import org.jboss.logging.Logger; + +import java.util.Set; + +/** + * CloudFormation provisioning for {@code AWS::Lambda::Version} and {@code AWS::Lambda::Alias}. + * + *

Covers only these two types, not {@code AWS::Lambda::Function} — that one still lives in + * {@code CloudFormationResourceProvisioner}'s switch, which the registry falls through to. The + * two types are what SAM's {@code AutoPublishAlias} expands into, and without them an + * alias-qualified invoke ({@code :production}) fails with "Alias not found" even though + * the template declared the alias and the stack reported CREATE_COMPLETE. + * + *

The Lambda service already implements both operations, so this is plumbing rather than new + * service behavior. + */ +@ApplicationScoped +public class LambdaVersionAliasCfnProvisioner implements CfnResourceProvisioner { + + private static final Logger LOG = Logger.getLogger(LambdaVersionAliasCfnProvisioner.class); + + private final LambdaService lambdaService; + + @Inject + public LambdaVersionAliasCfnProvisioner(LambdaService lambdaService) { + this.lambdaService = lambdaService; + } + + @Override + public Set resourceTypes() { + return Set.of("AWS::Lambda::Version", "AWS::Lambda::Alias"); + } + + @Override + public void provision(StackResource r, JsonNode props, ProvisionContext ctx) { + switch (r.getResourceType()) { + case "AWS::Lambda::Version" -> provisionVersion(r, props, ctx); + case "AWS::Lambda::Alias" -> provisionAlias(r, props, ctx); + default -> throw new IllegalStateException( + "LambdaVersionAliasCfnProvisioner cannot handle " + r.getResourceType()); + } + } + + @Override + public void delete(String resourceType, String physicalId, String region) { + if (!"AWS::Lambda::Alias".equals(resourceType)) { + // AWS::Lambda::Version has no backing delete: Lambda exposes no DeleteVersion, and + // deleting the function drops its versions with it. + return; + } + // The physical id is the alias ARN (arn:…:function::), so the function name + // and alias name come back out of it. + LambdaArnUtils.ResolvedFunctionRef ref = LambdaArnUtils.resolve(physicalId); + if (ref.qualifier() == null) { + LOG.debugv("Not an alias ARN, nothing to delete: {0}", physicalId); + return; + } + try { + lambdaService.deleteAlias(region, ref.name(), ref.qualifier()); + } catch (AwsException e) { + // Already gone (function deleted first, or a partial rollback) — deleting a stack + // must stay idempotent. + LOG.debugv("Alias {0} already absent: {1}", physicalId, e.getMessage()); + } + } + + private void provisionVersion(StackResource r, JsonNode props, ProvisionContext ctx) { + String functionName = ctx.resolveOptional(props, "FunctionName"); + if (functionName == null || functionName.isBlank()) { + throw new IllegalArgumentException( + "AWS::Lambda::Version requires FunctionName (" + r.getLogicalId() + ")"); + } + String description = ctx.resolveOptional(props, "Description"); + + LambdaFunction version = lambdaService.publishVersion(ctx.region(), functionName, description); + + // Matches real CloudFormation: Ref returns the qualified ARN, GetAtt Version the version + // number (what the Alias resource references), GetAtt FunctionArn the qualified ARN. + r.setPhysicalId(version.getFunctionArn()); + r.getAttributes().put("Version", version.getVersion()); + r.getAttributes().put("FunctionArn", version.getFunctionArn()); + } + + private void provisionAlias(StackResource r, JsonNode props, ProvisionContext ctx) { + String functionName = ctx.resolveOptional(props, "FunctionName"); + String aliasName = ctx.resolveOptional(props, "Name"); + if (functionName == null || functionName.isBlank() || aliasName == null || aliasName.isBlank()) { + throw new IllegalArgumentException( + "AWS::Lambda::Alias requires FunctionName and Name (" + r.getLogicalId() + ")"); + } + String functionVersion = ctx.resolveOptional(props, "FunctionVersion"); + String description = ctx.resolveOptional(props, "Description"); + + // RoutingConfig is not carried over yet — the alias APIs support it, but nothing in the + // SAM expansion emits it, so wiring it here would be untested surface. + LambdaAlias alias; + try { + alias = lambdaService.createAlias(ctx.region(), functionName, aliasName, + functionVersion, description, null); + } catch (AwsException e) { + // An alias surviving from a prior deploy makes create conflict; converge on it rather + // than failing the stack, so a redeploy is idempotent. + if (!"ResourceConflictException".equals(e.getErrorCode())) { + throw e; + } + LOG.debugv("Alias {0} exists on {1}, updating instead", aliasName, functionName); + alias = lambdaService.updateAlias(ctx.region(), functionName, aliasName, + functionVersion, description, null); + } + + r.setPhysicalId(alias.getAliasArn()); + r.getAttributes().put("AliasArn", alias.getAliasArn()); + } +} 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 939353d5d2..b3c8003764 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 @@ -14,6 +14,7 @@ import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.containsString; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.not; +import static org.hamcrest.Matchers.nullValue; @QuarkusTest class SamTransformIntegrationTest { @@ -95,6 +96,142 @@ class SamTransformIntegrationTest { assertThat(resourcesXml, not(containsString("AWS::Serverless::Function"))); } + @Test + void samFunction_withAutoPublishAlias_createsVersionAndAlias() { + String stackName = "sam-alias-stack"; + stacksToDelete.add(stackName); + + String template = """ + AWSTemplateFormatVersion: '2010-09-09' + Transform: AWS::Serverless-2016-10-31 + Resources: + AliasFunction: + Type: AWS::Serverless::Function + Properties: + FunctionName: sam-alias-func + Handler: index.handler + Runtime: nodejs20.x + AutoPublishAlias: production + 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"); + + // The point of the fix: an alias-qualified reference resolves. Before it, this 404'd with + // "Alias not found: production" even though the template declared the alias. + given() + .when() + .get("/2015-03-31/functions/sam-alias-func/aliases/production") + .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("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. + 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()) + .body("ok", equalTo(true)); + + given() + .when() + .get("/2015-03-31/functions/sam-alias-func/aliases") + .then() + .statusCode(200) + .body("Aliases.size()", equalTo(1)) + .body("Aliases[0].Name", equalTo("production")); + + String resourcesXml = given() + .contentType("application/x-www-form-urlencoded") + .formParam("Action", "DescribeStackResources") + .formParam("StackName", stackName) + .when() + .post("/") + .then() + .statusCode(200) + .extract().asString(); + + assertThat(resourcesXml, containsString("AWS::Lambda::Version")); + assertThat(resourcesXml, containsString("AWS::Lambda::Alias")); + assertThat(resourcesXml, containsString("AliasFunctionAliasProduction")); + } + + @Test + void samFunction_withoutAutoPublishAlias_createsNoAlias() { + String stackName = "sam-no-alias-stack"; + stacksToDelete.add(stackName); + + String template = """ + AWSTemplateFormatVersion: '2010-09-09' + Transform: AWS::Serverless-2016-10-31 + Resources: + PlainFunction: + Type: AWS::Serverless::Function + Properties: + FunctionName: sam-no-alias-func + Handler: index.handler + Runtime: nodejs22.x + InlineCode: | + exports.handler = async () => ({ statusCode: 200, body: 'ok' }); + """; + + 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/sam-no-alias-func/aliases") + .then() + .statusCode(200) + .body("Aliases.size()", equalTo(0)); + + String resourcesXml = given() + .contentType("application/x-www-form-urlencoded") + .formParam("Action", "DescribeStackResources") + .formParam("StackName", stackName) + .when() + .post("/") + .then() + .statusCode(200) + .extract().asString(); + + assertThat(resourcesXml, not(containsString("AWS::Lambda::Version"))); + assertThat(resourcesXml, not(containsString("AWS::Lambda::Alias"))); + } + @Test void samFunction_withExplicitRole_skipsRoleGeneration() { String stackName = "sam-explicit-role-stack"; diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/SamTransformProcessorTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/SamTransformProcessorTest.java index ed70a141ca..25be1e1117 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 @@ -101,6 +101,151 @@ class SamTransformProcessorTest { assertEquals("Arn", roleRef.path("Fn::GetAtt").get(1).asText()); } + @Test + void expandSamTemplate_autoPublishAliasGeneratesVersionAndAlias() throws Exception { + // AutoPublishAlias must expand into the Version + Alias pair real SAM generates. Dropping it + // leaves the function with only $LATEST, so an alias-qualified invoke (:production, + // which the declaration exists to enable) fails with "Alias not found" long after the deploy + // reported CREATE_COMPLETE. + JsonNode template = objectMapper.readTree(""" + { + "Transform": "AWS::Serverless-2016-10-31", + "Resources": { + "MyFunc": { + "Type": "AWS::Serverless::Function", + "Properties": { + "Handler": "index.handler", + "Runtime": "nodejs20.x", + "AutoPublishAlias": "production", + "InlineCode": "exports.handler = async () => ({});" + } + } + } + } + """); + + JsonNode resources = processor.expandSamTemplate(template).path("Resources"); + + assertTrue(resources.has("MyFuncVersion")); + assertEquals("AWS::Lambda::Version", resources.path("MyFuncVersion").path("Type").asText()); + assertEquals("MyFunc", + resources.path("MyFuncVersion").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. + assertTrue(resources.has("MyFuncAliasProduction")); + JsonNode aliasProps = resources.path("MyFuncAliasProduction").path("Properties"); + assertEquals("AWS::Lambda::Alias", resources.path("MyFuncAliasProduction").path("Type").asText()); + // The alias NAME itself is untouched — only the logical id is sanitized. + 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()); + } + + @Test + void expandSamTemplate_withoutAutoPublishAliasGeneratesNeither() throws Exception { + JsonNode template = objectMapper.readTree(""" + { + "Transform": "AWS::Serverless-2016-10-31", + "Resources": { + "MyFunc": { + "Type": "AWS::Serverless::Function", + "Properties": { + "Handler": "index.handler", + "Runtime": "nodejs20.x", + "InlineCode": "exports.handler = async () => ({});" + } + } + } + } + """); + + JsonNode resources = processor.expandSamTemplate(template).path("Resources"); + + Iterator names = resources.fieldNames(); + while (names.hasNext()) { + String name = names.next(); + String type = resources.path(name).path("Type").asText(); + assertNotEquals("AWS::Lambda::Version", type, name + " should not exist"); + assertNotEquals("AWS::Lambda::Alias", type, name + " should not exist"); + } + } + + @Test + void expandSamTemplate_autoPublishAliasFromIntrinsicPassesNodeThrough() throws Exception { + // SAM allows an intrinsic alias name (e.g. !Ref StageName). The logical id needs a literal, + // so it drops the suffix, but the node itself is passed through to Name for the template + // engine to resolve at provision time. + JsonNode template = objectMapper.readTree(""" + { + "Transform": "AWS::Serverless-2016-10-31", + "Parameters": {"StageName": {"Type": "String", "Default": "live"}}, + "Resources": { + "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"); + + assertTrue(resources.has("MyFuncAlias")); + assertEquals("StageName", + resources.path("MyFuncAlias").path("Properties").path("Name").path("Ref").asText()); + } + + @Test + void expandSamTemplate_autoPublishAliasWithSeparatorsYieldsAlphanumericLogicalId() throws Exception { + // '-' and '_' are legal in a Lambda alias name but not in a CloudFormation logical id, so + // the suffix has to be sanitized. Using the raw name emits "MyFuncAliasblue-green". + JsonNode template = objectMapper.readTree(""" + { + "Transform": "AWS::Serverless-2016-10-31", + "Resources": { + "MyFunc": { + "Type": "AWS::Serverless::Function", + "Properties": { + "Handler": "index.handler", + "Runtime": "nodejs20.x", + "AutoPublishAlias": "blue-green_2", + "InlineCode": "exports.handler = async () => ({});" + } + } + } + } + """); + + JsonNode resources = processor.expandSamTemplate(template).path("Resources"); + + String aliasId = null; + Iterator names = resources.fieldNames(); + while (names.hasNext()) { + String name = names.next(); + if ("AWS::Lambda::Alias".equals(resources.path(name).path("Type").asText())) { + aliasId = name; + } + } + assertNotNull(aliasId, "expansion emitted no AWS::Lambda::Alias"); + assertTrue(aliasId.matches("[A-Za-z0-9]+"), + "logical id must be alphanumeric, was: " + aliasId); + assertEquals("MyFuncAliasBlueGreen2", aliasId); + + // The alias name reaching Lambda keeps its separators — only the logical id is sanitized. + assertEquals("blue-green_2", resources.path(aliasId).path("Properties").path("Name").asText()); + } + @Test void expandSamTemplate_functionWithPackageTypeImage() throws Exception { // PackageType must be carried through to the expanded AWS::Lambda::Function: without it, diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/LambdaVersionAliasCfnProvisionerTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/LambdaVersionAliasCfnProvisionerTest.java new file mode 100644 index 0000000000..763baff86a --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/LambdaVersionAliasCfnProvisionerTest.java @@ -0,0 +1,187 @@ +package io.github.hectorvent.floci.services.cloudformation.provisioners; + +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 io.github.hectorvent.floci.services.cloudformation.CloudFormationTemplateEngine; +import io.github.hectorvent.floci.services.cloudformation.model.StackResource; +import io.github.hectorvent.floci.services.lambda.LambdaService; +import io.github.hectorvent.floci.services.lambda.model.LambdaAlias; +import io.github.hectorvent.floci.services.lambda.model.LambdaFunction; +import org.junit.jupiter.api.Test; + +import java.util.HashMap; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.ArgumentMatchers.isNull; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +/** + * The Lambda Version/Alias CFN provisioner in isolation. Covers the two paths the SAM + * integration test cannot reach: the already-exists fallback, and delete. + */ +class LambdaVersionAliasCfnProvisionerTest { + + private static final String ALIAS_ARN = + "arn:aws:lambda:us-east-1:000000000000:function:my-fn:production"; + + private final LambdaService lambda = mock(LambdaService.class); + private final LambdaVersionAliasCfnProvisioner provisioner = new LambdaVersionAliasCfnProvisioner(lambda); + private final ObjectMapper mapper = new ObjectMapper(); + + private ProvisionContext ctx() { + // Scalar properties only: intrinsic resolution (Ref/GetAtt) is the engine's job and is + // covered by its own tests, so a passthrough keeps this a true isolated unit test. + CloudFormationTemplateEngine engine = mock(CloudFormationTemplateEngine.class); + when(engine.resolve(any())).thenAnswer(inv -> { + JsonNode node = inv.getArgument(0); + return node == null ? null : node.asText(); + }); + return new ProvisionContext(engine, "us-east-1", "000000000000", "my-stack"); + } + + private StackResource resource(String type, String logicalId) { + StackResource r = new StackResource(); + r.setLogicalId(logicalId); + r.setResourceType(type); + r.setAttributes(new HashMap<>()); + return r; + } + + private LambdaFunction publishedVersion() { + LambdaFunction version = new LambdaFunction(); + version.setFunctionName("my-fn"); + version.setVersion("3"); + version.setFunctionArn("arn:aws:lambda:us-east-1:000000000000:function:my-fn:3"); + return version; + } + + private LambdaAlias alias(String functionVersion) { + LambdaAlias alias = new LambdaAlias(); + alias.setName("production"); + alias.setFunctionName("my-fn"); + alias.setFunctionVersion(functionVersion); + alias.setAliasArn(ALIAS_ARN); + return alias; + } + + @Test + void versionSetsPhysicalIdAndGetAttAttributes() { + when(lambda.publishVersion(eq("us-east-1"), eq("my-fn"), isNull())).thenReturn(publishedVersion()); + + ObjectNode props = mapper.createObjectNode(); + props.put("FunctionName", "my-fn"); + StackResource r = resource("AWS::Lambda::Version", "MyFuncVersion"); + + provisioner.provision(r, props, ctx()); + + // Ref -> qualified ARN, GetAtt Version -> the number the Alias resource references. + assertEquals("arn:aws:lambda:us-east-1:000000000000:function:my-fn:3", r.getPhysicalId()); + assertEquals("3", r.getAttributes().get("Version")); + assertEquals("arn:aws:lambda:us-east-1:000000000000:function:my-fn:3", + r.getAttributes().get("FunctionArn")); + } + + @Test + void versionWithoutFunctionNameFails() { + StackResource r = resource("AWS::Lambda::Version", "MyFuncVersion"); + assertThrows(IllegalArgumentException.class, + () -> provisioner.provision(r, mapper.createObjectNode(), ctx())); + verifyNoInteractions(lambda); + } + + @Test + void aliasSetsPhysicalIdFromAliasArn() { + when(lambda.createAlias(eq("us-east-1"), eq("my-fn"), eq("production"), eq("3"), isNull(), isNull())) + .thenReturn(alias("3")); + + ObjectNode props = mapper.createObjectNode(); + props.put("FunctionName", "my-fn"); + props.put("Name", "production"); + props.put("FunctionVersion", "3"); + StackResource r = resource("AWS::Lambda::Alias", "MyFuncAliasproduction"); + + provisioner.provision(r, props, ctx()); + + assertEquals(ALIAS_ARN, r.getPhysicalId()); + assertEquals(ALIAS_ARN, r.getAttributes().get("AliasArn")); + } + + @Test + void aliasSurvivingAPriorDeployIsUpdatedRatherThanFailingTheStack() { + // Floci deletes and recreates a stack on redeploy; an alias that outlived the delete makes + // createAlias conflict. Converging on it keeps a redeploy idempotent instead of leaving the + // stack in ROLLBACK. + when(lambda.createAlias(any(), any(), any(), any(), any(), any())) + .thenThrow(new AwsException("ResourceConflictException", "Alias already exists: production", 409)); + when(lambda.updateAlias(eq("us-east-1"), eq("my-fn"), eq("production"), eq("4"), isNull(), isNull())) + .thenReturn(alias("4")); + + ObjectNode props = mapper.createObjectNode(); + props.put("FunctionName", "my-fn"); + props.put("Name", "production"); + props.put("FunctionVersion", "4"); + StackResource r = resource("AWS::Lambda::Alias", "MyFuncAliasproduction"); + + provisioner.provision(r, props, ctx()); + + verify(lambda).updateAlias(eq("us-east-1"), eq("my-fn"), eq("production"), eq("4"), isNull(), isNull()); + assertEquals(ALIAS_ARN, r.getPhysicalId()); + } + + @Test + void aliasFailureOtherThanConflictPropagates() { + // Only the already-exists case is convergeable. A missing function (for example) must fail + // the stack rather than be silently swallowed by the fallback. + when(lambda.createAlias(any(), any(), any(), any(), any(), any())) + .thenThrow(new AwsException("ResourceNotFoundException", "Function not found: my-fn", 404)); + + ObjectNode props = mapper.createObjectNode(); + props.put("FunctionName", "my-fn"); + props.put("Name", "production"); + StackResource r = resource("AWS::Lambda::Alias", "MyFuncAliasproduction"); + + AwsException e = assertThrows(AwsException.class, () -> provisioner.provision(r, props, ctx())); + assertEquals("ResourceNotFoundException", e.getErrorCode()); + } + + @Test + void deleteAliasParsesFunctionAndAliasFromArn() { + provisioner.delete("AWS::Lambda::Alias", ALIAS_ARN, "us-east-1"); + verify(lambda).deleteAlias("us-east-1", "my-fn", "production"); + } + + @Test + void deleteAliasAlreadyGoneIsIdempotent() { + // The function may have been deleted first, taking its aliases with it; a stack delete has + // to stay idempotent rather than transition to DELETE_FAILED. + org.mockito.Mockito.doThrow(new AwsException("ResourceNotFoundException", "Alias not found: production", 404)) + .when(lambda).deleteAlias(any(), any(), any()); + + provisioner.delete("AWS::Lambda::Alias", ALIAS_ARN, "us-east-1"); + } + + @Test + void deleteVersionIsANoOp() { + // Lambda exposes no DeleteVersion; deleting the function drops its versions with it. + provisioner.delete("AWS::Lambda::Version", + "arn:aws:lambda:us-east-1:000000000000:function:my-fn:3", "us-east-1"); + verifyNoInteractions(lambda); + } + + @Test + void deleteToleratesAPhysicalIdThatIsNotAnAliasArn() { + // Stacks created before this provisioner existed got the generic fallback's physical id + // (logicalId + "-" + short uuid) for an explicitly declared Lambda::Alias. Deleting such a + // stack after upgrading must not fail on an unparseable id. + provisioner.delete("AWS::Lambda::Alias", "MyFuncAliasproduction-1a2b3c4d", "us-east-1"); + verifyNoInteractions(lambda); + } +}