mirror of
https://github.com/floci-io/floci.git
synced 2026-12-01 01:12:48 -05:00
fix(cloudformation): keep a rule target's dead-letter queue, retry policy, role and ECS parameters (#5958)
* fix(cloudformation): keep a rule target's dead-letter queue, retry policy, role and ECS parameters EventsCfnProvisioner built each AWS::Events::Rule target from Id, Arn, the inputs, HttpParameters, SqsParameters and BatchParameters only. A target's DeadLetterConfig and RetryPolicy were dropped, so ListTargetsByRule showed neither, delivery ran on the defaults (185 attempts over 24 hours) and an event the target could not take was logged and lost instead of reaching the queue the stack declared. RoleArn and EcsParameters, which PutTargets keeps, were dropped as well. Targets set through PutTargets already get the delivery semantics from TargetDispatcher, so the provisioner now passes the four members through, validated by putTargets as the API validates them. EcsParameters is converted to the API's shape: the resource schema spells AwsVpcConfiguration, PlacementStrategies, TagList and the placement and capacity provider items differently from the EventBridge API, which spells them awsvpcConfiguration, PlacementStrategy, Tags and in camel case; ListTargetsByRule on AWS returns the converted shape (measured). RoleArn is stored, not used for delivery, as Floci does not invoke targets under the role. Targets is resolved once, with the engine's resolveNodeOmittingNoValue, so an Fn::If choosing the whole list works, and a member, a list item or an Fn::If branch that is AWS::NoValue is left out of the call while a literal "" stays. An earlier version marked AWS::NoValue itself before resolving, with a sentinel; the engine's rule does the same without one. The four members are read against the types AWS::Events::Rule's resource schema gives them, before the rule exists, with the messages measured on CloudFormation (eu-west-1): template validation's "Property [MaximumRetryAttempts] expected type: Integer, found: Float", and the handler's "Model validation failed (#/Targets/0/EcsParameters/ EnableECSManagedTags: expected type: Boolean, found: String)" for what only the handler refuses, which waits until every target has passed template validation, as on AWS. What CloudFormation converts is converted the same way: "4" is 4, "TRUE" is true, 5 in a list of strings is "5". Reading them with convertValue alone truncated 4.5 to 4, ignored a RetryPolicy given as a string and failed on "abc" with Jackson's message. A list of strings (Subnets, SecurityGroups) takes every form that yields a list on AWS, as Lambda's list properties do since #5923 and #5949: a Ref to a CommaDelimitedList, Fn::Split and an Fn::If choosing either, also inside an EcsParameters an Fn::If chooses; a Ref to a String is refused (measured). That is why the reader walks the template as written, with the engine's omitNoValue, now public, and resolves each call it meets, instead of checking the resolved tree, where a CommaDelimitedList is already text. The check is the new CfnPropertyTypes, which also takes over LambdaCfnProvisioner's requireType and its list-of-strings reading, so template validation has one implementation for both provisioners. * test(cloudformation): read the rule's only target without List.getFirst The SDK compatibility tests compile for Java 17, which has no List.getFirst; the image build of sdk-test-java and ec2-containers failed on it. A local JDK 25 with source 17 does not check the API, so the class was compiled again with --release 17. * test(compat): wait for a stack 50 ms at a time against Floci Review of #5958: TestFixtures.awaitStackTerminal slept 500 ms between checks, so each stack, which Floci finishes in milliseconds, cost at least half a second. It now checks every 50 ms against Floci, as the integration tests' CfnStackWaits does, and keeps 500 ms against real AWS. The rule target test waits 10 seconds for a stack against Floci instead of 60, and 10 minutes against AWS, where the queues take minutes.
This commit is contained in:
1 parent
6027872078
commit
d60c973865
10 files changed
+1261
-91
No files matched your search
+349
@@ -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<String, String> 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<String, String> 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<String, String> 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);
|
||||
}
|
||||
}
|
||||
+256
@@ -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<String> 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<Arguments> 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<List<Target>> 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
|
||||
|
||||
+5
-1
@@ -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")));
|
||||
|
||||
|
||||
Reference in new issue
Block a user