diff --git a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/CloudFormationLambdaEventInvokeConfigTest.java b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/CloudFormationLambdaEventInvokeConfigTest.java new file mode 100644 index 0000000000..8676aa3fb0 --- /dev/null +++ b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/CloudFormationLambdaEventInvokeConfigTest.java @@ -0,0 +1,236 @@ +package com.floci.test; + +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; +import software.amazon.awssdk.services.cloudformation.CloudFormationClient; +import software.amazon.awssdk.services.cloudformation.model.CloudFormationException; +import software.amazon.awssdk.services.cloudformation.model.DescribeStacksRequest; +import software.amazon.awssdk.services.cloudformation.model.Output; +import software.amazon.awssdk.services.cloudformation.model.Parameter; +import software.amazon.awssdk.services.cloudformation.model.Stack; +import software.amazon.awssdk.services.cloudformation.model.StackResource; +import software.amazon.awssdk.services.lambda.LambdaClient; +import software.amazon.awssdk.services.lambda.model.GetFunctionEventInvokeConfigResponse; +import software.amazon.awssdk.services.lambda.model.ResourceNotFoundException; + +import java.util.List; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +/** + * Drives an {@code AWS::Lambda::EventInvokeConfig} through the CloudFormation SDK and reads it + * back through the Lambda SDK: the physical id is {@code FunctionName|Qualifier}, a settings + * change updates in place, a qualifier change replaces the configuration and removes the + * displaced one, and the stack delete removes it. + */ +@DisplayName("CloudFormation AWS::Lambda::EventInvokeConfig") +class CloudFormationLambdaEventInvokeConfigTest { + + private static final String ROLE = "arn:aws:iam::000000000000:role/cfn-lambda-role"; + private static final String DLQ_ARN = "arn:aws:sqs:us-east-1:000000000000:compat-async-dlq"; + + private static CloudFormationClient cloudFormation; + private static LambdaClient lambda; + private static String functionStackName; + private static String stackName; + private static String functionName; + + @BeforeAll + static void setup() { + cloudFormation = TestFixtures.cloudFormationClient(); + lambda = TestFixtures.lambdaClient(); + functionStackName = TestFixtures.uniqueName("compat-cfn-eic-fn"); + stackName = TestFixtures.uniqueName("compat-cfn-eic"); + functionName = TestFixtures.uniqueName("eic-fn"); + } + + @AfterAll + static void cleanup() { + if (cloudFormation != null) { + for (String name : List.of(stackName, functionStackName)) { + try { + cloudFormation.deleteStack(r -> r.stackName(name)); + waitForDeleted(name, 60); + } catch (Exception e) { + System.err.println("CloudFormation event invoke config cleanup skipped: " + e.getMessage()); + } + } + cloudFormation.close(); + } + if (lambda != null) { + lambda.close(); + } + } + + @Test + void configurationFollowsTheTemplateThroughCreateUpdateReplacementAndDelete() throws InterruptedException { + cloudFormation.createStack(r -> r.stackName(functionStackName).templateBody(functionTemplate())); + assertThat(waitForTerminal(functionStackName, 60)).isEqualTo("CREATE_COMPLETE"); + String version = output(functionStackName, "Version"); + + cloudFormation.createStack(r -> r + .stackName(stackName) + .templateBody(configTemplate()) + .parameters(parameters("$LATEST", "1"))); + assertThat(waitForTerminal(stackName, 60)).isEqualTo("CREATE_COMPLETE"); + + assertThat(output(stackName, "ConfigRef")) + .as("Ref is the composite FunctionName|Qualifier identifier") + .isEqualTo(functionName + "|$LATEST"); + StackResource resource = cloudFormation.describeStackResources(r -> r.stackName(stackName)) + .stackResources().stream() + .filter(sr -> "AWS::Lambda::EventInvokeConfig".equals(sr.resourceType())) + .findFirst() + .orElseThrow(); + assertThat(resource.physicalResourceId()).isEqualTo(functionName + "|$LATEST"); + + GetFunctionEventInvokeConfigResponse created = get("$LATEST"); + assertThat(created.functionArn()).endsWith(":function:" + functionName + ":$LATEST"); + assertThat(created.maximumRetryAttempts()).isEqualTo(1); + assertThat(created.maximumEventAgeInSeconds()).isEqualTo(300); + assertThat(created.destinationConfig().onFailure().destination()).isEqualTo(DLQ_ARN); + + cloudFormation.updateStack(r -> r + .stackName(stackName) + .templateBody(configTemplate()) + .parameters(parameters("$LATEST", "0"))); + assertThat(waitForTerminal(stackName, 60)).isEqualTo("UPDATE_COMPLETE"); + assertThat(output(stackName, "ConfigRef")) + .as("a settings change updates the configuration in place") + .isEqualTo(functionName + "|$LATEST"); + GetFunctionEventInvokeConfigResponse updated = get("$LATEST"); + assertThat(updated.maximumRetryAttempts()).isEqualTo(0); + assertThat(updated.maximumEventAgeInSeconds()).isEqualTo(300); + + cloudFormation.updateStack(r -> r + .stackName(stackName) + .templateBody(configTemplate()) + .parameters(parameters(version, "0"))); + assertThat(waitForTerminal(stackName, 60)).isEqualTo("UPDATE_COMPLETE"); + assertThat(output(stackName, "ConfigRef")) + .as("a qualifier change replaces the configuration") + .isEqualTo(functionName + "|" + version); + assertThat(get(version).functionArn()).endsWith(":function:" + functionName + ":" + version); + assertThatThrownBy(() -> get("$LATEST")) + .as("the displaced configuration is deleted once the update commits") + .isInstanceOf(ResourceNotFoundException.class); + + cloudFormation.deleteStack(r -> r.stackName(stackName)); + waitForDeleted(stackName, 60); + assertThatThrownBy(() -> get(version)).isInstanceOf(ResourceNotFoundException.class); + } + + private static GetFunctionEventInvokeConfigResponse get(String qualifier) { + return lambda.getFunctionEventInvokeConfig(r -> r.functionName(functionName).qualifier(qualifier)); + } + + private static String functionTemplate() { + return """ + { + "Resources": { + "Fn": { + "Type": "AWS::Lambda::Function", + "Properties": { + "FunctionName": "%s", + "Runtime": "nodejs20.x", + "Handler": "index.handler", + "Role": "%s", + "Code": {"ZipFile": "exports.handler = async (e) => ({ statusCode: 200 });"} + } + }, + "Ver": { + "Type": "AWS::Lambda::Version", + "Properties": {"FunctionName": {"Ref": "Fn"}} + } + }, + "Outputs": { + "Version": {"Value": {"Fn::GetAtt": ["Ver", "Version"]}} + } + } + """.formatted(functionName, ROLE); + } + + private static String configTemplate() { + return """ + { + "Parameters": { + "Qualifier": {"Type": "String"}, + "Retries": {"Type": "String"} + }, + "Resources": { + "AsyncConfig": { + "Type": "AWS::Lambda::EventInvokeConfig", + "Properties": { + "FunctionName": "%s", + "Qualifier": {"Ref": "Qualifier"}, + "MaximumRetryAttempts": {"Ref": "Retries"}, + "MaximumEventAgeInSeconds": 300, + "DestinationConfig": {"OnFailure": {"Destination": "%s"}} + } + } + }, + "Outputs": { + "ConfigRef": {"Value": {"Ref": "AsyncConfig"}} + } + } + """.formatted(functionName, DLQ_ARN); + } + + private static List parameters(String qualifier, String retries) { + return List.of( + Parameter.builder().parameterKey("Qualifier").parameterValue(qualifier).build(), + Parameter.builder().parameterKey("Retries").parameterValue(retries).build()); + } + + private static String output(String stack, String key) { + Stack described = cloudFormation.describeStacks( + DescribeStacksRequest.builder().stackName(stack).build()).stacks().get(0); + return described.outputs().stream() + .filter(o -> key.equals(o.outputKey())) + .map(Output::outputValue) + .findFirst() + .orElseThrow(() -> new AssertionError("stack " + stack + " has no output " + key)); + } + + private static String waitForTerminal(String name, int maxSeconds) throws InterruptedException { + long deadline = System.currentTimeMillis() + maxSeconds * 1000L; + while (System.currentTimeMillis() < deadline) { + List stacks = cloudFormation.describeStacks( + DescribeStacksRequest.builder().stackName(name).build()).stacks(); + if (!stacks.isEmpty()) { + String status = stacks.get(0).stackStatusAsString(); + if (!status.endsWith("_IN_PROGRESS")) { + return status; + } + } + Thread.sleep(500); + } + throw new AssertionError( + "Stack " + name + " did not reach a terminal state within " + maxSeconds + "s"); + } + + private static void waitForDeleted(String name, int maxSeconds) throws InterruptedException { + long deadline = System.currentTimeMillis() + maxSeconds * 1000L; + while (System.currentTimeMillis() < deadline) { + try { + List stacks = cloudFormation.describeStacks( + DescribeStacksRequest.builder().stackName(name).build()).stacks(); + if (stacks.isEmpty() + || "DELETE_COMPLETE".equals(stacks.get(0).stackStatusAsString())) { + return; + } + } catch (CloudFormationException e) { + if (e.getMessage() != null && e.getMessage().contains("does not exist")) { + return; + } + throw e; + } + Thread.sleep(500); + } + throw new AssertionError( + "Stack " + name + " was not deleted within " + maxSeconds + "s"); + } +} diff --git a/docs/services/cloudformation.md b/docs/services/cloudformation.md index 2a7f16486f..76f6640d63 100644 --- a/docs/services/cloudformation.md +++ b/docs/services/cloudformation.md @@ -70,7 +70,7 @@ cross-resource references. | SQS | `Queue`, `QueuePolicy` (accepted; policy not enforced) | | SNS | `Topic`, `Subscription`, `TopicPolicy` | | DynamoDB | `Table`, `GlobalTable` | -| Lambda | `Function` (Zip via S3/inline `ZipFile`, and Image), `LayerVersion`, `EventSourceMapping` (SQS, Kinesis, DynamoDB Streams), `Version`, `Alias` (also what SAM's `AutoPublishAlias` expands into), `Permission`, `MicrovmImage`, `NetworkConnector`. Inline `ZipFile` packages include the `cfn-response` (Node.js) / `cfnresponse` (Python) module AWS injects for that code path, so Solutions-style custom-resource handlers work. | +| Lambda | `Function` (Zip via S3/inline `ZipFile`, and Image), `LayerVersion`, `EventSourceMapping` (SQS, Kinesis, DynamoDB Streams), `Version`, `Alias` (also what SAM's `AutoPublishAlias` expands into), `Permission`, `EventInvokeConfig`, `MicrovmImage`, `NetworkConnector`. Inline `ZipFile` packages include the `cfn-response` (Node.js) / `cfnresponse` (Python) module AWS injects for that code path, so Solutions-style custom-resource handlers work. | | IAM | `Role`, `User`, `AccessKey`, `Policy`, `ManagedPolicy`, `InstanceProfile` | | Organizations | `Organization`, `OrganizationalUnit`, `Account`, `Policy`, `ResourcePolicy` | | SSM | `Parameter` | diff --git a/docs/services/lambda.md b/docs/services/lambda.md index f165fb41ee..1e60403a19 100644 --- a/docs/services/lambda.md +++ b/docs/services/lambda.md @@ -45,6 +45,15 @@ Floci Lambda runs your function code locally inside real Docker containers - clo | `GetFunctionConcurrency` | Get reserved concurrent executions | | `DeleteFunctionConcurrency` | Clear reserved concurrent executions | | `GetAccountSettings` | Account limits plus usage derived from the caller's stored functions | +| `PutFunctionEventInvokeConfig` | Set the asynchronous invocation settings of a function, version or alias (retries, event age, destinations) | +| `UpdateFunctionEventInvokeConfig` | Change some of those settings, leaving the rest as they are | +| `GetFunctionEventInvokeConfig` | Read the asynchronous invocation settings | +| `DeleteFunctionEventInvokeConfig` | Remove the asynchronous invocation settings | +| `ListFunctionEventInvokeConfigs` | List the asynchronous invocation settings of every version and alias of a function | + +The event invoke configuration is stored and returned as AWS does, and `AWS::Lambda::EventInvokeConfig` +provisions it from a stack. Asynchronous invocations do not yet apply its retry, event age or +destination settings. ## Hot-Reloading via Reactive S3 Sync @@ -205,7 +214,6 @@ These AWS Lambda operations have no handler in Floci. Calls will return `404` or - Layer permissions (`AddLayerVersionPermission`, `RemoveLayerVersionPermission`, `GetLayerVersionPolicy`) - Provisioned concurrency (`PutProvisionedConcurrencyConfig`, `GetProvisionedConcurrencyConfig`, `ListProvisionedConcurrencyConfigs`, `DeleteProvisionedConcurrencyConfig`) -- Dead-letter, async invoke config, and event invoke config operations - `InvokeWithResponseStream` - Code signing management (only `GetFunctionCodeSigningConfig` and `ListFunctionsByCodeSigningConfig` are wired; there is no `PutFunctionCodeSigningConfig` or `CreateCodeSigningConfig`, so no code-signing config can exist and `ListFunctionsByCodeSigningConfig` reports every well-formed ARN as `ResourceNotFoundException` — a malformed ARN or an out-of-range `MaxItems` is rejected with `InvalidParameterValueException` first) diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/CfnRollback.java b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/CfnRollback.java index 8f00ddc534..45b8ea29a7 100644 --- a/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/CfnRollback.java +++ b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/CfnRollback.java @@ -44,6 +44,14 @@ public final class CfnRollback { */ public static final String PIPE_UPDATE_SNAPSHOT_ATTR = "__FlociPipeUpdateSnapshot"; + /** + * Holds the settings an event invoke configuration carried before an in-place update changed + * them, in the request shape a put takes, so a failed stack update can put them back. Written + * by {@code LambdaEventInvokeConfigCfnProvisioner} before its update call and spent by its + * {@code rollbackUpdate}. + */ + public static final String EVENT_INVOKE_CONFIG_SNAPSHOT_ATTR = "__FlociEventInvokeConfigSnapshot"; + /** * Holds the pipe a rename displaced: the name it still lives under, the region that addresses * it, how many times deleting it has been attempted, and when the replacement was created. diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/LambdaEventInvokeConfigCfnProvisioner.java b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/LambdaEventInvokeConfigCfnProvisioner.java new file mode 100644 index 0000000000..b37b0308dd --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/LambdaEventInvokeConfigCfnProvisioner.java @@ -0,0 +1,314 @@ +package io.github.hectorvent.floci.services.cloudformation.provisioners; + +import com.fasterxml.jackson.core.JsonProcessingException; +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.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.FunctionEventInvokeConfig; +import jakarta.enterprise.context.ApplicationScoped; +import jakarta.inject.Inject; + +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.Set; + +/** + * Provisions {@code AWS::Lambda::EventInvokeConfig}, the asynchronous invocation settings of one + * function version or alias. + * + *

The physical id is the registry schema's composite primary identifier, {@code FunctionName} + * and {@code Qualifier} joined by a pipe, which is what a real stack shows and all that + * {@link #delete(String, String, String)} receives. Neither part can contain a pipe. + * + *

Both identifier parts are create-only. An update that still names the same function version + * or alias, whether by the same text or by another form of the function name (a short name and + * the function's ARN address one configuration), applies the template's settings through the + * merge-style update call, as the AWS handler does, so a setting the template drops keeps its + * stored value. The settings the configuration had are kept on the resource so a failed stack + * update can put them back. An update that names another function or qualifier creates the + * configuration for the new target and leaves the displaced one to the {@link ReplacementCleanup} + * record, which deletes it once the stack update commits or puts it back on rollback. + * + *

The schema declares no read-only properties, so there is nothing for {@code Fn::GetAtt}. + */ +@ApplicationScoped +public class LambdaEventInvokeConfigCfnProvisioner implements CfnResourceProvisioner { + + private static final String TYPE = "AWS::Lambda::EventInvokeConfig"; + private static final ObjectMapper MAPPER = new ObjectMapper(); + private static final int MIN_RETRY_ATTEMPTS = 0; + private static final int MAX_RETRY_ATTEMPTS = 2; + private static final int MIN_EVENT_AGE_SECONDS = 60; + private static final int MAX_EVENT_AGE_SECONDS = 21600; + + private final LambdaService lambdaService; + + @Inject + public LambdaEventInvokeConfigCfnProvisioner(LambdaService lambdaService) { + this.lambdaService = lambdaService; + } + + @Override + public Set resourceTypes() { + return Set.of(TYPE); + } + + @Override + public void provision(StackResource r, JsonNode props, ProvisionContext ctx) { + // A snapshot describes the update in flight; one an earlier update left behind is stale. + r.getAttributes().remove(CfnRollback.EVENT_INVOKE_CONFIG_SNAPSHOT_ATTR); + Map attributesBefore = Map.copyOf(r.getAttributes()); + String functionName = required(ctx.resolveOptional(props, "FunctionName"), "FunctionName"); + String qualifier = required(ctx.resolveOptional(props, "Qualifier"), "Qualifier"); + Map settings = settings(props, ctx); + + if (ctx.isUpdate() && namesTheSameTarget(ctx.priorPhysicalId(), functionName, qualifier)) { + snapshotBeforeUpdate(r, functionName, qualifier, ctx.region()); + lambdaService.updateEventInvokeConfig(ctx.region(), functionName, qualifier, settings); + // The prior id stays, so a function renamed to another form of the same name is not + // recorded as a replacement whose cleanup would delete the one configuration. + r.setPhysicalId(ctx.priorPhysicalId()); + } else { + lambdaService.putEventInvokeConfig(ctx.region(), functionName, qualifier, settings); + r.setPhysicalId(functionName + "|" + qualifier); + } + ReplacementCleanup.record(r, ctx, attributesBefore); + } + + /** + * Whether the prior physical id addresses the configuration the template now names. The + * service keys a configuration by the function's ARN and the qualifier, so a short name and the + * function's ARN are the same target, and treating them as a replacement would delete that one + * configuration through the old name once the update committed. + */ + private static boolean namesTheSameTarget(String priorPhysicalId, String functionName, String qualifier) { + int separator = priorPhysicalId.lastIndexOf('|'); + if (separator <= 0 || !qualifier.equals(priorPhysicalId.substring(separator + 1))) { + return false; + } + String priorFunction = priorPhysicalId.substring(0, separator); + if (priorFunction.equals(functionName)) { + return true; + } + try { + LambdaArnUtils.ResolvedFunctionRef prior = LambdaArnUtils.resolve(priorFunction); + LambdaArnUtils.ResolvedFunctionRef current = LambdaArnUtils.resolve(functionName); + return prior.name().equals(current.name()) + && (prior.region() == null || current.region() == null + || prior.region().equals(current.region())); + } catch (AwsException malformed) { + return false; + } + } + + /** + * The settings the template names, in the request shape the Lambda service reads. Only named + * settings are sent: on a create the service stores nothing for the rest, and on an in-place + * update the merge-style call leaves them as they are. {@code DestinationConfig} is resolved + * before it is looked at, so a conditional value that resolves to {@code AWS::NoValue} is + * omitted rather than sent as an empty destination set that would clear the stored ones. + */ + private Map settings(JsonNode props, ProvisionContext ctx) { + Map settings = new LinkedHashMap<>(); + Integer retryAttempts = integerInRange(ctx.resolveOptional(props, "MaximumRetryAttempts"), + "MaximumRetryAttempts", MIN_RETRY_ATTEMPTS, MAX_RETRY_ATTEMPTS); + if (retryAttempts != null) { + settings.put("MaximumRetryAttempts", retryAttempts); + } + Integer eventAge = integerInRange(ctx.resolveOptional(props, "MaximumEventAgeInSeconds"), + "MaximumEventAgeInSeconds", MIN_EVENT_AGE_SECONDS, MAX_EVENT_AGE_SECONDS); + if (eventAge != null) { + settings.put("MaximumEventAgeInSeconds", eventAge); + } + JsonNode destinations = props == null || !props.hasNonNull("DestinationConfig") + ? null + : ctx.engine().resolveNode(props.get("DestinationConfig")); + if (destinations != null && destinations.isObject()) { + settings.put("DestinationConfig", destinationConfig(destinations)); + } + return settings; + } + + private Map destinationConfig(JsonNode resolved) { + Map config = new LinkedHashMap<>(); + for (String side : new String[] {"OnSuccess", "OnFailure"}) { + JsonNode destination = resolved.get(side); + if (destination == null || !destination.isObject()) { + continue; + } + JsonNode arn = destination.get("Destination"); + if (arn == null || arn.isNull() || !arn.isValueNode()) { + throw new AwsException("ValidationError", + TYPE + " DestinationConfig." + side + " requires Destination", 400); + } + config.put(side, Map.of("Destination", arn.asText())); + } + return config; + } + + /** + * Checks a numeric property against the bounds the registry schema declares. Real + * CloudFormation validates the template against the schema before the handler runs, so an + * out-of-range value fails the resource here rather than being stored. + */ + private static Integer integerInRange(String value, String property, int min, int max) { + if (value == null || value.isBlank()) { + return null; + } + int parsed; + try { + parsed = Integer.parseInt(value.trim()); + } catch (NumberFormatException e) { + throw new AwsException("ValidationError", + TYPE + " " + property + " must be an integer, got '" + value + "'", 400); + } + if (parsed < min || parsed > max) { + throw new AwsException("ValidationError", + TYPE + " " + property + " must be between " + min + " and " + max + ", got " + parsed, 400); + } + return parsed; + } + + private static String required(String value, String property) { + if (value == null || value.isBlank()) { + throw new AwsException("ValidationError", TYPE + " requires " + property, 400); + } + return value; + } + + /** + * Keeps the settings the configuration has before an in-place update changes them, in the + * request shape a put takes, so {@link #rollbackUpdate} can put every one of them back. A + * configuration that is already gone leaves no snapshot; the update that follows fails on the + * same absence and changes nothing. + */ + private void snapshotBeforeUpdate(StackResource r, String functionName, String qualifier, String region) { + FunctionEventInvokeConfig current; + try { + current = lambdaService.getEventInvokeConfig(region, functionName, qualifier); + } catch (AwsException e) { + if ("ResourceNotFoundException".equals(e.getErrorCode())) { + return; + } + throw e; + } + ObjectNode snapshot = MAPPER.createObjectNode(); + snapshot.put("region", region); + snapshot.put("functionName", functionName); + snapshot.put("qualifier", qualifier); + ObjectNode settings = snapshot.putObject("settings"); + if (current.getMaximumRetryAttempts() != null) { + settings.put("MaximumRetryAttempts", current.getMaximumRetryAttempts()); + } + if (current.getMaximumEventAgeInSeconds() != null) { + settings.put("MaximumEventAgeInSeconds", current.getMaximumEventAgeInSeconds()); + } + FunctionEventInvokeConfig.DestinationConfig destinations = current.getDestinationConfig(); + if (destinations != null) { + ObjectNode config = settings.putObject("DestinationConfig"); + if (destinations.getOnSuccess() != null && destinations.getOnSuccess().getDestination() != null) { + config.putObject("OnSuccess").put("Destination", destinations.getOnSuccess().getDestination()); + } + if (destinations.getOnFailure() != null && destinations.getOnFailure().getDestination() != null) { + config.putObject("OnFailure").put("Destination", destinations.getOnFailure().getDestination()); + } + } + r.getAttributes().put(CfnRollback.EVENT_INVOKE_CONFIG_SNAPSHOT_ATTR, snapshot.toString()); + } + + @Override + public void delete(String resourceType, String physicalId, String region) { + if (physicalId == null) { + return; + } + int separator = physicalId.lastIndexOf('|'); + if (separator <= 0) { + return; + } + String functionName = physicalId.substring(0, separator); + String qualifier = physicalId.substring(separator + 1); + // The service answers ResourceNotFoundException both for a missing configuration and + // for a function that is already gone; either way there is nothing left to delete. + CfnDeletes.safeDelete("Lambda event invoke config", physicalId, + () -> lambdaService.deleteEventInvokeConfig(region, functionName, qualifier), + "ResourceNotFoundException"); + } + + @Override + public boolean hasReplacementUpdate(StackResource resource) { + return ReplacementCleanup.hasReplacement(resource); + } + + @Override + public String updateCleanupPhysicalId(StackResource resource) { + return ReplacementCleanup.cleanupPhysicalId(resource); + } + + @Override + public UpdateCleanupResult completeUpdate(StackResource resource) { + return ReplacementCleanup.complete(resource, this::delete); + } + + @Override + public void clearUpdate(StackResource resource) { + resource.getAttributes().remove(CfnRollback.EVENT_INVOKE_CONFIG_SNAPSHOT_ATTR); + ReplacementCleanup.clear(resource); + } + + /** + * A replacement is undone through the cleanup record and an in-place update from the snapshot + * taken before it, put back in full so a setting the update changed or cleared is as it was. + * With neither on the resource the provision failed before it changed anything, since every + * mutation is preceded by the snapshot or followed by the record, so there is nothing to undo. + */ + @Override + public boolean rollbackUpdate(StackResource resource) { + if (ReplacementCleanup.rollback(resource, this::delete)) { + return true; + } + // The snapshot is spent only once the restore succeeded: a restore that throws leaves it in + // place for the next attempt instead of reporting a rollback that never happened. + String raw = resource.getAttributes().get(CfnRollback.EVENT_INVOKE_CONFIG_SNAPSHOT_ATTR); + if (raw == null) { + return true; + } + JsonNode snapshot; + try { + snapshot = MAPPER.readTree(raw); + } catch (JsonProcessingException e) { + throw new IllegalStateException("Could not read the event invoke config snapshot for " + + resource.getLogicalId(), e); + } + lambdaService.putEventInvokeConfig(snapshot.path("region").asText(), + snapshot.path("functionName").asText(), snapshot.path("qualifier").asText(), + settingsFrom(snapshot.path("settings"))); + resource.getAttributes().remove(CfnRollback.EVENT_INVOKE_CONFIG_SNAPSHOT_ATTR); + return true; + } + + private static Map settingsFrom(JsonNode settings) { + Map request = new LinkedHashMap<>(); + if (settings.hasNonNull("MaximumRetryAttempts")) { + request.put("MaximumRetryAttempts", settings.get("MaximumRetryAttempts").asInt()); + } + if (settings.hasNonNull("MaximumEventAgeInSeconds")) { + request.put("MaximumEventAgeInSeconds", settings.get("MaximumEventAgeInSeconds").asInt()); + } + JsonNode destinations = settings.get("DestinationConfig"); + if (destinations != null && destinations.isObject()) { + Map config = new LinkedHashMap<>(); + for (String side : new String[] {"OnSuccess", "OnFailure"}) { + String destination = destinations.path(side).path("Destination").asText(null); + if (destination != null) { + config.put(side, Map.of("Destination", destination)); + } + } + request.put("DestinationConfig", config); + } + return request; + } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/CfnProvisionerFixture.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CfnProvisionerFixture.java index 7a20f61490..32b70a6932 100644 --- a/src/test/java/io/github/hectorvent/floci/services/cloudformation/CfnProvisionerFixture.java +++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CfnProvisionerFixture.java @@ -52,6 +52,7 @@ import io.github.hectorvent.floci.services.cloudformation.provisioners.IotDomain import io.github.hectorvent.floci.services.cloudformation.provisioners.KinesisCfnProvisioner; import io.github.hectorvent.floci.services.cloudformation.provisioners.KmsCfnProvisioner; import io.github.hectorvent.floci.services.cloudformation.provisioners.LambdaAddressingCfnProvisioner; +import io.github.hectorvent.floci.services.cloudformation.provisioners.LambdaEventInvokeConfigCfnProvisioner; import io.github.hectorvent.floci.services.cloudformation.provisioners.LambdaEventSourceMappingCfnProvisioner; import io.github.hectorvent.floci.services.cloudformation.provisioners.LambdaVersionAliasCfnProvisioner; import io.github.hectorvent.floci.services.cloudformation.provisioners.LogsCfnProvisioner; @@ -266,6 +267,7 @@ final class CfnProvisionerFixture { } if (lambdaService != null) { discovered.add(new LambdaAddressingCfnProvisioner(lambdaService)); + discovered.add(new LambdaEventInvokeConfigCfnProvisioner(lambdaService)); discovered.add(new LambdaVersionAliasCfnProvisioner(lambdaService)); discovered.add(new LambdaEventSourceMappingCfnProvisioner(lambdaService)); } diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationLambdaEventInvokeConfigIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationLambdaEventInvokeConfigIntegrationTest.java new file mode 100644 index 0000000000..cd723f2e25 --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationLambdaEventInvokeConfigIntegrationTest.java @@ -0,0 +1,337 @@ +package io.github.hectorvent.floci.services.cloudformation; + +import io.github.hectorvent.floci.core.common.XmlParser; +import io.github.hectorvent.floci.testing.RestAssuredJsonUtils; +import io.quarkus.test.junit.QuarkusTest; +import io.restassured.response.Response; +import io.restassured.specification.RequestSpecification; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; + +import java.util.Map; + +import static io.restassured.RestAssured.given; +import static org.hamcrest.Matchers.containsString; +import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.nullValue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; + +/** + * Provisions an {@code AWS::Lambda::EventInvokeConfig} through a CloudFormation stack and reads + * it back through the Lambda API. {@code Ref} is the composite {@code FunctionName|Qualifier} id + * a real stack shows; a settings change updates the configuration in place; a qualifier change + * replaces it, deleting the displaced configuration once the update commits; a failed update rolls + * the replacement back; and the stack delete removes the configuration. + */ +@QuarkusTest +class CloudFormationLambdaEventInvokeConfigIntegrationTest { + + private static final String CFN_AUTH = + "AWS4-HMAC-SHA256 Credential=test/20260908/us-east-1/cloudformation/aws4_request"; + private static final String DLQ_ARN = "arn:aws:sqs:us-east-1:000000000000:async-dlq"; + + /** The function and its first version, in a stack of their own so the configuration stacks hold nothing else. */ + private static final String FUNCTION_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'"} + } + }, + "Ver": { + "Type": "AWS::Lambda::Version", + "Properties": {"FunctionName": {"Ref": "Fn"}} + } + }, + "Outputs": { + "Version": {"Value": {"Fn::GetAtt": ["Ver", "Version"]}} + } + } + """; + + private static final String CONFIG_TEMPLATE = """ + { + "Parameters": { + "Qualifier": {"Type": "String", "Default": "$LATEST"}, + "Retries": {"Type": "String", "Default": "1"} + }, + "Resources": { + "AsyncConfig": { + "Type": "AWS::Lambda::EventInvokeConfig", + "Properties": { + "FunctionName": "%s", + "Qualifier": {"Ref": "Qualifier"}, + "MaximumRetryAttempts": {"Ref": "Retries"}, + "MaximumEventAgeInSeconds": 300, + "DestinationConfig": {"OnFailure": {"Destination": "%s"}} + } + }%s + }, + "Outputs": { + "ConfigRef": {"Value": {"Ref": "AsyncConfig"}} + } + } + """; + + /** A resource that fails after the configuration, so the update rolls the replacement back. */ + private static final String FAILING_RESOURCE = """ + , + "BadSecret": { + "Type": "AWS::SecretsManager::Secret", + "DependsOn": "AsyncConfig", + "Properties": { + "Name": "event-invoke-rollback-%s", + "SecretString": "explicit", + "GenerateSecretString": {"PasswordLength": 32} + } + }"""; + + @BeforeAll + static void configureRestAssured() { + RestAssuredJsonUtils.configureAwsContentTypes(); + } + + @Test + void configurationFollowsTheTemplateThroughCreateUpdateReplacementAndDelete() throws InterruptedException { + String suffix = Long.toString(System.nanoTime(), 36); + String functionStack = "cfn-event-invoke-fn-" + suffix; + String stack = "cfn-event-invoke-" + suffix; + String fn = "event-invoke-fn-" + suffix; + String version = createFunctionStack(functionStack, fn); + String template = CONFIG_TEMPLATE.formatted(fn, DLQ_ARN, ""); + + cloudFormation(stack, "CreateStack", template, Map.of()); + assertEquals(fn + "|$LATEST", outputValue(describeStacks(stack, "CREATE_COMPLETE"), "ConfigRef"), + "Ref is the composite FunctionName|Qualifier identifier"); + getConfig(fn, "$LATEST").then() + .statusCode(200) + .body("FunctionArn", containsString(":function:" + fn + ":$LATEST")) + .body("MaximumRetryAttempts", equalTo(1)) + .body("MaximumEventAgeInSeconds", equalTo(300)) + .body("DestinationConfig.OnFailure.Destination", equalTo(DLQ_ARN)) + .body("DestinationConfig.OnSuccess", nullValue()); + + cloudFormation(stack, "UpdateStack", template, Map.of("Retries", "0")); + assertEquals(fn + "|$LATEST", outputValue(describeStacks(stack, "UPDATE_COMPLETE"), "ConfigRef"), + "a settings change keeps the same configuration"); + getConfig(fn, "$LATEST").then() + .statusCode(200) + .body("MaximumRetryAttempts", equalTo(0)) + .body("MaximumEventAgeInSeconds", equalTo(300)) + .body("DestinationConfig.OnFailure.Destination", equalTo(DLQ_ARN)); + + cloudFormation(stack, "UpdateStack", template, Map.of("Retries", "0", "Qualifier", version)); + assertEquals(fn + "|" + version, outputValue(describeStacks(stack, "UPDATE_COMPLETE"), "ConfigRef"), + "a qualifier change is a replacement"); + getConfig(fn, version).then() + .statusCode(200) + .body("FunctionArn", containsString(":function:" + fn + ":" + version)) + .body("MaximumRetryAttempts", equalTo(0)); + getConfig(fn, "$LATEST").then() + .statusCode(404) + .body("__type", equalTo("ResourceNotFoundException")); + assertEvent(describeEvents(stack), "DELETE_COMPLETE", fn + "|$LATEST"); + + cloudFormation(stack, "DeleteStack", null, Map.of()); + awaitStackDeleted(stack); + getConfig(fn, version).then() + .statusCode(404) + .body("__type", equalTo("ResourceNotFoundException")); + given().when().get("/2015-03-31/functions/" + fn).then().statusCode(200); + + cloudFormation(functionStack, "DeleteStack", null, Map.of()); + awaitStackDeleted(functionStack); + } + + @Test + void aFailedUpdateRollsTheReplacementBack() throws InterruptedException { + String suffix = Long.toString(System.nanoTime(), 36); + String functionStack = "cfn-event-invoke-rb-fn-" + suffix; + String stack = "cfn-event-invoke-rb-" + suffix; + String fn = "event-invoke-rb-fn-" + suffix; + String version = createFunctionStack(functionStack, fn); + + cloudFormation(stack, "CreateStack", CONFIG_TEMPLATE.formatted(fn, DLQ_ARN, ""), Map.of()); + describeStacks(stack, "CREATE_COMPLETE"); + + cloudFormation(stack, "UpdateStack", CONFIG_TEMPLATE.formatted(fn, DLQ_ARN, FAILING_RESOURCE.formatted(suffix)), + Map.of("Qualifier", version)); + String rolledBack = describeStacks(stack, "UPDATE_ROLLBACK_COMPLETE"); + assertEquals(fn + "|$LATEST", outputValue(rolledBack, "ConfigRef"), + "the resource names the prior configuration again"); + getConfig(fn, "$LATEST").then() + .statusCode(200) + .body("MaximumRetryAttempts", equalTo(1)); + getConfig(fn, version).then() + .statusCode(404) + .body("__type", equalTo("ResourceNotFoundException")); + + cloudFormation(stack, "DeleteStack", null, Map.of()); + awaitStackDeleted(stack); + cloudFormation(functionStack, "DeleteStack", null, Map.of()); + awaitStackDeleted(functionStack); + } + + /** An in-place settings change is put back from the snapshot the update took. */ + @Test + void aFailedUpdateRestoresTheSettingsAnInPlaceUpdateChanged() throws InterruptedException { + String suffix = Long.toString(System.nanoTime(), 36); + String functionStack = "cfn-event-invoke-ip-fn-" + suffix; + String stack = "cfn-event-invoke-ip-" + suffix; + String fn = "event-invoke-ip-fn-" + suffix; + createFunctionStack(functionStack, fn); + + cloudFormation(stack, "CreateStack", CONFIG_TEMPLATE.formatted(fn, DLQ_ARN, ""), Map.of()); + describeStacks(stack, "CREATE_COMPLETE"); + + cloudFormation(stack, "UpdateStack", CONFIG_TEMPLATE.formatted(fn, DLQ_ARN, FAILING_RESOURCE.formatted(suffix)), + Map.of("Retries", "0")); + String rolledBack = describeStacks(stack, "UPDATE_ROLLBACK_COMPLETE"); + assertEquals(fn + "|$LATEST", outputValue(rolledBack, "ConfigRef")); + getConfig(fn, "$LATEST").then() + .statusCode(200) + .body("MaximumRetryAttempts", equalTo(1)) + .body("MaximumEventAgeInSeconds", equalTo(300)) + .body("DestinationConfig.OnFailure.Destination", equalTo(DLQ_ARN)); + + cloudFormation(stack, "DeleteStack", null, Map.of()); + awaitStackDeleted(stack); + cloudFormation(functionStack, "DeleteStack", null, Map.of()); + awaitStackDeleted(functionStack); + } + + @Test + void anOutOfRangeSettingFailsTheResource() throws InterruptedException { + String suffix = Long.toString(System.nanoTime(), 36); + String functionStack = "cfn-event-invoke-bad-fn-" + suffix; + String stack = "cfn-event-invoke-bad-" + suffix; + String fn = "event-invoke-bad-fn-" + suffix; + createFunctionStack(functionStack, fn); + + cloudFormation(stack, "CreateStack", CONFIG_TEMPLATE.formatted(fn, DLQ_ARN, ""), Map.of("Retries", "3")); + + String failed = awaitStackStatus(stack, "ROLLBACK_COMPLETE"); + assertTrue(failed.contains("MaximumRetryAttempts"), + "the status reason names the property: " + failed); + getConfig(fn, "$LATEST").then().statusCode(404); + + cloudFormation(stack, "DeleteStack", null, Map.of()); + awaitStackDeleted(stack); + cloudFormation(functionStack, "DeleteStack", null, Map.of()); + awaitStackDeleted(functionStack); + } + + /** Creates the function stack and returns the number of the version it published. */ + private static String createFunctionStack(String stack, String fn) { + cloudFormation(stack, "CreateStack", FUNCTION_TEMPLATE.formatted(fn), Map.of()); + return outputValue(describeStacks(stack, "CREATE_COMPLETE"), "Version"); + } + + private static Response getConfig(String functionName, String qualifier) { + return given() + .queryParam("Qualifier", qualifier) + .when().get("/2019-09-25/functions/" + functionName + "/event-invoke-config"); + } + + private static void cloudFormation(String stack, String action, String templateBody, + Map parameters) { + RequestSpecification request = given() + .contentType("application/x-www-form-urlencoded") + .header("Authorization", CFN_AUTH) + .formParam("Action", action) + .formParam("StackName", stack) + .formParam("Capabilities.member.1", "CAPABILITY_IAM"); + if (templateBody != null) { + request.formParam("TemplateBody", templateBody); + } + int index = 1; + for (Map.Entry parameter : parameters.entrySet()) { + request.formParam("Parameters.member." + index + ".ParameterKey", parameter.getKey()); + request.formParam("Parameters.member." + index + ".ParameterValue", parameter.getValue()); + index++; + } + request.when().post("/").then().statusCode(200); + } + + private static String describeStacks(String stack, String expectedStatus) { + return given() + .contentType("application/x-www-form-urlencoded") + .header("Authorization", CFN_AUTH) + .formParam("Action", "DescribeStacks") + .formParam("StackName", stack) + .when().post("/").then().statusCode(200) + .body(containsString("" + expectedStatus + "")) + .extract().asString(); + } + + private static String describeEvents(String stack) { + return given() + .contentType("application/x-www-form-urlencoded") + .header("Authorization", CFN_AUTH) + .formParam("Action", "DescribeStackEvents") + .formParam("StackName", stack) + .when().post("/").then().statusCode(200).extract().asString(); + } + + private static void assertEvent(String eventsXml, String status, String physicalId) { + boolean found = XmlParser.extractGroups(eventsXml, "member").stream() + .anyMatch(event -> status.equals(event.get("ResourceStatus")) + && physicalId.equals(event.get("PhysicalResourceId"))); + assertTrue(found, "no " + status + " event for " + physicalId + " in " + eventsXml); + } + + /** A failed create rolls back asynchronously; returns the events once the status is reached. */ + private static String awaitStackStatus(String stack, String expectedStatus) throws InterruptedException { + for (int i = 0; i < 100; i++) { + String body = given() + .contentType("application/x-www-form-urlencoded") + .header("Authorization", CFN_AUTH) + .formParam("Action", "DescribeStacks") + .formParam("StackName", stack) + .when().post("/").then().extract().asString(); + if (body.contains("" + expectedStatus + "")) { + return describeEvents(stack); + } + Thread.sleep(50); + } + return fail("stack " + stack + " did not reach " + expectedStatus + " within the timeout"); + } + + private static void awaitStackDeleted(String stack) throws InterruptedException { + for (int i = 0; i < 100; i++) { + String body = given() + .contentType("application/x-www-form-urlencoded") + .header("Authorization", CFN_AUTH) + .formParam("Action", "DescribeStacks") + .formParam("StackName", stack) + .when().post("/").then().extract().asString(); + if (body.contains("does not exist")) { + return; + } + if (body.contains("DELETE_FAILED")) { + fail("stack delete failed: " + body); + } + Thread.sleep(50); + } + fail("stack " + stack + " was not deleted within the timeout"); + } + + private static String outputValue(String xml, String key) { + return XmlParser.extractPairs(xml, "Outputs", "OutputKey", "OutputValue").get(key); + } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/LambdaEventInvokeConfigCfnProvisionerTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/LambdaEventInvokeConfigCfnProvisionerTest.java new file mode 100644 index 0000000000..2297e936ee --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/LambdaEventInvokeConfigCfnProvisionerTest.java @@ -0,0 +1,527 @@ +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.TextNode; +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.FunctionEventInvokeConfig; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.mockito.ArgumentCaptor; + +import java.util.HashMap; +import java.util.Map; +import java.util.Set; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; +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.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.verifyNoInteractions; +import static org.mockito.Mockito.when; + +/** + * {@code AWS::Lambda::EventInvokeConfig}: the physical id is the schema's composite identifier, + * a create keeps only the properties the template names, an update with the same identity goes + * through the merge-style update call, and a changed identity is a replacement whose displaced + * configuration is left to the cleanup record. + */ +class LambdaEventInvokeConfigCfnProvisionerTest { + + private static final ObjectMapper MAPPER = new ObjectMapper(); + private static final String REGION = "us-east-1"; + private static final String ACCOUNT_ID = "000000000000"; + private static final String STACK = "my-stack"; + private static final String TYPE = "AWS::Lambda::EventInvokeConfig"; + + private LambdaService lambda; + private LambdaEventInvokeConfigCfnProvisioner provisioner; + private CloudFormationTemplateEngine engine; + + @BeforeEach + void setUp() { + lambda = mock(LambdaService.class); + provisioner = new LambdaEventInvokeConfigCfnProvisioner(lambda); + engine = mock(CloudFormationTemplateEngine.class); + when(engine.resolve(any())).thenAnswer(i -> { + JsonNode node = i.getArgument(0); + return node == null || node.isMissingNode() || node.isNull() ? null : node.asText(); + }); + when(engine.resolveNode(any())).thenAnswer(i -> i.getArgument(0)); + // The service never answers null: a missing configuration throws. Tests that care about + // the settings before an update stub their own. + when(lambda.getEventInvokeConfig(anyString(), anyString(), anyString())) + .thenReturn(config(2, 21600, null, null)); + } + + private static JsonNode props(String json) { + try { + return MAPPER.readTree(json); + } catch (Exception e) { + throw new IllegalArgumentException(e); + } + } + + private static StackResource resource() { + StackResource r = new StackResource(); + r.setLogicalId("AsyncConfig"); + r.setResourceType(TYPE); + return r; + } + + private StackResource provision(String json, String priorPhysicalId) { + StackResource r = resource(); + r.setPhysicalId(priorPhysicalId); + r.setAttributes(new HashMap<>()); + provisioner.provision(r, props(json), + new ProvisionContext(engine, REGION, ACCOUNT_ID, STACK, priorPhysicalId)); + return r; + } + + @Test + void servesOnlyTheEventInvokeConfigType() { + assertEquals(Set.of(TYPE), provisioner.resourceTypes()); + } + + @Test + void createPutsTheConfigurationAndJoinsTheIdentityWithAPipe() { + StackResource r = provision(""" + {"FunctionName": "orders", "Qualifier": "$LATEST", + "MaximumRetryAttempts": 1, "MaximumEventAgeInSeconds": 300, + "DestinationConfig": { + "OnSuccess": {"Destination": "arn:aws:sqs:us-east-1:000000000000:ok"}, + "OnFailure": {"Destination": "arn:aws:sqs:us-east-1:000000000000:dlq"}}} + """, null); + + ArgumentCaptor> request = ArgumentCaptor.captor(); + verify(lambda).putEventInvokeConfig(eq(REGION), eq("orders"), eq("$LATEST"), request.capture()); + verify(lambda, never()).updateEventInvokeConfig(anyString(), anyString(), anyString(), anyMap()); + assertEquals(1, request.getValue().get("MaximumRetryAttempts")); + assertEquals(300, request.getValue().get("MaximumEventAgeInSeconds")); + assertEquals(Map.of( + "OnSuccess", Map.of("Destination", "arn:aws:sqs:us-east-1:000000000000:ok"), + "OnFailure", Map.of("Destination", "arn:aws:sqs:us-east-1:000000000000:dlq")), + request.getValue().get("DestinationConfig")); + assertEquals("orders|$LATEST", r.getPhysicalId(), "Ref is FunctionName|Qualifier"); + assertTrue(r.getAttributes().isEmpty(), "the schema declares no Fn::GetAtt attributes"); + assertFalse(provisioner.hasReplacementUpdate(r)); + } + + /** Numbers arrive as strings after intrinsic resolution as often as they arrive as numbers. */ + @Test + void numericSettingsGivenAsStringsAreParsed() { + provision(""" + {"FunctionName": "orders", "Qualifier": "live", + "MaximumRetryAttempts": "0", "MaximumEventAgeInSeconds": "60"} + """, null); + + ArgumentCaptor> request = ArgumentCaptor.captor(); + verify(lambda).putEventInvokeConfig(eq(REGION), eq("orders"), eq("live"), request.capture()); + assertEquals(0, request.getValue().get("MaximumRetryAttempts")); + assertEquals(60, request.getValue().get("MaximumEventAgeInSeconds")); + } + + /** A setting the template leaves out is left out of the request; the service stores nothing for it. */ + @Test + void omittedSettingsAreNotSent() { + provision(""" + {"FunctionName": "orders", "Qualifier": "3"} + """, null); + + ArgumentCaptor> request = ArgumentCaptor.captor(); + verify(lambda).putEventInvokeConfig(eq(REGION), eq("orders"), eq("3"), request.capture()); + assertTrue(request.getValue().isEmpty(), "no setting means an empty request: " + request.getValue()); + } + + @Test + void aDestinationSideThatIsOmittedIsNotSent() { + provision(""" + {"FunctionName": "orders", "Qualifier": "live", + "DestinationConfig": {"OnFailure": {"Destination": "arn:aws:sns:us-east-1:000000000000:alerts"}}} + """, null); + + ArgumentCaptor> request = ArgumentCaptor.captor(); + verify(lambda).putEventInvokeConfig(eq(REGION), eq("orders"), eq("live"), request.capture()); + assertEquals(Map.of("OnFailure", Map.of("Destination", "arn:aws:sns:us-east-1:000000000000:alerts")), + request.getValue().get("DestinationConfig")); + } + + @Test + void functionNameIsRequired() { + AwsException e = assertThrows(AwsException.class, () -> provision(""" + {"Qualifier": "$LATEST"} + """, null)); + + assertEquals("ValidationError", e.getErrorCode()); + assertTrue(e.getMessage().contains("FunctionName"), e.getMessage()); + verifyNoInteractions(lambda); + } + + @Test + void qualifierIsRequired() { + AwsException e = assertThrows(AwsException.class, () -> provision(""" + {"FunctionName": "orders"} + """, null)); + + assertEquals("ValidationError", e.getErrorCode()); + assertTrue(e.getMessage().contains("Qualifier"), e.getMessage()); + verifyNoInteractions(lambda); + } + + /** The registry schema caps MaximumRetryAttempts at 0..2; CloudFormation rejects the template before any call. */ + @Test + void retryAttemptsOutsideTheSchemaRangeAreRejectedBeforeAnyCall() { + for (String value : new String[] {"-1", "3", "two"}) { + AwsException e = assertThrows(AwsException.class, () -> provision(""" + {"FunctionName": "orders", "Qualifier": "$LATEST", "MaximumRetryAttempts": "%s"} + """.formatted(value), null), value); + assertEquals("ValidationError", e.getErrorCode(), value); + assertTrue(e.getMessage().contains("MaximumRetryAttempts"), e.getMessage()); + } + verifyNoInteractions(lambda); + } + + /** MaximumEventAgeInSeconds is 60..21600 in the schema. */ + @Test + void eventAgeOutsideTheSchemaRangeIsRejectedBeforeAnyCall() { + for (String value : new String[] {"59", "21601", "1h"}) { + AwsException e = assertThrows(AwsException.class, () -> provision(""" + {"FunctionName": "orders", "Qualifier": "$LATEST", "MaximumEventAgeInSeconds": "%s"} + """.formatted(value), null), value); + assertEquals("ValidationError", e.getErrorCode(), value); + assertTrue(e.getMessage().contains("MaximumEventAgeInSeconds"), e.getMessage()); + } + verifyNoInteractions(lambda); + } + + @Test + void theRangeBoundsThemselvesAreAccepted() { + provision(""" + {"FunctionName": "orders", "Qualifier": "$LATEST", + "MaximumRetryAttempts": 2, "MaximumEventAgeInSeconds": 21600} + """, null); + + ArgumentCaptor> request = ArgumentCaptor.captor(); + verify(lambda).putEventInvokeConfig(eq(REGION), eq("orders"), eq("$LATEST"), request.capture()); + assertEquals(2, request.getValue().get("MaximumRetryAttempts")); + assertEquals(21600, request.getValue().get("MaximumEventAgeInSeconds")); + } + + @Test + void aDestinationWithoutAnArnIsRejected() { + AwsException e = assertThrows(AwsException.class, () -> provision(""" + {"FunctionName": "orders", "Qualifier": "$LATEST", + "DestinationConfig": {"OnFailure": {}}} + """, null)); + + assertEquals("ValidationError", e.getErrorCode()); + assertTrue(e.getMessage().contains("Destination"), e.getMessage()); + verifyNoInteractions(lambda); + } + + /** Same function and qualifier: the update path, applied through the merge-style update call. */ + @Test + void anUpdateWithTheSameIdentityUpdatesInPlace() { + when(lambda.getEventInvokeConfig(REGION, "orders", "$LATEST")).thenReturn(config(2, 21600, null, null)); + StackResource r = provision(""" + {"FunctionName": "orders", "Qualifier": "$LATEST", "MaximumRetryAttempts": 0} + """, "orders|$LATEST"); + + ArgumentCaptor> request = ArgumentCaptor.captor(); + verify(lambda).updateEventInvokeConfig(eq(REGION), eq("orders"), eq("$LATEST"), request.capture()); + verify(lambda, never()).putEventInvokeConfig(anyString(), anyString(), anyString(), anyMap()); + assertEquals(Map.of("MaximumRetryAttempts", 0), request.getValue()); + assertEquals("orders|$LATEST", r.getPhysicalId()); + assertFalse(provisioner.hasReplacementUpdate(r)); + assertNull(provisioner.updateCleanupPhysicalId(r)); + } + + /** Both identifier parts are create-only: changing the qualifier creates a new configuration. */ + @Test + void aChangedQualifierIsAReplacementThatLeavesThePriorToTheCleanup() { + StackResource r = provision(""" + {"FunctionName": "orders", "Qualifier": "live", "MaximumRetryAttempts": 1} + """, "orders|$LATEST"); + + verify(lambda).putEventInvokeConfig(eq(REGION), eq("orders"), eq("live"), anyMap()); + verify(lambda, never()).updateEventInvokeConfig(anyString(), anyString(), anyString(), anyMap()); + verify(lambda, never()).deleteEventInvokeConfig(anyString(), anyString(), anyString()); + assertEquals("orders|live", r.getPhysicalId()); + assertTrue(provisioner.hasReplacementUpdate(r)); + assertEquals("orders|$LATEST", provisioner.updateCleanupPhysicalId(r)); + } + + @Test + void aChangedFunctionIsAReplacement() { + StackResource r = provision(""" + {"FunctionName": "payments", "Qualifier": "$LATEST"} + """, "orders|$LATEST"); + + verify(lambda).putEventInvokeConfig(eq(REGION), eq("payments"), eq("$LATEST"), anyMap()); + assertEquals("payments|$LATEST", r.getPhysicalId()); + assertEquals("orders|$LATEST", provisioner.updateCleanupPhysicalId(r)); + } + + @Test + void completingAReplacementDeletesTheDisplacedConfiguration() { + StackResource r = provision(""" + {"FunctionName": "orders", "Qualifier": "live"} + """, "orders|$LATEST"); + + UpdateCleanupResult result = provisioner.completeUpdate(r); + + assertTrue(result.applicable()); + assertTrue(result.complete()); + verify(lambda).deleteEventInvokeConfig(REGION, "orders", "$LATEST"); + assertFalse(provisioner.hasReplacementUpdate(r)); + } + + @Test + void rollingBackAReplacementDeletesTheNewConfigurationAndRestoresThePriorId() { + StackResource r = provision(""" + {"FunctionName": "orders", "Qualifier": "live"} + """, "orders|$LATEST"); + + assertTrue(provisioner.rollbackUpdate(r)); + + verify(lambda).deleteEventInvokeConfig(REGION, "orders", "live"); + verify(lambda, never()).deleteEventInvokeConfig(REGION, "orders", "$LATEST"); + assertEquals("orders|$LATEST", r.getPhysicalId()); + assertFalse(provisioner.hasReplacementUpdate(r)); + } + + /** + * The service keys a configuration by the function's ARN, so a short name and the ARN address + * one configuration: treating the change as a replacement would put over that configuration + * and then delete it through the old name once the update committed. + */ + @Test + void aFunctionNameGivenAsTheArnOfTheSameFunctionUpdatesInPlace() { + StackResource r = provision(""" + {"FunctionName": "arn:aws:lambda:us-east-1:000000000000:function:orders", "Qualifier": "$LATEST", + "MaximumRetryAttempts": 0} + """, "orders|$LATEST"); + + verify(lambda).updateEventInvokeConfig(eq(REGION), + eq("arn:aws:lambda:us-east-1:000000000000:function:orders"), eq("$LATEST"), anyMap()); + verify(lambda, never()).putEventInvokeConfig(anyString(), anyString(), anyString(), anyMap()); + assertEquals("orders|$LATEST", r.getPhysicalId(), "the prior id stays so nothing is recorded as displaced"); + assertFalse(provisioner.hasReplacementUpdate(r)); + assertNull(provisioner.updateCleanupPhysicalId(r)); + } + + @Test + void theSameNameInAnotherRegionIsAnotherTarget() { + StackResource r = provision(""" + {"FunctionName": "arn:aws:lambda:eu-west-1:000000000000:function:orders", "Qualifier": "$LATEST"} + """, "arn:aws:lambda:us-east-1:000000000000:function:orders|$LATEST"); + + verify(lambda).putEventInvokeConfig(eq(REGION), + eq("arn:aws:lambda:eu-west-1:000000000000:function:orders"), eq("$LATEST"), anyMap()); + assertTrue(provisioner.hasReplacementUpdate(r)); + } + + /** The settings before an in-place update are kept, and a failed stack update puts every one back. */ + @Test + void anInPlaceUpdateIsRolledBackFromTheSettingsItReplaced() { + when(lambda.getEventInvokeConfig(REGION, "orders", "$LATEST")).thenReturn(config(2, 21600, + "arn:aws:sqs:us-east-1:000000000000:ok", "arn:aws:sqs:us-east-1:000000000000:dlq")); + + StackResource r = provision(""" + {"FunctionName": "orders", "Qualifier": "$LATEST", "MaximumRetryAttempts": 0, + "DestinationConfig": {"OnFailure": {"Destination": "arn:aws:sns:us-east-1:000000000000:alerts"}}} + """, "orders|$LATEST"); + assertTrue(r.getAttributes().containsKey(CfnRollback.EVENT_INVOKE_CONFIG_SNAPSHOT_ATTR)); + + assertTrue(provisioner.rollbackUpdate(r)); + + ArgumentCaptor> restored = ArgumentCaptor.captor(); + verify(lambda).putEventInvokeConfig(eq(REGION), eq("orders"), eq("$LATEST"), restored.capture()); + assertEquals(2, restored.getValue().get("MaximumRetryAttempts")); + assertEquals(21600, restored.getValue().get("MaximumEventAgeInSeconds")); + assertEquals(Map.of( + "OnSuccess", Map.of("Destination", "arn:aws:sqs:us-east-1:000000000000:ok"), + "OnFailure", Map.of("Destination", "arn:aws:sqs:us-east-1:000000000000:dlq")), + restored.getValue().get("DestinationConfig")); + assertFalse(r.getAttributes().containsKey(CfnRollback.EVENT_INVOKE_CONFIG_SNAPSHOT_ATTR), + "the snapshot is spent by the rollback"); + } + + /** A restore that fails keeps the snapshot, so the next rollback attempt still has it. */ + @Test + void aFailedRestoreKeepsTheSnapshot() { + StackResource r = provision(""" + {"FunctionName": "orders", "Qualifier": "$LATEST", "MaximumRetryAttempts": 0} + """, "orders|$LATEST"); + doThrow(new AwsException("ServiceException", "boom", 500)) + .when(lambda).putEventInvokeConfig(eq(REGION), eq("orders"), eq("$LATEST"), anyMap()); + + assertThrows(AwsException.class, () -> provisioner.rollbackUpdate(r)); + + assertTrue(r.getAttributes().containsKey(CfnRollback.EVENT_INVOKE_CONFIG_SNAPSHOT_ATTR)); + } + + /** Settings the configuration did not carry are restored as absent, not as defaults. */ + @Test + void rollbackRestoresAbsentSettingsAsAbsent() { + when(lambda.getEventInvokeConfig(REGION, "orders", "live")).thenReturn(config(null, null, null, null)); + + StackResource r = provision(""" + {"FunctionName": "orders", "Qualifier": "live", "MaximumEventAgeInSeconds": 120} + """, "orders|live"); + assertTrue(provisioner.rollbackUpdate(r)); + + ArgumentCaptor> restored = ArgumentCaptor.captor(); + verify(lambda).putEventInvokeConfig(eq(REGION), eq("orders"), eq("live"), restored.capture()); + assertTrue(restored.getValue().isEmpty(), restored.getValue().toString()); + } + + /** A successful update clears the snapshot, so a later rollback cannot restore stale settings. */ + @Test + void aCommittedUpdateDropsTheSnapshot() { + when(lambda.getEventInvokeConfig(REGION, "orders", "$LATEST")).thenReturn(config(2, 21600, null, null)); + StackResource r = provision(""" + {"FunctionName": "orders", "Qualifier": "$LATEST", "MaximumRetryAttempts": 0} + """, "orders|$LATEST"); + + provisioner.clearUpdate(r); + + assertFalse(r.getAttributes().containsKey(CfnRollback.EVENT_INVOKE_CONFIG_SNAPSHOT_ATTR)); + assertTrue(provisioner.rollbackUpdate(r), "nothing is left to undo"); + verify(lambda, never()).putEventInvokeConfig(anyString(), anyString(), anyString(), anyMap()); + } + + /** A provision that failed before it changed anything has nothing to undo. */ + @Test + void aProvisionThatFailedBeforeMutatingReportsRolledBack() { + doThrow(new AwsException("ResourceNotFoundException", "Function not found: payments", 404)) + .when(lambda).putEventInvokeConfig(eq(REGION), eq("payments"), eq("$LATEST"), anyMap()); + StackResource r = resource(); + r.setPhysicalId("orders|$LATEST"); + assertThrows(AwsException.class, () -> provisioner.provision(r, props(""" + {"FunctionName": "payments", "Qualifier": "$LATEST"} + """), new ProvisionContext(engine, REGION, ACCOUNT_ID, STACK, "orders|$LATEST"))); + + assertTrue(provisioner.rollbackUpdate(r)); + verify(lambda, never()).deleteEventInvokeConfig(anyString(), anyString(), anyString()); + } + + /** A conditional DestinationConfig that resolves to AWS::NoValue is omitted, not sent as an empty set. */ + @Test + void aDestinationConfigResolvingToNoValueIsNotSent() { + when(engine.resolveNode(any())).thenAnswer(i -> { + JsonNode node = i.getArgument(0); + return node.has("Ref") ? TextNode.valueOf("") : node; + }); + + provision(""" + {"FunctionName": "orders", "Qualifier": "$LATEST", + "DestinationConfig": {"Ref": "AWS::NoValue"}} + """, "orders|$LATEST"); + + ArgumentCaptor> request = ArgumentCaptor.captor(); + verify(lambda).updateEventInvokeConfig(eq(REGION), eq("orders"), eq("$LATEST"), request.capture()); + assertFalse(request.getValue().containsKey("DestinationConfig"), request.getValue().toString()); + } + + @Test + void aDestinationSideResolvingToNoValueIsNotSent() { + when(engine.resolveNode(any())).thenAnswer(i -> { + JsonNode node = i.getArgument(0); + if (node.isObject() && node.has("OnSuccess")) { + ((com.fasterxml.jackson.databind.node.ObjectNode) node).set("OnSuccess", TextNode.valueOf("")); + } + return node; + }); + + provision(""" + {"FunctionName": "orders", "Qualifier": "$LATEST", + "DestinationConfig": {"OnSuccess": {"Ref": "AWS::NoValue"}, + "OnFailure": {"Destination": "arn:aws:sqs:us-east-1:000000000000:dlq"}}} + """, null); + + ArgumentCaptor> request = ArgumentCaptor.captor(); + verify(lambda).putEventInvokeConfig(eq(REGION), eq("orders"), eq("$LATEST"), request.capture()); + assertEquals(Map.of("OnFailure", Map.of("Destination", "arn:aws:sqs:us-east-1:000000000000:dlq")), + request.getValue().get("DestinationConfig")); + } + + private static FunctionEventInvokeConfig config(Integer retries, Integer eventAge, + String onSuccess, String onFailure) { + FunctionEventInvokeConfig config = new FunctionEventInvokeConfig(); + config.setFunctionArn("arn:aws:lambda:us-east-1:000000000000:function:orders:$LATEST"); + config.setMaximumRetryAttempts(retries); + config.setMaximumEventAgeInSeconds(eventAge); + if (onSuccess != null || onFailure != null) { + FunctionEventInvokeConfig.DestinationConfig destinations = new FunctionEventInvokeConfig.DestinationConfig(); + if (onSuccess != null) { + destinations.setOnSuccess(new FunctionEventInvokeConfig.Destination(onSuccess)); + } + if (onFailure != null) { + destinations.setOnFailure(new FunctionEventInvokeConfig.Destination(onFailure)); + } + config.setDestinationConfig(destinations); + } + return config; + } + + @Test + void aFailedPutLeavesThePriorIdInPlace() { + doThrow(new AwsException("ResourceNotFoundException", "Function not found: payments", 404)) + .when(lambda).putEventInvokeConfig(eq(REGION), eq("payments"), eq("$LATEST"), anyMap()); + + StackResource r = resource(); + r.setPhysicalId("orders|$LATEST"); + assertThrows(AwsException.class, () -> provisioner.provision(r, props(""" + {"FunctionName": "payments", "Qualifier": "$LATEST"} + """), new ProvisionContext(engine, REGION, ACCOUNT_ID, STACK, "orders|$LATEST"))); + + assertEquals("orders|$LATEST", r.getPhysicalId()); + assertFalse(provisioner.hasReplacementUpdate(r)); + } + + @Test + void deleteSplitsTheIdentityAtThePipe() { + provisioner.delete(TYPE, "arn:aws:lambda:us-east-1:000000000000:function:orders|live", REGION); + + verify(lambda).deleteEventInvokeConfig(REGION, + "arn:aws:lambda:us-east-1:000000000000:function:orders", "live"); + } + + @Test + void deleteToleratesAConfigurationThatIsAlreadyGone() { + doThrow(new AwsException("ResourceNotFoundException", + "The function arn:aws:lambda:us-east-1:000000000000:function:orders doesn't have an EventInvokeConfig", 404)) + .when(lambda).deleteEventInvokeConfig(REGION, "orders", "$LATEST"); + + provisioner.delete(TYPE, "orders|$LATEST", REGION); + } + + @Test + void deletePropagatesAnyOtherFailure() { + doThrow(new AwsException("ServiceException", "boom", 500)) + .when(lambda).deleteEventInvokeConfig(REGION, "orders", "$LATEST"); + + assertThrows(AwsException.class, () -> provisioner.delete(TYPE, "orders|$LATEST", REGION)); + } + + @Test + void deleteIgnoresAnIdWithoutAQualifier() { + provisioner.delete(TYPE, "orders", REGION); + provisioner.delete(TYPE, null, REGION); + + verifyNoInteractions(lambda); + } +} diff --git a/src/test/resources/cloudformation/supported-resource-types.tsv b/src/test/resources/cloudformation/supported-resource-types.tsv index a29e5e930e..bc36c487b7 100644 --- a/src/test/resources/cloudformation/supported-resource-types.tsv +++ b/src/test/resources/cloudformation/supported-resource-types.tsv @@ -88,6 +88,7 @@ AWS::KMS::Key KmsCfnProvisioner AWS::Kinesis::Stream KinesisCfnProvisioner AWS::KinesisFirehose::DeliveryStream FirehoseCfnProvisioner AWS::Lambda::Alias LambdaVersionAliasCfnProvisioner +AWS::Lambda::EventInvokeConfig LambdaEventInvokeConfigCfnProvisioner AWS::Lambda::EventSourceMapping LambdaEventSourceMappingCfnProvisioner AWS::Lambda::Function LEGACY_SWITCH AWS::Lambda::LayerVersion LEGACY_SWITCH