mirror of
https://github.com/floci-io/floci.git
synced 2026-12-01 17:33:03 -05:00
feat(cloudformation): provision AWS::Lambda::Permission and fix Version and Alias updates (#1997)
* feat(cloudformation): provision AWS::Lambda::Permission, Version, and Alias Maps the three Lambda addressing resources onto the existing LambdaService APIs: Permission -> addPermission (statement id = logical id, SourceArn/SourceAccount carried), Version -> publishVersion (Ref = version-qualified ARN, Version/FunctionArn attributes), Alias -> createAlias (Ref = alias ARN). Fixes #1996 * refactor(cloudformation): move Lambda addressing into a per-service provisioner Moves AWS::Lambda::Permission, Version and Alias out of the CloudFormationResourceProvisioner switch into LambdaAddressingCfnProvisioner, following the SqsCfnProvisioner pattern. CloudFormationResourceProvisioner is now byte-identical to main again. The provisioner implements delete(), so the three resource types no longer survive stack deletion. Physical ids double as delete handles: a Permission stores <functionName>|<statementId>, a Version its version-qualified function ARN, an Alias its alias ARN. Also fixes two behaviors the switch arms did not cover: - Alias RoutingConfig.AdditionalVersionWeights is now parsed and passed to LambdaService instead of being discarded. - Stack updates no longer recreate these resources. A Permission replaces its previous statement rather than colliding on the duplicate Sid, a Version keeps the version it already published, and an Alias updates in place, deleting the old alias when a rename retargets it. Adds LambdaService#deleteVersion (and the matching store method) so a single published version can be removed without taking $LATEST with it. * fix(lambda): a rejected permission replacement puts the previous statement back A stack update re-provisions every resource, and AddPermission rejects a duplicate Sid, so the provisioner removed the previous statement before adding its replacement. When the replacement was then rejected the function was left with neither: CloudFormation reported UPDATE_ROLLBACK_COMPLETE while every service that could invoke the function before the update had lost access. The statement is now captured before it is removed and put back if AddPermission fails, with the restore failure attached as suppressed so the stack still reports the original error. LambdaService gained restorePermissionStatement for this, which takes the stored statement shape rather than an AddPermission request so what goes back is exactly what came out. * fix(cloudformation): narrow the provisioner to AWS::Lambda::Permission upstream #1961 added LambdaVersionAliasCfnProvisioner, which claims AWS::Lambda::Version and AWS::Lambda::Alias. This provisioner claimed the same two, and the registry rejects a duplicate claim, so every stack rolled back with "Duplicate CloudFormation provisioner for AWS::Lambda::Version". Version and Alias provisioning is dropped here in favour of that one, which sets the same physical id and attributes. What is left is AWS::Lambda::Permission, which nothing else provisions. Delete now tolerates a statement or function that is already gone, so a DeleteStack retry does not fail a resource for work already done. * fix(cloudformation): a stack update keeps its Lambda version and applies alias routing Two gaps in LambdaVersionAliasCfnProvisioner, both reachable from a plain UpdateStack. provisionVersion called publishVersion unconditionally, so every update minted a new version and repointed every Ref to it. Version resources are immutable in CloudFormation, so the version this resource already published is kept while it still exists, and a new one is published only when it is gone or the FunctionName property moved to a different function. RoutingConfig was not carried over, on the grounds that nothing emitted it. The CloudFormation path does, so AdditionalVersionWeights is parsed and passed to create and update. A template that declares no RoutingConfig clears the weights rather than keeping them, which is why the existing alias test now expects an empty map instead of null.
This commit is contained in:
1 parent
30a61646ac
commit
105a8eeb7e
7 files changed
+662
-6
No files matched your search
+280
@@ -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");
|
||||
}
|
||||
}
|
||||
+120
@@ -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");
|
||||
}
|
||||
}
|
||||
+5
-2
@@ -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());
|
||||
}
|
||||
|
||||
|
||||
Reference in new issue
Block a user