mirror of
https://github.com/floci-io/floci.git
synced 2026-11-22 21:50:46 -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
+156
@@ -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;
|
||||
}
|
||||
|
||||
}
|
||||
+57
-4
@@ -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 CfnResourceProvisioner
|
||||
r.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 CfnResourceProvisioner
|
||||
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.
|
||||
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 CfnResourceProvisioner
|
||||
throw 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;
|
||||
}
|
||||
}
|
||||
@@ -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");
|
||||
}
|
||||
|
||||
@@ -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());
|
||||
|
||||
+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