Light, fluffy, and always free - The AWS Local Emulator alternative
feat(cloudformation): provision AWS::Lambda::Permission and fix Version and Alias updates (#1997)
lex00105a8eeb7e3d
diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/LambdaAddressingCfnProvisioner.java b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/LambdaAddressingCfnProvisioner.javanew file mode 100644index 0000000000..2baac4ec99--- /dev/null+++ b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/LambdaAddressingCfnProvisioner.java@@ -0,0 +1,156 @@+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.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 java.util.HashMap;+import java.util.LinkedHashMap;+import java.util.List;+import java.util.Map;+import java.util.Set;++/**+ * CloudFormation provisioning for {@code AWS::Lambda::Permission}. {@code AWS::Lambda::Version} and+ * {@code AWS::Lambda::Alias} belong to {@link LambdaVersionAliasCfnProvisioner}.+ *+ * <p>The physical id doubles as the delete handle, since {@link #delete(String, String, String)}+ * only receives the physical id. It stores {@code <functionName>|<statementId>}, and '|' cannot+ * appear in a function name or ARN.+ *+ * <p>Stack updates re-provision every resource in the template, so this is idempotent. The previous+ * statement is captured and removed before the replacement is added, since AddPermission rejects a+ * duplicate Sid, and it goes back if the replacement is rejected.+ */+@ApplicationScoped+public class LambdaAddressingCfnProvisioner implements CfnResourceProvisioner {++ private final LambdaService lambdaService;++ @Inject+ public LambdaAddressingCfnProvisioner(LambdaService lambdaService) {+ this.lambdaService = lambdaService;+ }++ @Override+ public Set<String> resourceTypes() {+ return Set.of("AWS::Lambda::Permission");+ }++ @Override+ public void provision(StackResource r, JsonNode props, ProvisionContext ctx) {+ if (!"AWS::Lambda::Permission".equals(r.getResourceType())) {+ throw new IllegalStateException(+ "LambdaPermissionCfnProvisioner cannot handle " + r.getResourceType());+ }+ provisionPermission(r, props, ctx);+ }++ @Override+ public void delete(String resourceType, String physicalId, String region) {+ if (!"AWS::Lambda::Permission".equals(resourceType) || physicalId == null) {+ return;+ }+ int sep = physicalId.lastIndexOf('|');+ if (sep <= 0) {+ return;+ }+ try {+ // Null qualifier: this provisioner only ever adds statements on the unqualified+ // function, so that is the resource the statement is scoped to.+ lambdaService.removePermission(region, physicalId.substring(0, sep), null,+ physicalId.substring(sep + 1));+ } catch (AwsException e) {+ // The statement or its function is already gone, so a DeleteStack retry must not+ // fail the resource for work that is already done.+ if (!"ResourceNotFoundException".equals(e.getErrorCode()) && e.getHttpStatus() != 404) {+ throw e;+ }+ }+ }++ private void provisionPermission(StackResource r, JsonNode props, ProvisionContext ctx) {+ String functionName = ctx.resolveOptional(props, "FunctionName");+ String statementId = r.getLogicalId();+ // Stack updates re-provision every resource; drop the previous statement first so+ // AddPermission does not reject the duplicate Sid. The old physical id carries the+ // function the statement was originally attached to. AddPermission rejects a duplicate+ // Sid, so the new statement cannot simply be added first — instead the old one is+ // captured before removal and put back if the replacement is rejected.+ RemovedStatement removed = removePreviousStatement(r.getPhysicalId(), ctx.region());++ Map<String, Object> request = new HashMap<>();+ request.put("StatementId", statementId);+ request.put("Action", ctx.resolveOptional(props, "Action"));+ request.put("Principal", ctx.resolveOptional(props, "Principal"));+ String sourceArn = ctx.resolveOptional(props, "SourceArn");+ if (sourceArn != null && !sourceArn.isBlank()) request.put("SourceArn", sourceArn);+ String sourceAccount = ctx.resolveOptional(props, "SourceAccount");+ if (sourceAccount != null && !sourceAccount.isBlank()) request.put("SourceAccount", sourceAccount);+ try {+ lambdaService.addPermission(ctx.region(), functionName, null, request);+ } catch (RuntimeException failure) {+ // Without this the rejected update leaves the function with no statement at all, and+ // rollback does not restore it: callers that could invoke before the update lose access.+ if (removed != null) {+ try {+ lambdaService.restorePermissionStatement(ctx.region(), removed.functionName(),+ removed.statement());+ } catch (RuntimeException restoreFailure) {+ failure.addSuppressed(restoreFailure);+ }+ }+ throw failure;+ }+ r.setPhysicalId(functionName + "|" + statementId);+ }++ /** A statement taken off a function so it can be put back if the replacement fails. */+ private record RemovedStatement(String functionName, Map<String, Object> statement) {}++ private RemovedStatement removePreviousStatement(String physicalId, String region) {+ if (physicalId == null) {+ return null;+ }+ int sep = physicalId.lastIndexOf('|');+ if (sep <= 0) {+ return null;+ }+ String functionName = physicalId.substring(0, sep);+ String statementId = physicalId.substring(sep + 1);+ Map<String, Object> statement = findStatement(region, functionName, statementId);+ try {+ lambdaService.removePermission(region, functionName, null, statementId);+ } catch (AwsException ignored) {+ // statement or function already gone — nothing to replace, nothing to restore+ return null;+ }+ return statement == null ? null : new RemovedStatement(functionName, statement);+ }++ private Map<String, Object> findStatement(String region, String functionName, String statementId) {+ try {+ Object policy = lambdaService.getPolicy(region, functionName, null).get("policy");+ if (policy instanceof Map<?, ?> policyMap+ && policyMap.get("Statement") instanceof List<?> statements) {+ for (Object candidate : statements) {+ if (candidate instanceof Map<?, ?> statement+ && statementId.equals(statement.get("Sid"))) {+ Map<String, Object> copy = new LinkedHashMap<>();+ statement.forEach((k, v) -> copy.put(String.valueOf(k), v));+ return copy;+ }+ }+ }+ } catch (AwsException ignored) {+ // no policy on the function yet+ }+ return null;+ }++}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.javaindex 462d85a886..a3c50baf9c 100644--- 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@@ -11,6 +11,8 @@ import jakarta.enterprise.context.ApplicationScoped;import jakarta.inject.Inject;import org.jboss.logging.Logger;+import java.util.LinkedHashMap;+import java.util.Map;import java.util.Set;/**@@ -83,6 +85,16 @@ public class LambdaVersionAliasCfnProvisioner implements CfnResourceProvisioner}String description = ctx.resolveOptional(props, "Description");+ // Version resources are immutable in CloudFormation. An update re-invokes provision with+ // the prior physical id, and publishing again would mint a new version and repoint every+ // Ref to it, so the version this resource already published is kept while it still exists.+ String previous = r.getPhysicalId();+ if (previous != null && existingVersionIsCurrent(ctx.region(), functionName, previous)) {+ r.getAttributes().put("Version", previous.substring(previous.lastIndexOf(':') + 1));+ r.getAttributes().put("FunctionArn", previous);+ return;+ }+LambdaFunction version = lambdaService.publishVersion(ctx.region(), functionName, description);// Matches real CloudFormation: Ref returns the qualified ARN, GetAtt Version the version@@ -92,6 +104,26 @@ public class LambdaVersionAliasCfnProvisioner implements CfnResourceProvisionerr.getAttributes().put("FunctionArn", version.getFunctionArn());}+ /** True when {@code physicalId} names a still-published version of the function in the template. */+ private boolean existingVersionIsCurrent(String region, String functionName, String physicalId) {+ int sep = physicalId.lastIndexOf(':');+ if (sep <= 0) {+ return false;+ }+ String version = physicalId.substring(sep + 1);+ String baseArn = physicalId.substring(0, sep);+ try {+ LambdaFunction fn = lambdaService.getFunction(region, functionName);+ if (!baseArn.equals(fn.getFunctionArn().replace(":$LATEST", ""))) {+ return false; // the FunctionName property now points at a different function+ }+ return lambdaService.listVersionsByFunction(region, functionName).stream()+ .anyMatch(v -> version.equals(v.getVersion()));+ } catch (AwsException e) {+ return false;+ }+ }+private void provisionAlias(StackResource r, JsonNode props, ProvisionContext ctx) {String functionName = ctx.resolveOptional(props, "FunctionName");String aliasName = ctx.resolveOptional(props, "Name");@@ -102,12 +134,12 @@ public class LambdaVersionAliasCfnProvisioner implements CfnResourceProvisionerString 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.+ Map<String, Double> routingConfig = parseRoutingConfig(props, ctx);+LambdaAlias alias;try {alias = lambdaService.createAlias(ctx.region(), functionName, aliasName,- functionVersion, description, null);+ functionVersion, description, routingConfig);} 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.@@ -115,11 +147,32 @@ public class LambdaVersionAliasCfnProvisioner implements CfnResourceProvisionerthrow e;}LOG.debugv("Alias {0} exists on {1}, updating instead", aliasName, functionName);+ // An absent RoutingConfig clears any previous weights, since an empty map clears in+ // LambdaService#updateAlias while null keeps what is there.alias = lambdaService.updateAlias(ctx.region(), functionName, aliasName,- functionVersion, description, null);+ functionVersion, description, routingConfig != null ? routingConfig : Map.of());}r.setPhysicalId(alias.getAliasArn());r.getAttributes().put("AliasArn", alias.getAliasArn());}++ /**+ * Parses the CloudFormation {@code RoutingConfig.AdditionalVersionWeights} list+ * ({@code [{FunctionVersion, FunctionWeight}]}) into the service's version-to-weight map.+ */+ private Map<String, Double> parseRoutingConfig(JsonNode props, ProvisionContext ctx) {+ if (props == null || !props.has("RoutingConfig") || props.get("RoutingConfig").isNull()) {+ return null;+ }+ Map<String, Double> routing = new LinkedHashMap<>();+ JsonNode weights = props.get("RoutingConfig").path("AdditionalVersionWeights");+ if (weights.isArray()) {+ for (JsonNode weight : weights) {+ String version = ctx.engine().resolve(weight.get("FunctionVersion"));+ routing.put(version, Double.parseDouble(ctx.engine().resolve(weight.get("FunctionWeight"))));+ }+ }+ return routing;+ }}diff --git a/src/main/java/io/github/hectorvent/floci/services/lambda/LambdaFunctionStore.java b/src/main/java/io/github/hectorvent/floci/services/lambda/LambdaFunctionStore.javaindex 8958f6cb05..e0bd9310e9 100644--- a/src/main/java/io/github/hectorvent/floci/services/lambda/LambdaFunctionStore.java+++ b/src/main/java/io/github/hectorvent/floci/services/lambda/LambdaFunctionStore.java@@ -122,6 +122,14 @@ public class LambdaFunctionStore implements Resettable {});}+ /** Deletes one published version, leaving {@code $LATEST} and the other versions in place. */+ public void deleteVersion(String region, String functionName, String version) {+ get(region, functionName, version).ifPresent(fn -> {+ deindexFunction(fn);+ backend.delete(regionKey(region, functionName, version));+ });+ }+private static String regionKey(String region, String functionName, String version) {return "lambda::" + region + "::" + functionName + "::" + (version != null ? version : "$LATEST");}diff --git a/src/main/java/io/github/hectorvent/floci/services/lambda/LambdaService.java b/src/main/java/io/github/hectorvent/floci/services/lambda/LambdaService.javaindex 62d20b1bf1..a283395ad2 100644--- a/src/main/java/io/github/hectorvent/floci/services/lambda/LambdaService.java+++ b/src/main/java/io/github/hectorvent/floci/services/lambda/LambdaService.java@@ -1047,6 +1047,21 @@ public class LambdaService {return functionStore.listVersions(region, fn.getFunctionName());}+ /**+ * Deletes a single published version of a function (DeleteFunction with a numeric qualifier),+ * leaving {@code $LATEST} and every other version untouched. Deleting an already-gone version+ * is a no-op; a missing function is a 404.+ */+ public void deleteVersion(String region, String functionName, String version) {+ if (version == null || version.isBlank() || "$LATEST".equals(version)) {+ throw new AwsException("InvalidParameterValueException",+ "Version must be a published version number, got: " + version, 400);+ }+ LambdaFunction fn = getFunction(region, functionName); // throws 404 if not found+ functionStore.deleteVersion(region, fn.getFunctionName(), version);+ LOG.infov("Deleted version {0} of function {1}", version, fn.getFunctionName());+ }+// ──────────────────────────── Aliases ────────────────────────────public LambdaAlias createAlias(String region, String functionName, String aliasName,@@ -1566,6 +1581,27 @@ public class LambdaService {return Map.of("policy", policy, "revisionId", fn.getRevisionId());}+ /**+ * Puts a previously captured policy statement back. Used to compensate when a replacement fails+ * after the original was removed: it takes the stored statement shape rather than an+ * AddPermission request, so what goes back is exactly what came out.+ *+ * <p>Scoped to the unqualified function, matching where the captured statement came from. A Sid+ * is unique only within one resource ARN, so matching on it alone would take out an+ * identically named statement on an alias or version and leave that one lost.+ */+ public void restorePermissionStatement(String region, String functionName, Map<String, Object> statement) {+ LambdaFunction fn = getFunction(region, functionName);+ String statementId = (String) statement.get("Sid");+ String resourceArn = policyResourceArn(fn, null);+ if (statementId != null) {+ fn.getPolicies().removeIf(s -> statementId.equals(s.get("Sid")) && scopedTo(s, resourceArn));+ }+ fn.getPolicies().add(statement);+ functionStore.save(region, fn);+ LOG.infov("Restored permission {0} on function {1}", statementId, functionName);+ }+public void removePermission(String region, String functionName, String qualifier, String statementId) {LambdaArnUtils.ResolvedFunctionRef ref = resolveWithRegion(region, functionName, qualifier);LambdaFunction fn = getFunction(region, ref.name());diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationLambdaAddressingIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationLambdaAddressingIntegrationTest.javanew file mode 100644index 0000000000..abae70a23f--- /dev/null+++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationLambdaAddressingIntegrationTest.java@@ -0,0 +1,280 @@+package io.github.hectorvent.floci.services.cloudformation;++import io.quarkus.test.junit.QuarkusTest;+import org.junit.jupiter.api.Test;++import static io.restassured.RestAssured.given;+import static org.hamcrest.Matchers.containsString;+import static org.junit.jupiter.api.Assertions.assertEquals;+import static org.junit.jupiter.api.Assertions.assertFalse;++/**+ * End-to-end check that CloudFormation provisions the Lambda addressing+ * resources (issue #1996): Permission lands in the function's resource+ * policy, Version publishes, and Alias resolves — all via LambdaService.+ * Uses a zip-less inline function definition, so the test is Docker-free+ * (no invoke, only control plane).+ */+@QuarkusTest+class CloudFormationLambdaAddressingIntegrationTest {++ private static final String CFN_AUTH =+ "AWS4-HMAC-SHA256 Credential=test/20260205/us-east-1/cloudformation/aws4_request";++ @Test+ void permissionVersionAliasAllProvision() {+ String suffix = Long.toString(System.nanoTime(), 36);+ String stackName = "cfn-lambda-addr-" + suffix;+ String fnName = "addr-fn-" + suffix;++ String template = """+ {+ "Resources": {+ "Role": {+ "Type": "AWS::IAM::Role",+ "Properties": {+ "AssumeRolePolicyDocument": {"Version": "2012-10-17", "Statement": [+ {"Effect": "Allow", "Principal": {"Service": "lambda.amazonaws.com"}, "Action": "sts:AssumeRole"}]}+ }+ },+ "Fn": {+ "Type": "AWS::Lambda::Function",+ "Properties": {+ "FunctionName": "%s",+ "Runtime": "python3.12",+ "Handler": "index.handler",+ "Role": {"Fn::GetAtt": ["Role", "Arn"]},+ "Code": {"ZipFile": "def handler(e, c): return 'ok'"}+ }+ },+ "Perm": {+ "Type": "AWS::Lambda::Permission",+ "Properties": {+ "FunctionName": {"Ref": "Fn"},+ "Action": "lambda:InvokeFunction",+ "Principal": "s3.amazonaws.com",+ "SourceArn": "arn:aws:s3:::some-bucket"+ }+ },+ "Ver": {+ "Type": "AWS::Lambda::Version",+ "Properties": {"FunctionName": {"Ref": "Fn"}}+ },+ "Live": {+ "Type": "AWS::Lambda::Alias",+ "Properties": {+ "FunctionName": {"Ref": "Fn"},+ "Name": "live",+ "FunctionVersion": {"Fn::GetAtt": ["Ver", "Version"]}+ }+ }+ },+ "Outputs": {+ "AliasArn": {"Value": {"Ref": "Live"}},+ "VersionArn": {"Value": {"Ref": "Ver"}}+ }+ }+ """.formatted(fnName);++ given()+ .contentType("application/x-www-form-urlencoded")+ .header("Authorization", CFN_AUTH)+ .formParam("Action", "CreateStack")+ .formParam("StackName", stackName)+ .formParam("TemplateBody", template)+ .formParam("Capabilities.member.1", "CAPABILITY_IAM")+ .when()+ .post("/")+ .then()+ .statusCode(200);++ given()+ .contentType("application/x-www-form-urlencoded")+ .header("Authorization", CFN_AUTH)+ .formParam("Action", "DescribeStacks")+ .formParam("StackName", stackName)+ .when()+ .post("/")+ .then()+ .statusCode(200)+ .body(containsString("<StackStatus>CREATE_COMPLETE</StackStatus>"))+ .body(containsString(":function:" + fnName + ":1"))+ .body(containsString(":function:" + fnName + ":live"));++ // The permission is in the function's resource policy.+ given()+ .when().get("/2015-03-31/functions/" + fnName + "/policy")+ .then()+ .statusCode(200)+ .body(containsString("s3.amazonaws.com"))+ .body(containsString("arn:aws:s3:::some-bucket"));+ }++ @Test+ void updateKeepsVersionAppliesRoutingAndDeleteCleansUp() throws InterruptedException {+ String suffix = Long.toString(System.nanoTime(), 36);+ String stackName = "cfn-lambda-addr-upd-" + suffix;+ String fnName = "addr-upd-fn-" + suffix;++ String base = """+ "Role": {+ "Type": "AWS::IAM::Role",+ "Properties": {+ "AssumeRolePolicyDocument": {"Version": "2012-10-17", "Statement": [+ {"Effect": "Allow", "Principal": {"Service": "lambda.amazonaws.com"}, "Action": "sts:AssumeRole"}]}+ }+ },+ "Fn": {+ "Type": "AWS::Lambda::Function",+ "Properties": {+ "FunctionName": "%s",+ "Runtime": "python3.12",+ "Handler": "index.handler",+ "Role": {"Fn::GetAtt": ["Role", "Arn"]},+ "Code": {"ZipFile": "def handler(e, c): return 'ok'"}+ }+ },+ "Perm": {+ "Type": "AWS::Lambda::Permission",+ "Properties": {+ "FunctionName": {"Ref": "Fn"},+ "Action": "lambda:InvokeFunction",+ "Principal": "s3.amazonaws.com",+ "SourceArn": "arn:aws:s3:::some-bucket"+ }+ },+ "Ver": {+ "Type": "AWS::Lambda::Version",+ "Properties": {"FunctionName": {"Ref": "Fn"}}+ }""".formatted(fnName);++ String template = """+ {+ "Resources": {+ %s,+ "Live": {+ "Type": "AWS::Lambda::Alias",+ "Properties": {+ "FunctionName": {"Ref": "Fn"},+ "Name": "live",+ "FunctionVersion": {"Fn::GetAtt": ["Ver", "Version"]}+ }+ }+ },+ "Outputs": {"VersionArn": {"Value": {"Ref": "Ver"}}}+ }+ """.formatted(base);++ // Second revision: a new version plus weighted routing on the alias.+ String updatedTemplate = """+ {+ "Resources": {+ %s,+ "Ver2": {+ "Type": "AWS::Lambda::Version",+ "Properties": {"FunctionName": {"Ref": "Fn"}}+ },+ "Live": {+ "Type": "AWS::Lambda::Alias",+ "Properties": {+ "FunctionName": {"Ref": "Fn"},+ "Name": "live",+ "FunctionVersion": {"Fn::GetAtt": ["Ver", "Version"]},+ "RoutingConfig": {"AdditionalVersionWeights": [+ {"FunctionVersion": {"Fn::GetAtt": ["Ver2", "Version"]}, "FunctionWeight": 0.5}]}+ }+ }+ },+ "Outputs": {"VersionArn": {"Value": {"Ref": "Ver"}}}+ }+ """.formatted(base);++ given()+ .contentType("application/x-www-form-urlencoded")+ .header("Authorization", CFN_AUTH)+ .formParam("Action", "CreateStack")+ .formParam("StackName", stackName)+ .formParam("TemplateBody", template)+ .formParam("Capabilities.member.1", "CAPABILITY_IAM")+ .when()+ .post("/")+ .then()+ .statusCode(200);++ given()+ .contentType("application/x-www-form-urlencoded")+ .header("Authorization", CFN_AUTH)+ .formParam("Action", "UpdateStack")+ .formParam("StackName", stackName)+ .formParam("TemplateBody", updatedTemplate)+ .formParam("Capabilities.member.1", "CAPABILITY_IAM")+ .when()+ .post("/")+ .then()+ .statusCode(200);++ // "Ver" must still be version 1: the update must not republish an unchanged version.+ given()+ .contentType("application/x-www-form-urlencoded")+ .header("Authorization", CFN_AUTH)+ .formParam("Action", "DescribeStacks")+ .formParam("StackName", stackName)+ .when()+ .post("/")+ .then()+ .statusCode(200)+ .body(containsString("<StackStatus>UPDATE_COMPLETE</StackStatus>"))+ .body(containsString(":function:" + fnName + ":1"));++ // The alias carries the routing weights, and the permission was replaced, not duplicated.+ given()+ .when().get("/2015-03-31/functions/" + fnName + "/aliases/live")+ .then()+ .statusCode(200)+ .body(containsString("AdditionalVersionWeights"))+ .body(containsString("0.5"));++ String policy = given()+ .when().get("/2015-03-31/functions/" + fnName + "/policy")+ .then()+ .statusCode(200)+ .body(containsString("s3.amazonaws.com"))+ .extract().asString();+ assertEquals(policy.indexOf("\"Perm\""), policy.lastIndexOf("\"Perm\""),+ "permission statement must not be duplicated by the update: " + policy);++ given()+ .contentType("application/x-www-form-urlencoded")+ .header("Authorization", CFN_AUTH)+ .formParam("Action", "DeleteStack")+ .formParam("StackName", stackName)+ .when()+ .post("/")+ .then()+ .statusCode(200);++ // A permission, version or alias whose delete fails leaves the stack in DELETE_FAILED+ // and it never drops out of DescribeStacks — so waiting for the stack to disappear+ // exercises all three delete paths.+ awaitStackGone(stackName);+ }++ private static void awaitStackGone(String stackName) throws InterruptedException {+ for (int i = 0; i < 200; i++) {+ var response = given()+ .contentType("application/x-www-form-urlencoded")+ .header("Authorization", CFN_AUTH)+ .formParam("Action", "DescribeStacks")+ .formParam("StackName", stackName)+ .when().post("/").then().extract();+ if (response.statusCode() != 200) {+ return;+ }+ String body = response.asString();+ assertFalse(body.contains("DELETE_FAILED"),+ "stack delete failed instead of completing: " + body);+ Thread.sleep(50);+ }+ throw new AssertionError("Timed out waiting for stack " + stackName + " to be deleted");+ }+}diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/LambdaAddressingCfnProvisionerTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/LambdaAddressingCfnProvisionerTest.javanew file mode 100644index 0000000000..660eb5cd15--- /dev/null+++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/LambdaAddressingCfnProvisionerTest.java@@ -0,0 +1,120 @@+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 org.junit.jupiter.api.Test;+import org.mockito.ArgumentCaptor;++import java.util.HashMap;+import java.util.LinkedHashMap;+import java.util.List;+import java.util.Map;++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.anyMap;+import static org.mockito.ArgumentMatchers.anyString;+import static org.mockito.ArgumentMatchers.eq;+import static org.mockito.ArgumentMatchers.isNull;+import static org.mockito.Mockito.doThrow;+import static org.mockito.Mockito.mock;+import static org.mockito.Mockito.never;+import static org.mockito.Mockito.verify;+import static org.mockito.Mockito.when;++/**+ * The permission-replacement path: a stack update removes the previous statement before adding+ * its replacement, so a rejected replacement must not leave the function with neither.+ */+class LambdaAddressingCfnProvisionerTest {++ private static final String REGION = "us-east-1";++ private final LambdaService lambda = mock(LambdaService.class);+ private final LambdaAddressingCfnProvisioner provisioner = new LambdaAddressingCfnProvisioner(lambda);+ private final ObjectMapper mapper = new ObjectMapper();++ @Test+ void aRejectedPermissionReplacementRestoresThePreviousStatement() {+ Map<String, Object> existing = new LinkedHashMap<>();+ existing.put("Sid", "InvokePermission");+ existing.put("Effect", "Allow");+ existing.put("Principal", Map.of("Service", "s3.amazonaws.com"));+ existing.put("Action", "lambda:InvokeFunction");+ when(lambda.getPolicy(REGION, "app-fn", null))+ .thenReturn(Map.of("policy", Map.of("Statement", List.of(existing))));+ doThrow(new AwsException("InvalidParameterValueException", "bad principal", 400))+ .when(lambda).addPermission(eq(REGION), eq("app-fn"), isNull(), anyMap());++ StackResource r = resource();+ r.setPhysicalId("app-fn|InvokePermission");++ assertThrows(AwsException.class, () -> provisioner.provision(r, props("app-fn"), ctx()));++ ArgumentCaptor<Map<String, Object>> restored = ArgumentCaptor.captor();+ verify(lambda).removePermission(REGION, "app-fn", null, "InvokePermission");+ verify(lambda).restorePermissionStatement(eq(REGION), eq("app-fn"), restored.capture());+ assertEquals("InvokePermission", restored.getValue().get("Sid"));+ assertEquals("lambda:InvokeFunction", restored.getValue().get("Action"));+ // The physical id still points at the statement that is actually there.+ assertEquals("app-fn|InvokePermission", r.getPhysicalId());+ }++ @Test+ void aSuccessfulReplacementDoesNotRestoreAnything() {+ Map<String, Object> existing = new LinkedHashMap<>();+ existing.put("Sid", "InvokePermission");+ when(lambda.getPolicy(REGION, "app-fn", null))+ .thenReturn(Map.of("policy", Map.of("Statement", List.of(existing))));++ StackResource r = resource();+ r.setPhysicalId("app-fn|InvokePermission");++ provisioner.provision(r, props("app-fn"), ctx());++ verify(lambda).removePermission(REGION, "app-fn", null, "InvokePermission");+ verify(lambda, never()).restorePermissionStatement(anyString(), anyString(), anyMap());+ assertEquals("app-fn|InvokePermission", r.getPhysicalId());+ }++ @Test+ void aFirstCreateHasNothingToRemoveOrRestore() {+ StackResource r = resource();++ provisioner.provision(r, props("app-fn"), ctx());++ verify(lambda, never()).removePermission(anyString(), anyString(), any(), anyString());+ verify(lambda, never()).restorePermissionStatement(anyString(), anyString(), anyMap());+ assertEquals("app-fn|InvokePermission", r.getPhysicalId());+ }++ private ProvisionContext ctx() {+ 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, REGION, "000000000000", "test-stack");+ }++ private StackResource resource() {+ StackResource r = new StackResource();+ r.setLogicalId("InvokePermission");+ r.setResourceType("AWS::Lambda::Permission");+ r.setAttributes(new HashMap<>());+ return r;+ }++ private ObjectNode props(String functionName) {+ return mapper.createObjectNode()+ .put("FunctionName", functionName)+ .put("Action", "lambda:InvokeFunction")+ .put("Principal", "s3.amazonaws.com");+ }+}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.javaindex 763baff86a..d527e30c6e 100644--- 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@@ -12,6 +12,7 @@ import io.github.hectorvent.floci.services.lambda.model.LambdaFunction;import org.junit.jupiter.api.Test;import java.util.HashMap;+import java.util.Map;import static org.junit.jupiter.api.Assertions.assertEquals;import static org.junit.jupiter.api.Assertions.assertThrows;@@ -121,7 +122,9 @@ class LambdaVersionAliasCfnProvisionerTest {// 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()))+ // A template that declares no RoutingConfig means the alias carries no weights, so the+ // update clears them with an empty map rather than keeping whatever was there.+ when(lambda.updateAlias(eq("us-east-1"), eq("my-fn"), eq("production"), eq("4"), isNull(), eq(Map.of()))).thenReturn(alias("4"));ObjectNode props = mapper.createObjectNode();@@ -132,7 +135,7 @@ class LambdaVersionAliasCfnProvisionerTest {provisioner.provision(r, props, ctx());- verify(lambda).updateAlias(eq("us-east-1"), eq("my-fn"), eq("production"), eq("4"), isNull(), isNull());+ verify(lambda).updateAlias(eq("us-east-1"), eq("my-fn"), eq("production"), eq("4"), isNull(), eq(Map.of()));assertEquals(ALIAS_ARN, r.getPhysicalId());}