diff --git a/docs/services/cloudformation.md b/docs/services/cloudformation.md index aa350af190..9d3c7003a4 100644 --- a/docs/services/cloudformation.md +++ b/docs/services/cloudformation.md @@ -128,7 +128,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`, Image, and the `hot-reload` bind-mount bucket), `LayerVersion`, `EventSourceMapping` (SQS, Kinesis, DynamoDB Streams; `ParallelizationFactor` and `TumblingWindowInSeconds` are ignored), `Version`, `Alias` (also what SAM's `AutoPublishAlias` expands into), `Permission`, `EventInvokeConfig`, `MicrovmImage`, `NetworkConnector`, `Url`. 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`, Image, and the `hot-reload` bind-mount bucket), `LayerVersion`, `EventSourceMapping` (SQS, Kinesis, DynamoDB Streams; `ParallelizationFactor` and `TumblingWindowInSeconds` are ignored), `Version`, `Alias` (also what SAM's `AutoPublishAlias` expands into), `Permission`, `EventInvokeConfig` (also what a SAM function's `EventInvokeConfig` expands into), `MicrovmImage`, `NetworkConnector`, `Url`. 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` (template `LoginProfile` and `PermissionsBoundary` are ignored; an API-created login profile is removed on delete), `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 c212e161d2..6a149c5886 100644 --- a/docs/services/lambda.md +++ b/docs/services/lambda.md @@ -70,8 +70,11 @@ supported ranges before changing any stored settings. A rejected value returns `InvalidParameterValueException` and leaves the function configuration unchanged. The event invoke configuration is stored and returned as AWS does, and `AWS::Lambda::EventInvokeConfig` -provisions it from a stack. Asynchronous invocations apply its retry, event age, destination settings, -and dead-letter queue configurations (`DeadLetterConfig`). +provisions it from a stack. A SAM function's `EventInvokeConfig` expands into that resource as +`sam deploy` does: on `$LATEST`, or on the `AutoPublishAlias` alias, with the inline role policy for +each destination and the SQS queue or SNS topic SAM creates when a destination gives only its `Type`. +Asynchronous invocations apply its retry, event age, destination settings, and dead-letter queue +configurations (`DeadLetterConfig`). ### Function policies under IAM enforcement diff --git a/src/main/java/io/github/hectorvent/floci/core/common/Digests.java b/src/main/java/io/github/hectorvent/floci/core/common/Digests.java index 905774f1f6..c5523334cc 100644 --- a/src/main/java/io/github/hectorvent/floci/core/common/Digests.java +++ b/src/main/java/io/github/hectorvent/floci/core/common/Digests.java @@ -11,6 +11,19 @@ public final class Digests { private Digests() { } + public static byte[] sha1(byte[] data) { + try { + return MessageDigest.getInstance("SHA-1").digest(data); + } catch (NoSuchAlgorithmException e) { + throw new IllegalStateException("SHA-1 is not available", e); + } + } + + /** The SHA-1 digest of the UTF-8 bytes of {@code text} as lowercase hex. */ + public static String sha1Hex(String text) { + return HexFormat.of().formatHex(sha1(text.getBytes(StandardCharsets.UTF_8))); + } + public static byte[] sha256(byte[] data) { try { return MessageDigest.getInstance("SHA-256").digest(data); diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationService.java b/src/main/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationService.java index 9c405d5464..6b9602cbe9 100644 --- a/src/main/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationService.java +++ b/src/main/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationService.java @@ -354,7 +354,7 @@ public class CloudFormationService implements ResourceProvider { // unpackaged DefinitionUri) does not fail the API call: it creates the change set and // marks it FAILED, with the transform's own error in StatusReason. Match that here instead // of throwing, so this failure is reported by the change set, not by a 400 on creation. - String samTransformFailureReason = samTransformFailureReason(stackName, resolvedTemplate); + String samTransformFailureReason = samTransformFailureReason(stackName, resolvedTemplate, parameters, region); // Reject an unresolvable or circular dependency graph up front, before any stack state is // created, so CreateStack/UpdateStack fail synchronously the way real CloudFormation does. @@ -493,7 +493,8 @@ public class CloudFormationService implements ResourceProvider { * transform's own per-resource message. The count is always 1: {@code expandSamTemplate} * throws on the first bad resource rather than accumulating them. */ - private String samTransformFailureReason(String stackName, String templateBody) { + private String samTransformFailureReason(String stackName, String templateBody, Map parameters, + String region) { JsonNode template; try { template = parseTemplate(templateBody); @@ -505,9 +506,9 @@ public class CloudFormationService implements ResourceProvider { if (!samTransformProcessor.hasSamTransform(template)) { return null; } + JsonNode expanded; try { - samTransformProcessor.expandSamTemplate(template); - return null; + expanded = samTransformProcessor.expandSamTemplate(template, samTransformParameters(template, parameters, region)); } catch (AwsException e) { return "Transform AWS::Serverless-2016-10-31 failed with: Invalid Serverless " + "Application Specification document. Number of errors found: 1. " @@ -522,6 +523,14 @@ public class CloudFormationService implements ResourceProvider { stackName, e.getMessage()); throw e; } + // The transform succeeded but produced a template CloudFormation rejects: AWS fails the + // change set with the template error itself, not a transform failure. + try { + requireStringConditionReferencesIn(expanded); + } catch (AwsException e) { + return e.getMessage(); + } + return null; } // ── DescribeChangeSet ───────────────────────────────────────────────────── @@ -554,7 +563,8 @@ public class CloudFormationService implements ResourceProvider { // The deployed stack's template is always the SAM-expanded form (see // executeTemplate); comparing the change set's raw SAM source against it would // report every SAM-generated resource as Add/Remove even on a no-op update. - newTemplate = samTransformProcessor.expandSamTemplate(newTemplate); + newTemplate = samTransformProcessor.expandSamTemplate(newTemplate, + samTransformParameters(newTemplate, cs.getParameters(), region)); } JsonNode newResources = newTemplate.path("Resources"); boolean createType = "CREATE".equalsIgnoreCase(cs.getChangeSetType()) @@ -1464,6 +1474,22 @@ public class CloudFormationService implements ResourceProvider { return resolved; } + /** + * The parameter values the SAM transform sees: the given ones over each {@code Default}, with + * {@code AWS::SSM::Parameter::Value} parameters already read from Parameter Store, as + * CloudFormation resolves them before it runs the transform. A parameter that cannot be fetched + * leaves the values unresolved here; the execution path reports that failure with its own error. + */ + private Map samTransformParameters(JsonNode template, Map params, String region) { + Map given = resolveDefaultParameters(template, params); + try { + return resolveSsmParameters(template, given, region); + } catch (AwsException e) { + LOG.debugv("SAM transform sees unresolved parameters: {0}", e.getMessage()); + return given; + } + } + /** * Substitutes {@code AWS::SSM::Parameter::Value}-typed parameter values — which carry * an SSM parameter name — with the value stored in Parameter Store for the stack's @@ -1530,13 +1556,16 @@ public class CloudFormationService implements ResourceProvider { boolean hasSamTransform = samTransformProcessor.hasSamTransform(template); if (hasSamTransform) { LOG.infov("Applying SAM transform for stack {0}", stack.getStackName()); - template = samTransformProcessor.expandSamTemplate(template); + template = samTransformProcessor.expandSamTemplate(template, samTransformParameters(template, params, region)); } // Persist the merged/expanded tree, not the raw submitted body, whenever either // processor actually changed it, so the change-set baseline diffs against it instead of // against a stale Fn::Transform node. A template neither processor touched keeps its // submitted body byte for byte. + // A template CloudFormation rejects outright fails before the stack takes it on, as the + // synchronous check does for a template no transform touched. + requireStringConditionReferencesIn(template); if (includeMerged || hasSamTransform) { templateBody = objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(template); } @@ -2670,6 +2699,35 @@ public class CloudFormationService implements ResourceProvider { return conditions; } + private static final String NON_STRING_CONDITION_REFERENCE = + "Template error: every Condition object must have a single String value."; + + /** + * Rejects a template whose conditions name another one with anything but a string, as + * CloudFormation does before evaluating any of them: {@code Fn::And}, {@code Fn::Or} and + * {@code Fn::Not} stop early, so evaluation alone would read such an operand as false or never + * reach it. SAM's translator emits this shape when a conditional function's event invoke + * destination is itself conditional. Checked on the template being deployed only, so a stored + * template is never a reason an update cannot proceed. + */ + private static void requireStringConditionReferencesIn(JsonNode template) { + template.path("Conditions").forEach(CloudFormationService::requireStringConditionReferences); + } + + private static void requireStringConditionReferences(JsonNode expression) { + if (expression.isArray()) { + expression.forEach(CloudFormationService::requireStringConditionReferences); + return; + } + if (!expression.isObject()) { + return; + } + if (expression.has("Condition") && !expression.get("Condition").isTextual()) { + throw new AwsException("ValidationError", NON_STRING_CONDITION_REFERENCE, 400); + } + expression.forEach(CloudFormationService::requireStringConditionReferences); + } + /** * Fails a create/update before any stack state is mutated when a resource that will be created * depends on a resource excluded by a false condition, or when resources depend on each other @@ -2700,6 +2758,7 @@ public class CloudFormationService implements ResourceProvider { return; } + requireStringConditionReferencesIn(template); Map resolvedParams = resolveDefaultParameters(template, params); Map conditions = resolveConditions(template, resolvedParams, null, region, accountId); diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudformation/SamTransformProcessor.java b/src/main/java/io/github/hectorvent/floci/services/cloudformation/SamTransformProcessor.java index 5efd9548ef..f30712ad0f 100644 --- a/src/main/java/io/github/hectorvent/floci/services/cloudformation/SamTransformProcessor.java +++ b/src/main/java/io/github/hectorvent/floci/services/cloudformation/SamTransformProcessor.java @@ -5,6 +5,7 @@ import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.node.ArrayNode; import com.fasterxml.jackson.databind.node.ObjectNode; import io.github.hectorvent.floci.core.common.AwsException; +import io.github.hectorvent.floci.core.common.Digests; import io.github.hectorvent.floci.core.common.ServicePrincipals; import org.jboss.logging.Logger; @@ -17,8 +18,9 @@ import java.util.regex.Pattern; /** * Expands {@code AWS::Serverless-2016-10-31} SAM resource types into standard CloudFormation - * resources. Inline policy documents in {@code Policies} are silently ignored — only ARN - * references are attached as managed policies on the generated execution role. + * resources. Inline policy documents in a function's {@code Policies} are silently ignored: only + * ARN references are attached as managed policies on the generated execution role. The role does + * carry the inline policies SAM generates for {@code EventInvokeConfig} destinations. */ class SamTransformProcessor { @@ -56,7 +58,20 @@ class SamTransformProcessor { return false; } + /** + * Expands the template with no parameter values: a parameter reference SAM resolves falls back + * to the parameter's {@code Default}. Every stack operation passes its values to + * {@link #expandSamTemplate(JsonNode, Map)} instead. + */ JsonNode expandSamTemplate(JsonNode template) { + return expandSamTemplate(template, Map.of()); + } + + /** + * Expands the template with the stack's parameter values, which SAM's translator resolves + * parameter references against (falling back to each parameter's {@code Default}). + */ + JsonNode expandSamTemplate(JsonNode template, Map parameterValues) { if (!hasSamTransform(template)) { return template; } @@ -104,7 +119,8 @@ class SamTransformProcessor { // copyResourceLevelAttributes runs once per arm, right after that arm builds its node. switch (type) { case "AWS::Serverless::Function" -> { - expandServerlessFunction(logicalId, mergeGlobals(globals, "Function", properties), expandedResources); + expandServerlessFunction(logicalId, mergeGlobals(globals, "Function", properties), + resDef, expanded, expandedResources, parameterValues); copyResourceLevelAttributes(resDef, (ObjectNode) expandedResources.path(logicalId)); } case "AWS::Serverless::SimpleTable" -> { @@ -914,22 +930,28 @@ class SamTransformProcessor { return base; } - private void expandServerlessFunction(String logicalId, JsonNode properties, ObjectNode resources) { + private void expandServerlessFunction(String logicalId, JsonNode properties, JsonNode source, + ObjectNode template, ObjectNode resources, + Map parameterValues) { resources.remove(logicalId); + ObjectNode passthrough = passthroughAttributes(source); boolean hasExplicitRole = !properties.path("Role").isMissingNode() && !properties.path("Role").isNull(); String roleLogicalId = logicalId + "Role"; - if (!hasExplicitRole) { - ObjectNode roleResource = createExecutionRole(properties); - resources.set(roleLogicalId, roleResource); - } - ObjectNode lambdaResource = createLambdaFunction(logicalId, roleLogicalId, properties, hasExplicitRole); resources.set(logicalId, lambdaResource); - expandAutoPublishAlias(logicalId, properties, resources); + String aliasLogicalId = expandAutoPublishAlias(logicalId, properties, passthrough, resources); + List eventInvokePolicies = expandEventInvokeConfig( + logicalId, properties, aliasLogicalId, passthrough, template, resources, parameterValues); + + if (!hasExplicitRole) { + ObjectNode roleResource = createExecutionRole(properties, eventInvokePolicies); + roleResource.setAll(passthrough.deepCopy()); + resources.set(roleLogicalId, roleResource); + } JsonNode events = properties.path("Events"); if (events.isObject()) { @@ -959,11 +981,12 @@ class SamTransformProcessor { * {@code $LATEST}; none is required, since the alias does not reference the version. It * returns with the {@code Fn::GetAtt} form once #1987 lands. */ - private void expandAutoPublishAlias(String functionLogicalId, JsonNode properties, ObjectNode resources) { + private String expandAutoPublishAlias(String functionLogicalId, JsonNode properties, ObjectNode passthrough, + ObjectNode resources) { JsonNode aliasName = properties.path("AutoPublishAlias"); if (aliasName.isMissingNode() || aliasName.isNull() || (aliasName.isTextual() && aliasName.asText().isBlank())) { - return; + return null; } String versionId = uniqueId(functionLogicalId + "Version", resources); @@ -972,6 +995,7 @@ class SamTransformProcessor { ObjectNode versionProps = objectMapper.createObjectNode(); versionProps.set("FunctionName", ref(functionLogicalId)); versionDef.set("Properties", versionProps); + versionDef.setAll(passthrough.deepCopy()); resources.set(versionId, versionDef); // Alias names may legally contain '-' and '_', neither of which is valid in a @@ -993,10 +1017,358 @@ class SamTransformProcessor { // Switch to the GetAtt form once #1987 lands. aliasProps.put("FunctionVersion", "$LATEST"); aliasDef.set("Properties", aliasProps); + aliasDef.setAll(passthrough.deepCopy()); resources.set(aliasId, aliasDef); + return aliasId; } - private ObjectNode createExecutionRole(JsonNode properties) { + private static final List EVENT_INVOKE_DESTINATION_TYPES = + List.of("SQS", "SNS", "EventBridge", "Lambda", "S3Bucket"); + + /** The resource attributes SAM copies from a function onto every resource it generates for it. */ + private static final List PASSTHROUGH_ATTRIBUTES = List.of("Condition", "DeletionPolicy", "UpdateReplacePolicy"); + + private ObjectNode passthroughAttributes(JsonNode source) { + ObjectNode attributes = objectMapper.createObjectNode(); + for (String attribute : PASSTHROUGH_ATTRIBUTES) { + if (isPropertyPresent(source.path(attribute))) { + attributes.set(attribute, source.path(attribute).deepCopy()); + } + } + return attributes; + } + + /** What expanding one function's EventInvokeConfig shares between its destinations. */ + private record EventInvokeContext(String functionLogicalId, String configLogicalId, ObjectNode passthrough, + ObjectNode template, ObjectNode resources, List policies, + Map parameterValues) { + + String functionCondition() { + return passthrough.path("Condition").asText(null); + } + } + + /** + * Expands {@code EventInvokeConfig} as SAM's translator does: an + * {@code AWS::Lambda::EventInvokeConfig} named {@code EventInvokeConfig}, on + * {@code $LATEST} or, with {@code AutoPublishAlias}, on that alias. Each destination's SAM-only + * {@code Type} is dropped from the configuration and becomes the inline role policy letting + * the function deliver there. An SQS or SNS destination given only its {@code Type} gets the + * queue or topic SAM creates for it. Returns those policies, for the generated execution role. + * + *

A {@code Destination} that is an {@code Fn::If} with {@code AWS::NoValue} in one branch + * creates the queue or topic only under that branch's condition, using the condition names + * SAM generates, so the expanded template matches {@code sam deploy}'s. + */ + private List expandEventInvokeConfig(String functionLogicalId, JsonNode properties, + String aliasLogicalId, ObjectNode passthrough, + ObjectNode template, ObjectNode resources, + Map parameterValues) { + JsonNode config = properties.path("EventInvokeConfig"); + if (isPropertyPresent(config) && !config.isObject()) { + throw invalidResource(functionLogicalId, "Property 'EventInvokeConfig' should be a map."); + } + if (!config.isObject() || config.isEmpty()) { + return List.of(); + } + EventInvokeContext context = new EventInvokeContext(functionLogicalId, + functionLogicalId + "EventInvokeConfig", passthrough, template, resources, new ArrayList<>(), + parameterValues); + requireUnused(context, context.configLogicalId(), "AWS::Lambda::EventInvokeConfig"); + ObjectNode destinations = objectMapper.createObjectNode(); + + JsonNode destinationConfig = config.path("DestinationConfig"); + if (isTruthy(destinationConfig)) { + if (!destinationConfig.isObject()) { + throw invalidResource(functionLogicalId, + "Property 'EventInvokeConfig.DestinationConfig' should be a map."); + } + for (String event : List.of("OnSuccess", "OnFailure")) { + JsonNode destination = destinationConfig.path(event); + if (!isPropertyPresent(destination)) { + continue; + } + if (!destination.isObject()) { + throw invalidResource(functionLogicalId, + "Property 'EventInvokeConfig.DestinationConfig." + event + "' should be a map."); + } + ObjectNode target = objectMapper.createObjectNode(); + target.set("Destination", expandDestination(context, context.configLogicalId() + event, destination)); + destinations.set(event, target); + } + } + + ObjectNode configProps = objectMapper.createObjectNode(); + configProps.set("FunctionName", ref(functionLogicalId)); + if (aliasLogicalId != null) { + configProps.set("Qualifier", properties.path("AutoPublishAlias").deepCopy()); + } else { + configProps.put("Qualifier", "$LATEST"); + } + configProps.set("DestinationConfig", destinations); + copyIfPresent(config, "MaximumEventAgeInSeconds", configProps); + copyIfPresent(config, "MaximumRetryAttempts", configProps); + + ObjectNode configDef = objectMapper.createObjectNode(); + configDef.put("Type", "AWS::Lambda::EventInvokeConfig"); + configDef.set("Properties", configProps); + if (aliasLogicalId != null) { + configDef.set("DependsOn", objectMapper.createArrayNode().add(aliasLogicalId)); + } + configDef.setAll(passthrough.deepCopy()); + resources.set(context.configLogicalId(), configDef); + return context.policies(); + } + + /** The queue or topic SAM creates for an SQS or SNS destination given only its Type. */ + private record CreatedDestination(String suffix, String resourceType, boolean arnIsRef) { + + static CreatedDestination forType(String type) { + return switch (type) { + case "SQS" -> new CreatedDestination("Queue", "AWS::SQS::Queue", false); + case "SNS" -> new CreatedDestination("Topic", "AWS::SNS::Topic", true); + default -> null; + }; + } + } + + /** + * One destination's ARN for the configuration, creating the queue or topic SAM creates when + * none is given, and adding the policy that lets the function deliver to it. + */ + private JsonNode expandDestination(EventInvokeContext context, String destinationLogicalId, JsonNode destination) { + String type = destinationType(destination.path("Type"), context.template(), context.parameterValues()); + if (type == null) { + throw invalidResource(context.functionLogicalId(), "'Type: " + pythonRepr(destination.path("Type")) + + "' must be one of " + pythonRepr(EVENT_INVOKE_DESTINATION_TYPES)); + } + JsonNode given = destination.path("Destination"); + boolean hasDestination = isPropertyPresent(given); + + String propertyCondition = null; + JsonNode otherBranch = null; + if (hasDestination && given.isObject() && given.size() == 1 && given.path("Fn::If").isArray() + && given.path("Fn::If").size() == 3 && given.path("Fn::If").get(0).isTextual()) { + JsonNode branches = given.path("Fn::If"); + boolean trueIsNoValue = isNoValue(branches.get(1)); + boolean falseIsNoValue = isNoValue(branches.get(2)); + if (trueIsNoValue && !falseIsNoValue) { + propertyCondition = branches.get(0).asText(); + otherBranch = branches.get(2); + } else if (falseIsNoValue && !trueIsNoValue) { + propertyCondition = generatedConditionName("NOT" + branches.get(0).asText(), context.configLogicalId()); + ObjectNode not = objectMapper.createObjectNode(); + not.set("Fn::Not", objectMapper.createArrayNode().add(conditionRef(branches.get(0).asText()))); + conditions(context.template()).set(propertyCondition, not); + otherBranch = branches.get(1); + } + } + + JsonNode resolved = given.deepCopy(); + if (!hasDestination || propertyCondition != null) { + CreatedDestination created = CreatedDestination.forType(type); + if (created == null) { + throw invalidResource(context.functionLogicalId(), "Destination is required if Type is not " + + pythonRepr(List.of("SQS", "SNS"))); + } + String createdLogicalId = destinationLogicalId + created.suffix(); + requireUnused(context, createdLogicalId, created.resourceType()); + ObjectNode createdDef = objectMapper.createObjectNode(); + createdDef.put("Type", created.resourceType()); + createdDef.set("Properties", objectMapper.createObjectNode()); + createdDef.setAll(context.passthrough().deepCopy()); + String createdCondition = andConditions(context, propertyCondition); + if (createdCondition != null) { + createdDef.put("Condition", createdCondition); + } + context.resources().set(createdLogicalId, createdDef); + JsonNode createdArn = created.arnIsRef() ? ref(createdLogicalId) : getAtt(createdLogicalId, "Arn"); + if (propertyCondition != null) { + ObjectNode conditional = objectMapper.createObjectNode(); + conditional.set("Fn::If", objectMapper.createArrayNode() + .add(propertyCondition).add(createdArn).add(otherBranch.deepCopy())); + resolved = conditional; + } else { + resolved = createdArn; + } + } + context.policies().add(destinationPolicy(type, destinationLogicalId, resolved)); + return resolved; + } + + /** + * The destination type, one of {@link #EVENT_INVOKE_DESTINATION_TYPES} exactly as SAM spells + * them, or null. SAM resolves a {@code Ref} to a template parameter before checking it: to the + * value the stack was given, or else to the parameter's {@code Default}. + */ + private static String destinationType(JsonNode type, JsonNode template, Map parameterValues) { + String value = type.isTextual() ? type.asText() : null; + if (type.isObject() && type.size() == 1 && type.path("Ref").isTextual()) { + String parameter = type.path("Ref").asText(); + JsonNode defaultValue = template.path("Parameters").path(parameter).path("Default"); + if (parameterValues.containsKey(parameter)) { + value = parameterValues.get(parameter); + } else if (defaultValue.isTextual()) { + value = defaultValue.asText(); + } + } + return value != null && EVENT_INVOKE_DESTINATION_TYPES.contains(value) ? value : null; + } + + /** The inline policy SAM adds to the execution role for a destination of {@code type}. */ + private ObjectNode destinationPolicy(String type, String destinationLogicalId, JsonNode destination) { + ArrayNode statements = objectMapper.createArrayNode(); + String policySuffix = type; + switch (type) { + case "SQS" -> statements.add(allow("sqs:SendMessage", destination.deepCopy())); + // SAM's own policy template spells the action in lower case. + case "SNS" -> statements.add(allow("sns:publish", destination.deepCopy())); + case "EventBridge" -> statements.add(allow("events:PutEvents", destination.deepCopy())); + case "Lambda" -> statements.add(allow("lambda:InvokeFunction", destination.deepCopy())); + default -> { + ObjectNode objects = objectMapper.createObjectNode(); + objects.set("Fn::Join", objectMapper.createArrayNode().add("/") + .add(objectMapper.createArrayNode().add(destination.deepCopy()).add("*"))); + statements.add(allow("s3:PutObject", objects)); + statements.add(allow("s3:ListBucket", destination.deepCopy())); + policySuffix = "S3"; + } + } + ObjectNode document = objectMapper.createObjectNode(); + document.set("Statement", statements); + ObjectNode policy = objectMapper.createObjectNode(); + policy.set("PolicyDocument", document); + policy.put("PolicyName", destinationLogicalId + policySuffix + "Policy"); + return policy; + } + + private ObjectNode allow(String action, JsonNode resource) { + ObjectNode statement = objectMapper.createObjectNode(); + statement.put("Action", action); + statement.put("Effect", "Allow"); + statement.set("Resource", resource); + return statement; + } + + /** SAM refuses to replace a resource the template already declares with one it generates. */ + private static void requireUnused(EventInvokeContext context, String logicalId, String resourceType) { + if (context.resources().has(logicalId)) { + throw new AwsException("ValidationError", "Transforming resource with id [" + context.functionLogicalId() + + "] attempts to create a new resource with id [" + logicalId + "] and type \"" + resourceType + + "\". A resource with that id already exists within this template. Please use a different id" + + " for that resource.", 400); + } + } + + /** + * The condition a created destination carries: the function's, the destination's, or a new + * one requiring both, named and built as SAM's translator builds it. SAM nests each operand + * as {@code {"Condition": {"Condition": name}}}, which CloudFormation rejects ("every Condition + * object must have a single String value."); the shape is kept so floci rejects the stack as + * AWS does. + */ + private String andConditions(EventInvokeContext context, String propertyCondition) { + String functionCondition = context.functionCondition(); + if (functionCondition == null) { + return propertyCondition; + } + if (propertyCondition == null) { + return functionCondition; + } + String name = generatedConditionName(functionCondition + "AND" + propertyCondition, context.functionLogicalId()); + ObjectNode and = objectMapper.createObjectNode(); + and.set("Fn::And", objectMapper.createArrayNode() + .add(objectMapper.createObjectNode().set("Condition", conditionRef(functionCondition))) + .add(objectMapper.createObjectNode().set("Condition", conditionRef(propertyCondition)))); + conditions(context.template()).set(name, and); + return name; + } + + /** + * SAM's generated condition name: the name plus the first ten hex digits of the SHA-1 of + * {@code hashInput}, cut to CloudFormation's 255-character limit. SHA-1 is SAM's choice and is + * kept so the names match; nothing here relies on it being collision-resistant. + */ + private static String generatedConditionName(String name, String hashInput) { + String conditionName = name + Digests.sha1Hex(hashInput).substring(0, 10); + return conditionName.length() > 255 ? conditionName.substring(0, 255) : conditionName; + } + + private ObjectNode conditionRef(String conditionName) { + return objectMapper.createObjectNode().put("Condition", conditionName); + } + + private static ObjectNode conditions(ObjectNode template) { + JsonNode existing = template.path("Conditions"); + return existing.isObject() ? (ObjectNode) existing : template.putObject("Conditions"); + } + + private static boolean isNoValue(JsonNode node) { + return node.isObject() && node.size() == 1 && "AWS::NoValue".equals(node.path("Ref").asText()); + } + + /** Python truthiness, which SAM applies to an optional property before reading it. */ + private static boolean isTruthy(JsonNode node) { + if (node.isMissingNode() || node.isNull()) { + return false; + } + if (node.isContainerNode()) { + return !node.isEmpty(); + } + if (node.isTextual()) { + return !node.asText().isEmpty(); + } + if (node.isBoolean()) { + return node.asBoolean(); + } + return node.isNumber() ? node.asDouble() != 0 : true; + } + + /** + * How Python's {@code format} prints a value, which is how SAM's messages show one: a top-level + * string bare, strings inside a dict or list quoted with {@code '}, a missing value as + * {@code None}. + */ + private static String pythonRepr(JsonNode value) { + return value.isTextual() ? value.asText() : pythonNested(value); + } + + private static String pythonRepr(List values) { + StringBuilder out = new StringBuilder("["); + for (int i = 0; i < values.size(); i++) { + out.append(i == 0 ? "" : ", ").append('\'').append(values.get(i)).append('\''); + } + return out.append(']').toString(); + } + + private static String pythonNested(JsonNode value) { + if (value.isMissingNode() || value.isNull()) { + return "None"; + } + if (value.isTextual()) { + return "'" + value.asText() + "'"; + } + if (value.isBoolean()) { + return value.asBoolean() ? "True" : "False"; + } + if (value.isArray()) { + List items = new ArrayList<>(); + value.forEach(item -> items.add(pythonNested(item))); + return "[" + String.join(", ", items) + "]"; + } + if (value.isObject()) { + List entries = new ArrayList<>(); + value.properties().forEach(entry -> entries.add("'" + entry.getKey() + "': " + pythonNested(entry.getValue()))); + return "{" + String.join(", ", entries) + "}"; + } + return value.asText(); + } + + private static AwsException invalidResource(String logicalId, String reason) { + return new AwsException("ValidationError", "Resource with id [" + logicalId + "] is invalid. " + reason, 400); + } + + private ObjectNode createExecutionRole(JsonNode properties, List inlinePolicies) { ObjectNode roleDef = objectMapper.createObjectNode(); roleDef.put("Type", "AWS::IAM::Role"); @@ -1031,6 +1403,9 @@ class SamTransformProcessor { managedPolicies.add(userPolicies.asText()); } roleProps.set("ManagedPolicyArns", managedPolicies); + if (!inlinePolicies.isEmpty()) { + roleProps.set("Policies", objectMapper.createArrayNode().addAll(inlinePolicies)); + } roleDef.set("Properties", roleProps); return roleDef; @@ -1542,8 +1917,7 @@ class SamTransformProcessor { } else { reason = "Type of property 'DefinitionUri' is invalid."; } - throw new AwsException("ValidationError", - "Resource with id [" + logicalId + "] is invalid. " + reason, 400); + throw invalidResource(logicalId, reason); } /** Copies {@code source.} to {@code target.} when present and non-null. */ 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 index b37b0308dd..da2f050a1f 100644 --- 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 @@ -124,9 +124,11 @@ public class LambdaEventInvokeConfigCfnProvisioner implements CfnResourceProvisi if (eventAge != null) { settings.put("MaximumEventAgeInSeconds", eventAge); } + // AWS::NoValue drops a Destination rather than resolving to an empty one, so a destination + // left without one fails below as the registry schema requires. JsonNode destinations = props == null || !props.hasNonNull("DestinationConfig") ? null - : ctx.engine().resolveNode(props.get("DestinationConfig")); + : ctx.engine().resolveNodeOmittingNoValue(props.get("DestinationConfig")); if (destinations != null && destinations.isObject()) { settings.put("DestinationConfig", destinationConfig(destinations)); } diff --git a/src/main/java/io/github/hectorvent/floci/services/ec2/Ec2KeyMaterial.java b/src/main/java/io/github/hectorvent/floci/services/ec2/Ec2KeyMaterial.java index 4a6a94bc16..1f65917ea3 100644 --- a/src/main/java/io/github/hectorvent/floci/services/ec2/Ec2KeyMaterial.java +++ b/src/main/java/io/github/hectorvent/floci/services/ec2/Ec2KeyMaterial.java @@ -8,7 +8,6 @@ import java.io.IOException; import java.io.StringWriter; import java.nio.charset.StandardCharsets; import java.security.KeyPairGenerator; -import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.security.interfaces.RSAPublicKey; import java.util.Base64; @@ -58,8 +57,7 @@ public final class Ec2KeyMaterial { // "The SHA-1 digest of the DER encoded private key" for a key pair AWS created. // (Imported keys use the MD5 of the public key instead -- see fingerprintOf.) - String fingerprint = colonHex( - MessageDigest.getInstance("SHA-1").digest(pair.getPrivate().getEncoded())); + String fingerprint = colonHex(Digests.sha1(pair.getPrivate().getEncoded())); return new Generated( out.toString(), diff --git a/src/main/java/io/github/hectorvent/floci/services/iam/SAMLAssertionVerifier.java b/src/main/java/io/github/hectorvent/floci/services/iam/SAMLAssertionVerifier.java index de82f5e555..dc0f6a7ccc 100644 --- a/src/main/java/io/github/hectorvent/floci/services/iam/SAMLAssertionVerifier.java +++ b/src/main/java/io/github/hectorvent/floci/services/iam/SAMLAssertionVerifier.java @@ -2,6 +2,7 @@ package io.github.hectorvent.floci.services.iam; import io.github.hectorvent.floci.core.common.AwsArnUtils; import io.github.hectorvent.floci.core.common.AwsRegionFacts; +import io.github.hectorvent.floci.core.common.Digests; import io.github.hectorvent.floci.services.iam.model.SAMLProvider; import org.w3c.dom.Document; import org.w3c.dom.Element; @@ -14,7 +15,6 @@ import javax.xml.crypto.dsig.XMLSignatureFactory; import javax.xml.crypto.dsig.dom.DOMValidateContext; import java.io.ByteArrayInputStream; import java.nio.charset.StandardCharsets; -import java.security.MessageDigest; import java.security.cert.CertificateFactory; import java.security.cert.X509Certificate; import java.time.Instant; @@ -167,8 +167,8 @@ final class SAMLAssertionVerifier { if (roles.isEmpty()) { throw invalid("role pair missing"); } - String nameQualifier = java.util.Base64.getEncoder().encodeToString(MessageDigest.getInstance("SHA-1") - .digest((issuer + provider.getArn()).getBytes(StandardCharsets.UTF_8))); + String nameQualifier = java.util.Base64.getEncoder().encodeToString( + Digests.sha1((issuer + provider.getArn()).getBytes(StandardCharsets.UTF_8))); return new Verified(issuer, name, subjectType, nameQualifier, notOnOrAfter, roles); } catch (InvalidAssertionException e) { throw e; diff --git a/src/test/java/io/github/hectorvent/floci/core/common/DigestsTest.java b/src/test/java/io/github/hectorvent/floci/core/common/DigestsTest.java index 5d4665e18e..f7f1e33618 100644 --- a/src/test/java/io/github/hectorvent/floci/core/common/DigestsTest.java +++ b/src/test/java/io/github/hectorvent/floci/core/common/DigestsTest.java @@ -9,8 +9,20 @@ import static org.junit.jupiter.api.Assertions.assertEquals; class DigestsTest { + private static final String ABC_SHA1 = "a9993e364706816aba3e25717850c26c9cd0d89d"; private static final String ABC_SHA256 = "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad"; + @Test + void sha1MatchesTheFipsTestVector() { + assertEquals(ABC_SHA1, HexFormat.of().formatHex(Digests.sha1("abc".getBytes(StandardCharsets.UTF_8)))); + } + + @Test + void sha1HexOfTextDigestsItsUtf8Bytes() { + assertEquals(ABC_SHA1, Digests.sha1Hex("abc")); + assertEquals(HexFormat.of().formatHex(Digests.sha1("é".getBytes(StandardCharsets.UTF_8))), Digests.sha1Hex("é")); + } + @Test void sha256MatchesTheFipsTestVector() { assertEquals(ABC_SHA256, HexFormat.of().formatHex(Digests.sha256("abc".getBytes(StandardCharsets.UTF_8)))); diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationResourceConditionIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationResourceConditionIntegrationTest.java index d5c0c56f03..ba046b329b 100644 --- a/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationResourceConditionIntegrationTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationResourceConditionIntegrationTest.java @@ -19,6 +19,49 @@ class CloudFormationResourceConditionIntegrationTest { RestAssuredJsonUtils.configureAwsContentTypes(); } + /** + * A condition naming another with anything but a string is a template error, which + * CloudFormation (measured in us-east-2) answers synchronously on CreateStack. The malformed + * operand comes first in an Fn::And, where evaluation alone would stop and read it as false. + */ + @Test + void aConditionReferenceThatIsNotAStringIsATemplateError() { + String template = """ + { + "Conditions": { + "Deploy": { "Fn::Equals": ["a", "a"] }, + "Other": { "Fn::Equals": ["a", "b"] }, + "Both": { "Fn::And": [ { "Condition": { "Condition": "Deploy" } }, { "Condition": "Other" } ] } + }, + "Resources": { + "Queue": { "Type": "AWS::SQS::Queue", "Condition": "Both" }, + "Always": { "Type": "AWS::SQS::Queue" } + } + } + """; + String stackName = "cfn-cond-malformed-" + Long.toString(System.nanoTime(), 36); + + given() + .contentType("application/x-www-form-urlencoded") + .formParam("Action", "CreateStack") + .formParam("StackName", stackName) + .formParam("TemplateBody", template) + .when() + .post("/") + .then() + .statusCode(400) + .body(containsString("ValidationError")) + .body(containsString("Template error: every Condition object must have a single String value.")); + given() + .contentType("application/x-www-form-urlencoded") + .formParam("Action", "DescribeStacks") + .formParam("StackName", stackName) + .when() + .post("/") + .then() + .statusCode(400); + } + @Test void createStack_skipsResourceWhenResourceLevelConditionIsFalse() { String suffix = Long.toString(System.nanoTime(), 36); diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationSamEventInvokeConfigIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationSamEventInvokeConfigIntegrationTest.java new file mode 100644 index 0000000000..36b6603d89 --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationSamEventInvokeConfigIntegrationTest.java @@ -0,0 +1,421 @@ +package io.github.hectorvent.floci.services.cloudformation; + +import io.github.hectorvent.floci.testing.RestAssuredJsonUtils; +import io.quarkus.test.junit.QuarkusTest; +import io.restassured.path.xml.XmlPath; +import io.restassured.response.ValidatableResponse; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; + +import java.util.ArrayList; +import java.util.List; + +import static io.restassured.RestAssured.given; +import static org.hamcrest.Matchers.containsString; +import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.not; +import static org.junit.jupiter.api.Assertions.assertEquals; + +/** + * A SAM function's {@code EventInvokeConfig}, deployed and read back through the Lambda and IAM + * APIs. Before this the property was dropped, so a function declaring retries and a failure + * destination deployed with Lambda's defaults and no destination at all. + */ +@QuarkusTest +class CloudFormationSamEventInvokeConfigIntegrationTest { + + /** + * A conditional function whose failure destination is itself conditional, which makes SAM's + * translator join the two conditions in a shape CloudFormation rejects. + */ + private static final String CONDITIONAL_FUNCTION_AND_DESTINATION = """ + { + "Transform": "AWS::Serverless-2016-10-31", + "Conditions": { + "Deploy": { "Fn::Equals": ["a", "a"] }, + "UseOwn": { "Fn::Equals": ["a", "b"] } + }, + "Resources": { + "Fn": { + "Type": "AWS::Serverless::Function", + "Condition": "Deploy", + "Properties": { + "Runtime": "python3.12", + "Handler": "index.handler", + "InlineCode": "def handler(e, c): return 'ok'", + "EventInvokeConfig": { "DestinationConfig": { "OnFailure": { "Type": "SQS", + "Destination": { "Fn::If": ["UseOwn", "arn:aws:sqs:us-east-1:000000000000:q", { "Ref": "AWS::NoValue" }] } } } } + } + } + } + } + """; + + private final List stacksToDelete = new ArrayList<>(); + + @BeforeAll + static void configureRestAssured() { + RestAssuredJsonUtils.configureAwsContentTypes(); + } + + @AfterEach + void deleteStacks() { + for (String stackName : stacksToDelete) { + given() + .contentType("application/x-www-form-urlencoded") + .formParam("Action", "DeleteStack") + .formParam("StackName", stackName) + .when() + .post("/"); + } + stacksToDelete.clear(); + } + + /** + * The shape kbdb's moderation function uses: two retries, six hours, and an SQS queue in the + * same template as the failure destination. The generated role may send to that queue. + */ + @Test + void retriesAgeAndAFailureQueueReachTheFunction() { + String name = "sam-eic-" + Long.toString(System.nanoTime(), 36); + createStack(name, """ + { + "Transform": "AWS::Serverless-2016-10-31", + "Resources": { + "Dlq": { "Type": "AWS::SQS::Queue", "Properties": { "QueueName": "%1$s-dlq" } }, + "Fn": { + "Type": "AWS::Serverless::Function", + "Properties": { + "FunctionName": "%1$s", + "Runtime": "python3.12", + "Handler": "index.handler", + "InlineCode": "def handler(e, c): return 'ok'", + "EventInvokeConfig": { + "MaximumRetryAttempts": 2, + "MaximumEventAgeInSeconds": 21600, + "DestinationConfig": { "OnFailure": { "Type": "SQS", "Destination": { "Fn::GetAtt": ["Dlq", "Arn"] } } } + } + } + } + } + } + """.formatted(name)); + CfnStackWaits.awaitStatus(name, "CREATE_COMPLETE"); + + String queueArn = "arn:aws:sqs:us-east-1:000000000000:" + name + "-dlq"; + given().queryParam("Qualifier", "$LATEST") + .when().get("/2019-09-25/functions/" + name + "/event-invoke-config") + .then() + .statusCode(200) + .body("MaximumRetryAttempts", equalTo(2)) + .body("MaximumEventAgeInSeconds", equalTo(21600)) + .body("DestinationConfig.OnFailure.Destination", equalTo(queueArn)); + + getRolePolicy(physicalId(name, "FnRole"), "FnEventInvokeConfigOnFailureSQSPolicy") + .body(containsString("sqs:SendMessage")) + .body(containsString(queueArn)) + .body(not(containsString("Fn::GetAtt"))); + } + + /** With AutoPublishAlias the configuration is on the alias, not on $LATEST. */ + @Test + void anAutoPublishedFunctionGetsItsConfigurationOnTheAlias() { + String name = "sam-eic-alias-" + Long.toString(System.nanoTime(), 36); + createStack(name, """ + { + "Transform": "AWS::Serverless-2016-10-31", + "Resources": { + "Fn": { + "Type": "AWS::Serverless::Function", + "Properties": { + "FunctionName": "%1$s", + "Runtime": "python3.12", + "Handler": "index.handler", + "InlineCode": "def handler(e, c): return 'ok'", + "AutoPublishAlias": "live", + "EventInvokeConfig": { "MaximumRetryAttempts": 0 } + } + } + } + } + """.formatted(name)); + CfnStackWaits.awaitStatus(name, "CREATE_COMPLETE"); + + given().queryParam("Qualifier", "live") + .when().get("/2019-09-25/functions/" + name + "/event-invoke-config") + .then() + .statusCode(200) + .body("MaximumRetryAttempts", equalTo(0)); + given().queryParam("Qualifier", "$LATEST") + .when().get("/2019-09-25/functions/" + name + "/event-invoke-config") + .then() + .statusCode(404); + } + + /** An SNS destination given only its Type gets the topic SAM creates for it. */ + @Test + void aDestinationGivenOnlyItsTypeGetsTheTopicSamCreates() { + String name = "sam-eic-topic-" + Long.toString(System.nanoTime(), 36); + createStack(name, """ + { + "Transform": "AWS::Serverless-2016-10-31", + "Resources": { + "Fn": { + "Type": "AWS::Serverless::Function", + "Properties": { + "FunctionName": "%1$s", + "Runtime": "python3.12", + "Handler": "index.handler", + "InlineCode": "def handler(e, c): return 'ok'", + "EventInvokeConfig": { "DestinationConfig": { "OnSuccess": { "Type": "SNS" } } } + } + } + } + } + """.formatted(name)); + CfnStackWaits.awaitStatus(name, "CREATE_COMPLETE"); + + String topicArn = physicalId(name, "FnEventInvokeConfigOnSuccessTopic"); + given().queryParam("Qualifier", "$LATEST") + .when().get("/2019-09-25/functions/" + name + "/event-invoke-config") + .then() + .statusCode(200) + .body("DestinationConfig.OnSuccess.Destination", equalTo(topicArn)); + getRolePolicy(physicalId(name, "FnRole"), "FnEventInvokeConfigOnSuccessSNSPolicy") + .body(containsString("sns:publish")) + .body(containsString(topicArn)); + } + + /** SAM rejects a destination Type it does not know, with its own message. */ + @Test + void anUnknownDestinationTypeFailsTheStackWithSamsMessage() { + String name = "sam-eic-badtype-" + Long.toString(System.nanoTime(), 36); + createStack(name, """ + { + "Transform": "AWS::Serverless-2016-10-31", + "Resources": { + "Fn": { + "Type": "AWS::Serverless::Function", + "Properties": { + "Runtime": "python3.12", + "Handler": "index.handler", + "InlineCode": "def handler(e, c): return 'ok'", + "EventInvokeConfig": { "DestinationConfig": { "OnFailure": { + "Type": "sqs", "Destination": "arn:aws:sqs:us-east-1:000000000000:q" } } } + } + } + } + } + """); + CfnStackWaits.StackState state = CfnStackWaits.awaitStatus(name, "CREATE_FAILED"); + + assertEquals("Resource with id [Fn] is invalid. 'Type: sqs' must be one of " + + "['SQS', 'SNS', 'EventBridge', 'Lambda', 'S3Bucket']", state.reason()); + } + + /** + * A conditional function whose destination is itself conditional: SAM's translator joins the + * two conditions with an Fn::And whose operands are {"Condition": {"Condition": name}}, and + * CloudFormation rejects the template it submits. Measured on CloudFormation (us-east-2), the + * stack fails during creation, after the transform, with this reason. + */ + @Test + void aConditionalFunctionWithAConditionalDestinationFailsAsOnAws() { + String name = "sam-eic-and-" + Long.toString(System.nanoTime(), 36); + createStack(name, CONDITIONAL_FUNCTION_AND_DESTINATION); + CfnStackWaits.StackState state = CfnStackWaits.awaitStatus(name, "CREATE_FAILED"); + + assertEquals("Template error: every Condition object must have a single String value.", state.reason()); + } + + /** + * The same template through a change set, as {@code sam deploy} submits it. Measured on + * CloudFormation (us-east-2): the change set is FAILED, not executable, with the template error + * as its reason, and DescribeChangeSet answers normally rather than with an error. + */ + @Test + void theSameTemplateFailsItsChangeSetWithTheTemplateError() { + String name = "sam-eic-cs-" + Long.toString(System.nanoTime(), 36); + stacksToDelete.add(name); + given() + .contentType("application/x-www-form-urlencoded") + .formParam("Action", "CreateChangeSet") + .formParam("StackName", name) + .formParam("ChangeSetName", "deploy") + .formParam("ChangeSetType", "CREATE") + .formParam("TemplateBody", CONDITIONAL_FUNCTION_AND_DESTINATION) + .formParam("Capabilities.member.1", "CAPABILITY_IAM") + .when() + .post("/") + .then() + .statusCode(200); + + XmlPath changeSet = given() + .contentType("application/x-www-form-urlencoded") + .formParam("Action", "DescribeChangeSet") + .formParam("StackName", name) + .formParam("ChangeSetName", "deploy") + .when().post("/").then().statusCode(200).extract().xmlPath(); + assertEquals("FAILED", changeSet.getString("**.find { it.name() == 'Status' }")); + assertEquals("UNAVAILABLE", changeSet.getString("**.find { it.name() == 'ExecutionStatus' }")); + assertEquals("Template error: every Condition object must have a single String value.", + changeSet.getString("**.find { it.name() == 'StatusReason' }")); + } + + /** A Type given as a parameter reference takes the value the stack is given over the Default. */ + @Test + void aParameterTypeTakesTheValueTheStackIsGiven() { + String name = "sam-eic-param-" + Long.toString(System.nanoTime(), 36); + stacksToDelete.add(name); + given() + .contentType("application/x-www-form-urlencoded") + .formParam("Action", "CreateStack") + .formParam("StackName", name) + .formParam("TemplateBody", """ + { + "Transform": "AWS::Serverless-2016-10-31", + "Parameters": { "DestType": { "Type": "String", "Default": "SQS" } }, + "Resources": { + "Fn": { + "Type": "AWS::Serverless::Function", + "Properties": { + "FunctionName": "%1$s", + "Runtime": "python3.12", + "Handler": "index.handler", + "InlineCode": "def handler(e, c): return 'ok'", + "EventInvokeConfig": { "DestinationConfig": { "OnFailure": { "Type": { "Ref": "DestType" } } } } + } + } + } + } + """.formatted(name)) + .formParam("Parameters.member.1.ParameterKey", "DestType") + .formParam("Parameters.member.1.ParameterValue", "SNS") + .formParam("Capabilities.member.1", "CAPABILITY_IAM") + .when() + .post("/") + .then() + .statusCode(200); + CfnStackWaits.awaitStatus(name, "CREATE_COMPLETE"); + + String topicArn = physicalId(name, "FnEventInvokeConfigOnFailureTopic"); + given().queryParam("Qualifier", "$LATEST") + .when().get("/2019-09-25/functions/" + name + "/event-invoke-config") + .then() + .statusCode(200) + .body("DestinationConfig.OnFailure.Destination", equalTo(topicArn)); + } + + /** + * CloudFormation resolves an AWS::SSM::Parameter::Value parameter before it runs the + * transform, so SAM reads the stored value. Measured on CloudFormation (us-east-2): a Type + * taken from such a parameter holding SNS creates the topic and makes it the destination. + */ + @Test + void aTypeFromAnSsmParameterUsesTheStoredValue() { + String name = "sam-eic-ssm-" + Long.toString(System.nanoTime(), 36); + String parameterName = "/" + name + "/dest-type"; + given() + .contentType("application/x-amz-json-1.1") + .header("X-Amz-Target", "AmazonSSM.PutParameter") + .body("{\"Name\": \"" + parameterName + "\", \"Type\": \"String\", \"Value\": \"SNS\"}") + .when() + .post("/") + .then() + .statusCode(200); + createStack(name, """ + { + "Transform": "AWS::Serverless-2016-10-31", + "Parameters": { "DestType": { "Type": "AWS::SSM::Parameter::Value", "Default": "%2$s" } }, + "Resources": { + "Fn": { + "Type": "AWS::Serverless::Function", + "Properties": { + "FunctionName": "%1$s", + "Runtime": "python3.12", + "Handler": "index.handler", + "InlineCode": "def handler(e, c): return 'ok'", + "EventInvokeConfig": { "DestinationConfig": { "OnFailure": { "Type": { "Ref": "DestType" } } } } + } + } + } + } + """.formatted(name, parameterName)); + CfnStackWaits.awaitStatus(name, "CREATE_COMPLETE"); + + String topicArn = physicalId(name, "FnEventInvokeConfigOnFailureTopic"); + given().queryParam("Qualifier", "$LATEST") + .when().get("/2019-09-25/functions/" + name + "/event-invoke-config") + .then() + .statusCode(200) + .body("DestinationConfig.OnFailure.Destination", equalTo(topicArn)); + } + + /** + * A Destination of AWS::NoValue passes through SAM unchanged and leaves the destination without + * an ARN. Measured on CloudFormation (us-east-2): the stack fails validation instead of + * creating a configuration with an empty destination. + */ + @Test + void aNoValueDestinationFailsTheStackInsteadOfStoringAnEmptyOne() { + String name = "sam-eic-novalue-" + Long.toString(System.nanoTime(), 36); + createStack(name, """ + { + "Transform": "AWS::Serverless-2016-10-31", + "Resources": { + "Fn": { + "Type": "AWS::Serverless::Function", + "Properties": { + "FunctionName": "%s", + "Runtime": "python3.12", + "Handler": "index.handler", + "InlineCode": "def handler(e, c): return 'ok'", + "EventInvokeConfig": { "DestinationConfig": { "OnFailure": { "Type": "SQS", "Destination": { "Ref": "AWS::NoValue" } } } } + } + } + } + } + """.formatted(name)); + CfnStackWaits.StackState state = CfnStackWaits.awaitStatus(name, "ROLLBACK_COMPLETE"); + + given().queryParam("Qualifier", "$LATEST") + .when().get("/2019-09-25/functions/" + name + "/event-invoke-config") + .then() + .statusCode(404); + assertEquals("ROLLBACK_COMPLETE", state.status()); + } + + private void createStack(String stackName, String template) { + stacksToDelete.add(stackName); + given() + .contentType("application/x-www-form-urlencoded") + .formParam("Action", "CreateStack") + .formParam("StackName", stackName) + .formParam("TemplateBody", template) + .formParam("Capabilities.member.1", "CAPABILITY_IAM") + .when() + .post("/") + .then() + .statusCode(200); + } + + private static String physicalId(String stackName, String logicalId) { + XmlPath xml = given() + .contentType("application/x-www-form-urlencoded") + .formParam("Action", "DescribeStackResource") + .formParam("StackName", stackName) + .formParam("LogicalResourceId", logicalId) + .when().post("/").then().statusCode(200).extract().xmlPath(); + return xml.getString("**.find { it.name() == 'PhysicalResourceId' }"); + } + + private static ValidatableResponse getRolePolicy(String roleName, String policyName) { + return given() + .contentType("application/x-www-form-urlencoded") + .formParam("Action", "GetRolePolicy") + .formParam("RoleName", roleName) + .formParam("PolicyName", policyName) + .when().post("/").then().statusCode(200); + } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/SamEventInvokeConfigTransformTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/SamEventInvokeConfigTransformTest.java new file mode 100644 index 0000000000..1350ed148a --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/SamEventInvokeConfigTransformTest.java @@ -0,0 +1,236 @@ +package io.github.hectorvent.floci.services.cloudformation; + +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 org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; + +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.stream.Stream; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +/** + * A SAM function's {@code EventInvokeConfig}, expanded as AWS's own SAM translator expands it. + * + *

Each fixture under {@code src/test/resources/cloudformation/sam-event-invoke-config} holds a + * template and what aws-sam-translator 1.115.0 (the library behind {@code sam deploy} and the + * {@code AWS::Serverless-2016-10-31} transform) generated from it: the + * {@code FnEventInvokeConfig*} resources, the generated role's attributes and inline policies, and + * any conditions it added, or the error it rejected the template with. They were produced with + * {@code samtranslator.translator.transform.transform(template, {}, loader)}, a loader whose + * {@code load()} returns {@code {}}. + */ +class SamEventInvokeConfigTransformTest { + + private static final Path FIXTURES = Path.of("src/test/resources/cloudformation/sam-event-invoke-config"); + + private final ObjectMapper mapper = new ObjectMapper(); + private final SamTransformProcessor processor = new SamTransformProcessor(mapper); + + static Stream fixtures() throws IOException { + try (Stream files = Files.list(FIXTURES)) { + return files.map(file -> file.getFileName().toString()) + .filter(name -> name.endsWith(".json")) + .sorted() + .toList() + .stream(); + } + } + + @ParameterizedTest(name = "{0}") + @MethodSource("fixtures") + void matchesTheSamTranslator(String fixtureName) throws IOException { + JsonNode fixture = mapper.readTree(FIXTURES.resolve(fixtureName).toFile()); + JsonNode input = fixture.path("input"); + + if (fixture.has("error")) { + AwsException e = assertThrows(AwsException.class, () -> processor.expandSamTemplate(input)); + assertEquals("ValidationError", e.getErrorCode()); + assertEquals(fixture.path("error").asText(), e.getMessage()); + return; + } + + JsonNode expanded = processor.expandSamTemplate(input); + JsonNode resources = expanded.path("Resources"); + JsonNode expected = fixture.path("expected"); + + List generated = new ArrayList<>(); + resources.fieldNames().forEachRemaining(id -> { + if (id.startsWith("FnEventInvokeConfig")) { + generated.add(id); + } + }); + List expectedIds = new ArrayList<>(); + expected.fieldNames().forEachRemaining(id -> { + if (id.startsWith("FnEventInvokeConfig")) { + expectedIds.add(id); + } + }); + assertEquals(expectedIds.stream().sorted().toList(), generated.stream().sorted().toList(), + "the resources SAM generates for EventInvokeConfig"); + for (String id : expectedIds) { + assertEquals(withFlociAliasId(expected.path(id), resources), resources.path(id), id); + } + + JsonNode expectedRole = expected.path("FnRole"); + JsonNode role = resources.path("FnRole"); + if (expectedRole.isMissingNode()) { + assertTrue(role.isMissingNode(), "a function with its own Role gets no generated role"); + } else { + assertEquals(expectedRole.path("Condition"), role.path("Condition"), "the role's Condition"); + JsonNode expectedPolicies = expectedRole.path("Policies"); + JsonNode policies = role.path("Properties").path("Policies"); + if (expectedPolicies.isNull() || expectedPolicies.isMissingNode()) { + assertTrue(policies.isMissingNode(), "no inline policies: " + policies); + } else { + assertEquals(expectedPolicies, policies, "the role's inline policies"); + } + } + + // SAM passes the function's Condition, DeletionPolicy and UpdateReplacePolicy to the alias + // and version AutoPublishAlias generates as well. Only what the function declares is + // checked: SAM also retains every published version on its own (DeletionPolicy: Retain), + // which floci's AutoPublishAlias expansion has never done and this change does not touch. + JsonNode function = input.path("Resources").path("Fn"); + for (Map.Entry byType : fixture.path("expectedAttributesByType").properties()) { + JsonNode generatedResource = null; + for (Map.Entry resource : resources.properties()) { + if (byType.getKey().equals(resource.getValue().path("Type").asText())) { + generatedResource = resource.getValue(); + } + } + for (Map.Entry attribute : byType.getValue().properties()) { + if (function.has(attribute.getKey())) { + assertEquals(attribute.getValue(), generatedResource.path(attribute.getKey()), + byType.getKey() + " " + attribute.getKey()); + } + } + } + + JsonNode inputConditions = input.path("Conditions"); + JsonNode expectedConditions = fixture.path("expectedConditions"); + List added = new ArrayList<>(); + expanded.path("Conditions").fieldNames().forEachRemaining(name -> { + if (!inputConditions.has(name)) { + added.add(name); + } + }); + List expectedAdded = new ArrayList<>(); + expectedConditions.fieldNames().forEachRemaining(expectedAdded::add); + assertEquals(expectedAdded.stream().sorted().toList(), added.stream().sorted().toList(), + "the conditions SAM adds"); + for (Map.Entry condition : expectedConditions.properties()) { + assertEquals(condition.getValue(), expanded.path("Conditions").path(condition.getKey()), + condition.getKey()); + } + } + + /** + * The expected resource with a {@code DependsOn} on SAM's alias id replaced by floci's. SAM + * names an {@code AutoPublishAlias} alias {@code FnAlias} with the name as written; floci + * capitalises it ({@code FnAliasLive}), which predates this expansion and would rename the alias + * in existing stacks if changed. The configuration must depend on the alias floci creates. + */ + private JsonNode withFlociAliasId(JsonNode expected, JsonNode resources) { + if (!expected.path("DependsOn").isArray()) { + return expected; + } + String flociAlias = null; + for (Map.Entry resource : resources.properties()) { + if ("AWS::Lambda::Alias".equals(resource.getValue().path("Type").asText())) { + flociAlias = resource.getKey(); + } + } + ObjectNode copy = expected.deepCopy(); + copy.set("DependsOn", mapper.createArrayNode().add(flociAlias)); + return copy; + } + + /** Without the property nothing changes: no configuration, and the generated role carries no inline policies. */ + @Test + void aFunctionWithoutEventInvokeConfigGetsNoneAndAnUnchangedRole() throws IOException { + JsonNode expanded = processor.expandSamTemplate(mapper.readTree(""" + {"Transform": "AWS::Serverless-2016-10-31", + "Resources": {"Fn": {"Type": "AWS::Serverless::Function", + "Properties": {"Runtime": "python3.12", "Handler": "index.handler", "CodeUri": "s3://b/k"}}}} + """)); + + assertTrue(expanded.path("Resources").path("FnEventInvokeConfig").isMissingNode()); + assertTrue(expanded.path("Resources").path("FnRole").path("Properties").path("Policies").isMissingNode()); + assertTrue(expanded.path("Resources").path("FnRole").path("Condition").isMissingNode()); + assertFalse(expanded.has("Conditions"), "no Conditions section is added when none is needed"); + } + + private static final String TYPE_FROM_PARAMETER = """ + {"Transform": "AWS::Serverless-2016-10-31", + "Parameters": {"DestType": {"Type": "String" %s}}, + "Resources": {"Fn": {"Type": "AWS::Serverless::Function", + "Properties": {"Runtime": "python3.12", "Handler": "index.handler", "CodeUri": "s3://b/k", + "EventInvokeConfig": {"DestinationConfig": {"OnFailure": {"Type": {"Ref": "DestType"}}}}}}}} + """; + + /** SAM resolves a parameter reference to the value the stack is given before its Default. */ + @Test + void aTypeFromAParameterTakesTheGivenValueOverTheDefault() throws IOException { + JsonNode expanded = processor.expandSamTemplate( + mapper.readTree(TYPE_FROM_PARAMETER.formatted(", \"Default\": \"SQS\"")), Map.of("DestType", "SNS")); + + assertEquals("AWS::SNS::Topic", + expanded.path("Resources").path("FnEventInvokeConfigOnFailureTopic").path("Type").asText()); + assertTrue(expanded.path("Resources").path("FnEventInvokeConfigOnFailureQueue").isMissingNode()); + } + + @Test + void aTypeFromAParameterWithoutADefaultTakesTheGivenValue() throws IOException { + JsonNode expanded = processor.expandSamTemplate( + mapper.readTree(TYPE_FROM_PARAMETER.formatted("")), Map.of("DestType", "SQS")); + + assertEquals("AWS::SQS::Queue", + expanded.path("Resources").path("FnEventInvokeConfigOnFailureQueue").path("Type").asText()); + } + + /** An Fn::If whose condition is not a name is passed through as given, not read as a conditional destination. */ + @Test + void anFnIfWithoutAConditionNameIsPassedThroughAsGiven() throws IOException { + JsonNode expanded = processor.expandSamTemplate(mapper.readTree(""" + {"Transform": "AWS::Serverless-2016-10-31", + "Resources": {"Fn": {"Type": "AWS::Serverless::Function", + "Properties": {"Runtime": "python3.12", "Handler": "index.handler", "CodeUri": "s3://b/k", + "EventInvokeConfig": {"DestinationConfig": {"OnFailure": {"Type": "SQS", + "Destination": {"Fn::If": [{"Ref": "X"}, {"Ref": "AWS::NoValue"}, "arn:aws:sqs:us-east-1:123456789012:q"]}}}}}}}} + """)); + + JsonNode resources = expanded.path("Resources"); + assertTrue(resources.path("FnEventInvokeConfigOnFailureQueue").isMissingNode(), "no queue is created"); + assertEquals(mapper.readTree(""" + {"Fn::If": [{"Ref": "X"}, {"Ref": "AWS::NoValue"}, "arn:aws:sqs:us-east-1:123456789012:q"]} + """), resources.path("FnEventInvokeConfig").path("Properties").path("DestinationConfig") + .path("OnFailure").path("Destination")); + assertFalse(expanded.has("Conditions"), "no condition is generated"); + } + + /** An empty EventInvokeConfig is falsy to SAM, which then generates nothing for it. */ + @Test + void anEmptyEventInvokeConfigGeneratesNothing() throws IOException { + JsonNode expanded = processor.expandSamTemplate(mapper.readTree(""" + {"Transform": "AWS::Serverless-2016-10-31", + "Resources": {"Fn": {"Type": "AWS::Serverless::Function", + "Properties": {"Runtime": "python3.12", "Handler": "index.handler", "CodeUri": "s3://b/k", + "EventInvokeConfig": {}}}}} + """)); + + assertTrue(expanded.path("Resources").path("FnEventInvokeConfig").isMissingNode()); + } +} 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 index 2297e936ee..7d9e932769 100644 --- 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 @@ -2,7 +2,8 @@ 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 com.fasterxml.jackson.databind.node.MissingNode; +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; @@ -60,6 +61,7 @@ class LambdaEventInvokeConfigCfnProvisionerTest { return node == null || node.isMissingNode() || node.isNull() ? null : node.asText(); }); when(engine.resolveNode(any())).thenAnswer(i -> i.getArgument(0)); + when(engine.resolveNodeOmittingNoValue(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())) @@ -421,9 +423,9 @@ class LambdaEventInvokeConfigCfnProvisionerTest { /** 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 -> { + when(engine.resolveNodeOmittingNoValue(any())).thenAnswer(i -> { JsonNode node = i.getArgument(0); - return node.has("Ref") ? TextNode.valueOf("") : node; + return node.has("Ref") ? MissingNode.getInstance() : node; }); provision(""" @@ -438,10 +440,10 @@ class LambdaEventInvokeConfigCfnProvisionerTest { @Test void aDestinationSideResolvingToNoValueIsNotSent() { - when(engine.resolveNode(any())).thenAnswer(i -> { + when(engine.resolveNodeOmittingNoValue(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("")); + ((ObjectNode) node).remove("OnSuccess"); } return node; }); @@ -458,6 +460,31 @@ class LambdaEventInvokeConfigCfnProvisionerTest { request.getValue().get("DestinationConfig")); } + /** + * A Destination that resolves to AWS::NoValue leaves its side without one, which the registry + * schema does not allow. CloudFormation fails such a template's validation rather than + * creating a configuration with an empty destination. + */ + @Test + void aDestinationResolvingToNoValueIsRejectedRatherThanSentEmpty() { + when(engine.resolveNodeOmittingNoValue(any())).thenAnswer(i -> { + JsonNode node = i.getArgument(0); + JsonNode onFailure = node.path("OnFailure"); + if (onFailure.isObject() && onFailure.path("Destination").has("Ref")) { + ((ObjectNode) onFailure).remove("Destination"); + } + return node; + }); + + AwsException e = assertThrows(AwsException.class, () -> provision(""" + {"FunctionName": "orders", "Qualifier": "$LATEST", + "DestinationConfig": {"OnFailure": {"Destination": {"Ref": "AWS::NoValue"}}}} + """, null)); + + assertTrue(e.getMessage().contains("DestinationConfig.OnFailure requires Destination"), e.getMessage()); + verify(lambda, never()).putEventInvokeConfig(anyString(), anyString(), anyString(), any()); + } + private static FunctionEventInvokeConfig config(Integer retries, Integer eventAge, String onSuccess, String onFailure) { FunctionEventInvokeConfig config = new FunctionEventInvokeConfig(); diff --git a/src/test/resources/cloudformation/sam-event-invoke-config/auto-publish-alias.json b/src/test/resources/cloudformation/sam-event-invoke-config/auto-publish-alias.json new file mode 100644 index 0000000000..8745bb8f0d --- /dev/null +++ b/src/test/resources/cloudformation/sam-event-invoke-config/auto-publish-alias.json @@ -0,0 +1,85 @@ +{ + "expected": { + "FnEventInvokeConfig": { + "DependsOn": [ + "FnAliaslive" + ], + "Properties": { + "DestinationConfig": { + "OnFailure": { + "Destination": { + "Fn::GetAtt": [ + "Dlq", + "Arn" + ] + } + } + }, + "FunctionName": { + "Ref": "Fn" + }, + "MaximumRetryAttempts": 0, + "Qualifier": "live" + }, + "Type": "AWS::Lambda::EventInvokeConfig" + }, + "FnRole": { + "Policies": [ + { + "PolicyDocument": { + "Statement": [ + { + "Action": "sqs:SendMessage", + "Effect": "Allow", + "Resource": { + "Fn::GetAtt": [ + "Dlq", + "Arn" + ] + } + } + ] + }, + "PolicyName": "FnEventInvokeConfigOnFailureSQSPolicy" + } + ], + "Type": "AWS::IAM::Role" + } + }, + "expectedAttributesByType": { + "AWS::Lambda::Version": { + "DeletionPolicy": "Retain" + } + }, + "input": { + "Resources": { + "Dlq": { + "Type": "AWS::SQS::Queue" + }, + "Fn": { + "Properties": { + "AutoPublishAlias": "live", + "CodeUri": "s3://b/k", + "EventInvokeConfig": { + "DestinationConfig": { + "OnFailure": { + "Destination": { + "Fn::GetAtt": [ + "Dlq", + "Arn" + ] + }, + "Type": "SQS" + } + }, + "MaximumRetryAttempts": 0 + }, + "Handler": "index.handler", + "Runtime": "python3.12" + }, + "Type": "AWS::Serverless::Function" + } + }, + "Transform": "AWS::Serverless-2016-10-31" + } +} diff --git a/src/test/resources/cloudformation/sam-event-invoke-config/empty-destination-config.json b/src/test/resources/cloudformation/sam-event-invoke-config/empty-destination-config.json new file mode 100644 index 0000000000..36f20674db --- /dev/null +++ b/src/test/resources/cloudformation/sam-event-invoke-config/empty-destination-config.json @@ -0,0 +1,36 @@ +{ + "expected": { + "FnEventInvokeConfig": { + "Properties": { + "DestinationConfig": {}, + "FunctionName": { + "Ref": "Fn" + }, + "MaximumEventAgeInSeconds": 60, + "Qualifier": "$LATEST" + }, + "Type": "AWS::Lambda::EventInvokeConfig" + }, + "FnRole": { + "Policies": null, + "Type": "AWS::IAM::Role" + } + }, + "input": { + "Resources": { + "Fn": { + "Properties": { + "CodeUri": "s3://b/k", + "EventInvokeConfig": { + "DestinationConfig": {}, + "MaximumEventAgeInSeconds": 60 + }, + "Handler": "index.handler", + "Runtime": "python3.12" + }, + "Type": "AWS::Serverless::Function" + } + }, + "Transform": "AWS::Serverless-2016-10-31" + } +} diff --git a/src/test/resources/cloudformation/sam-event-invoke-config/error-collision-config.json b/src/test/resources/cloudformation/sam-event-invoke-config/error-collision-config.json new file mode 100644 index 0000000000..0923ef01a0 --- /dev/null +++ b/src/test/resources/cloudformation/sam-event-invoke-config/error-collision-config.json @@ -0,0 +1,22 @@ +{ + "error": "Transforming resource with id [Fn] attempts to create a new resource with id [FnEventInvokeConfig] and type \"AWS::Lambda::EventInvokeConfig\". A resource with that id already exists within this template. Please use a different id for that resource.", + "input": { + "Resources": { + "Fn": { + "Properties": { + "CodeUri": "s3://b/k", + "EventInvokeConfig": { + "MaximumRetryAttempts": 1 + }, + "Handler": "index.handler", + "Runtime": "python3.12" + }, + "Type": "AWS::Serverless::Function" + }, + "FnEventInvokeConfig": { + "Type": "AWS::SQS::Queue" + } + }, + "Transform": "AWS::Serverless-2016-10-31" + } +} diff --git a/src/test/resources/cloudformation/sam-event-invoke-config/error-collision-queue.json b/src/test/resources/cloudformation/sam-event-invoke-config/error-collision-queue.json new file mode 100644 index 0000000000..8e33bdd9bc --- /dev/null +++ b/src/test/resources/cloudformation/sam-event-invoke-config/error-collision-queue.json @@ -0,0 +1,29 @@ +{ + "error": "Transforming resource with id [Fn] attempts to create a new resource with id [FnEventInvokeConfigOnFailureQueue] and type \"AWS::SQS::Queue\". A resource with that id already exists within this template. Please use a different id for that resource.", + "input": { + "Resources": { + "Fn": { + "Properties": { + "CodeUri": "s3://b/k", + "EventInvokeConfig": { + "DestinationConfig": { + "OnFailure": { + "Type": "SQS" + } + } + }, + "Handler": "index.handler", + "Runtime": "python3.12" + }, + "Type": "AWS::Serverless::Function" + }, + "FnEventInvokeConfigOnFailureQueue": { + "Properties": { + "QueueName": "mine" + }, + "Type": "AWS::SQS::Queue" + } + }, + "Transform": "AWS::Serverless-2016-10-31" + } +} diff --git a/src/test/resources/cloudformation/sam-event-invoke-config/error-destination-config-not-map.json b/src/test/resources/cloudformation/sam-event-invoke-config/error-destination-config-not-map.json new file mode 100644 index 0000000000..04a13c247a --- /dev/null +++ b/src/test/resources/cloudformation/sam-event-invoke-config/error-destination-config-not-map.json @@ -0,0 +1,19 @@ +{ + "error": "Resource with id [Fn] is invalid. Property 'EventInvokeConfig.DestinationConfig' should be a map.", + "input": { + "Resources": { + "Fn": { + "Properties": { + "CodeUri": "s3://b/k", + "EventInvokeConfig": { + "DestinationConfig": "nope" + }, + "Handler": "index.handler", + "Runtime": "python3.12" + }, + "Type": "AWS::Serverless::Function" + } + }, + "Transform": "AWS::Serverless-2016-10-31" + } +} diff --git a/src/test/resources/cloudformation/sam-event-invoke-config/error-event-invoke-config-not-map.json b/src/test/resources/cloudformation/sam-event-invoke-config/error-event-invoke-config-not-map.json new file mode 100644 index 0000000000..8e75a7c4a8 --- /dev/null +++ b/src/test/resources/cloudformation/sam-event-invoke-config/error-event-invoke-config-not-map.json @@ -0,0 +1,17 @@ +{ + "error": "Resource with id [Fn] is invalid. Property 'EventInvokeConfig' should be a map.", + "input": { + "Resources": { + "Fn": { + "Properties": { + "CodeUri": "s3://b/k", + "EventInvokeConfig": "oops", + "Handler": "index.handler", + "Runtime": "python3.12" + }, + "Type": "AWS::Serverless::Function" + } + }, + "Transform": "AWS::Serverless-2016-10-31" + } +} diff --git a/src/test/resources/cloudformation/sam-event-invoke-config/error-intrinsic-type-no-default.json b/src/test/resources/cloudformation/sam-event-invoke-config/error-intrinsic-type-no-default.json new file mode 100644 index 0000000000..b734b8e0fa --- /dev/null +++ b/src/test/resources/cloudformation/sam-event-invoke-config/error-intrinsic-type-no-default.json @@ -0,0 +1,31 @@ +{ + "error": "Resource with id [Fn] is invalid. 'Type: {'Ref': 'DestType'}' must be one of ['SQS', 'SNS', 'EventBridge', 'Lambda', 'S3Bucket']", + "input": { + "Parameters": { + "DestType": { + "Type": "String" + } + }, + "Resources": { + "Fn": { + "Properties": { + "CodeUri": "s3://b/k", + "EventInvokeConfig": { + "DestinationConfig": { + "OnFailure": { + "Destination": "arn:aws:sqs:us-east-1:123456789012:q", + "Type": { + "Ref": "DestType" + } + } + } + }, + "Handler": "index.handler", + "Runtime": "python3.12" + }, + "Type": "AWS::Serverless::Function" + } + }, + "Transform": "AWS::Serverless-2016-10-31" + } +} diff --git a/src/test/resources/cloudformation/sam-event-invoke-config/error-lambda-without-destination.json b/src/test/resources/cloudformation/sam-event-invoke-config/error-lambda-without-destination.json new file mode 100644 index 0000000000..39dce31f91 --- /dev/null +++ b/src/test/resources/cloudformation/sam-event-invoke-config/error-lambda-without-destination.json @@ -0,0 +1,23 @@ +{ + "error": "Resource with id [Fn] is invalid. Destination is required if Type is not ['SQS', 'SNS']", + "input": { + "Resources": { + "Fn": { + "Properties": { + "CodeUri": "s3://b/k", + "EventInvokeConfig": { + "DestinationConfig": { + "OnFailure": { + "Type": "Lambda" + } + } + }, + "Handler": "index.handler", + "Runtime": "python3.12" + }, + "Type": "AWS::Serverless::Function" + } + }, + "Transform": "AWS::Serverless-2016-10-31" + } +} diff --git a/src/test/resources/cloudformation/sam-event-invoke-config/error-on-failure-not-map.json b/src/test/resources/cloudformation/sam-event-invoke-config/error-on-failure-not-map.json new file mode 100644 index 0000000000..4e78dcb36c --- /dev/null +++ b/src/test/resources/cloudformation/sam-event-invoke-config/error-on-failure-not-map.json @@ -0,0 +1,21 @@ +{ + "error": "Resource with id [Fn] is invalid. Property 'EventInvokeConfig.DestinationConfig.OnFailure' should be a map.", + "input": { + "Resources": { + "Fn": { + "Properties": { + "CodeUri": "s3://b/k", + "EventInvokeConfig": { + "DestinationConfig": { + "OnFailure": "nope" + } + }, + "Handler": "index.handler", + "Runtime": "python3.12" + }, + "Type": "AWS::Serverless::Function" + } + }, + "Transform": "AWS::Serverless-2016-10-31" + } +} diff --git a/src/test/resources/cloudformation/sam-event-invoke-config/error-type-missing.json b/src/test/resources/cloudformation/sam-event-invoke-config/error-type-missing.json new file mode 100644 index 0000000000..386759d9ea --- /dev/null +++ b/src/test/resources/cloudformation/sam-event-invoke-config/error-type-missing.json @@ -0,0 +1,23 @@ +{ + "error": "Resource with id [Fn] is invalid. 'Type: None' must be one of ['SQS', 'SNS', 'EventBridge', 'Lambda', 'S3Bucket']", + "input": { + "Resources": { + "Fn": { + "Properties": { + "CodeUri": "s3://b/k", + "EventInvokeConfig": { + "DestinationConfig": { + "OnFailure": { + "Destination": "arn:aws:sqs:us-east-1:123456789012:q" + } + } + }, + "Handler": "index.handler", + "Runtime": "python3.12" + }, + "Type": "AWS::Serverless::Function" + } + }, + "Transform": "AWS::Serverless-2016-10-31" + } +} diff --git a/src/test/resources/cloudformation/sam-event-invoke-config/error-type-wrong-case.json b/src/test/resources/cloudformation/sam-event-invoke-config/error-type-wrong-case.json new file mode 100644 index 0000000000..123d10d6d9 --- /dev/null +++ b/src/test/resources/cloudformation/sam-event-invoke-config/error-type-wrong-case.json @@ -0,0 +1,24 @@ +{ + "error": "Resource with id [Fn] is invalid. 'Type: sqs' must be one of ['SQS', 'SNS', 'EventBridge', 'Lambda', 'S3Bucket']", + "input": { + "Resources": { + "Fn": { + "Properties": { + "CodeUri": "s3://b/k", + "EventInvokeConfig": { + "DestinationConfig": { + "OnFailure": { + "Destination": "arn:aws:sqs:us-east-1:123456789012:q", + "Type": "sqs" + } + } + }, + "Handler": "index.handler", + "Runtime": "python3.12" + }, + "Type": "AWS::Serverless::Function" + } + }, + "Transform": "AWS::Serverless-2016-10-31" + } +} diff --git a/src/test/resources/cloudformation/sam-event-invoke-config/explicit-role.json b/src/test/resources/cloudformation/sam-event-invoke-config/explicit-role.json new file mode 100644 index 0000000000..24dbd43205 --- /dev/null +++ b/src/test/resources/cloudformation/sam-event-invoke-config/explicit-role.json @@ -0,0 +1,55 @@ +{ + "expected": { + "FnEventInvokeConfig": { + "Properties": { + "DestinationConfig": { + "OnFailure": { + "Destination": { + "Fn::GetAtt": [ + "Dlq", + "Arn" + ] + } + } + }, + "FunctionName": { + "Ref": "Fn" + }, + "MaximumRetryAttempts": 1, + "Qualifier": "$LATEST" + }, + "Type": "AWS::Lambda::EventInvokeConfig" + } + }, + "input": { + "Resources": { + "Dlq": { + "Type": "AWS::SQS::Queue" + }, + "Fn": { + "Properties": { + "CodeUri": "s3://b/k", + "EventInvokeConfig": { + "DestinationConfig": { + "OnFailure": { + "Destination": { + "Fn::GetAtt": [ + "Dlq", + "Arn" + ] + }, + "Type": "SQS" + } + }, + "MaximumRetryAttempts": 1 + }, + "Handler": "index.handler", + "Role": "arn:aws:iam::123456789012:role/given", + "Runtime": "python3.12" + }, + "Type": "AWS::Serverless::Function" + } + }, + "Transform": "AWS::Serverless-2016-10-31" + } +} diff --git a/src/test/resources/cloudformation/sam-event-invoke-config/function-condition-and-if-novalue.json b/src/test/resources/cloudformation/sam-event-invoke-config/function-condition-and-if-novalue.json new file mode 100644 index 0000000000..185d9334d2 --- /dev/null +++ b/src/test/resources/cloudformation/sam-event-invoke-config/function-condition-and-if-novalue.json @@ -0,0 +1,131 @@ +{ + "expected": { + "FnEventInvokeConfig": { + "Condition": "Deploy", + "Properties": { + "DestinationConfig": { + "OnFailure": { + "Destination": { + "Fn::If": [ + "NOTUseOwnef6eca6cf7", + { + "Fn::GetAtt": [ + "FnEventInvokeConfigOnFailureQueue", + "Arn" + ] + }, + "arn:aws:sqs:us-east-1:123456789012:q" + ] + } + } + }, + "FunctionName": { + "Ref": "Fn" + }, + "Qualifier": "$LATEST" + }, + "Type": "AWS::Lambda::EventInvokeConfig" + }, + "FnEventInvokeConfigOnFailureQueue": { + "Condition": "DeployANDNOTUseOwnef6eca6cf797f22050b4", + "Properties": {}, + "Type": "AWS::SQS::Queue" + }, + "FnRole": { + "Condition": "Deploy", + "Policies": [ + { + "PolicyDocument": { + "Statement": [ + { + "Action": "sqs:SendMessage", + "Effect": "Allow", + "Resource": { + "Fn::If": [ + "NOTUseOwnef6eca6cf7", + { + "Fn::GetAtt": [ + "FnEventInvokeConfigOnFailureQueue", + "Arn" + ] + }, + "arn:aws:sqs:us-east-1:123456789012:q" + ] + } + } + ] + }, + "PolicyName": "FnEventInvokeConfigOnFailureSQSPolicy" + } + ], + "Type": "AWS::IAM::Role" + } + }, + "expectedConditions": { + "DeployANDNOTUseOwnef6eca6cf797f22050b4": { + "Fn::And": [ + { + "Condition": { + "Condition": "Deploy" + } + }, + { + "Condition": { + "Condition": "NOTUseOwnef6eca6cf7" + } + } + ] + }, + "NOTUseOwnef6eca6cf7": { + "Fn::Not": [ + { + "Condition": "UseOwn" + } + ] + } + }, + "input": { + "Conditions": { + "Deploy": { + "Fn::Equals": [ + "a", + "a" + ] + }, + "UseOwn": { + "Fn::Equals": [ + "a", + "b" + ] + } + }, + "Resources": { + "Fn": { + "Condition": "Deploy", + "Properties": { + "CodeUri": "s3://b/k", + "EventInvokeConfig": { + "DestinationConfig": { + "OnFailure": { + "Destination": { + "Fn::If": [ + "UseOwn", + "arn:aws:sqs:us-east-1:123456789012:q", + { + "Ref": "AWS::NoValue" + } + ] + }, + "Type": "SQS" + } + } + }, + "Handler": "index.handler", + "Runtime": "python3.12" + }, + "Type": "AWS::Serverless::Function" + } + }, + "Transform": "AWS::Serverless-2016-10-31" + } +} diff --git a/src/test/resources/cloudformation/sam-event-invoke-config/function-condition.json b/src/test/resources/cloudformation/sam-event-invoke-config/function-condition.json new file mode 100644 index 0000000000..422e66ed10 --- /dev/null +++ b/src/test/resources/cloudformation/sam-event-invoke-config/function-condition.json @@ -0,0 +1,81 @@ +{ + "expected": { + "FnEventInvokeConfig": { + "Condition": "Deploy", + "Properties": { + "DestinationConfig": { + "OnFailure": { + "Destination": { + "Fn::GetAtt": [ + "FnEventInvokeConfigOnFailureQueue", + "Arn" + ] + } + } + }, + "FunctionName": { + "Ref": "Fn" + }, + "Qualifier": "$LATEST" + }, + "Type": "AWS::Lambda::EventInvokeConfig" + }, + "FnEventInvokeConfigOnFailureQueue": { + "Condition": "Deploy", + "Properties": {}, + "Type": "AWS::SQS::Queue" + }, + "FnRole": { + "Condition": "Deploy", + "Policies": [ + { + "PolicyDocument": { + "Statement": [ + { + "Action": "sqs:SendMessage", + "Effect": "Allow", + "Resource": { + "Fn::GetAtt": [ + "FnEventInvokeConfigOnFailureQueue", + "Arn" + ] + } + } + ] + }, + "PolicyName": "FnEventInvokeConfigOnFailureSQSPolicy" + } + ], + "Type": "AWS::IAM::Role" + } + }, + "input": { + "Conditions": { + "Deploy": { + "Fn::Equals": [ + "a", + "a" + ] + } + }, + "Resources": { + "Fn": { + "Condition": "Deploy", + "Properties": { + "CodeUri": "s3://b/k", + "EventInvokeConfig": { + "DestinationConfig": { + "OnFailure": { + "Type": "SQS" + } + } + }, + "Handler": "index.handler", + "Runtime": "python3.12" + }, + "Type": "AWS::Serverless::Function" + } + }, + "Transform": "AWS::Serverless-2016-10-31" + } +} diff --git a/src/test/resources/cloudformation/sam-event-invoke-config/globals.json b/src/test/resources/cloudformation/sam-event-invoke-config/globals.json new file mode 100644 index 0000000000..d6b5826d94 --- /dev/null +++ b/src/test/resources/cloudformation/sam-event-invoke-config/globals.json @@ -0,0 +1,39 @@ +{ + "expected": { + "FnEventInvokeConfig": { + "Properties": { + "DestinationConfig": {}, + "FunctionName": { + "Ref": "Fn" + }, + "MaximumRetryAttempts": 1, + "Qualifier": "$LATEST" + }, + "Type": "AWS::Lambda::EventInvokeConfig" + }, + "FnRole": { + "Policies": null, + "Type": "AWS::IAM::Role" + } + }, + "input": { + "Globals": { + "Function": { + "EventInvokeConfig": { + "MaximumRetryAttempts": 1 + } + } + }, + "Resources": { + "Fn": { + "Properties": { + "CodeUri": "s3://b/k", + "Handler": "index.handler", + "Runtime": "python3.12" + }, + "Type": "AWS::Serverless::Function" + } + }, + "Transform": "AWS::Serverless-2016-10-31" + } +} diff --git a/src/test/resources/cloudformation/sam-event-invoke-config/if-novalue-false-branch.json b/src/test/resources/cloudformation/sam-event-invoke-config/if-novalue-false-branch.json new file mode 100644 index 0000000000..50130389c1 --- /dev/null +++ b/src/test/resources/cloudformation/sam-event-invoke-config/if-novalue-false-branch.json @@ -0,0 +1,108 @@ +{ + "expected": { + "FnEventInvokeConfig": { + "Properties": { + "DestinationConfig": { + "OnFailure": { + "Destination": { + "Fn::If": [ + "NOTUseOwnef6eca6cf7", + { + "Fn::GetAtt": [ + "FnEventInvokeConfigOnFailureQueue", + "Arn" + ] + }, + "arn:aws:sqs:us-east-1:123456789012:q" + ] + } + } + }, + "FunctionName": { + "Ref": "Fn" + }, + "Qualifier": "$LATEST" + }, + "Type": "AWS::Lambda::EventInvokeConfig" + }, + "FnEventInvokeConfigOnFailureQueue": { + "Condition": "NOTUseOwnef6eca6cf7", + "Properties": {}, + "Type": "AWS::SQS::Queue" + }, + "FnRole": { + "Policies": [ + { + "PolicyDocument": { + "Statement": [ + { + "Action": "sqs:SendMessage", + "Effect": "Allow", + "Resource": { + "Fn::If": [ + "NOTUseOwnef6eca6cf7", + { + "Fn::GetAtt": [ + "FnEventInvokeConfigOnFailureQueue", + "Arn" + ] + }, + "arn:aws:sqs:us-east-1:123456789012:q" + ] + } + } + ] + }, + "PolicyName": "FnEventInvokeConfigOnFailureSQSPolicy" + } + ], + "Type": "AWS::IAM::Role" + } + }, + "expectedConditions": { + "NOTUseOwnef6eca6cf7": { + "Fn::Not": [ + { + "Condition": "UseOwn" + } + ] + } + }, + "input": { + "Conditions": { + "UseOwn": { + "Fn::Equals": [ + "a", + "b" + ] + } + }, + "Resources": { + "Fn": { + "Properties": { + "CodeUri": "s3://b/k", + "EventInvokeConfig": { + "DestinationConfig": { + "OnFailure": { + "Destination": { + "Fn::If": [ + "UseOwn", + "arn:aws:sqs:us-east-1:123456789012:q", + { + "Ref": "AWS::NoValue" + } + ] + }, + "Type": "SQS" + } + } + }, + "Handler": "index.handler", + "Runtime": "python3.12" + }, + "Type": "AWS::Serverless::Function" + } + }, + "Transform": "AWS::Serverless-2016-10-31" + } +} diff --git a/src/test/resources/cloudformation/sam-event-invoke-config/if-novalue-true-branch.json b/src/test/resources/cloudformation/sam-event-invoke-config/if-novalue-true-branch.json new file mode 100644 index 0000000000..6eca5c5ec2 --- /dev/null +++ b/src/test/resources/cloudformation/sam-event-invoke-config/if-novalue-true-branch.json @@ -0,0 +1,99 @@ +{ + "expected": { + "FnEventInvokeConfig": { + "Properties": { + "DestinationConfig": { + "OnFailure": { + "Destination": { + "Fn::If": [ + "UseOwn", + { + "Fn::GetAtt": [ + "FnEventInvokeConfigOnFailureQueue", + "Arn" + ] + }, + "arn:aws:sqs:us-east-1:123456789012:q" + ] + } + } + }, + "FunctionName": { + "Ref": "Fn" + }, + "Qualifier": "$LATEST" + }, + "Type": "AWS::Lambda::EventInvokeConfig" + }, + "FnEventInvokeConfigOnFailureQueue": { + "Condition": "UseOwn", + "Properties": {}, + "Type": "AWS::SQS::Queue" + }, + "FnRole": { + "Policies": [ + { + "PolicyDocument": { + "Statement": [ + { + "Action": "sqs:SendMessage", + "Effect": "Allow", + "Resource": { + "Fn::If": [ + "UseOwn", + { + "Fn::GetAtt": [ + "FnEventInvokeConfigOnFailureQueue", + "Arn" + ] + }, + "arn:aws:sqs:us-east-1:123456789012:q" + ] + } + } + ] + }, + "PolicyName": "FnEventInvokeConfigOnFailureSQSPolicy" + } + ], + "Type": "AWS::IAM::Role" + } + }, + "input": { + "Conditions": { + "UseOwn": { + "Fn::Equals": [ + "a", + "b" + ] + } + }, + "Resources": { + "Fn": { + "Properties": { + "CodeUri": "s3://b/k", + "EventInvokeConfig": { + "DestinationConfig": { + "OnFailure": { + "Destination": { + "Fn::If": [ + "UseOwn", + { + "Ref": "AWS::NoValue" + }, + "arn:aws:sqs:us-east-1:123456789012:q" + ] + }, + "Type": "SQS" + } + } + }, + "Handler": "index.handler", + "Runtime": "python3.12" + }, + "Type": "AWS::Serverless::Function" + } + }, + "Transform": "AWS::Serverless-2016-10-31" + } +} diff --git a/src/test/resources/cloudformation/sam-event-invoke-config/if-plain.json b/src/test/resources/cloudformation/sam-event-invoke-config/if-plain.json new file mode 100644 index 0000000000..bafb2d6a63 --- /dev/null +++ b/src/test/resources/cloudformation/sam-event-invoke-config/if-plain.json @@ -0,0 +1,82 @@ +{ + "expected": { + "FnEventInvokeConfig": { + "Properties": { + "DestinationConfig": { + "OnFailure": { + "Destination": { + "Fn::If": [ + "UseOwn", + "arn:aws:sqs:us-east-1:123456789012:a", + "arn:aws:sqs:us-east-1:123456789012:b" + ] + } + } + }, + "FunctionName": { + "Ref": "Fn" + }, + "Qualifier": "$LATEST" + }, + "Type": "AWS::Lambda::EventInvokeConfig" + }, + "FnRole": { + "Policies": [ + { + "PolicyDocument": { + "Statement": [ + { + "Action": "sqs:SendMessage", + "Effect": "Allow", + "Resource": { + "Fn::If": [ + "UseOwn", + "arn:aws:sqs:us-east-1:123456789012:a", + "arn:aws:sqs:us-east-1:123456789012:b" + ] + } + } + ] + }, + "PolicyName": "FnEventInvokeConfigOnFailureSQSPolicy" + } + ], + "Type": "AWS::IAM::Role" + } + }, + "input": { + "Conditions": { + "UseOwn": { + "Fn::Equals": [ + "a", + "b" + ] + } + }, + "Resources": { + "Fn": { + "Properties": { + "CodeUri": "s3://b/k", + "EventInvokeConfig": { + "DestinationConfig": { + "OnFailure": { + "Destination": { + "Fn::If": [ + "UseOwn", + "arn:aws:sqs:us-east-1:123456789012:a", + "arn:aws:sqs:us-east-1:123456789012:b" + ] + }, + "Type": "SQS" + } + } + }, + "Handler": "index.handler", + "Runtime": "python3.12" + }, + "Type": "AWS::Serverless::Function" + } + }, + "Transform": "AWS::Serverless-2016-10-31" + } +} diff --git a/src/test/resources/cloudformation/sam-event-invoke-config/intrinsic-type-default.json b/src/test/resources/cloudformation/sam-event-invoke-config/intrinsic-type-default.json new file mode 100644 index 0000000000..751cf45b84 --- /dev/null +++ b/src/test/resources/cloudformation/sam-event-invoke-config/intrinsic-type-default.json @@ -0,0 +1,64 @@ +{ + "expected": { + "FnEventInvokeConfig": { + "Properties": { + "DestinationConfig": { + "OnFailure": { + "Destination": "arn:aws:sqs:us-east-1:123456789012:q" + } + }, + "FunctionName": { + "Ref": "Fn" + }, + "Qualifier": "$LATEST" + }, + "Type": "AWS::Lambda::EventInvokeConfig" + }, + "FnRole": { + "Policies": [ + { + "PolicyDocument": { + "Statement": [ + { + "Action": "sqs:SendMessage", + "Effect": "Allow", + "Resource": "arn:aws:sqs:us-east-1:123456789012:q" + } + ] + }, + "PolicyName": "FnEventInvokeConfigOnFailureSQSPolicy" + } + ], + "Type": "AWS::IAM::Role" + } + }, + "input": { + "Parameters": { + "DestType": { + "Default": "SQS", + "Type": "String" + } + }, + "Resources": { + "Fn": { + "Properties": { + "CodeUri": "s3://b/k", + "EventInvokeConfig": { + "DestinationConfig": { + "OnFailure": { + "Destination": "arn:aws:sqs:us-east-1:123456789012:q", + "Type": { + "Ref": "DestType" + } + } + } + }, + "Handler": "index.handler", + "Runtime": "python3.12" + }, + "Type": "AWS::Serverless::Function" + } + }, + "Transform": "AWS::Serverless-2016-10-31" + } +} diff --git a/src/test/resources/cloudformation/sam-event-invoke-config/kbdb-shape.json b/src/test/resources/cloudformation/sam-event-invoke-config/kbdb-shape.json new file mode 100644 index 0000000000..b7e6347218 --- /dev/null +++ b/src/test/resources/cloudformation/sam-event-invoke-config/kbdb-shape.json @@ -0,0 +1,78 @@ +{ + "expected": { + "FnEventInvokeConfig": { + "Properties": { + "DestinationConfig": { + "OnFailure": { + "Destination": { + "Fn::GetAtt": [ + "Dlq", + "Arn" + ] + } + } + }, + "FunctionName": { + "Ref": "Fn" + }, + "MaximumEventAgeInSeconds": 21600, + "MaximumRetryAttempts": 2, + "Qualifier": "$LATEST" + }, + "Type": "AWS::Lambda::EventInvokeConfig" + }, + "FnRole": { + "Policies": [ + { + "PolicyDocument": { + "Statement": [ + { + "Action": "sqs:SendMessage", + "Effect": "Allow", + "Resource": { + "Fn::GetAtt": [ + "Dlq", + "Arn" + ] + } + } + ] + }, + "PolicyName": "FnEventInvokeConfigOnFailureSQSPolicy" + } + ], + "Type": "AWS::IAM::Role" + } + }, + "input": { + "Resources": { + "Dlq": { + "Type": "AWS::SQS::Queue" + }, + "Fn": { + "Properties": { + "CodeUri": "s3://b/k", + "EventInvokeConfig": { + "DestinationConfig": { + "OnFailure": { + "Destination": { + "Fn::GetAtt": [ + "Dlq", + "Arn" + ] + }, + "Type": "SQS" + } + }, + "MaximumEventAgeInSeconds": 21600, + "MaximumRetryAttempts": 2 + }, + "Handler": "index.handler", + "Runtime": "python3.12" + }, + "Type": "AWS::Serverless::Function" + } + }, + "Transform": "AWS::Serverless-2016-10-31" + } +} diff --git a/src/test/resources/cloudformation/sam-event-invoke-config/lambda-and-eventbridge.json b/src/test/resources/cloudformation/sam-event-invoke-config/lambda-and-eventbridge.json new file mode 100644 index 0000000000..13000700b0 --- /dev/null +++ b/src/test/resources/cloudformation/sam-event-invoke-config/lambda-and-eventbridge.json @@ -0,0 +1,98 @@ +{ + "expected": { + "FnEventInvokeConfig": { + "Properties": { + "DestinationConfig": { + "OnFailure": { + "Destination": "arn:aws:events:us-east-1:123456789012:event-bus/default" + }, + "OnSuccess": { + "Destination": { + "Fn::GetAtt": [ + "Target", + "Arn" + ] + } + } + }, + "FunctionName": { + "Ref": "Fn" + }, + "Qualifier": "$LATEST" + }, + "Type": "AWS::Lambda::EventInvokeConfig" + }, + "FnRole": { + "Policies": [ + { + "PolicyDocument": { + "Statement": [ + { + "Action": "lambda:InvokeFunction", + "Effect": "Allow", + "Resource": { + "Fn::GetAtt": [ + "Target", + "Arn" + ] + } + } + ] + }, + "PolicyName": "FnEventInvokeConfigOnSuccessLambdaPolicy" + }, + { + "PolicyDocument": { + "Statement": [ + { + "Action": "events:PutEvents", + "Effect": "Allow", + "Resource": "arn:aws:events:us-east-1:123456789012:event-bus/default" + } + ] + }, + "PolicyName": "FnEventInvokeConfigOnFailureEventBridgePolicy" + } + ], + "Type": "AWS::IAM::Role" + } + }, + "input": { + "Resources": { + "Fn": { + "Properties": { + "CodeUri": "s3://b/k", + "EventInvokeConfig": { + "DestinationConfig": { + "OnFailure": { + "Destination": "arn:aws:events:us-east-1:123456789012:event-bus/default", + "Type": "EventBridge" + }, + "OnSuccess": { + "Destination": { + "Fn::GetAtt": [ + "Target", + "Arn" + ] + }, + "Type": "Lambda" + } + } + }, + "Handler": "index.handler", + "Runtime": "python3.12" + }, + "Type": "AWS::Serverless::Function" + }, + "Target": { + "Properties": { + "CodeUri": "s3://b/k", + "Handler": "index.handler", + "Runtime": "python3.12" + }, + "Type": "AWS::Serverless::Function" + } + }, + "Transform": "AWS::Serverless-2016-10-31" + } +} diff --git a/src/test/resources/cloudformation/sam-event-invoke-config/no-destination.json b/src/test/resources/cloudformation/sam-event-invoke-config/no-destination.json new file mode 100644 index 0000000000..ac71e4e4d1 --- /dev/null +++ b/src/test/resources/cloudformation/sam-event-invoke-config/no-destination.json @@ -0,0 +1,35 @@ +{ + "expected": { + "FnEventInvokeConfig": { + "Properties": { + "DestinationConfig": {}, + "FunctionName": { + "Ref": "Fn" + }, + "MaximumRetryAttempts": 2, + "Qualifier": "$LATEST" + }, + "Type": "AWS::Lambda::EventInvokeConfig" + }, + "FnRole": { + "Policies": null, + "Type": "AWS::IAM::Role" + } + }, + "input": { + "Resources": { + "Fn": { + "Properties": { + "CodeUri": "s3://b/k", + "EventInvokeConfig": { + "MaximumRetryAttempts": 2 + }, + "Handler": "index.handler", + "Runtime": "python3.12" + }, + "Type": "AWS::Serverless::Function" + } + }, + "Transform": "AWS::Serverless-2016-10-31" + } +} diff --git a/src/test/resources/cloudformation/sam-event-invoke-config/passthrough-attributes.json b/src/test/resources/cloudformation/sam-event-invoke-config/passthrough-attributes.json new file mode 100644 index 0000000000..a7bc5a013a --- /dev/null +++ b/src/test/resources/cloudformation/sam-event-invoke-config/passthrough-attributes.json @@ -0,0 +1,91 @@ +{ + "expected": { + "FnEventInvokeConfig": { + "DeletionPolicy": "Retain", + "DependsOn": [ + "FnAliaslive" + ], + "Properties": { + "DestinationConfig": { + "OnFailure": { + "Destination": { + "Fn::GetAtt": [ + "FnEventInvokeConfigOnFailureQueue", + "Arn" + ] + } + } + }, + "FunctionName": { + "Ref": "Fn" + }, + "Qualifier": "live" + }, + "Type": "AWS::Lambda::EventInvokeConfig", + "UpdateReplacePolicy": "Retain" + }, + "FnEventInvokeConfigOnFailureQueue": { + "DeletionPolicy": "Retain", + "Properties": {}, + "Type": "AWS::SQS::Queue", + "UpdateReplacePolicy": "Retain" + }, + "FnRole": { + "DeletionPolicy": "Retain", + "Policies": [ + { + "PolicyDocument": { + "Statement": [ + { + "Action": "sqs:SendMessage", + "Effect": "Allow", + "Resource": { + "Fn::GetAtt": [ + "FnEventInvokeConfigOnFailureQueue", + "Arn" + ] + } + } + ] + }, + "PolicyName": "FnEventInvokeConfigOnFailureSQSPolicy" + } + ], + "Type": "AWS::IAM::Role", + "UpdateReplacePolicy": "Retain" + } + }, + "expectedAttributesByType": { + "AWS::Lambda::Alias": { + "DeletionPolicy": "Retain", + "UpdateReplacePolicy": "Retain" + }, + "AWS::Lambda::Version": { + "DeletionPolicy": "Retain", + "UpdateReplacePolicy": "Retain" + } + }, + "input": { + "Resources": { + "Fn": { + "DeletionPolicy": "Retain", + "Properties": { + "AutoPublishAlias": "live", + "CodeUri": "s3://b/k", + "EventInvokeConfig": { + "DestinationConfig": { + "OnFailure": { + "Type": "SQS" + } + } + }, + "Handler": "index.handler", + "Runtime": "python3.12" + }, + "Type": "AWS::Serverless::Function", + "UpdateReplacePolicy": "Retain" + } + }, + "Transform": "AWS::Serverless-2016-10-31" + } +} diff --git a/src/test/resources/cloudformation/sam-event-invoke-config/s3-destination.json b/src/test/resources/cloudformation/sam-event-invoke-config/s3-destination.json new file mode 100644 index 0000000000..6c1052fee5 --- /dev/null +++ b/src/test/resources/cloudformation/sam-event-invoke-config/s3-destination.json @@ -0,0 +1,69 @@ +{ + "expected": { + "FnEventInvokeConfig": { + "Properties": { + "DestinationConfig": { + "OnFailure": { + "Destination": "arn:aws:s3:::failures" + } + }, + "FunctionName": { + "Ref": "Fn" + }, + "Qualifier": "$LATEST" + }, + "Type": "AWS::Lambda::EventInvokeConfig" + }, + "FnRole": { + "Policies": [ + { + "PolicyDocument": { + "Statement": [ + { + "Action": "s3:PutObject", + "Effect": "Allow", + "Resource": { + "Fn::Join": [ + "/", + [ + "arn:aws:s3:::failures", + "*" + ] + ] + } + }, + { + "Action": "s3:ListBucket", + "Effect": "Allow", + "Resource": "arn:aws:s3:::failures" + } + ] + }, + "PolicyName": "FnEventInvokeConfigOnFailureS3Policy" + } + ], + "Type": "AWS::IAM::Role" + } + }, + "input": { + "Resources": { + "Fn": { + "Properties": { + "CodeUri": "s3://b/k", + "EventInvokeConfig": { + "DestinationConfig": { + "OnFailure": { + "Destination": "arn:aws:s3:::failures", + "Type": "S3Bucket" + } + } + }, + "Handler": "index.handler", + "Runtime": "python3.12" + }, + "Type": "AWS::Serverless::Function" + } + }, + "Transform": "AWS::Serverless-2016-10-31" + } +} diff --git a/src/test/resources/cloudformation/sam-event-invoke-config/sns-type-only.json b/src/test/resources/cloudformation/sam-event-invoke-config/sns-type-only.json new file mode 100644 index 0000000000..411531c05e --- /dev/null +++ b/src/test/resources/cloudformation/sam-event-invoke-config/sns-type-only.json @@ -0,0 +1,63 @@ +{ + "expected": { + "FnEventInvokeConfig": { + "Properties": { + "DestinationConfig": { + "OnSuccess": { + "Destination": { + "Ref": "FnEventInvokeConfigOnSuccessTopic" + } + } + }, + "FunctionName": { + "Ref": "Fn" + }, + "Qualifier": "$LATEST" + }, + "Type": "AWS::Lambda::EventInvokeConfig" + }, + "FnEventInvokeConfigOnSuccessTopic": { + "Properties": {}, + "Type": "AWS::SNS::Topic" + }, + "FnRole": { + "Policies": [ + { + "PolicyDocument": { + "Statement": [ + { + "Action": "sns:publish", + "Effect": "Allow", + "Resource": { + "Ref": "FnEventInvokeConfigOnSuccessTopic" + } + } + ] + }, + "PolicyName": "FnEventInvokeConfigOnSuccessSNSPolicy" + } + ], + "Type": "AWS::IAM::Role" + } + }, + "input": { + "Resources": { + "Fn": { + "Properties": { + "CodeUri": "s3://b/k", + "EventInvokeConfig": { + "DestinationConfig": { + "OnSuccess": { + "Type": "SNS" + } + } + }, + "Handler": "index.handler", + "Runtime": "python3.12" + }, + "Type": "AWS::Serverless::Function" + } + }, + "Transform": "AWS::Serverless-2016-10-31" + } +} diff --git a/src/test/resources/cloudformation/sam-event-invoke-config/sqs-ref-destination.json b/src/test/resources/cloudformation/sam-event-invoke-config/sqs-ref-destination.json new file mode 100644 index 0000000000..081ff867f3 --- /dev/null +++ b/src/test/resources/cloudformation/sam-event-invoke-config/sqs-ref-destination.json @@ -0,0 +1,65 @@ +{ + "expected": { + "FnEventInvokeConfig": { + "Properties": { + "DestinationConfig": { + "OnFailure": { + "Destination": { + "Ref": "Dlq" + } + } + }, + "FunctionName": { + "Ref": "Fn" + }, + "Qualifier": "$LATEST" + }, + "Type": "AWS::Lambda::EventInvokeConfig" + }, + "FnRole": { + "Policies": [ + { + "PolicyDocument": { + "Statement": [ + { + "Action": "sqs:SendMessage", + "Effect": "Allow", + "Resource": { + "Ref": "Dlq" + } + } + ] + }, + "PolicyName": "FnEventInvokeConfigOnFailureSQSPolicy" + } + ], + "Type": "AWS::IAM::Role" + } + }, + "input": { + "Resources": { + "Dlq": { + "Type": "AWS::SQS::Queue" + }, + "Fn": { + "Properties": { + "CodeUri": "s3://b/k", + "EventInvokeConfig": { + "DestinationConfig": { + "OnFailure": { + "Destination": { + "Ref": "Dlq" + }, + "Type": "SQS" + } + } + }, + "Handler": "index.handler", + "Runtime": "python3.12" + }, + "Type": "AWS::Serverless::Function" + } + }, + "Transform": "AWS::Serverless-2016-10-31" + } +} diff --git a/src/test/resources/cloudformation/sam-event-invoke-config/sqs-type-only.json b/src/test/resources/cloudformation/sam-event-invoke-config/sqs-type-only.json new file mode 100644 index 0000000000..d69c8ebf09 --- /dev/null +++ b/src/test/resources/cloudformation/sam-event-invoke-config/sqs-type-only.json @@ -0,0 +1,69 @@ +{ + "expected": { + "FnEventInvokeConfig": { + "Properties": { + "DestinationConfig": { + "OnFailure": { + "Destination": { + "Fn::GetAtt": [ + "FnEventInvokeConfigOnFailureQueue", + "Arn" + ] + } + } + }, + "FunctionName": { + "Ref": "Fn" + }, + "Qualifier": "$LATEST" + }, + "Type": "AWS::Lambda::EventInvokeConfig" + }, + "FnEventInvokeConfigOnFailureQueue": { + "Properties": {}, + "Type": "AWS::SQS::Queue" + }, + "FnRole": { + "Policies": [ + { + "PolicyDocument": { + "Statement": [ + { + "Action": "sqs:SendMessage", + "Effect": "Allow", + "Resource": { + "Fn::GetAtt": [ + "FnEventInvokeConfigOnFailureQueue", + "Arn" + ] + } + } + ] + }, + "PolicyName": "FnEventInvokeConfigOnFailureSQSPolicy" + } + ], + "Type": "AWS::IAM::Role" + } + }, + "input": { + "Resources": { + "Fn": { + "Properties": { + "CodeUri": "s3://b/k", + "EventInvokeConfig": { + "DestinationConfig": { + "OnFailure": { + "Type": "SQS" + } + } + }, + "Handler": "index.handler", + "Runtime": "python3.12" + }, + "Type": "AWS::Serverless::Function" + } + }, + "Transform": "AWS::Serverless-2016-10-31" + } +} diff --git a/tools/docs/cfn_resource_types.yaml b/tools/docs/cfn_resource_types.yaml index 9d347bc821..8ba08b05c2 100644 --- a/tools/docs/cfn_resource_types.yaml +++ b/tools/docs/cfn_resource_types.yaml @@ -169,6 +169,7 @@ notes: AWS::Lambda::Function: Zip via S3/inline `ZipFile`, Image, and the `hot-reload` bind-mount bucket AWS::Lambda::EventSourceMapping: 'SQS, Kinesis, DynamoDB Streams; `ParallelizationFactor` and `TumblingWindowInSeconds` are ignored' AWS::Lambda::Alias: also what SAM's `AutoPublishAlias` expands into + AWS::Lambda::EventInvokeConfig: also what a SAM function's `EventInvokeConfig` expands into AWS::EC2::SecurityGroup: inline `SecurityGroupIngress`/`SecurityGroupEgress` supported AWS::ApplicationAutoScaling::ScalableTarget: '`ScheduledActions` are accepted and not run; Floci has no scheduled scaling' AWS::RDS::DBInstance: starts a real container