diff --git a/compatibility-tests/sdk-test-java/src/main/java/com/floci/test/TestFixtures.java b/compatibility-tests/sdk-test-java/src/main/java/com/floci/test/TestFixtures.java index e26ea9e342..3edbd7f0af 100644 --- a/compatibility-tests/sdk-test-java/src/main/java/com/floci/test/TestFixtures.java +++ b/compatibility-tests/sdk-test-java/src/main/java/com/floci/test/TestFixtures.java @@ -931,9 +931,14 @@ public final class TestFixtures { } } - /** The stack's status once it is no longer {@code *_IN_PROGRESS}, or its last status at the timeout. */ + /** + * The stack's status once it is no longer {@code *_IN_PROGRESS}, or its last status at the timeout. + * It checks every 50 ms against Floci, where a stack usually finishes in milliseconds, as the + * integration tests' {@code CfnStackWaits} does, and every 500 ms against real AWS. + */ public static String awaitStackTerminal(CloudFormationClient cfn, String stackName, Duration timeout) throws InterruptedException { + long pollMillis = isRealAws() ? 500 : 50; long deadline = System.nanoTime() + timeout.toNanos(); while (true) { String status = cfn.describeStacks(request -> request.stackName(stackName)) @@ -945,7 +950,7 @@ public final class TestFixtures { if (remainingNanos <= 0) { return status; } - Thread.sleep(Math.min(500, Math.max(1, Duration.ofNanos(remainingNanos).toMillis()))); + Thread.sleep(Math.min(pollMillis, Math.max(1, Duration.ofNanos(remainingNanos).toMillis()))); } } diff --git a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/CloudFormationEventsRuleTargetTest.java b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/CloudFormationEventsRuleTargetTest.java new file mode 100644 index 0000000000..c5c00a9e8a --- /dev/null +++ b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/CloudFormationEventsRuleTargetTest.java @@ -0,0 +1,192 @@ +package com.floci.test; + +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; +import software.amazon.awssdk.services.cloudformation.CloudFormationClient; +import software.amazon.awssdk.services.cloudformation.model.OperationEvent; +import software.amazon.awssdk.services.cloudformation.model.StackEvent; +import software.amazon.awssdk.services.eventbridge.EventBridgeClient; +import software.amazon.awssdk.services.eventbridge.model.EcsParameters; +import software.amazon.awssdk.services.eventbridge.model.Target; + +import java.time.Duration; +import java.util.ArrayList; +import java.util.List; + +import static org.assertj.core.api.Assertions.assertThat; + +/** + * An AWS::Events::Rule target's dead-letter queue, retry policy, role and ECS parameters, read + * back through the EventBridge SDK client, and the members of the wrong type CloudFormation + * refuses. Measured on AWS (eu-west-1, 2026-10-18): the target keeps all four, EcsParameters in + * the EventBridge API's spelling; a Ref to a CommaDelimitedList is a list of subnets and a Ref to a + * String is refused; a retry attempt count of 4.5 fails template validation, read through + * DescribeEvents on AWS, and an EnableECSManagedTags of "yes" fails the handler's model + * validation. Floci reports both on the resource's failed event. + */ +@DisplayName("CloudFormation AWS::Events::Rule targets") +class CloudFormationEventsRuleTargetTest { + + /** Floci finishes these stacks in milliseconds; AWS takes minutes for the queues. */ + private static final Duration DEPLOY_TIMEOUT = + TestFixtures.isRealAws() ? Duration.ofMinutes(10) : Duration.ofSeconds(10); + private static final String KEPT_STACK = TestFixtures.uniqueName("compat-cfn-rule-targets"); + private static final String STRING_SUBNETS_STACK = TestFixtures.uniqueName("compat-cfn-rule-subnets"); + private static final String FLOAT_STACK = TestFixtures.uniqueName("compat-cfn-rule-float"); + private static final String BOOLEAN_STACK = TestFixtures.uniqueName("compat-cfn-rule-boolean"); + private static final String CLUSTER = + "{\"Fn::Sub\": \"arn:${AWS::Partition}:ecs:${AWS::Region}:${AWS::AccountId}:cluster/compat-absent\"}"; + private static final String ROLE = + "{\"Fn::Sub\": \"arn:${AWS::Partition}:iam::${AWS::AccountId}:role/compat-absent\"}"; + private static final String TASK_DEFINITION = "{\"Fn::Sub\": \"arn:${AWS::Partition}:ecs:${AWS::Region}" + + ":${AWS::AccountId}:task-definition/compat-absent:1\"}"; + + private static CloudFormationClient cfn; + private static EventBridgeClient eventBridge; + + @BeforeAll + static void setup() { + cfn = TestFixtures.cloudFormationClient(); + eventBridge = TestFixtures.eventBridgeClient(); + } + + @AfterAll + static void cleanup() { + if (cfn != null) { + // DeleteStack answers for a stack that is gone too, so a failure here is a real one. + for (String stack : List.of(KEPT_STACK, STRING_SUBNETS_STACK, FLOAT_STACK, BOOLEAN_STACK)) { + cfn.deleteStack(request -> request.stackName(stack)); + } + cfn.close(); + } + if (eventBridge != null) { + eventBridge.close(); + } + } + + @Test + @DisplayName("a target keeps its dead-letter queue, retry policy, role and ECS parameters") + void aTargetKeepsWhatPutTargetsWouldSet() throws InterruptedException { + cfn.createStack(request -> request.stackName(KEPT_STACK).templateBody(""" + { + "Parameters": {"Subnets": {"Type": "CommaDelimitedList", + "Default": "subnet-0123456789abcdef0,subnet-0123456789abcdef1"}}, + "Resources": { + "Dlq": {"Type": "AWS::SQS::Queue"}, + "Queue": {"Type": "AWS::SQS::Queue"}, + "Delivery": {"Type": "AWS::Events::Rule", "Properties": { + "EventPattern": {"source": ["compat.rule.targets"]}, + "Targets": [{"Id": "Queue", "Arn": {"Fn::GetAtt": ["Queue", "Arn"]}, + "DeadLetterConfig": {"Arn": {"Fn::GetAtt": ["Dlq", "Arn"]}}, + "RetryPolicy": {"MaximumRetryAttempts": "4", "MaximumEventAgeInSeconds": 7200}}]}}, + "RunTask": {"Type": "AWS::Events::Rule", "Properties": { + "EventPattern": {"source": ["compat.rule.targets"]}, + "Targets": [{"Id": "Task", "Arn": %s, "RoleArn": %s, + "EcsParameters": {"TaskDefinitionArn": %s, "TaskCount": 2, "LaunchType": "FARGATE", + "NetworkConfiguration": {"AwsVpcConfiguration": {"Subnets": {"Ref": "Subnets"}, + "AssignPublicIp": "DISABLED"}}, + "PlacementConstraints": [{"Type": "memberOf", "Expression": "attribute:ecs.os-type == linux"}], + "TagList": [{"Key": "team", "Value": "jobs"}]}}]}} + } + } + """.formatted(CLUSTER, ROLE, TASK_DEFINITION))); + assertThat(TestFixtures.awaitStackTerminal(cfn, KEPT_STACK, DEPLOY_TIMEOUT)).isEqualTo("CREATE_COMPLETE"); + + Target delivery = onlyTarget("Delivery"); + String dlqUrl = physicalId("Dlq"); + assertThat(delivery.deadLetterConfig().arn()).endsWith(":" + dlqUrl.substring(dlqUrl.lastIndexOf('/') + 1)); + assertThat(delivery.retryPolicy().maximumRetryAttempts()).isEqualTo(4); + assertThat(delivery.retryPolicy().maximumEventAgeInSeconds()).isEqualTo(7200); + + Target task = onlyTarget("RunTask"); + assertThat(task.roleArn()).endsWith(":role/compat-absent"); + EcsParameters ecs = task.ecsParameters(); + assertThat(ecs.taskDefinitionArn()).endsWith(":task-definition/compat-absent:1"); + assertThat(ecs.taskCount()).isEqualTo(2); + assertThat(ecs.networkConfiguration().awsvpcConfiguration().subnets()) + .containsExactly("subnet-0123456789abcdef0", "subnet-0123456789abcdef1"); + assertThat(ecs.placementConstraints()).singleElement().satisfies(constraint -> { + assertThat(constraint.typeAsString()).isEqualTo("memberOf"); + assertThat(constraint.expression()).isEqualTo("attribute:ecs.os-type == linux"); + }); + assertThat(ecs.tags()).singleElement().satisfies(tag -> { + assertThat(tag.key()).isEqualTo("team"); + assertThat(tag.value()).isEqualTo("jobs"); + }); + } + + @Test + @DisplayName("subnets from a String parameter fail the stack") + void subnetsFromAStringParameterFailTheStack() throws InterruptedException { + cfn.createStack(request -> request.stackName(STRING_SUBNETS_STACK).templateBody(ecsRule( + "{\"Subnets\": {\"Type\": \"String\", \"Default\": \"subnet-0123456789abcdef0\"}}", + "\"NetworkConfiguration\": {\"AwsVpcConfiguration\": {\"Subnets\": {\"Ref\": \"Subnets\"}}}"))); + assertThat(TestFixtures.awaitStackTerminal(cfn, STRING_SUBNETS_STACK, DEPLOY_TIMEOUT)) + .isEqualTo("ROLLBACK_COMPLETE"); + assertThat(reasons(STRING_SUBNETS_STACK)).anyMatch(reason -> + reason.contains("Property [Subnets] expected type: JSONArray, found: String")); + } + + @Test + @DisplayName("a retry attempt count of 4.5 fails template validation") + void aFractionalRetryAttemptCountFailsTheStack() throws InterruptedException { + cfn.createStack(request -> request.stackName(FLOAT_STACK).templateBody(""" + {"Resources": {"Rule": {"Type": "AWS::Events::Rule", "Properties": { + "EventPattern": {"source": ["compat.rule.targets"]}, + "Targets": [{"Id": "T", "Arn": %s, "RoleArn": %s, "RetryPolicy": {"MaximumRetryAttempts": 4.5}}]}}}} + """.formatted(CLUSTER, ROLE))); + assertThat(TestFixtures.awaitStackTerminal(cfn, FLOAT_STACK, DEPLOY_TIMEOUT)).isEqualTo("ROLLBACK_COMPLETE"); + assertThat(reasons(FLOAT_STACK)).anyMatch(reason -> + reason.contains("Property [MaximumRetryAttempts] expected type: Integer, found: Float")); + } + + @Test + @DisplayName("an EnableECSManagedTags of \"yes\" fails the handler's model validation") + void aBooleanThatIsNotTrueOrFalseFailsTheStack() throws InterruptedException { + cfn.createStack(request -> request.stackName(BOOLEAN_STACK).templateBody(ecsRule("{}", + "\"EnableECSManagedTags\": \"yes\""))); + assertThat(TestFixtures.awaitStackTerminal(cfn, BOOLEAN_STACK, DEPLOY_TIMEOUT)).isEqualTo("ROLLBACK_COMPLETE"); + assertThat(reasons(BOOLEAN_STACK)).anyMatch(reason -> reason.contains( + "Model validation failed (#/Targets/0/EcsParameters/EnableECSManagedTags:" + + " expected type: Boolean, found: String)")); + } + + private static String ecsRule(String parameters, String ecsMembers) { + return """ + {"Parameters": %s, + "Resources": {"Rule": {"Type": "AWS::Events::Rule", "Properties": { + "EventPattern": {"source": ["compat.rule.targets"]}, + "Targets": [{"Id": "T", "Arn": %s, "RoleArn": %s, + "EcsParameters": {"TaskDefinitionArn": %s, %s}}]}}}} + """.formatted(parameters, CLUSTER, ROLE, TASK_DEFINITION, ecsMembers); + } + + private static String physicalId(String logicalId) { + return cfn.describeStackResource(request -> request.stackName(KEPT_STACK).logicalResourceId(logicalId)) + .stackResourceDetail().physicalResourceId(); + } + + private static Target onlyTarget(String logicalId) { + List targets = eventBridge.listTargetsByRule(request -> request.rule(physicalId(logicalId))).targets(); + assertThat(targets).hasSize(1); + return targets.get(0); + } + + /** On AWS, template validation's reasons are read through DescribeEvents, the handler's on the stack events. */ + private static List reasons(String stackName) { + List reasons = new ArrayList<>(); + if (TestFixtures.isRealAws()) { + cfn.describeEvents(request -> request.stackName(stackName)).operationEvents().stream() + .map(OperationEvent::validationStatusReason) + .filter(reason -> reason != null) + .forEach(reasons::add); + } + cfn.describeStackEvents(request -> request.stackName(stackName)).stackEvents().stream() + .map(StackEvent::resourceStatusReason) + .filter(reason -> reason != null) + .forEach(reasons::add); + return reasons; + } +} diff --git a/docs/services/eventbridge.md b/docs/services/eventbridge.md index 79b53eed8a..9ac4e3ec2d 100644 --- a/docs/services/eventbridge.md +++ b/docs/services/eventbridge.md @@ -216,6 +216,7 @@ aws events put-targets \ - A retry uses the target's current definition, so `PutTargets` changes apply to pending retries, and a target removed with `RemoveTargets` stops being retried. - An accepted asynchronous Lambda invocation counts as delivered. A later function error is handled by Lambda's own retry and destination settings, not by the rule. - Pending retries are kept in memory and are dropped by an emulator reset or restart. +- An `AWS::Events::Rule` target in a CloudFormation template keeps its `RetryPolicy`, `DeadLetterConfig`, `RoleArn` and `EcsParameters`, which reach the rule as `PutTargets` would set them. A value of another type than the resource schema declares for them fails the rule before it is created, with the message CloudFormation gives. ## Current Behavior diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationTemplateEngine.java b/src/main/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationTemplateEngine.java index 6a1c6f9a5f..356bd5223e 100644 --- a/src/main/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationTemplateEngine.java +++ b/src/main/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationTemplateEngine.java @@ -280,7 +280,7 @@ public class CloudFormationTemplateEngine { if (node.has("Fn::Split") || node.has("Fn::GetAZs") || node.has("Fn::Cidr")) { return objectMapper.valueToTree(resolveList(node)); } - if (isIntrinsic(node) || node.has(GET_STACK_OUTPUT)) { + if (callsIntrinsic(node)) { return TextNode.valueOf(resolve(node)); } // Plain object: resolve each field. @@ -307,7 +307,14 @@ public class CloudFormationTemplateEngine { return resolveNode(omitNoValue(node)); } - private JsonNode omitNoValue(JsonNode node) { + /** + * The template node with every {@code AWS::NoValue} that stands for a member, a list item or an + * {@code Fn::If} branch left out, and every {@code Fn::If} outside another function replaced by + * the branch its condition chooses; other intrinsic calls stay as they are, unresolved. A + * {@link MissingNode} when the node itself is {@code AWS::NoValue}. A caller that needs to see how + * a member is written, a literal or a call, reads it from here before resolving it. + */ + public JsonNode omitNoValue(JsonNode node) { if (node == null || node.isNull() || node.isMissingNode()) { return node; } @@ -348,6 +355,14 @@ public class CloudFormationTemplateEngine { return node; } + /** + * Whether {@code node} calls an intrinsic function, which {@link #resolveNode} evaluates, rather + * than being a literal object whose fields it resolves one by one. + */ + public static boolean callsIntrinsic(JsonNode node) { + return node.isObject() && (isIntrinsic(node) || node.has(GET_STACK_OUTPUT)); + } + private static boolean isIntrinsic(JsonNode node) { return node.has("Ref") || node.has("Fn::Sub") || node.has("Fn::Join") || node.has("Fn::Select") || node.has("Fn::Base64") || node.has("Fn::GetAtt") diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/CfnPropertyTypes.java b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/CfnPropertyTypes.java new file mode 100644 index 0000000000..64e56a5e70 --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/CfnPropertyTypes.java @@ -0,0 +1,278 @@ +package io.github.hectorvent.floci.services.cloudformation.provisioners; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.node.ArrayNode; +import com.fasterxml.jackson.databind.node.BooleanNode; +import com.fasterxml.jackson.databind.node.IntNode; +import com.fasterxml.jackson.databind.node.JsonNodeFactory; +import com.fasterxml.jackson.databind.node.JsonNodeType; +import com.fasterxml.jackson.databind.node.ObjectNode; +import com.fasterxml.jackson.databind.node.TextNode; +import io.github.hectorvent.floci.core.common.AwsException; +import io.github.hectorvent.floci.services.cloudformation.CloudFormationTemplateEngine; + +import java.math.BigDecimal; +import java.util.List; +import java.util.Map; +import java.util.regex.Pattern; + +/** + * CloudFormation's checks of a property value against the type the resource schema declares, with + * the messages they give (measured in eu-west-1, 2026-10-18). + * + *

Template validation runs over the whole template before any resource is touched and names the + * property, or the list index, alone: "Property [Layers] expected type: JSONArray, found: String". + * Where an object or a list is expected, a number or a boolean reads as a String. Where text is + * expected, any scalar is taken as its text. Where an integer is expected, a whole number or text + * that spells one is taken, and anything else is named by what it is: Float (4.5 or "4.5"), + * Boolean, String, JSONObject, JSONArray. Where a boolean is expected, only an object or a list is + * refused there. A list of strings also takes every intrinsic that yields a list, as + * {@link #readStringList} says. + * + *

The resource handler's model validation runs after it, on the values CloudFormation converted, + * and names the whole path: a boolean that is not true or false in any case, and an integer beyond + * 32 bits, fail as "Model validation failed (#/Targets/0/EcsParameters/EnableECSManagedTags: + * expected type: Boolean, found: String)". + */ +final class CfnPropertyTypes { + + /** A type a resource schema declares for a property. */ + enum Kind { + STRING("String"), INTEGER("Integer"), BOOLEAN("Boolean"), OBJECT("JSONObject"), LIST("JSONArray"); + + private final String schemaName; + + Kind(String schemaName) { + this.schemaName = schemaName; + } + } + + /** A property's type: a scalar, an object with the members it declares, or a list of {@code items}. */ + record Type(Kind kind, Map members, Type items) { + static final Type STRING = new Type(Kind.STRING, null, null); + static final Type INTEGER = new Type(Kind.INTEGER, null, null); + static final Type BOOLEAN = new Type(Kind.BOOLEAN, null, null); + + static Type object(Map members) { + return new Type(Kind.OBJECT, members, null); + } + + static Type list(Type items) { + return new Type(Kind.LIST, null, items); + } + } + + private static final Pattern WHOLE_NUMBER = Pattern.compile("-?\\d+"); + private static final String INTEGER_RANGE_HINT = ". This may occur when a numeric value exceeds 32-bit" + + " integer max (2147483647). Consider using 'number' type or ensure value fits in integer range."; + + private CfnPropertyTypes() { + } + + /** + * Refuses a value of another type than {@code expected}, an object or a list, with template + * validation's message, where a number or a boolean reads as a String. + */ + static void requireType(String property, JsonNode value, JsonNodeType expected) { + if (value.getNodeType() != expected) { + throw templateMismatch(property, expected == JsonNodeType.OBJECT ? Kind.OBJECT : Kind.LIST, + containerName(value)); + } + } + + /** + * The list-of-strings property written as {@code raw} in the template, or null when it is + * {@code Ref: AWS::NoValue}, directly or through {@code Fn::If}. A literal of another type is + * refused (see {@link #requireType}), and so is an intrinsic that yields a string (see + * {@link CloudFormationTemplateEngine#yieldsString}). Any other intrinsic is read through + * {@link CloudFormationTemplateEngine#resolveStringList}, as CloudFormation reads a {@code Ref} + * to a {@code CommaDelimitedList} parameter, which the engine resolves to the comma-joined text, + * and {@code Fn::Split} (measured, eu-west-1, 2026-10-18). + */ + static List readStringList(String property, JsonNode raw, CloudFormationTemplateEngine engine) { + if (raw.isValueNode()) { + requireType(property, raw, JsonNodeType.ARRAY); + } + if (raw.isObject()) { + JsonNode resolved = engine.resolveNodeOmittingNoValue(raw); + if (resolved == null || resolved.isNull() || resolved.isMissingNode()) { + return null; + } + if (resolved.isObject() || (!resolved.isArray() && engine.yieldsString(raw))) { + requireType(property, resolved, JsonNodeType.ARRAY); + } + } + return engine.resolveStringList(raw); + } + + /** + * Reads template values against their declared types and resolves them, converting them as + * CloudFormation does before the handler sees them: an integer or a boolean given as text + * becomes one, and a number or a boolean where text is expected becomes text. Members a type + * does not declare are resolved as they are. What {@code AWS::NoValue} stands for is left out. + * Template validation failures are thrown at once; the first model validation failure waits for + * {@link #finish}, so every value read has passed template validation first, as on AWS. + */ + static final class Reader { + + private final CloudFormationTemplateEngine engine; + private AwsException modelFailure; + + Reader(CloudFormationTemplateEngine engine) { + this.engine = engine; + } + + /** + * The template value {@code raw}, at {@code path} in the resource's properties, read as + * {@code type}; null when it is absent or {@code AWS::NoValue}. + */ + JsonNode read(String path, JsonNode raw, Type type) { + return read(path, path.substring(path.lastIndexOf('/') + 1), engine.omitNoValue(raw), type); + } + + /** Throws the first model validation failure found by {@link #read}, if any. */ + void finish() { + if (modelFailure != null) { + throw modelFailure; + } + } + + private JsonNode read(String path, String property, JsonNode raw, Type type) { + if (raw == null || raw.isNull() || raw.isMissingNode()) { + return null; + } + if (type.kind() == Kind.LIST && type.items().kind() == Kind.STRING) { + return readStringList(property, raw); + } + JsonNode value = raw.isContainerNode() && !CloudFormationTemplateEngine.callsIntrinsic(raw) + ? raw : engine.resolveNode(raw); + if (value == null || value.isNull() || value.isMissingNode()) { + return null; + } + return switch (type.kind()) { + case OBJECT -> readObject(path, property, value, type.members()); + case LIST -> readList(path, property, value, type.items()); + case STRING -> readString(property, value); + case INTEGER -> readInteger(path, property, value); + case BOOLEAN -> readBoolean(path, property, value); + }; + } + + private JsonNode readObject(String path, String property, JsonNode value, Map members) { + requireType(property, value, JsonNodeType.OBJECT); + ObjectNode out = JsonNodeFactory.instance.objectNode(); + for (Map.Entry member : value.properties()) { + Type memberType = members.get(member.getKey()); + JsonNode read = memberType == null ? engine.resolveNode(member.getValue()) + : read(path + "/" + member.getKey(), member.getKey(), member.getValue(), memberType); + if (read != null) { + out.set(member.getKey(), read); + } + } + return out; + } + + private JsonNode readList(String path, String property, JsonNode value, Type items) { + requireType(property, value, JsonNodeType.ARRAY); + ArrayNode out = JsonNodeFactory.instance.arrayNode(); + for (int i = 0; i < value.size(); i++) { + JsonNode read = read(path + "/" + i, String.valueOf(i), value.get(i), items); + if (read != null) { + out.add(read); + } + } + return out; + } + + /** A literal item that is an object or a list is refused by its index, as for any string. */ + private JsonNode readStringList(String property, JsonNode raw) { + if (raw.isArray()) { + for (int i = 0; i < raw.size(); i++) { + JsonNode item = raw.get(i); + if (item.isContainerNode() && !CloudFormationTemplateEngine.callsIntrinsic(item)) { + throw templateMismatch(String.valueOf(i), Kind.STRING, containerName(item)); + } + } + } + List values = CfnPropertyTypes.readStringList(property, raw, engine); + if (values == null) { + return null; + } + ArrayNode out = JsonNodeFactory.instance.arrayNode(); + values.forEach(out::add); + return out; + } + + private static JsonNode readString(String property, JsonNode value) { + if (value.isContainerNode()) { + throw templateMismatch(property, Kind.STRING, containerName(value)); + } + return value.isTextual() ? value : TextNode.valueOf(value.asText()); + } + + private JsonNode readInteger(String path, String property, JsonNode value) { + String text = value.isIntegralNumber() ? value.bigIntegerValue().toString() : value.asText(); + if (value.isContainerNode() || value.isBoolean() || !WHOLE_NUMBER.matcher(text).matches()) { + throw templateMismatch(property, Kind.INTEGER, scalarName(value)); + } + BigDecimal number = new BigDecimal(text); + if (number.compareTo(BigDecimal.valueOf(Integer.MIN_VALUE)) < 0 + || number.compareTo(BigDecimal.valueOf(Integer.MAX_VALUE)) > 0) { + recordModelFailure(path, Kind.INTEGER, INTEGER_RANGE_HINT); + return value; + } + return IntNode.valueOf(number.intValue()); + } + + private JsonNode readBoolean(String path, String property, JsonNode value) { + if (value.isContainerNode()) { + throw templateMismatch(property, Kind.BOOLEAN, containerName(value)); + } + String text = value.asText(); + if ("true".equalsIgnoreCase(text) || "false".equalsIgnoreCase(text)) { + return BooleanNode.valueOf(Boolean.parseBoolean(text)); + } + recordModelFailure(path, Kind.BOOLEAN, ""); + return value; + } + + private void recordModelFailure(String path, Kind expected, String hint) { + if (modelFailure == null) { + modelFailure = new AwsException("InvalidRequest", "Model validation failed (#/" + path + + ": expected type: " + expected.schemaName + ", found: String" + hint + ")", 400); + } + } + } + + private static AwsException templateMismatch(String property, Kind expected, String found) { + return new AwsException("ValidationError", "Property [" + property + "] expected type: " + + expected.schemaName + ", found: " + found, 400); + } + + private static String containerName(JsonNode value) { + return switch (value.getNodeType()) { + case OBJECT -> "JSONObject"; + case ARRAY -> "JSONArray"; + default -> "String"; + }; + } + + /** What template validation calls a value that is not a whole number where an integer is expected. */ + private static String scalarName(JsonNode value) { + if (value.isContainerNode()) { + return containerName(value); + } + if (value.isBoolean()) { + return "Boolean"; + } + if (value.isNumber()) { + return "Float"; + } + try { + new BigDecimal(value.asText()); + return "Float"; + } catch (NumberFormatException notANumber) { + return "String"; + } + } +} diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/EventsCfnProvisioner.java b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/EventsCfnProvisioner.java index 6bc90c132f..f062cee693 100644 --- a/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/EventsCfnProvisioner.java +++ b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/EventsCfnProvisioner.java @@ -9,9 +9,11 @@ import com.fasterxml.jackson.databind.node.JsonNodeFactory; import com.fasterxml.jackson.databind.node.ObjectNode; import io.github.hectorvent.floci.core.common.AwsException; import io.github.hectorvent.floci.services.cloudformation.model.StackResource; +import io.github.hectorvent.floci.services.cloudformation.provisioners.CfnPropertyTypes.Type; import io.github.hectorvent.floci.services.eventbridge.EventBridgeService; import io.github.hectorvent.floci.services.eventbridge.model.ApiDestination; import io.github.hectorvent.floci.services.eventbridge.model.BatchParameters; +import io.github.hectorvent.floci.services.eventbridge.model.EcsParameters; import io.github.hectorvent.floci.services.eventbridge.model.EventBus; import io.github.hectorvent.floci.services.eventbridge.model.HttpParameters; import io.github.hectorvent.floci.services.eventbridge.model.InputTransformer; @@ -51,6 +53,38 @@ public class EventsCfnProvisioner implements CfnResourceProvisioner { private static final Logger LOG = Logger.getLogger(EventsCfnProvisioner.class); private static final ObjectMapper MAPPER = new ObjectMapper(); + /** + * The types AWS::Events::Rule's resource schema gives the target members this provisioner reads + * as typed values (describe-type, eu-west-1, 2026-10-18), in the template's spelling. + */ + private static final Type ECS_PARAMETERS = Type.object(Map.ofEntries( + Map.entry("CapacityProviderStrategy", Type.list(Type.object(Map.of( + "CapacityProvider", Type.STRING, "Base", Type.INTEGER, "Weight", Type.INTEGER)))), + Map.entry("EnableECSManagedTags", Type.BOOLEAN), + Map.entry("EnableExecuteCommand", Type.BOOLEAN), + Map.entry("Group", Type.STRING), + Map.entry("LaunchType", Type.STRING), + Map.entry("NetworkConfiguration", Type.object(Map.of("AwsVpcConfiguration", Type.object(Map.of( + "AssignPublicIp", Type.STRING, + "SecurityGroups", Type.list(Type.STRING), + "Subnets", Type.list(Type.STRING)))))), + Map.entry("PlacementConstraints", Type.list(Type.object(Map.of( + "Expression", Type.STRING, "Type", Type.STRING)))), + Map.entry("PlacementStrategies", Type.list(Type.object(Map.of( + "Field", Type.STRING, "Type", Type.STRING)))), + Map.entry("PlatformVersion", Type.STRING), + Map.entry("PropagateTags", Type.STRING), + Map.entry("ReferenceId", Type.STRING), + Map.entry("TagList", Type.list(Type.object(Map.of("Key", Type.STRING, "Value", Type.STRING)))), + Map.entry("TaskCount", Type.INTEGER), + Map.entry("TaskDefinitionArn", Type.STRING))); + private static final Type TARGETS = Type.list(Type.object(Map.of( + "RoleArn", Type.STRING, + "RetryPolicy", Type.object(Map.of( + "MaximumRetryAttempts", Type.INTEGER, "MaximumEventAgeInSeconds", Type.INTEGER)), + "DeadLetterConfig", Type.object(Map.of("Arn", Type.STRING)), + "EcsParameters", ECS_PARAMETERS))); + private static final String EVENT_BUS_CREATED_TIME_ATTR = "FlociEventBusCreatedTime"; private static final String EVENT_BUS_MANAGED_TAG_KEYS_ATTR = "FlociEventBusManagedTagKeys"; private static final String EVENT_BUS_MANAGED_POLICY_ATTR = "FlociEventBusManagedPolicy"; @@ -143,6 +177,10 @@ public class EventsCfnProvisioner implements CfnResourceProvisioner { String stateStr = ctx.resolveOptional(props, "State"); RuleState state = "DISABLED".equals(stateStr) ? RuleState.DISABLED : RuleState.ENABLED; + // Read before the rule exists, as CloudFormation refuses a target of the wrong type before it + // touches the rule. + List targets = declaredTargets(props, ctx); + Rule rule = eventBridgeService.putRule(ruleName, busName, eventPattern, scheduleExpression, state, description, roleArn, Map.of(), ctx.region()); r.setPhysicalId(ruleName); @@ -154,49 +192,6 @@ public class EventsCfnProvisioner implements CfnResourceProvisioner { r.getAttributes().put("EventBusName", busName); } - // Provision inline targets - List targets = new ArrayList<>(); - if (props != null && props.has("Targets") && props.get("Targets").isArray()) { - for (JsonNode targetNode : props.get("Targets")) { - JsonNode resolved = ctx.engine().resolveNode(targetNode); - String targetId = resolved.path("Id").asText(null); - String targetArn = resolved.path("Arn").asText(null); - String input = resolved.path("Input").asText(null); - String inputPath = resolved.path("InputPath").asText(null); - if (targetId != null && targetArn != null) { - Target target = new Target(targetId, targetArn, input, inputPath); - target.setInputTransformer(InputTransformer.fromJson(resolved.path("InputTransformer"))); - JsonNode httpParamsNode = resolved.path("HttpParameters"); - if (httpParamsNode.isObject()) { - target.setHttpParameters(MAPPER.convertValue(httpParamsNode, HttpParameters.class)); - } - JsonNode sqsParamsNode = resolved.path("SqsParameters"); - if (!sqsParamsNode.isMissingNode() && sqsParamsNode.isObject()) { - String messageGroupId = sqsParamsNode.path("MessageGroupId").asText(null); - if (messageGroupId != null) { - SqsParameters sqsParameters = new SqsParameters(); - sqsParameters.setMessageGroupId(messageGroupId); - target.setSqsParameters(sqsParameters); - } - } - JsonNode batchParamsNode = resolved.path("BatchParameters"); - if (!batchParamsNode.isMissingNode() && batchParamsNode.isObject()) { - JsonNode arrayProperties = batchParamsNode.path("ArrayProperties"); - BatchParameters batchParameters = new BatchParameters(); - batchParameters.setJobDefinition(batchParamsNode.path("JobDefinition").asText(null)); - batchParameters.setJobName(batchParamsNode.path("JobName").asText(null)); - if (arrayProperties.isObject()) { - batchParameters.setArrayProperties(jsonObjectToMap(arrayProperties)); - } - if (batchParamsNode.has("RetryStrategy")) { - batchParameters.setRetryStrategy(batchParamsNode.get("RetryStrategy")); - } - target.setBatchParameters(batchParameters); - } - targets.add(target); - } - } - } if (ctx.isUpdate()) { snapshotTargetsBeforeUpdate(r, ruleName, busName, ctx.region()); } @@ -211,6 +206,80 @@ public class EventsCfnProvisioner implements CfnResourceProvisioner { } } + /** + * The rule's {@code Targets}, each carrying what PutTargets would set. An Fn::If that chooses the + * whole list works, and AWS::NoValue is left out wherever it stands for a member, a list item or + * an Fn::If branch, as CloudFormation leaves them out of the PutTargets call, while a literal "" + * stays. The members typed in {@link #TARGETS} are read against the resource schema's types; the + * others are resolved as they come. + */ + private List declaredTargets(JsonNode props, ProvisionContext ctx) { + List targets = new ArrayList<>(); + if (props == null || !props.has("Targets")) { + return targets; + } + CfnPropertyTypes.Reader types = new CfnPropertyTypes.Reader(ctx.engine()); + JsonNode targetNodes = types.read("Targets", props.get("Targets"), TARGETS); + types.finish(); + if (targetNodes == null || !targetNodes.isArray()) { + return targets; + } + for (JsonNode resolved : targetNodes) { + String targetId = resolved.path("Id").asText(null); + String targetArn = resolved.path("Arn").asText(null); + String input = resolved.path("Input").asText(null); + String inputPath = resolved.path("InputPath").asText(null); + if (targetId == null || targetArn == null) { + continue; + } + Target target = new Target(targetId, targetArn, input, inputPath); + target.setInputTransformer(InputTransformer.fromJson(resolved.path("InputTransformer"))); + JsonNode httpParamsNode = resolved.path("HttpParameters"); + if (httpParamsNode.isObject()) { + target.setHttpParameters(MAPPER.convertValue(httpParamsNode, HttpParameters.class)); + } + JsonNode sqsParamsNode = resolved.path("SqsParameters"); + if (!sqsParamsNode.isMissingNode() && sqsParamsNode.isObject()) { + String messageGroupId = sqsParamsNode.path("MessageGroupId").asText(null); + if (messageGroupId != null) { + SqsParameters sqsParameters = new SqsParameters(); + sqsParameters.setMessageGroupId(messageGroupId); + target.setSqsParameters(sqsParameters); + } + } + JsonNode batchParamsNode = resolved.path("BatchParameters"); + if (!batchParamsNode.isMissingNode() && batchParamsNode.isObject()) { + JsonNode arrayProperties = batchParamsNode.path("ArrayProperties"); + BatchParameters batchParameters = new BatchParameters(); + batchParameters.setJobDefinition(batchParamsNode.path("JobDefinition").asText(null)); + batchParameters.setJobName(batchParamsNode.path("JobName").asText(null)); + if (arrayProperties.isObject()) { + batchParameters.setArrayProperties(jsonObjectToMap(arrayProperties)); + } + if (batchParamsNode.has("RetryStrategy")) { + batchParameters.setRetryStrategy(batchParamsNode.get("RetryStrategy")); + } + target.setBatchParameters(batchParameters); + } + target.setRoleArn(resolved.path("RoleArn").asText(null)); + JsonNode ecsParamsNode = resolved.path("EcsParameters"); + if (ecsParamsNode.isObject()) { + target.setEcsParameters(MAPPER.convertValue( + ecsParametersInApiShape(ecsParamsNode), EcsParameters.class)); + } + JsonNode retryPolicyNode = resolved.path("RetryPolicy"); + if (retryPolicyNode.isObject()) { + target.setRetryPolicy(MAPPER.convertValue(retryPolicyNode, Target.RetryPolicy.class)); + } + JsonNode deadLetterConfigNode = resolved.path("DeadLetterConfig"); + if (deadLetterConfigNode.isObject()) { + target.setDeadLetterConfig(MAPPER.convertValue(deadLetterConfigNode, Target.DeadLetterConfig.class)); + } + targets.add(target); + } + return targets; + } + /** * Records the targets the rule carries before this update reconciles them, so they can be put * back when the stack update fails: by {@link #restoreTargetsAfterFailedUpdate} when this @@ -831,6 +900,44 @@ public class EventsCfnProvisioner implements CfnResourceProvisioner { "ResourceNotFoundException"); } + /** + * A template's {@code EcsParameters} in the shape PutTargets takes. The resource schema + * capitalizes members the EventBridge API spells in camel case ({@code AwsVpcConfiguration}, + * the placement and capacity provider items) and names two lists differently + * ({@code PlacementStrategies}, {@code TagList}); the rest is the same. + */ + private static ObjectNode ecsParametersInApiShape(JsonNode template) { + ObjectNode api = template.deepCopy(); + rename(api, "PlacementStrategies", "PlacementStrategy"); + rename(api, "TagList", "Tags"); + if (api.get("NetworkConfiguration") instanceof ObjectNode network) { + rename(network, "AwsVpcConfiguration", "awsvpcConfiguration"); + } + renameInItems(api.get("PlacementStrategy"), Map.of("Type", "type", "Field", "field")); + renameInItems(api.get("PlacementConstraints"), Map.of("Type", "type", "Expression", "expression")); + renameInItems(api.get("CapacityProviderStrategy"), + Map.of("CapacityProvider", "capacityProvider", "Weight", "weight", "Base", "base")); + return api; + } + + private static void renameInItems(JsonNode items, Map names) { + if (items == null || !items.isArray()) { + return; + } + for (JsonNode item : items) { + if (item instanceof ObjectNode object) { + names.forEach((from, to) -> rename(object, from, to)); + } + } + } + + private static void rename(ObjectNode node, String from, String to) { + JsonNode value = node.remove(from); + if (value != null) { + node.set(to, value); + } + } + /** Copied from the monolith: the shared original serves six other callers and stays there. */ private Map jsonObjectToMap(JsonNode node) { Map out = new LinkedHashMap<>(); diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/LambdaCfnProvisioner.java b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/LambdaCfnProvisioner.java index c5772d7fa3..04525f3603 100644 --- a/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/LambdaCfnProvisioner.java +++ b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/LambdaCfnProvisioner.java @@ -780,7 +780,7 @@ public class LambdaCfnProvisioner implements CfnResourceProvisioner { if (variables == null || variables.isNull() || variables.isMissingNode()) { return Map.of(); } - requireType("Variables", variables, JsonNodeType.OBJECT); + CfnPropertyTypes.requireType("Variables", variables, JsonNodeType.OBJECT); Map vars = new HashMap<>(); variables.fields().forEachRemaining(e -> vars.put(e.getKey(), e.getValue().asText())); return vars; @@ -794,32 +794,15 @@ public class LambdaCfnProvisioner implements CfnResourceProvisioner { /** * The list-of-strings property {@code source}, or null when the template leaves it out, - * {@code Ref: AWS::NoValue} directly or through {@code Fn::If} included. A literal of another - * type is refused (see {@link #requireType}), and so is an intrinsic that yields a string (see - * {@link CloudFormationTemplateEngine#yieldsString}). Any other intrinsic is read through - * {@link CloudFormationTemplateEngine#resolveStringList}, as CloudFormation reads a {@code Ref} - * to a {@code CommaDelimitedList} parameter, which the engine resolves to the comma-joined text, - * and {@code Fn::Split} (measured, eu-west-1, 2026-10-18). + * {@code Ref: AWS::NoValue} directly or through {@code Fn::If} included; see + * {@link CfnPropertyTypes#readStringList}. */ private static List resolveStringList(JsonNode props, String source, CloudFormationTemplateEngine engine) { if (props == null || !props.has(source) || props.get(source).isNull()) { return null; } - JsonNode raw = props.get(source); - if (raw.isValueNode()) { - requireType(source, raw, JsonNodeType.ARRAY); - } - if (raw.isObject()) { - JsonNode resolved = engine.resolveNodeOmittingNoValue(raw); - if (resolved == null || resolved.isNull() || resolved.isMissingNode()) { - return null; - } - if (resolved.isObject() || (!resolved.isArray() && engine.yieldsString(raw))) { - requireType(source, resolved, JsonNodeType.ARRAY); - } - } - return engine.resolveStringList(raw); + return CfnPropertyTypes.readStringList(source, props.get(source), engine); } private List resolveObjectListOrEmpty(JsonNode props, String source, @@ -844,7 +827,7 @@ public class LambdaCfnProvisioner implements CfnResourceProvisioner { /** * The property {@code source}, or null when the template leaves it out, {@code Ref: AWS::NoValue} * directly or through {@code Fn::If} included. A value of another type than {@code expected} is - * refused before the function is touched; see {@link #requireType}. + * refused before the function is touched; see {@link CfnPropertyTypes#requireType}. */ private static JsonNode resolveTyped(JsonNode props, String source, JsonNodeType expected, CloudFormationTemplateEngine engine) { @@ -855,30 +838,10 @@ public class LambdaCfnProvisioner implements CfnResourceProvisioner { if (resolved == null || resolved.isNull() || resolved.isMissingNode()) { return null; } - requireType(source, resolved, expected); + CfnPropertyTypes.requireType(source, resolved, expected); return resolved; } - /** - * Refuses a value of another type than {@code expected} with the message CloudFormation's - * property validation gives (measured in eu-west-1, 2026-10-18), where a number or a boolean - * reads as a String: "Property [Layers] expected type: JSONArray, found: String". - */ - private static void requireType(String property, JsonNode value, JsonNodeType expected) { - if (value.getNodeType() != expected) { - throw new AwsException("ValidationError", "Property [" + property + "] expected type: " - + jsonTypeName(expected) + ", found: " + jsonTypeName(value.getNodeType()), 400); - } - } - - private static String jsonTypeName(JsonNodeType type) { - return switch (type) { - case OBJECT -> "JSONObject"; - case ARRAY -> "JSONArray"; - default -> "String"; - }; - } - private static Map mapWithNullValue(String key) { Map map = new HashMap<>(); map.put(key, null); diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationEventsRuleTargetIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationEventsRuleTargetIntegrationTest.java new file mode 100644 index 0000000000..6f193c3556 --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationEventsRuleTargetIntegrationTest.java @@ -0,0 +1,349 @@ +package io.github.hectorvent.floci.services.cloudformation; + +import io.github.hectorvent.floci.testing.RestAssuredJsonUtils; +import io.quarkus.test.junit.QuarkusTest; +import io.restassured.path.json.JsonPath; +import io.restassured.response.ValidatableResponse; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; + +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; + +import static io.restassured.RestAssured.given; +import static org.hamcrest.Matchers.contains; +import static org.hamcrest.Matchers.emptyOrNullString; +import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.hasKey; +import static org.hamcrest.Matchers.hasSize; +import static org.hamcrest.Matchers.not; +import static org.junit.jupiter.api.Assertions.assertEquals; + +/** + * An {@code AWS::Events::Rule} target's {@code DeadLetterConfig}, {@code RetryPolicy}, + * {@code RoleArn} and {@code EcsParameters} reach the rule as PutTargets would set them, and + * delivery honours the dead-letter queue the stack declares. + */ +@QuarkusTest +class CloudFormationEventsRuleTargetIntegrationTest { + + private static final String EB_CT = "application/x-amz-json-1.1"; + private static final String SQS_CT = "application/x-amz-json-1.0"; + private static final String STACK = "cfn-rule-targets"; + private static final String BUS = "cfn-rule-targets-bus"; + + private static final String TEMPLATE = """ + { + "Resources": { + "Dlq": {"Type": "AWS::SQS::Queue", "Properties": {"QueueName": "cfn-rule-targets-dlq"}}, + "Bus": {"Type": "AWS::Events::EventBus", "Properties": {"Name": "cfn-rule-targets-bus"}}, + "Undeliverable": { + "Type": "AWS::Events::Rule", + "Properties": { + "Name": "cfn-rule-targets-undeliverable", + "EventBusName": {"Ref": "Bus"}, + "EventPattern": {"source": ["cfn.rule.targets"]}, + "Targets": [{ + "Id": "MissingQueue", + "Arn": {"Fn::Sub": "arn:${AWS::Partition}:sqs:${AWS::Region}:${AWS::AccountId}:cfn-rule-targets-missing"}, + "DeadLetterConfig": {"Arn": {"Fn::GetAtt": ["Dlq", "Arn"]}}, + "RetryPolicy": {"MaximumRetryAttempts": 2, "MaximumEventAgeInSeconds": 60} + }] + } + }, + "RunTask": { + "Type": "AWS::Events::Rule", + "Properties": { + "Name": "cfn-rule-targets-ecs", + "EventBusName": {"Ref": "Bus"}, + "EventPattern": {"source": ["cfn.rule.targets.never"]}, + "Targets": [{ + "Id": "Jobs", + "Arn": {"Fn::Sub": "arn:${AWS::Partition}:ecs:${AWS::Region}:${AWS::AccountId}:cluster/jobs"}, + "RoleArn": {"Fn::Sub": "arn:${AWS::Partition}:iam::${AWS::AccountId}:role/events-run-task"}, + "EcsParameters": { + "TaskDefinitionArn": "arn:aws:ecs:us-east-1:000000000000:task-definition/job:1", + "TaskCount": 1, + "LaunchType": "FARGATE", + "NetworkConfiguration": {"AwsVpcConfiguration": { + "Subnets": ["subnet-1"], "SecurityGroups": ["sg-1"], "AssignPublicIp": "DISABLED"}}, + "PlacementStrategies": [{"Type": "spread", "Field": "attribute:ecs.availability-zone"}], + "TagList": [{"Key": "team", "Value": "jobs"}] + } + }] + } + } + } + } + """; + + @BeforeAll + static void configureRestAssured() { + RestAssuredJsonUtils.configureAwsContentTypes(); + } + + @Test + void ruleTargetsKeepTheirDeliverySettingsAndTheDeadLetterQueueReceivesUndeliverableEvents() { + given().contentType("application/x-www-form-urlencoded") + .formParam("Action", "CreateStack") + .formParam("StackName", STACK) + .formParam("TemplateBody", TEMPLATE) + .when().post("/").then().statusCode(200); + assertEquals("CREATE_COMPLETE", CfnStackWaits.awaitTerminal(STACK).status()); + + String dlqUrl = given().contentType(SQS_CT) + .header("X-Amz-Target", "AmazonSQS.GetQueueUrl") + .body("{\"QueueName\":\"cfn-rule-targets-dlq\"}") + .when().post("/").then().statusCode(200) + .extract().jsonPath().getString("QueueUrl"); + String dlqArn = given().contentType(SQS_CT) + .header("X-Amz-Target", "AmazonSQS.GetQueueAttributes") + .body("{\"QueueUrl\":\"" + dlqUrl + "\",\"AttributeNames\":[\"QueueArn\"]}") + .when().post("/").then().statusCode(200) + .extract().jsonPath().getString("Attributes.QueueArn"); + + listTargets("cfn-rule-targets-undeliverable") + .body("Targets", hasSize(1)) + .body("Targets[0].DeadLetterConfig.Arn", equalTo(dlqArn)) + .body("Targets[0].RetryPolicy.MaximumRetryAttempts", equalTo(2)) + .body("Targets[0].RetryPolicy.MaximumEventAgeInSeconds", equalTo(60)) + .body("Targets[0]", not(hasKey("RoleArn"))); + listTargets("cfn-rule-targets-ecs") + .body("Targets[0].RoleArn", equalTo("arn:aws:iam::000000000000:role/events-run-task")) + .body("Targets[0].EcsParameters.TaskDefinitionArn", + equalTo("arn:aws:ecs:us-east-1:000000000000:task-definition/job:1")) + .body("Targets[0].EcsParameters.NetworkConfiguration.awsvpcConfiguration.Subnets[0]", + equalTo("subnet-1")) + .body("Targets[0].EcsParameters.PlacementStrategy[0].type", equalTo("spread")) + .body("Targets[0].EcsParameters.Tags[0].Key", equalTo("team")) + .body("Targets[0]", not(hasKey("RetryPolicy"))) + .body("Targets[0]", not(hasKey("DeadLetterConfig"))); + + given().contentType(EB_CT) + .header("X-Amz-Target", "AWSEvents.PutEvents") + .body(""" + {"Entries": [{"EventBusName": "%s", "Source": "cfn.rule.targets", + "DetailType": "Undeliverable", "Detail": "{\\"orderId\\":\\"o-9\\"}"}]} + """.formatted(BUS)) + .when().post("/").then().statusCode(200) + .body("FailedEntryCount", equalTo(0)); + + String ruleArn = given().contentType(EB_CT) + .header("X-Amz-Target", "AWSEvents.DescribeRule") + .body("{\"Name\":\"cfn-rule-targets-undeliverable\",\"EventBusName\":\"" + BUS + "\"}") + .when().post("/").then().statusCode(200) + .extract().jsonPath().getString("Arn"); + JsonPath received = given().contentType(SQS_CT) + .header("X-Amz-Target", "AmazonSQS.ReceiveMessage") + .body("{\"QueueUrl\":\"" + dlqUrl + "\",\"MaxNumberOfMessages\":10," + + "\"MessageAttributeNames\":[\"All\"]}") + .when().post("/").then().statusCode(200) + .body("Messages", hasSize(1)) + .body("Messages[0].MessageAttributes.RULE_ARN.StringValue", equalTo(ruleArn)) + .body("Messages[0].MessageAttributes.TARGET_ARN.StringValue", + equalTo(dlqArn.replace("cfn-rule-targets-dlq", "cfn-rule-targets-missing"))) + .body("Messages[0].MessageAttributes.ERROR_CODE.StringValue", equalTo("NO_RESOURCE")) + .body("Messages[0].MessageAttributes.ERROR_MESSAGE.StringValue", not(emptyOrNullString())) + .body("Messages[0].MessageAttributes.RETRY_ATTEMPTS.StringValue", equalTo("0")) + .body("Messages[0].MessageAttributes", not(hasKey("EXHAUSTED_RETRY_CONDITION"))) + .extract().jsonPath(); + assertEquals("o-9", new JsonPath(received.getString("Messages[0].Body")).getString("detail.orderId")); + } + + /** + * With the real engine: a member whose Fn::If takes AWS::NoValue is left out of the target, + * and a literal empty string, a tag's Value, is kept. + */ + @Test + void aMemberAnFnIfDropsIsLeftOutAndAnEmptyStringKept() { + String template = """ + {"Conditions": {"Never": {"Fn::Equals": ["a", "b"]}}, + "Resources": {"Rule": {"Type": "AWS::Events::Rule", "Properties": { + "Name": "cfn-rule-targets-novalue", + "EventPattern": {"source": ["cfn.rule.targets.novalue"]}, + "Targets": [{"Id": "Ecs", "Arn": "arn:aws:ecs:us-east-1:000000000000:cluster/jobs", + "RoleArn": {"Fn::If": ["Never", "arn:aws:iam::000000000000:role/never", + {"Ref": "AWS::NoValue"}]}, + "RetryPolicy": {"MaximumRetryAttempts": {"Fn::If": ["Never", 3, {"Ref": "AWS::NoValue"}]}, + "MaximumEventAgeInSeconds": 120}, + "EcsParameters": {"TaskDefinitionArn": "arn:aws:ecs:us-east-1:000000000000:task-definition/job:1", + "TagList": [{"Key": "team", "Value": ""}]}}]}}}} + """; + given().contentType("application/x-www-form-urlencoded") + .formParam("Action", "CreateStack") + .formParam("StackName", "cfn-rule-targets-novalue") + .formParam("TemplateBody", template) + .when().post("/").then().statusCode(200); + try { + assertEquals("CREATE_COMPLETE", CfnStackWaits.awaitTerminal("cfn-rule-targets-novalue").status()); + listTargets("cfn-rule-targets-novalue", "default") + .body("Targets[0]", not(hasKey("RoleArn"))) + .body("Targets[0].RetryPolicy", not(hasKey("MaximumRetryAttempts"))) + .body("Targets[0].RetryPolicy.MaximumEventAgeInSeconds", equalTo(120)) + .body("Targets[0].EcsParameters.Tags[0].Value", equalTo("")); + } finally { + deleteStack("cfn-rule-targets-novalue"); + } + } + + /** An Fn::If that chooses the whole Targets list is resolved before the targets are read. */ + @Test + void targetsAnFnIfChoosesAreProvisioned() { + String template = """ + {"Conditions": {"Always": {"Fn::Equals": ["a", "a"]}}, + "Resources": {"Rule": {"Type": "AWS::Events::Rule", "Properties": { + "Name": "cfn-rule-targets-if", + "EventPattern": {"source": ["cfn.rule.targets.if"]}, + "Targets": {"Fn::If": ["Always", + [{"Id": "Queue", "Arn": "arn:aws:sqs:us-east-1:000000000000:cfn-rule-targets-if"}], + {"Ref": "AWS::NoValue"}]}}}}} + """; + given().contentType("application/x-www-form-urlencoded") + .formParam("Action", "CreateStack") + .formParam("StackName", "cfn-rule-targets-if") + .formParam("TemplateBody", template) + .when().post("/").then().statusCode(200); + try { + assertEquals("CREATE_COMPLETE", CfnStackWaits.awaitTerminal("cfn-rule-targets-if").status()); + listTargets("cfn-rule-targets-if", "default") + .body("Targets[0].Id", equalTo("Queue")) + .body("Targets[0].Arn", equalTo("arn:aws:sqs:us-east-1:000000000000:cfn-rule-targets-if")); + } finally { + deleteStack("cfn-rule-targets-if"); + } + } + + /** + * A target member of the wrong type fails the rule before it exists, with the message measured + * on CloudFormation (eu-west-1, 2026-10-18): template validation's where a member cannot be read + * as the object or the integer the resource schema declares, the handler's model validation for + * a boolean that is neither true nor false. + */ + @Test + void aTargetMemberOfTheWrongTypeFailsTheRuleBeforeItExists() { + Map members = new LinkedHashMap<>(); + members.put("\"RetryPolicy\": {\"MaximumRetryAttempts\": 4.5}", + "Property [MaximumRetryAttempts] expected type: Integer, found: Float"); + members.put("\"DeadLetterConfig\": \"arn:aws:sqs:us-east-1:000000000000:cfn-rule-targets-dlq\"", + "Property [DeadLetterConfig] expected type: JSONObject, found: String"); + members.put("\"EcsParameters\": {\"TaskDefinitionArn\": \"arn:aws:ecs:us-east-1:000000000000:task-definition/job:1\"," + + " \"EnableECSManagedTags\": \"yes\"}", + "Model validation failed (#/Targets/0/EcsParameters/EnableECSManagedTags:" + + " expected type: Boolean, found: String)"); + int n = 0; + for (Map.Entry member : members.entrySet()) { + String stack = "cfn-rule-targets-typed-" + n; + String rule = "cfn-rule-targets-typed-" + n++; + given().contentType("application/x-www-form-urlencoded") + .formParam("Action", "CreateStack") + .formParam("StackName", stack) + .formParam("TemplateBody", """ + {"Resources": {"Rule": {"Type": "AWS::Events::Rule", "Properties": { + "Name": "%s", "EventPattern": {"source": ["cfn.rule.targets.typed"]}, + "Targets": [{"Id": "T", "Arn": "arn:aws:sqs:us-east-1:000000000000:typed", %s}]}}}} + """.formatted(rule, member.getKey())) + .when().post("/").then().statusCode(200); + try { + assertEquals("ROLLBACK_COMPLETE", CfnStackWaits.awaitTerminal(stack).status(), member.getKey()); + assertEquals(member.getValue(), CfnStackWaits.failedResourceReason(stack), member.getKey()); + given().contentType(EB_CT) + .header("X-Amz-Target", "AWSEvents.DescribeRule") + .body("{\"Name\":\"" + rule + "\"}") + .when().post("/").then().statusCode(400) + .body("__type", equalTo("ResourceNotFoundException")); + } finally { + deleteStack(stack); + } + } + } + + /** + * Measured on CloudFormation (eu-west-1, 2026-10-18): a Ref to a CommaDelimitedList, Fn::Split + * and an Fn::If choosing either are lists of subnets, here also inside an EcsParameters an Fn::If + * chooses; a Ref to a String inside a literal list is one subnet; a Ref to a String where the + * list is expected fails template validation. + */ + @Test + void aSubnetListTakesEveryFormThatYieldsAList() { + Map forms = new LinkedHashMap<>(); + forms.put("cdl", "{\"Ref\": \"Cdl\"}"); + forms.put("split", "{\"Fn::Split\": [\",\", {\"Ref\": \"Str\"}]}"); + forms.put("if", "{\"Fn::If\": [\"Yes\", {\"Ref\": \"Cdl\"}, [\"subnet-x\"]]}"); + forms.put("item", "[{\"Ref\": \"Str\"}]"); + StringBuilder rules = new StringBuilder(); + forms.forEach((name, subnets) -> rules.append(rules.isEmpty() ? "" : ",").append(listRule(name, + "{\"TaskDefinitionArn\": \"arn:aws:ecs:us-east-1:000000000000:task-definition/job:1\"," + + " \"NetworkConfiguration\": {\"AwsVpcConfiguration\": {\"Subnets\": " + subnets + "}}}"))); + rules.append(",").append(listRule("chosen", "{\"Fn::If\": [\"Yes\", {\"TaskDefinitionArn\":" + + " \"arn:aws:ecs:us-east-1:000000000000:task-definition/job:1\", \"NetworkConfiguration\":" + + " {\"AwsVpcConfiguration\": {\"Subnets\": {\"Ref\": \"Cdl\"}}}}, {\"Ref\": \"AWS::NoValue\"}]}")); + String stack = "cfn-rule-targets-lists"; + createListStack(stack, rules.toString()); + try { + assertEquals("CREATE_COMPLETE", CfnStackWaits.awaitTerminal(stack).status()); + for (String name : List.of("cdl", "split", "if", "chosen")) { + listTargets("cfn-rule-targets-list-" + name, "default") + .body("Targets[0].EcsParameters.NetworkConfiguration.awsvpcConfiguration.Subnets", + contains("subnet-a", "subnet-b")); + } + listTargets("cfn-rule-targets-list-item", "default") + .body("Targets[0].EcsParameters.NetworkConfiguration.awsvpcConfiguration.Subnets", + contains("subnet-a,subnet-b")); + } finally { + deleteStack(stack); + } + + String refused = "cfn-rule-targets-list-string"; + createListStack(refused, listRule("string", "{\"TaskDefinitionArn\":" + + " \"arn:aws:ecs:us-east-1:000000000000:task-definition/job:1\", \"NetworkConfiguration\":" + + " {\"AwsVpcConfiguration\": {\"Subnets\": {\"Ref\": \"Str\"}}}}")); + try { + assertEquals("ROLLBACK_COMPLETE", CfnStackWaits.awaitTerminal(refused).status()); + assertEquals("Property [Subnets] expected type: JSONArray, found: String", + CfnStackWaits.failedResourceReason(refused)); + } finally { + deleteStack(refused); + } + } + + private static String listRule(String name, String ecsParameters) { + return """ + "Rule%s": {"Type": "AWS::Events::Rule", "Properties": { + "Name": "cfn-rule-targets-list-%s", "EventPattern": {"source": ["cfn.rule.targets.list"]}, + "Targets": [{"Id": "T", "Arn": "arn:aws:ecs:us-east-1:000000000000:cluster/jobs", + "RoleArn": "arn:aws:iam::000000000000:role/events-run-task", "EcsParameters": %s}]}} + """.formatted(name.substring(0, 1).toUpperCase() + name.substring(1), name, ecsParameters); + } + + private static void createListStack(String stack, String resources) { + given().contentType("application/x-www-form-urlencoded") + .formParam("Action", "CreateStack") + .formParam("StackName", stack) + .formParam("TemplateBody", """ + {"Parameters": {"Cdl": {"Type": "CommaDelimitedList", "Default": "subnet-a,subnet-b"}, + "Str": {"Type": "String", "Default": "subnet-a,subnet-b"}}, + "Conditions": {"Yes": {"Fn::Equals": ["a", "a"]}}, + "Resources": {%s}} + """.formatted(resources)) + .when().post("/").then().statusCode(200); + } + + private static void deleteStack(String stack) { + given().contentType("application/x-www-form-urlencoded") + .formParam("Action", "DeleteStack") + .formParam("StackName", stack) + .when().post("/").then().statusCode(200); + } + + private static ValidatableResponse listTargets(String rule) { + return listTargets(rule, BUS); + } + + private static ValidatableResponse listTargets(String rule, String bus) { + return given().contentType(EB_CT) + .header("X-Amz-Target", "AWSEvents.ListTargetsByRule") + .body("{\"Rule\":\"" + rule + "\",\"EventBusName\":\"" + bus + "\"}") + .when().post("/").then().statusCode(200); + } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/EventsCfnProvisionerTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/EventsCfnProvisionerTest.java index e4def3e78d..b36dfac116 100644 --- a/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/EventsCfnProvisionerTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/EventsCfnProvisionerTest.java @@ -9,15 +9,21 @@ import io.github.hectorvent.floci.services.cloudformation.CloudFormationTemplate import io.github.hectorvent.floci.services.cloudformation.model.StackResource; import io.github.hectorvent.floci.services.eventbridge.EventBridgeService; import io.github.hectorvent.floci.services.eventbridge.model.ApiDestination; +import io.github.hectorvent.floci.services.eventbridge.model.EcsParameters; import io.github.hectorvent.floci.services.eventbridge.model.HttpParameters; import io.github.hectorvent.floci.services.eventbridge.model.Rule; import io.github.hectorvent.floci.services.eventbridge.model.Target; import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; import org.mockito.ArgumentCaptor; import org.mockito.stubbing.OngoingStubbing; +import java.util.ArrayList; import java.util.HashMap; import java.util.List; +import java.util.stream.Stream; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; @@ -52,6 +58,13 @@ class EventsCfnProvisionerTest { return node == null ? null : node.asText(); }); when(engine.resolveNode(any())).thenAnswer(inv -> inv.getArgument(0)); + when(engine.resolveNodeOmittingNoValue(any())).thenAnswer(inv -> inv.getArgument(0)); + when(engine.omitNoValue(any())).thenAnswer(inv -> inv.getArgument(0)); + when(engine.resolveStringList(any())).thenAnswer(inv -> { + List values = new ArrayList<>(); + ((JsonNode) inv.getArgument(0)).forEach(value -> values.add(value.asText())); + return values; + }); return new ProvisionContext(engine, REGION, "000000000000", "my-stack", priorPhysicalId); } @@ -155,6 +168,249 @@ class EventsCfnProvisionerTest { verify(events, never()).removeTargets(anyString(), any(), any(), anyString()); } + // ── each target carries what PutTargets would set ──────────────────────── + + @Test + void aTargetKeepsItsDeadLetterConfigRetryPolicyRoleAndEcsParameters() throws Exception { + // The provisioner copied Id, Arn, the inputs, SqsParameters and BatchParameters only, so a + // stack's dead-letter queue and retry policy never reached delivery and an undeliverable + // event was logged and lost. + stubPutRule(); + ObjectNode props = mapper.createObjectNode().put("Name", "orders"); + props.putArray("Targets").add(mapper.readTree(""" + {"Id": "Run", "Arn": "arn:aws:ecs:us-east-1:000000000000:cluster/jobs", + "RoleArn": "arn:aws:iam::000000000000:role/events-run-task", + "DeadLetterConfig": {"Arn": "arn:aws:sqs:us-east-1:000000000000:orders-dlq"}, + "RetryPolicy": {"MaximumRetryAttempts": 3, "MaximumEventAgeInSeconds": 120}, + "EcsParameters": { + "TaskDefinitionArn": "arn:aws:ecs:us-east-1:000000000000:task-definition/job:1", + "TaskCount": 2, "LaunchType": "FARGATE", + "NetworkConfiguration": {"AwsVpcConfiguration": { + "Subnets": ["subnet-1"], "SecurityGroups": ["sg-1"], "AssignPublicIp": "DISABLED"}}, + "PlacementStrategies": [{"Type": "spread", "Field": "attribute:ecs.availability-zone"}], + "PlacementConstraints": [{"Type": "memberOf", "Expression": "attribute:ecs.os-type == linux"}], + "CapacityProviderStrategy": [{"CapacityProvider": "FARGATE_SPOT", "Weight": 1, "Base": 0}], + "TagList": [{"Key": "team", "Value": "jobs"}]}} + """)); + + provisioner.provision(resource("AWS::Events::Rule", "Rule"), props, ctx(null)); + + Target put = onlyPutTarget(); + assertEquals("arn:aws:iam::000000000000:role/events-run-task", put.getRoleArn()); + assertEquals("arn:aws:sqs:us-east-1:000000000000:orders-dlq", put.getDeadLetterConfig().arn()); + assertEquals(new Target.RetryPolicy(3, 120), put.getRetryPolicy()); + EcsParameters ecs = put.getEcsParameters(); + assertEquals("arn:aws:ecs:us-east-1:000000000000:task-definition/job:1", ecs.getTaskDefinitionArn()); + assertEquals(2, ecs.getTaskCount()); + assertEquals("FARGATE", ecs.getLaunchType()); + assertEquals(List.of("subnet-1"), ecs.getNetworkConfiguration().getAwsvpcConfiguration().getSubnets()); + assertEquals("DISABLED", ecs.getNetworkConfiguration().getAwsvpcConfiguration().getAssignPublicIp()); + assertEquals(mapper.readTree("[{\"type\": \"spread\", \"field\": \"attribute:ecs.availability-zone\"}]"), + ecs.getPlacementStrategy()); + assertEquals(mapper.readTree("[{\"type\": \"memberOf\", \"expression\": \"attribute:ecs.os-type == linux\"}]"), + ecs.getPlacementConstraints()); + assertEquals(mapper.readTree("[{\"capacityProvider\": \"FARGATE_SPOT\", \"weight\": 1, \"base\": 0}]"), + ecs.getCapacityProviderStrategy()); + assertEquals(mapper.readTree("[{\"Key\": \"team\", \"Value\": \"jobs\"}]"), ecs.getTags()); + } + + @Test + void aRetryPolicyResolvedToTextIsReadAsNumbers() throws Exception { + // A Ref or Fn::Sub resolves to text, which the template still means as an integer. + stubPutRule(); + ObjectNode props = mapper.createObjectNode().put("Name", "orders"); + props.putArray("Targets").add(mapper.readTree(""" + {"Id": "Q", "Arn": "arn:aws:sqs:us-east-1:000000000000:q", + "RetryPolicy": {"MaximumRetryAttempts": "0", "MaximumEventAgeInSeconds": "60"}} + """)); + + provisioner.provision(resource("AWS::Events::Rule", "Rule"), props, ctx(null)); + + assertEquals(new Target.RetryPolicy(0, 60), onlyPutTarget().getRetryPolicy()); + } + + /** + * With a real engine: a member or list item that is AWS::NoValue, directly or as the Fn::If + * branch taken, is left out, as CloudFormation leaves it out of PutTargets, at any depth. A + * literal empty string is a value and stays, such as a tag's empty Value. + */ + @Test + void membersThatAreNoValueAreLeftOutAndEmptyStringsKept() throws Exception { + stubPutRule(); + ObjectNode props = mapper.createObjectNode().put("Name", "orders"); + props.putArray("Targets").add(mapper.readTree(""" + {"Id": "Q", "Arn": "arn:aws:sqs:us-east-1:000000000000:q", "RoleArn": {"Ref": "AWS::NoValue"}, + "RetryPolicy": {"MaximumRetryAttempts": {"Ref": "AWS::NoValue"}, "MaximumEventAgeInSeconds": "60"}, + "EcsParameters": {"TaskDefinitionArn": "arn:aws:ecs:us-east-1:000000000000:task-definition/jobs:1", + "TaskCount": {"Ref": "AWS::NoValue"}, + "TagList": [{"Ref": "AWS::NoValue"}, {"Key": "team", "Value": ""}]}, + "DeadLetterConfig": {"Ref": "AWS::NoValue"}} + """)); + + provisioner.provision(resource("AWS::Events::Rule", "Rule"), props, new ProvisionContext( + CloudFormationTemplateEngine.standalone("000000000000", REGION, "my-stack", mapper, null), + REGION, "000000000000", "my-stack", null)); + + Target put = onlyPutTarget(); + assertNull(put.getRoleArn()); + assertNull(put.getDeadLetterConfig()); + assertEquals(new Target.RetryPolicy(null, 60), put.getRetryPolicy()); + assertNull(put.getEcsParameters().getTaskCount()); + assertEquals(mapper.readTree("[{\"Key\": \"team\", \"Value\": \"\"}]"), put.getEcsParameters().getTags()); + } + + @Test + void aTargetWithoutThemLeavesThemUnset() { + // Unset means EventBridge's defaults (185 attempts, 24 hours, no dead-letter queue). + stubPutRule(); + ObjectNode props = mapper.createObjectNode().put("Name", "orders"); + props.putArray("Targets").add(target("Q", "arn:aws:sqs:us-east-1:000000000000:q")); + + provisioner.provision(resource("AWS::Events::Rule", "Rule"), props, ctx(null)); + + Target put = onlyPutTarget(); + assertNull(put.getRetryPolicy()); + assertNull(put.getDeadLetterConfig()); + assertNull(put.getRoleArn()); + assertNull(put.getEcsParameters()); + } + + /** + * Measured on CloudFormation (eu-west-1, 2026-10-18): a member the resource schema types fails + * template validation, naming the member or the list index, or the handler's model validation, + * naming the whole path, before the rule exists. + */ + @ParameterizedTest(name = "{0}") + @MethodSource("mistypedMembers") + void aMemberOfTheWrongTypeFailsBeforeTheRuleExists(String members, String code, String message) throws Exception { + ObjectNode props = mapper.createObjectNode().put("Name", "orders"); + props.putArray("Targets").add(((ObjectNode) mapper.readTree(members)) + .put("Id", "T").put("Arn", "arn:aws:ecs:us-east-1:000000000000:cluster/jobs")); + + AwsException e = assertThrows(AwsException.class, + () -> provisioner.provision(resource("AWS::Events::Rule", "Rule"), props, ctx(null))); + + assertEquals(code, e.getErrorCode()); + assertEquals(message, e.getMessage()); + verify(events, never()).putRule(anyString(), any(), any(), any(), any(), any(), any(), any(), anyString()); + verify(events, never()).putTargets(anyString(), any(), any(), anyString()); + } + + static Stream mistypedMembers() { + String template = "ValidationError"; + String model = "InvalidRequest"; + String range = ". This may occur when a numeric value exceeds 32-bit integer max (2147483647)." + + " Consider using 'number' type or ensure value fits in integer range."; + return Stream.of( + Arguments.of("{\"RetryPolicy\": \"x\"}", template, + "Property [RetryPolicy] expected type: JSONObject, found: String"), + Arguments.of("{\"RetryPolicy\": 5}", template, + "Property [RetryPolicy] expected type: JSONObject, found: String"), + Arguments.of("{\"RetryPolicy\": []}", template, + "Property [RetryPolicy] expected type: JSONObject, found: JSONArray"), + Arguments.of("{\"RetryPolicy\": {\"MaximumRetryAttempts\": \"abc\"}}", template, + "Property [MaximumRetryAttempts] expected type: Integer, found: String"), + Arguments.of("{\"RetryPolicy\": {\"MaximumRetryAttempts\": 4.5}}", template, + "Property [MaximumRetryAttempts] expected type: Integer, found: Float"), + Arguments.of("{\"RetryPolicy\": {\"MaximumRetryAttempts\": \"4.5\"}}", template, + "Property [MaximumRetryAttempts] expected type: Integer, found: Float"), + Arguments.of("{\"RetryPolicy\": {\"MaximumRetryAttempts\": true}}", template, + "Property [MaximumRetryAttempts] expected type: Integer, found: Boolean"), + Arguments.of("{\"RetryPolicy\": {\"MaximumRetryAttempts\": {\"a\": 1}}}", template, + "Property [MaximumRetryAttempts] expected type: Integer, found: JSONObject"), + Arguments.of("{\"RetryPolicy\": {\"MaximumRetryAttempts\": [1]}}", template, + "Property [MaximumRetryAttempts] expected type: Integer, found: JSONArray"), + Arguments.of("{\"DeadLetterConfig\": \"arn:aws:sqs:us-east-1:000000000000:dlq\"}", template, + "Property [DeadLetterConfig] expected type: JSONObject, found: String"), + Arguments.of("{\"DeadLetterConfig\": {\"Arn\": {\"a\": 1}}}", template, + "Property [Arn] expected type: String, found: JSONObject"), + Arguments.of("{\"EcsParameters\": \"x\"}", template, + "Property [EcsParameters] expected type: JSONObject, found: String"), + Arguments.of("{\"EcsParameters\": {\"TaskCount\": \"abc\"}}", template, + "Property [TaskCount] expected type: Integer, found: String"), + Arguments.of("{\"EcsParameters\": {\"NetworkConfiguration\": \"x\"}}", template, + "Property [NetworkConfiguration] expected type: JSONObject, found: String"), + Arguments.of("{\"EcsParameters\": {\"NetworkConfiguration\": {\"AwsVpcConfiguration\": " + + "{\"Subnets\": \"subnet-1\"}}}}", template, + "Property [Subnets] expected type: JSONArray, found: String"), + Arguments.of("{\"EcsParameters\": {\"NetworkConfiguration\": {\"AwsVpcConfiguration\": " + + "{\"Subnets\": [{\"a\": 1}]}}}}", template, + "Property [0] expected type: String, found: JSONObject"), + Arguments.of("{\"EcsParameters\": {\"TagList\": {\"Key\": \"a\", \"Value\": \"b\"}}}", template, + "Property [TagList] expected type: JSONArray, found: JSONObject"), + Arguments.of("{\"EcsParameters\": {\"TagList\": [\"a\"]}}", template, + "Property [0] expected type: JSONObject, found: String"), + Arguments.of("{\"EcsParameters\": {\"EnableECSManagedTags\": {\"a\": 1}}}", template, + "Property [EnableECSManagedTags] expected type: Boolean, found: JSONObject"), + Arguments.of("{\"EcsParameters\": {\"EnableECSManagedTags\": [true]}}", template, + "Property [EnableECSManagedTags] expected type: Boolean, found: JSONArray"), + Arguments.of("{\"EcsParameters\": {\"Group\": {\"a\": 1}}}", template, + "Property [Group] expected type: String, found: JSONObject"), + Arguments.of("{\"EcsParameters\": {\"Group\": [\"a\"]}}", template, + "Property [Group] expected type: String, found: JSONArray"), + Arguments.of("{\"RetryPolicy\": {\"MaximumRetryAttempts\": 3000000000}}", model, + "Model validation failed (#/Targets/0/RetryPolicy/MaximumRetryAttempts:" + + " expected type: Integer, found: String" + range + ")"), + Arguments.of("{\"EcsParameters\": {\"TaskCount\": \"3000000000\"}}", model, + "Model validation failed (#/Targets/0/EcsParameters/TaskCount:" + + " expected type: Integer, found: String" + range + ")"), + Arguments.of("{\"EcsParameters\": {\"EnableECSManagedTags\": 1}}", model, + "Model validation failed (#/Targets/0/EcsParameters/EnableECSManagedTags:" + + " expected type: Boolean, found: String)"), + Arguments.of("{\"EcsParameters\": {\"EnableECSManagedTags\": \"yes\"}}", model, + "Model validation failed (#/Targets/0/EcsParameters/EnableECSManagedTags:" + + " expected type: Boolean, found: String)")); + } + + @Test + void templateValidationFailsBeforeAnEarlierTargetFailsModelValidation() throws Exception { + // CloudFormation validates the whole template before the handler validates its model. + ObjectNode props = mapper.createObjectNode().put("Name", "orders"); + props.putArray("Targets") + .add(mapper.readTree(""" + {"Id": "A", "Arn": "arn:aws:ecs:us-east-1:000000000000:cluster/jobs", + "EcsParameters": {"EnableECSManagedTags": "yes"}} + """)) + .add(mapper.readTree(""" + {"Id": "B", "Arn": "arn:aws:sqs:us-east-1:000000000000:q", "RetryPolicy": "x"} + """)); + + AwsException e = assertThrows(AwsException.class, + () -> provisioner.provision(resource("AWS::Events::Rule", "Rule"), props, ctx(null))); + + assertEquals("Property [RetryPolicy] expected type: JSONObject, found: String", e.getMessage()); + } + + @Test + void valuesAreConvertedAsCloudFormationConvertsThem() throws Exception { + // Measured: "TRUE" is true, a number in a list of strings is its text, and an integer + // given as text is the integer. + stubPutRule(); + ObjectNode props = mapper.createObjectNode().put("Name", "orders"); + props.putArray("Targets").add(mapper.readTree(""" + {"Id": "Run", "Arn": "arn:aws:ecs:us-east-1:000000000000:cluster/jobs", + "EcsParameters": {"TaskDefinitionArn": "arn:aws:ecs:us-east-1:000000000000:task-definition/job:1", + "TaskCount": "3", "EnableECSManagedTags": "TRUE", + "NetworkConfiguration": {"AwsVpcConfiguration": {"Subnets": [5]}}}} + """)); + + provisioner.provision(resource("AWS::Events::Rule", "Rule"), props, new ProvisionContext( + CloudFormationTemplateEngine.standalone("000000000000", REGION, "my-stack", mapper, null), + REGION, "000000000000", "my-stack", null)); + + EcsParameters ecs = onlyPutTarget().getEcsParameters(); + assertEquals(3, ecs.getTaskCount()); + assertEquals(Boolean.TRUE, ecs.getEnableECSManagedTags()); + assertEquals(List.of("5"), ecs.getNetworkConfiguration().getAwsvpcConfiguration().getSubnets()); + } + + private Target onlyPutTarget() { + ArgumentCaptor> put = ArgumentCaptor.forClass(List.class); + verify(events).putTargets(eq("orders"), any(), put.capture(), anyString()); + assertEquals(1, put.getValue().size()); + return put.getValue().getFirst(); + } + // ── a failed policy removal is not swallowed ───────────────────────────── @Test diff --git a/src/test/java/io/github/hectorvent/floci/services/eventbridge/EventBridgeTargetRetryIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/eventbridge/EventBridgeTargetRetryIntegrationTest.java index 80dec525ed..3de22dd694 100644 --- a/src/test/java/io/github/hectorvent/floci/services/eventbridge/EventBridgeTargetRetryIntegrationTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/eventbridge/EventBridgeTargetRetryIntegrationTest.java @@ -66,7 +66,7 @@ class EventBridgeTargetRetryIntegrationTest { @Test @Order(2) - void listTargetsByRuleEchoesRetryPolicyAndDeadLetterConfig() { + void listTargetsByRuleEchoesRoleRetryPolicyAndDeadLetterConfig() { given() .contentType(EB_CT) .header("X-Amz-Target", "AWSEvents.PutTargets") @@ -77,6 +77,7 @@ class EventBridgeTargetRetryIntegrationTest { { "Id": "WithPolicies", "Arn": "%s", + "RoleArn": "arn:aws:iam::000000000000:role/eb-retry-target-role", "RetryPolicy": {"MaximumRetryAttempts": 4, "MaximumEventAgeInSeconds": 120}, "DeadLetterConfig": {"Arn": "%s"} }, @@ -98,6 +99,9 @@ class EventBridgeTargetRetryIntegrationTest { .body("Targets.find { it.Id == 'WithPolicies' }.RetryPolicy.MaximumRetryAttempts", equalTo(4)) .body("Targets.find { it.Id == 'WithPolicies' }.RetryPolicy.MaximumEventAgeInSeconds", equalTo(120)) .body("Targets.find { it.Id == 'WithPolicies' }.DeadLetterConfig.Arn", equalTo(dlqArn)) + .body("Targets.find { it.Id == 'WithPolicies' }.RoleArn", + equalTo("arn:aws:iam::000000000000:role/eb-retry-target-role")) + .body("Targets.find { it.Id == 'Plain' }", not(hasKey("RoleArn"))) .body("Targets.find { it.Id == 'Plain' }", not(hasKey("RetryPolicy"))) .body("Targets.find { it.Id == 'Plain' }", not(hasKey("DeadLetterConfig")));