mirror of
https://github.com/floci-io/floci.git
synced 2026-12-01 01:12:48 -05:00
feat(cloudformation): provision AWS::Events::EventBus as a real custom bus (#1807)
* feat(cloudformation): provision EventBridge event buses * fix(cloudformation): restore main's provisioner changes lost in the EventBus merge The previous conflict resolution took this branch's whole CloudFormationResourceProvisioner, which silently reverted five commits main had landed on that file since the merge base — including the DynamoDB/Lambda delete idempotency from #1803 and AWS::EC2::LaunchTemplate from #1973. Re-resolve from main's file and apply only this branch's EventBus additions on top: the ownership-tracking provisioner, its validation helpers, and the typed rethrow in deleteEventBridgeRuleSafe. main's provisionEventBusPolicy and inline Policy support are kept, with Policy added to EVENT_BUS_SUPPORTED_PROPERTIES so the inline form is no longer rejected. * fix(cloudformation): delete EventBus resources created before ownership tracking deleteEventBusSafe(StackResource) refused to delete whenever the FlociEventBusCreatedTime attribute was absent, treating "ownership not tracked" the same as "ownership changed". Stacks provisioned by an earlier Floci build are restored from cloudformation-stacks.json without that attribute, so the first DeleteStack after upgrading left them permanently in DELETE_FAILED. Only refuse when a recorded created-time actually disagrees with the live bus. A missing attribute falls back to the pre-tracking behaviour of deleting what the stack recorded it created. * fix(cloudformation): adopt untracked EventBus on update and record identity before the policy call Two provision-side defects, both surfaced in review: UpdateStack broke for stacks provisioned before FlociEventBusCreatedTime existed. Those resources are restored without the attribute, so the adoption guard's 'existingCreatedTime == null' arm re-threw ResourceAlreadyExists on every update, including no-ops. Same inverted guard the delete path already uses: only a recorded time that actually disagrees means the bus was recreated out of band. The bus also leaked when Policy application failed. r.setPhysicalId ran after putPermission, and rollbackCreatedResources skips resources whose physicalId is null, so a malformed policy left a live bus rollback could not find. Identity and ROLLBACK_OWNED_ATTR are now recorded before the policy call, matching how provisionIamRole marks a freshly created role. The attribute is cleared on the adoption path so rollback never deletes a bus this stack did not create. * chore: re-run CI Build and Test failed on RuntimeApiServerTest's extension/stop race, a pre-existing flake unrelated to this change (no CloudFormation test failed). Root-caused separately: test-timing half in #2141, server-side shutdown-ordering half filed as an issue. * fix(cloudformation): adopt tagged pre-tracking event buses * test(dynamodb): retain Quarkus port for cleanup * chore: rerun CI after download outage * fix(cloudformation): reject unsafe EventBus policy updates --------- Co-authored-by: Alexander Banna <abanna@users.noreply.github.com>
This commit is contained in:
1 parent
33ba5ac59c
commit
bc21367cc4
10 files changed
+1824
-69
No files matched your search
+765
@@ -0,0 +1,765 @@
|
||||
package io.github.hectorvent.floci.services.cloudformation;
|
||||
|
||||
import io.github.hectorvent.floci.testing.RestAssuredJsonUtils;
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import org.junit.jupiter.api.BeforeAll;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.ValueSource;
|
||||
|
||||
import static io.restassured.RestAssured.given;
|
||||
import static org.hamcrest.Matchers.containsString;
|
||||
|
||||
/**
|
||||
* Verifies CloudFormation provisions {@code AWS::Events::EventBus} as a real custom EventBridge bus.
|
||||
*
|
||||
* <p>Previously the type had no provisioner case, so it fell through to the generic stub: the resource
|
||||
* reported CREATE_COMPLETE with a physical id but the bus was never registered with the EventBridge
|
||||
* service. Any {@code AWS::Events::Rule} referencing it via {@code {"Ref": bus}} then failed
|
||||
* "EventBus not found", rolling the whole stack back. Per the AWS spec {@code Ref} returns the bus
|
||||
* <em>name</em> and {@code Fn::GetAtt "Arn"} the ARN.
|
||||
*
|
||||
* <p>All resources are metadata-only (no container), so the test is Docker-free.
|
||||
*/
|
||||
@QuarkusTest
|
||||
class CloudFormationEventBusIntegrationTest {
|
||||
|
||||
private static final String CFN_AUTH =
|
||||
"AWS4-HMAC-SHA256 Credential=test/20260205/us-east-1/cloudformation/aws4_request";
|
||||
private static final String EVENTS_AUTH =
|
||||
"AWS4-HMAC-SHA256 Credential=test/20260205/us-east-1/events/aws4_request";
|
||||
|
||||
@BeforeAll
|
||||
static void configureRestAssured() {
|
||||
RestAssuredJsonUtils.configureAwsContentTypes();
|
||||
}
|
||||
|
||||
private void createStack(String stackName, String template) {
|
||||
given()
|
||||
.contentType("application/x-www-form-urlencoded")
|
||||
.header("Authorization", CFN_AUTH)
|
||||
.formParam("Action", "CreateStack")
|
||||
.formParam("StackName", stackName)
|
||||
.formParam("TemplateBody", template)
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200);
|
||||
}
|
||||
|
||||
private void assertStackStatus(String stackName, String status) {
|
||||
given()
|
||||
.contentType("application/x-www-form-urlencoded")
|
||||
.header("Authorization", CFN_AUTH)
|
||||
.formParam("Action", "DescribeStacks")
|
||||
.formParam("StackName", stackName)
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body(containsString("<StackStatus>" + status + "</StackStatus>"));
|
||||
}
|
||||
|
||||
private void deleteStack(String stackName) {
|
||||
given()
|
||||
.contentType("application/x-www-form-urlencoded")
|
||||
.header("Authorization", CFN_AUTH)
|
||||
.formParam("Action", "DeleteStack")
|
||||
.formParam("StackName", stackName)
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200);
|
||||
}
|
||||
|
||||
private void updateStack(String stackName, String template) {
|
||||
given()
|
||||
.contentType("application/x-www-form-urlencoded")
|
||||
.header("Authorization", CFN_AUTH)
|
||||
.formParam("Action", "UpdateStack")
|
||||
.formParam("StackName", stackName)
|
||||
.formParam("TemplateBody", template)
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200);
|
||||
}
|
||||
|
||||
private String describeStackResources(String stackName) {
|
||||
return given()
|
||||
.contentType("application/x-www-form-urlencoded")
|
||||
.header("Authorization", CFN_AUTH)
|
||||
.formParam("Action", "DescribeStackResources")
|
||||
.formParam("StackName", stackName)
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.extract().asString();
|
||||
}
|
||||
|
||||
private String describeStackEvents(String stackName) {
|
||||
return given()
|
||||
.contentType("application/x-www-form-urlencoded")
|
||||
.header("Authorization", CFN_AUTH)
|
||||
.formParam("Action", "DescribeStackEvents")
|
||||
.formParam("StackName", stackName)
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.extract().asString();
|
||||
}
|
||||
|
||||
private String getTemplate(String stackName) {
|
||||
return given()
|
||||
.contentType("application/x-www-form-urlencoded")
|
||||
.header("Authorization", CFN_AUTH)
|
||||
.formParam("Action", "GetTemplate")
|
||||
.formParam("StackName", stackName)
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.extract().asString();
|
||||
}
|
||||
|
||||
private static String eventBusOnlyTemplate(String busName, String description) {
|
||||
String nameProperty = busName == null ? "" : "\"Name\": \"" + busName + "\",";
|
||||
return """
|
||||
{
|
||||
"Resources": {
|
||||
"Bus": {
|
||||
"Type": "AWS::Events::EventBus",
|
||||
"Properties": {
|
||||
%s
|
||||
"Description": "%s"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
""".formatted(nameProperty, description);
|
||||
}
|
||||
|
||||
private static String eventBusWithTagsTemplate(String busName, String tags) {
|
||||
return """
|
||||
{
|
||||
"Resources": {
|
||||
"Bus": {
|
||||
"Type": "AWS::Events::EventBus",
|
||||
"Properties": {
|
||||
"Name": "%s",
|
||||
"Description": "tagged bus",
|
||||
"Tags": %s
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
""".formatted(busName, tags);
|
||||
}
|
||||
|
||||
private static String eventBusWithPolicyTemplate(String busName, String statementId) {
|
||||
return """
|
||||
{
|
||||
"Resources": {
|
||||
"Bus": {
|
||||
"Type": "AWS::Events::EventBus",
|
||||
"Properties": {
|
||||
"Name": "%s",
|
||||
"Policy": {
|
||||
"Version": "2012-10-17",
|
||||
"Statement": [{
|
||||
"Sid": "%s",
|
||||
"Effect": "Allow",
|
||||
"Principal": "*",
|
||||
"Action": "events:PutEvents",
|
||||
"Resource": "*"
|
||||
}]
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
""".formatted(busName, statementId);
|
||||
}
|
||||
|
||||
private void callEventBridge(String target, String body, int expectedStatus) {
|
||||
given()
|
||||
.contentType("application/x-amz-json-1.1")
|
||||
.header("Authorization", EVENTS_AUTH)
|
||||
.header("X-Amz-Target", target)
|
||||
.body(body)
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(expectedStatus);
|
||||
}
|
||||
|
||||
private static String eventBusAndRuleTemplate(String busName) {
|
||||
return """
|
||||
{
|
||||
"Resources": {
|
||||
"Bus": {
|
||||
"Type": "AWS::Events::EventBus",
|
||||
"Properties": { "Name": "%s" }
|
||||
},
|
||||
"Rule": {
|
||||
"Type": "AWS::Events::Rule",
|
||||
"Properties": {
|
||||
"EventBusName": { "Ref": "Bus" },
|
||||
"EventPattern": { "source": ["com.example.orders"] },
|
||||
"State": "ENABLED"
|
||||
}
|
||||
}
|
||||
},
|
||||
"Outputs": {
|
||||
"BusRef": { "Value": { "Ref": "Bus" } },
|
||||
"BusArn": { "Value": { "Fn::GetAtt": ["Bus", "Arn"] } }
|
||||
}
|
||||
}
|
||||
""".formatted(busName);
|
||||
}
|
||||
|
||||
@Test
|
||||
void customEventBusIsRegisteredSoRuleReferencingItSucceeds() throws InterruptedException {
|
||||
String suffix = Long.toString(System.nanoTime(), 36);
|
||||
String busName = "domain-events-" + suffix;
|
||||
String stackName = "eventbus-stack-" + suffix;
|
||||
|
||||
// The stub-only behaviour failed the Rule with "EventBus not found" -> ROLLBACK.
|
||||
createStack(stackName, eventBusAndRuleTemplate(busName));
|
||||
assertStackStatus(stackName, "CREATE_COMPLETE");
|
||||
|
||||
// Ref returns the bus NAME (not the ARN) per the AWS spec.
|
||||
given()
|
||||
.contentType("application/x-www-form-urlencoded")
|
||||
.header("Authorization", CFN_AUTH)
|
||||
.formParam("Action", "DescribeStacks")
|
||||
.formParam("StackName", stackName)
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body(containsString("<OutputKey>BusRef</OutputKey>"))
|
||||
.body(containsString("<OutputValue>" + busName + "</OutputValue>"))
|
||||
.body(containsString("event-bus/" + busName));
|
||||
|
||||
// The bus is really registered with the EventBridge service (not just a stub).
|
||||
given()
|
||||
.contentType("application/x-amz-json-1.1")
|
||||
.header("Authorization", EVENTS_AUTH)
|
||||
.header("X-Amz-Target", "AWSEvents.DescribeEventBus")
|
||||
.body("{\"Name\":\"" + busName + "\"}")
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body(containsString(busName));
|
||||
|
||||
// Deleting the stack must remove the bus (and its rule) from EventBridge, not leak it: the
|
||||
// rule lives on the custom bus, so its cleanup must target that bus or the bus delete fails.
|
||||
deleteStack(stackName);
|
||||
awaitStackDeleted(stackName);
|
||||
given()
|
||||
.contentType("application/x-amz-json-1.1")
|
||||
.header("Authorization", EVENTS_AUTH)
|
||||
.header("X-Amz-Target", "AWSEvents.DescribeEventBus")
|
||||
.body("{\"Name\":\"" + busName + "\"}")
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(400)
|
||||
.body(containsString("ResourceNotFoundException"));
|
||||
}
|
||||
|
||||
private void awaitStackDeleted(String stackName) throws InterruptedException {
|
||||
String lastBody = null;
|
||||
for (int i = 0; i < 100; i++) {
|
||||
lastBody = given()
|
||||
.contentType("application/x-www-form-urlencoded")
|
||||
.header("Authorization", CFN_AUTH)
|
||||
.formParam("Action", "DescribeStacks")
|
||||
.formParam("StackName", stackName)
|
||||
.when().post("/").then().extract().asString();
|
||||
if (lastBody.contains("does not exist")
|
||||
|| lastBody.contains("<StackStatus>DELETE_COMPLETE</StackStatus>")) {
|
||||
return;
|
||||
}
|
||||
if (lastBody.contains("<StackStatus>DELETE_FAILED</StackStatus>")) {
|
||||
throw new AssertionError("Stack " + stackName + " deletion failed: " + lastBody);
|
||||
}
|
||||
Thread.sleep(50);
|
||||
}
|
||||
throw new AssertionError(
|
||||
"Timed out waiting for stack " + stackName + " to be deleted. Last response: " + lastBody);
|
||||
}
|
||||
|
||||
private void awaitStackStatus(String stackName, String expectedStatus) throws InterruptedException {
|
||||
String lastBody = null;
|
||||
for (int i = 0; i < 100; i++) {
|
||||
lastBody = given()
|
||||
.contentType("application/x-www-form-urlencoded")
|
||||
.header("Authorization", CFN_AUTH)
|
||||
.formParam("Action", "DescribeStacks")
|
||||
.formParam("StackName", stackName)
|
||||
.when().post("/").then().extract().asString();
|
||||
if (lastBody.contains("<StackStatus>" + expectedStatus + "</StackStatus>")) {
|
||||
return;
|
||||
}
|
||||
Thread.sleep(50);
|
||||
}
|
||||
throw new AssertionError("Timed out waiting for stack " + stackName + " to reach "
|
||||
+ expectedStatus + ". Last response: " + lastBody);
|
||||
}
|
||||
|
||||
@Test
|
||||
void eventBusWithExistingNameInAnotherStackFailsWithoutAdoption() throws InterruptedException {
|
||||
String suffix = Long.toString(System.nanoTime(), 36);
|
||||
String busName = "collision-bus-" + suffix;
|
||||
String stackA = "eventbus-collision-a-" + suffix;
|
||||
String stackB = "eventbus-collision-b-" + suffix;
|
||||
|
||||
createStack(stackA, eventBusAndRuleTemplate(busName));
|
||||
assertStackStatus(stackA, "CREATE_COMPLETE");
|
||||
|
||||
// A second stack must not adopt a bus owned by the first stack.
|
||||
createStack(stackB, eventBusAndRuleTemplate(busName));
|
||||
assertStackStatus(stackB, "ROLLBACK_COMPLETE");
|
||||
String resources = describeStackResources(stackB);
|
||||
if (!resources.contains("<ResourceStatus>CREATE_FAILED</ResourceStatus>")) {
|
||||
throw new AssertionError("collision failure was not preserved: " + resources);
|
||||
}
|
||||
String events = describeStackEvents(stackB);
|
||||
if (!events.contains("EventBus already exists: " + busName)) {
|
||||
throw new AssertionError("collision reason was not preserved: " + events);
|
||||
}
|
||||
|
||||
deleteStack(stackB);
|
||||
awaitStackDeleted(stackB);
|
||||
callEventBridge("AWSEvents.DescribeEventBus", "{\"Name\":\"" + busName + "\"}", 200);
|
||||
|
||||
deleteStack(stackA);
|
||||
awaitStackDeleted(stackA);
|
||||
|
||||
given()
|
||||
.contentType("application/x-amz-json-1.1")
|
||||
.header("Authorization", EVENTS_AUTH)
|
||||
.header("X-Amz-Target", "AWSEvents.DescribeEventBus")
|
||||
.body("{\"Name\":\"" + busName + "\"}")
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(400)
|
||||
.body(containsString("ResourceNotFoundException"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void sameStackNoOpUpdateReusesOwnedBusAndMutableDescriptionIsRejected()
|
||||
throws InterruptedException {
|
||||
String suffix = Long.toString(System.nanoTime(), 36);
|
||||
String busName = "update-bus-" + suffix;
|
||||
String stackName = "eventbus-update-" + suffix;
|
||||
String originalTemplate = eventBusOnlyTemplate(busName, "before");
|
||||
|
||||
createStack(stackName, originalTemplate);
|
||||
assertStackStatus(stackName, "CREATE_COMPLETE");
|
||||
|
||||
updateStack(stackName, originalTemplate);
|
||||
assertStackStatus(stackName, "UPDATE_COMPLETE");
|
||||
|
||||
updateStack(stackName, eventBusOnlyTemplate(busName, "after"));
|
||||
assertStackStatus(stackName, "UPDATE_ROLLBACK_COMPLETE");
|
||||
|
||||
given()
|
||||
.contentType("application/x-amz-json-1.1")
|
||||
.header("Authorization", EVENTS_AUTH)
|
||||
.header("X-Amz-Target", "AWSEvents.DescribeEventBus")
|
||||
.body("{\"Name\":\"" + busName + "\"}")
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body(containsString("\"Description\":\"before\""));
|
||||
|
||||
String activeTemplate = getTemplate(stackName);
|
||||
if (!activeTemplate.contains("before") || activeTemplate.contains("after")) {
|
||||
throw new AssertionError("failed update replaced the active template: " + activeTemplate);
|
||||
}
|
||||
|
||||
deleteStack(stackName);
|
||||
awaitStackDeleted(stackName);
|
||||
}
|
||||
|
||||
@Test
|
||||
void explicitBusNameChangeFailsWithoutReplacingOwnedBus() throws InterruptedException {
|
||||
String suffix = Long.toString(System.nanoTime(), 36);
|
||||
String originalName = "original-bus-" + suffix;
|
||||
String replacementName = "replacement-bus-" + suffix;
|
||||
String stackName = "eventbus-rename-" + suffix;
|
||||
|
||||
createStack(stackName, eventBusOnlyTemplate(originalName, "original"));
|
||||
assertStackStatus(stackName, "CREATE_COMPLETE");
|
||||
|
||||
updateStack(stackName, eventBusOnlyTemplate(replacementName, "replacement"));
|
||||
assertStackStatus(stackName, "UPDATE_ROLLBACK_COMPLETE");
|
||||
|
||||
callEventBridge("AWSEvents.DescribeEventBus", "{\"Name\":\"" + originalName + "\"}", 200);
|
||||
callEventBridge("AWSEvents.DescribeEventBus", "{\"Name\":\"" + replacementName + "\"}", 400);
|
||||
String activeTemplate = getTemplate(stackName);
|
||||
if (!activeTemplate.contains(originalName) || activeTemplate.contains(replacementName)) {
|
||||
throw new AssertionError("failed update replaced the active template: " + activeTemplate);
|
||||
}
|
||||
|
||||
updateStack(stackName, eventBusOnlyTemplate(null, "missing"));
|
||||
assertStackStatus(stackName, "UPDATE_ROLLBACK_COMPLETE");
|
||||
callEventBridge("AWSEvents.DescribeEventBus", "{\"Name\":\"" + originalName + "\"}", 200);
|
||||
|
||||
deleteStack(stackName);
|
||||
awaitStackDeleted(stackName);
|
||||
callEventBridge("AWSEvents.DescribeEventBus", "{\"Name\":\"" + originalName + "\"}", 400);
|
||||
}
|
||||
|
||||
@Test
|
||||
void eventBusNameIsRequired() {
|
||||
String suffix = Long.toString(System.nanoTime(), 36);
|
||||
String stackName = "eventbus-missing-name-" + suffix;
|
||||
|
||||
createStack(stackName, eventBusOnlyTemplate(null, "missing"));
|
||||
assertStackStatus(stackName, "ROLLBACK_COMPLETE");
|
||||
String events = describeStackEvents(stackName);
|
||||
if (!events.contains("Name is required for AWS::Events::EventBus")) {
|
||||
throw new AssertionError("missing-name failure was not preserved: " + events);
|
||||
}
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(strings = {"default", "contains/slash", "contains space", "contains*star"})
|
||||
void invalidCustomEventBusNamesFailValidation(String busName) {
|
||||
String suffix = Long.toString(System.nanoTime(), 36);
|
||||
String stackName = "eventbus-invalid-name-" + suffix;
|
||||
|
||||
createStack(stackName, eventBusOnlyTemplate(busName, "invalid"));
|
||||
assertStackStatus(stackName, "ROLLBACK_COMPLETE");
|
||||
String events = describeStackEvents(stackName);
|
||||
if (!events.contains("Invalid custom event bus Name")) {
|
||||
throw new AssertionError("invalid-name failure was not preserved: " + events);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void eventBusNameAndDescriptionLengthLimitsAreValidated() {
|
||||
String suffix = Long.toString(System.nanoTime(), 36);
|
||||
String longNameStack = "eventbus-long-name-" + suffix;
|
||||
createStack(longNameStack, eventBusOnlyTemplate("n".repeat(257), "invalid"));
|
||||
assertStackStatus(longNameStack, "ROLLBACK_COMPLETE");
|
||||
if (!describeStackEvents(longNameStack).contains("Invalid custom event bus Name")) {
|
||||
throw new AssertionError("long-name validation failure was not preserved");
|
||||
}
|
||||
|
||||
String longDescriptionStack = "eventbus-long-description-" + suffix;
|
||||
createStack(longDescriptionStack,
|
||||
eventBusOnlyTemplate("valid-bus-" + suffix, "d".repeat(513)));
|
||||
assertStackStatus(longDescriptionStack, "ROLLBACK_COMPLETE");
|
||||
if (!describeStackEvents(longDescriptionStack).contains(
|
||||
"Description must not exceed 512 characters")) {
|
||||
throw new AssertionError("long-description validation failure was not preserved");
|
||||
}
|
||||
}
|
||||
|
||||
// "Policy" is deliberately absent: an inline resource policy is supported (see
|
||||
// provisionEventBridgeEventBus), so rejecting it would regress templates main supports today.
|
||||
@ParameterizedTest
|
||||
@ValueSource(strings = {
|
||||
"EventSourceName", "KmsKeyIdentifier", "DeadLetterConfig", "LogConfig"
|
||||
})
|
||||
void unsupportedEventBusPropertiesFailInsteadOfBeingIgnored(String propertyName) {
|
||||
String suffix = Long.toString(System.nanoTime(), 36);
|
||||
String stackName = "eventbus-unsupported-property-" + suffix;
|
||||
String template = """
|
||||
{
|
||||
"Resources": {
|
||||
"Bus": {
|
||||
"Type": "AWS::Events::EventBus",
|
||||
"Properties": {
|
||||
"Name": "unsupported-property-%s",
|
||||
"%s": "unsupported"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
""".formatted(suffix, propertyName);
|
||||
|
||||
createStack(stackName, template);
|
||||
assertStackStatus(stackName, "ROLLBACK_COMPLETE");
|
||||
String events = describeStackEvents(stackName);
|
||||
if (!events.contains("Unsupported AWS::Events::EventBus properties: " + propertyName)) {
|
||||
throw new AssertionError("unsupported-property failure was not preserved: " + events);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void mutableEventBusTagUpdateRollsBackWithoutChangingTags() throws InterruptedException {
|
||||
String suffix = Long.toString(System.nanoTime(), 36);
|
||||
String busName = "tagged-bus-" + suffix;
|
||||
String stackName = "eventbus-tags-" + suffix;
|
||||
|
||||
createStack(stackName, eventBusWithTagsTemplate(busName, """
|
||||
[{"Key":"keep","Value":"before"},{"Key":"remove","Value":"old"}]
|
||||
"""));
|
||||
assertStackStatus(stackName, "CREATE_COMPLETE");
|
||||
|
||||
String busArn = "arn:aws:events:us-east-1:000000000000:event-bus/" + busName;
|
||||
callEventBridge("AWSEvents.TagResource", """
|
||||
{"ResourceARN":"%s","Tags":[{"Key":"external","Value":"preserve"}]}
|
||||
""".formatted(busArn), 200);
|
||||
|
||||
updateStack(stackName, eventBusWithTagsTemplate(busName, """
|
||||
[{"Key":"keep","Value":"after"},{"Key":"add","Value":"new"}]
|
||||
"""));
|
||||
assertStackStatus(stackName, "UPDATE_ROLLBACK_COMPLETE");
|
||||
|
||||
String tags = given()
|
||||
.contentType("application/x-amz-json-1.1")
|
||||
.header("Authorization", EVENTS_AUTH)
|
||||
.header("X-Amz-Target", "AWSEvents.ListTagsForResource")
|
||||
.body("{\"ResourceARN\":\"" + busArn + "\"}")
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.extract().asString();
|
||||
if (!tags.contains("\"Key\":\"keep\",\"Value\":\"before\"")
|
||||
|| !tags.contains("\"Key\":\"remove\",\"Value\":\"old\"")
|
||||
|| !tags.contains("\"Key\":\"external\",\"Value\":\"preserve\"")
|
||||
|| tags.contains("\"Key\":\"add\"")
|
||||
|| tags.contains("\"Value\":\"after\"")) {
|
||||
throw new AssertionError("failed update changed event bus tags: " + tags);
|
||||
}
|
||||
|
||||
deleteStack(stackName);
|
||||
awaitStackDeleted(stackName);
|
||||
}
|
||||
|
||||
@Test
|
||||
void mutableEventBusPolicyUpdateRollsBackWithoutChangingPolicy() throws InterruptedException {
|
||||
String suffix = Long.toString(System.nanoTime(), 36);
|
||||
String busName = "policy-bus-" + suffix;
|
||||
String stackName = "eventbus-policy-" + suffix;
|
||||
String originalTemplate = eventBusWithPolicyTemplate(busName, "Before");
|
||||
|
||||
createStack(stackName, originalTemplate);
|
||||
assertStackStatus(stackName, "CREATE_COMPLETE");
|
||||
|
||||
updateStack(stackName, originalTemplate);
|
||||
assertStackStatus(stackName, "UPDATE_COMPLETE");
|
||||
|
||||
updateStack(stackName, eventBusWithPolicyTemplate(busName, "After"));
|
||||
assertStackStatus(stackName, "UPDATE_ROLLBACK_COMPLETE");
|
||||
|
||||
given()
|
||||
.contentType("application/x-amz-json-1.1")
|
||||
.header("Authorization", EVENTS_AUTH)
|
||||
.header("X-Amz-Target", "AWSEvents.DescribeEventBus")
|
||||
.body("{\"Name\":\"" + busName + "\"}")
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body("Policy", containsString("Before"));
|
||||
|
||||
String activeTemplate = getTemplate(stackName);
|
||||
if (!activeTemplate.contains("Before") || activeTemplate.contains("After")) {
|
||||
throw new AssertionError("failed policy update replaced the active template: " + activeTemplate);
|
||||
}
|
||||
|
||||
deleteStack(stackName);
|
||||
awaitStackDeleted(stackName);
|
||||
}
|
||||
|
||||
@Test
|
||||
void invalidEventBusTagsFailValidation() {
|
||||
String suffix = Long.toString(System.nanoTime(), 36);
|
||||
String[][] cases = {
|
||||
{"reserved-lower", """
|
||||
[{"Key":"aws:reserved","Value":"value"}]
|
||||
""", "reserved aws: prefix"},
|
||||
{"reserved-upper", """
|
||||
[{"Key":"AWS:reserved","Value":"value"}]
|
||||
""", "reserved aws: prefix"},
|
||||
{"invalid-key", """
|
||||
[{"Key":"bad*key","Value":"value"}]
|
||||
""", "Key contains unsupported characters"},
|
||||
{"invalid-value", """
|
||||
[{"Key":"key","Value":"bad*value"}]
|
||||
""", "Value contains unsupported characters"},
|
||||
{"duplicate-key", """
|
||||
[{"Key":"duplicate","Value":"one"},{"Key":"duplicate","Value":"two"}]
|
||||
""", "Duplicate event bus tag Key"}
|
||||
};
|
||||
|
||||
for (String[] testCase : cases) {
|
||||
String stackName = "eventbus-invalid-tag-" + testCase[0] + "-" + suffix;
|
||||
createStack(stackName,
|
||||
eventBusWithTagsTemplate("invalid-tag-" + testCase[0] + "-" + suffix,
|
||||
testCase[1]));
|
||||
assertStackStatus(stackName, "ROLLBACK_COMPLETE");
|
||||
String events = describeStackEvents(stackName);
|
||||
if (!events.contains(testCase[2])) {
|
||||
throw new AssertionError(
|
||||
testCase[0] + " tag failure was not preserved: " + events);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void eventBusTagCountAndLengthLimitsAreValidated() {
|
||||
String suffix = Long.toString(System.nanoTime(), 36);
|
||||
StringBuilder tooManyTags = new StringBuilder("[");
|
||||
for (int i = 0; i < 51; i++) {
|
||||
if (i > 0) {
|
||||
tooManyTags.append(',');
|
||||
}
|
||||
tooManyTags.append("""
|
||||
{"Key":"key-%d","Value":"value"}
|
||||
""".formatted(i).strip());
|
||||
}
|
||||
tooManyTags.append(']');
|
||||
|
||||
String[][] cases = {
|
||||
{"too-many", tooManyTags.toString(), "supports at most 50 tags"},
|
||||
{"long-key", """
|
||||
[{"Key":"%s","Value":"value"}]
|
||||
""".formatted("k".repeat(129)), "Key must contain 1 to 128 characters"},
|
||||
{"long-value", """
|
||||
[{"Key":"key","Value":"%s"}]
|
||||
""".formatted("v".repeat(257)), "Value must contain at most 256 characters"}
|
||||
};
|
||||
|
||||
for (String[] testCase : cases) {
|
||||
String stackName = "eventbus-tag-limit-" + testCase[0] + "-" + suffix;
|
||||
createStack(stackName,
|
||||
eventBusWithTagsTemplate("tag-limit-" + testCase[0] + "-" + suffix,
|
||||
testCase[1]));
|
||||
assertStackStatus(stackName, "ROLLBACK_COMPLETE");
|
||||
String events = describeStackEvents(stackName);
|
||||
if (!events.contains(testCase[2])) {
|
||||
throw new AssertionError(
|
||||
testCase[0] + " tag failure was not preserved: " + events);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void updateDoesNotAdoptBusRecreatedUnderSameName() throws InterruptedException {
|
||||
String suffix = Long.toString(System.nanoTime(), 36);
|
||||
String busName = "recreated-bus-" + suffix;
|
||||
String stackName = "eventbus-recreated-" + suffix;
|
||||
String template = eventBusOnlyTemplate(busName, "owned");
|
||||
|
||||
createStack(stackName, template);
|
||||
assertStackStatus(stackName, "CREATE_COMPLETE");
|
||||
callEventBridge("AWSEvents.DeleteEventBus", "{\"Name\":\"" + busName + "\"}", 200);
|
||||
Thread.sleep(2);
|
||||
callEventBridge("AWSEvents.CreateEventBus",
|
||||
"{\"Name\":\"" + busName + "\",\"Description\":\"external\"}", 200);
|
||||
|
||||
updateStack(stackName, template);
|
||||
assertStackStatus(stackName, "UPDATE_ROLLBACK_COMPLETE");
|
||||
callEventBridge("AWSEvents.DescribeEventBus", "{\"Name\":\"" + busName + "\"}", 200);
|
||||
|
||||
deleteStack(stackName);
|
||||
awaitStackStatus(stackName, "DELETE_FAILED");
|
||||
callEventBridge("AWSEvents.DescribeEventBus", "{\"Name\":\"" + busName + "\"}", 200);
|
||||
|
||||
callEventBridge("AWSEvents.DeleteEventBus", "{\"Name\":\"" + busName + "\"}", 200);
|
||||
deleteStack(stackName);
|
||||
awaitStackDeleted(stackName);
|
||||
}
|
||||
|
||||
@Test
|
||||
void eventBusDeleteFailurePropagatesAndRetrySucceeds() throws InterruptedException {
|
||||
String suffix = Long.toString(System.nanoTime(), 36);
|
||||
String busName = "blocked-delete-bus-" + suffix;
|
||||
String ruleName = "external-rule-" + suffix;
|
||||
String stackName = "eventbus-blocked-delete-" + suffix;
|
||||
|
||||
createStack(stackName, eventBusOnlyTemplate(busName, "blocked"));
|
||||
assertStackStatus(stackName, "CREATE_COMPLETE");
|
||||
callEventBridge("AWSEvents.PutRule", """
|
||||
{"Name":"%s","EventBusName":"%s","EventPattern":"{\\\"source\\\":[\\\"external\\\"]}"}
|
||||
""".formatted(ruleName, busName), 200);
|
||||
|
||||
deleteStack(stackName);
|
||||
awaitStackStatus(stackName, "DELETE_FAILED");
|
||||
callEventBridge("AWSEvents.DescribeEventBus", "{\"Name\":\"" + busName + "\"}", 200);
|
||||
|
||||
callEventBridge("AWSEvents.DeleteRule",
|
||||
"{\"Name\":\"" + ruleName + "\",\"EventBusName\":\"" + busName + "\"}", 200);
|
||||
deleteStack(stackName);
|
||||
awaitStackDeleted(stackName);
|
||||
callEventBridge("AWSEvents.DescribeEventBus", "{\"Name\":\"" + busName + "\"}", 400);
|
||||
}
|
||||
|
||||
@Test
|
||||
void deletingStackTreatsAlreadyAbsentBusAsSuccess() throws InterruptedException {
|
||||
String suffix = Long.toString(System.nanoTime(), 36);
|
||||
String busName = "already-gone-bus-" + suffix;
|
||||
String stackName = "eventbus-already-gone-" + suffix;
|
||||
|
||||
createStack(stackName, eventBusOnlyTemplate(busName, "gone"));
|
||||
assertStackStatus(stackName, "CREATE_COMPLETE");
|
||||
callEventBridge("AWSEvents.DeleteEventBus", "{\"Name\":\"" + busName + "\"}", 200);
|
||||
|
||||
deleteStack(stackName);
|
||||
awaitStackDeleted(stackName);
|
||||
}
|
||||
|
||||
@Test
|
||||
void failedStackCreateRollsBackRuleAndCustomEventBus() {
|
||||
String suffix = Long.toString(System.nanoTime(), 36);
|
||||
String busName = "rollback-bus-" + suffix;
|
||||
String stackName = "eventbus-rollback-" + suffix;
|
||||
String template = """
|
||||
{
|
||||
"Resources": {
|
||||
"Bus": {
|
||||
"Type": "AWS::Events::EventBus",
|
||||
"Properties": { "Name": "%s" }
|
||||
},
|
||||
"Rule": {
|
||||
"Type": "AWS::Events::Rule",
|
||||
"DependsOn": "Bus",
|
||||
"Properties": {
|
||||
"EventBusName": { "Ref": "Bus" },
|
||||
"EventPattern": { "source": ["com.example.rollback"] },
|
||||
"State": "ENABLED"
|
||||
}
|
||||
},
|
||||
"BadSecret": {
|
||||
"Type": "AWS::SecretsManager::Secret",
|
||||
"DependsOn": "Rule",
|
||||
"Properties": {
|
||||
"Name": "rollback-secret-%s",
|
||||
"SecretString": "explicit",
|
||||
"GenerateSecretString": { "PasswordLength": 32 }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
""".formatted(busName, suffix);
|
||||
|
||||
createStack(stackName, template);
|
||||
assertStackStatus(stackName, "ROLLBACK_COMPLETE");
|
||||
|
||||
given()
|
||||
.contentType("application/x-amz-json-1.1")
|
||||
.header("Authorization", EVENTS_AUTH)
|
||||
.header("X-Amz-Target", "AWSEvents.DescribeEventBus")
|
||||
.body("{\"Name\":\"" + busName + "\"}")
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(400)
|
||||
.body(containsString("ResourceNotFoundException"));
|
||||
}
|
||||
}
|
||||
+132
@@ -0,0 +1,132 @@
|
||||
package io.github.hectorvent.floci.services.cloudformation;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
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.CloudFormationResourceRegistry;
|
||||
import io.github.hectorvent.floci.services.eventbridge.EventBridgeService;
|
||||
import io.github.hectorvent.floci.services.eventbridge.model.EventBus;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.util.List;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.never;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
/**
|
||||
* Deleting an {@code AWS::Events::EventBus} is guarded by the created-time recorded at provision
|
||||
* time, so a bus that was destroyed and recreated under the same name out of band is not deleted
|
||||
* out from under whoever owns it now.
|
||||
*/
|
||||
class EventBusDeleteOwnershipTest {
|
||||
|
||||
private static final String REGION = "us-east-1";
|
||||
private static final String BUS = "orders-bus";
|
||||
private static final String CREATED_TIME_ATTR = "FlociEventBusCreatedTime";
|
||||
|
||||
private EventBridgeService eventBridgeService;
|
||||
private CloudFormationResourceProvisioner provisioner;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
eventBridgeService = mock(EventBridgeService.class);
|
||||
provisioner = new CloudFormationResourceProvisioner(
|
||||
null, null, null, null, null,
|
||||
null, null, null, null, eventBridgeService,
|
||||
null, null, null, null, null, null,
|
||||
new ObjectMapper(),
|
||||
null, null, null, null, null, null, null,
|
||||
null, null, null, null, null, null, null,
|
||||
null,
|
||||
new CloudFormationResourceRegistry(List.of()));
|
||||
}
|
||||
|
||||
@Test
|
||||
void busWhoseCreatedTimeStillMatchesIsDeleted() {
|
||||
Instant createdTime = Instant.parse("2026-01-01T00:00:00Z");
|
||||
when(eventBridgeService.describeEventBus(BUS, REGION)).thenReturn(bus(createdTime));
|
||||
|
||||
assertDoesNotThrow(() -> provisioner.delete(resource(createdTime.toString()), REGION));
|
||||
|
||||
verify(eventBridgeService).deleteEventBus(BUS, REGION);
|
||||
}
|
||||
|
||||
@Test
|
||||
void busRecreatedUnderTheSameNameIsNotDeleted() {
|
||||
when(eventBridgeService.describeEventBus(BUS, REGION))
|
||||
.thenReturn(bus(Instant.parse("2026-02-02T00:00:00Z")));
|
||||
|
||||
AwsException e = assertThrows(AwsException.class,
|
||||
() -> provisioner.delete(resource("2026-01-01T00:00:00Z"), REGION));
|
||||
|
||||
assertTrue(e.getMessage().contains("ownership changed"), e.getMessage());
|
||||
verify(eventBridgeService, never()).deleteEventBus(BUS, REGION);
|
||||
}
|
||||
|
||||
/**
|
||||
* Stacks provisioned before the created-time attribute existed are restored from
|
||||
* cloudformation-stacks.json without it. Treating "not tracked" as "ownership changed" would
|
||||
* leave every such stack permanently in DELETE_FAILED after a Floci upgrade.
|
||||
*/
|
||||
@Test
|
||||
void busProvisionedBeforeOwnershipTrackingIsStillDeleted() {
|
||||
when(eventBridgeService.describeEventBus(BUS, REGION))
|
||||
.thenReturn(bus(Instant.parse("2026-01-01T00:00:00Z")));
|
||||
|
||||
assertDoesNotThrow(() -> provisioner.delete(resource(null), REGION));
|
||||
|
||||
verify(eventBridgeService).deleteEventBus(BUS, REGION);
|
||||
}
|
||||
|
||||
@Test
|
||||
void alreadyDeletedBusIsTreatedAsDeleted() {
|
||||
when(eventBridgeService.describeEventBus(BUS, REGION))
|
||||
.thenThrow(new AwsException("ResourceNotFoundException", "gone", 400));
|
||||
|
||||
assertDoesNotThrow(() -> provisioner.delete(resource(null), REGION));
|
||||
|
||||
verify(eventBridgeService, never()).deleteEventBus(BUS, REGION);
|
||||
}
|
||||
|
||||
@Test
|
||||
void unexpectedRuleDeletionFailureIsNotReportedAsSuccess() {
|
||||
StackResource rule = new StackResource();
|
||||
rule.setLogicalId("OrdersRule");
|
||||
rule.setResourceType("AWS::Events::Rule");
|
||||
rule.setPhysicalId("orders-rule");
|
||||
rule.getAttributes().put("EventBusName", BUS);
|
||||
when(eventBridgeService.listTargetsByRule("orders-rule", BUS, REGION))
|
||||
.thenThrow(new IllegalStateException("storage unavailable"));
|
||||
|
||||
AwsException error = assertThrows(AwsException.class,
|
||||
() -> provisioner.delete(rule, REGION));
|
||||
|
||||
assertEquals("InternalFailure", error.getErrorCode());
|
||||
assertTrue(error.getMessage().contains("storage unavailable"), error.getMessage());
|
||||
verify(eventBridgeService, never()).deleteRule("orders-rule", BUS, REGION);
|
||||
}
|
||||
|
||||
private StackResource resource(String createdTimeAttr) {
|
||||
StackResource r = new StackResource();
|
||||
r.setLogicalId("OrdersBus");
|
||||
r.setResourceType("AWS::Events::EventBus");
|
||||
r.setPhysicalId(BUS);
|
||||
if (createdTimeAttr != null) {
|
||||
r.getAttributes().put(CREATED_TIME_ATTR, createdTimeAttr);
|
||||
}
|
||||
return r;
|
||||
}
|
||||
|
||||
private EventBus bus(Instant createdTime) {
|
||||
return new EventBus(BUS, "arn:aws:events:" + REGION + ":000000000000:event-bus/" + BUS,
|
||||
null, createdTime);
|
||||
}
|
||||
}
|
||||
+222
@@ -0,0 +1,222 @@
|
||||
package io.github.hectorvent.floci.services.cloudformation;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.databind.node.ObjectNode;
|
||||
import io.github.hectorvent.floci.core.common.AwsException;
|
||||
import io.github.hectorvent.floci.services.cloudformation.model.StackResource;
|
||||
import io.github.hectorvent.floci.services.cloudformation.provisioners.CloudFormationResourceRegistry;
|
||||
import io.github.hectorvent.floci.services.eventbridge.EventBridgeService;
|
||||
import io.github.hectorvent.floci.services.eventbridge.model.EventBus;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.function.Function;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertNull;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.anyString;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
import static org.mockito.Mockito.doThrow;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.never;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
/**
|
||||
* Provision-side ownership behaviour for {@code AWS::Events::EventBus}. The delete side is covered
|
||||
* by {@link EventBusDeleteOwnershipTest}; both have to agree about what a missing created-time
|
||||
* attribute means, or an upgrade wedges the stack in one direction or the other.
|
||||
*
|
||||
* <p>Note {@code provision} reports failure by returning a {@code CREATE_FAILED} resource rather
|
||||
* than throwing, so these assert on status.
|
||||
*/
|
||||
class EventBusProvisionOwnershipTest {
|
||||
|
||||
private static final String REGION = "us-east-1";
|
||||
private static final String BUS = "orders-bus";
|
||||
private static final String CREATED_TIME_ATTR = "FlociEventBusCreatedTime";
|
||||
private static final String MANAGED_TAG_KEYS_ATTR = "FlociEventBusManagedTagKeys";
|
||||
private static final String MANAGED_POLICY_ATTR = "FlociEventBusManagedPolicy";
|
||||
private static final String ROLLBACK_OWNED_ATTR = "__FlociRollbackOwned";
|
||||
private static final ObjectMapper MAPPER = new ObjectMapper();
|
||||
|
||||
private EventBridgeService eventBridgeService;
|
||||
private CloudFormationResourceProvisioner provisioner;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
eventBridgeService = mock(EventBridgeService.class);
|
||||
provisioner = new CloudFormationResourceProvisioner(
|
||||
null, null, null, null, null,
|
||||
null, null, null, null, eventBridgeService,
|
||||
null, null, null, null, null, null,
|
||||
MAPPER,
|
||||
null, null, null, null, null, null, null,
|
||||
null, null, null, null, null, null, null,
|
||||
null,
|
||||
new CloudFormationResourceRegistry(List.of()));
|
||||
}
|
||||
|
||||
/**
|
||||
* A stack provisioned before {@code FlociEventBusCreatedTime} existed is restored without it.
|
||||
* Treating that as "ownership changed" made the first UpdateStack after an upgrade fail, leaving
|
||||
* the stack stuck for every subsequent update — including no-op ones.
|
||||
*/
|
||||
@Test
|
||||
void updateOfBusProvisionedBeforeOwnershipTrackingAdoptsItInsteadOfFailing() {
|
||||
when(eventBridgeService.createEventBus(eq(BUS), any(), any(), eq(REGION)))
|
||||
.thenThrow(new AwsException("ResourceAlreadyExistsException", "exists", 400));
|
||||
when(eventBridgeService.describeEventBus(BUS, REGION))
|
||||
.thenReturn(bus(Instant.parse("2026-01-01T00:00:00Z")));
|
||||
|
||||
StackResource r = provisionExisting(Map.of());
|
||||
|
||||
assertEquals("CREATE_COMPLETE", r.getStatus(), r.getStatusReason());
|
||||
assertEquals(BUS, r.getPhysicalId());
|
||||
// and it starts tracking ownership from here on
|
||||
assertEquals("2026-01-01T00:00:00Z", r.getAttributes().get(CREATED_TIME_ATTR));
|
||||
}
|
||||
|
||||
@Test
|
||||
void updateOfTaggedBusProvisionedBeforeTagTrackingAdoptsItInsteadOfFailing() {
|
||||
when(eventBridgeService.createEventBus(eq(BUS), any(), any(), eq(REGION)))
|
||||
.thenThrow(new AwsException("ResourceAlreadyExistsException", "exists", 400));
|
||||
EventBus existingBus = bus(Instant.parse("2026-01-01T00:00:00Z"));
|
||||
existingBus.setTags(Map.of("environment", "test"));
|
||||
when(eventBridgeService.describeEventBus(BUS, REGION)).thenReturn(existingBus);
|
||||
JsonNode properties = props(false);
|
||||
((ObjectNode) properties).putArray("Tags")
|
||||
.addObject()
|
||||
.put("Key", "environment")
|
||||
.put("Value", "test");
|
||||
|
||||
StackResource r = provisionExisting(Map.of(), properties);
|
||||
|
||||
assertEquals("CREATE_COMPLETE", r.getStatus(), r.getStatusReason());
|
||||
assertEquals("[\"environment\"]", r.getAttributes().get(MANAGED_TAG_KEYS_ATTR));
|
||||
}
|
||||
|
||||
@Test
|
||||
void updateOfBusProvisionedBeforePolicyTrackingAdoptsUnchangedPolicyWithoutReapplyingIt()
|
||||
throws Exception {
|
||||
when(eventBridgeService.createEventBus(eq(BUS), any(), any(), eq(REGION)))
|
||||
.thenThrow(new AwsException("ResourceAlreadyExistsException", "exists", 400));
|
||||
EventBus existingBus = bus(Instant.parse("2026-01-01T00:00:00Z"));
|
||||
existingBus.setPolicy("{\"Version\":\"2012-10-17\"}");
|
||||
when(eventBridgeService.describeEventBus(BUS, REGION)).thenReturn(existingBus);
|
||||
|
||||
StackResource r = provisionExisting(Map.of(), props(true));
|
||||
|
||||
assertEquals("CREATE_COMPLETE", r.getStatus(), r.getStatusReason());
|
||||
assertEquals(
|
||||
MAPPER.readTree("{\"Version\":\"2012-10-17\"}"),
|
||||
MAPPER.readTree(r.getAttributes().get(MANAGED_POLICY_ATTR)));
|
||||
verify(eventBridgeService, never())
|
||||
.putPermission(anyString(), any(), any(), any(), any(), anyString(), anyString());
|
||||
}
|
||||
|
||||
@Test
|
||||
void changedTrackedPolicyFailsWithoutMutatingTheOwnedBus() {
|
||||
when(eventBridgeService.createEventBus(eq(BUS), any(), any(), eq(REGION)))
|
||||
.thenThrow(new AwsException("ResourceAlreadyExistsException", "exists", 400));
|
||||
EventBus existingBus = bus(Instant.parse("2026-01-01T00:00:00Z"));
|
||||
existingBus.setPolicy("{\"Version\":\"2008-10-17\"}");
|
||||
when(eventBridgeService.describeEventBus(BUS, REGION)).thenReturn(existingBus);
|
||||
|
||||
StackResource r = provisionExisting(
|
||||
Map.of(MANAGED_POLICY_ATTR, "{\"Version\":\"2008-10-17\"}"),
|
||||
props(true));
|
||||
|
||||
assertEquals("CREATE_FAILED", r.getStatus());
|
||||
assertEquals(
|
||||
"Updating AWS::Events::EventBus Description, Tags, or Policy is not supported "
|
||||
+ "until transactional rollback is available.",
|
||||
r.getStatusReason());
|
||||
verify(eventBridgeService, never())
|
||||
.putPermission(anyString(), any(), any(), any(), any(), anyString(), anyString());
|
||||
}
|
||||
|
||||
@Test
|
||||
void updateOfBusRecreatedOutOfBandStillFails() {
|
||||
when(eventBridgeService.createEventBus(eq(BUS), any(), any(), eq(REGION)))
|
||||
.thenThrow(new AwsException("ResourceAlreadyExistsException", "exists", 400));
|
||||
when(eventBridgeService.describeEventBus(BUS, REGION))
|
||||
.thenReturn(bus(Instant.parse("2026-02-02T00:00:00Z")));
|
||||
|
||||
StackResource r = provisionExisting(Map.of(CREATED_TIME_ATTR, "2026-01-01T00:00:00Z"));
|
||||
|
||||
assertEquals("CREATE_FAILED", r.getStatus());
|
||||
assertNull(r.getAttributes().get(ROLLBACK_OWNED_ATTR),
|
||||
"a bus this stack no longer owns must not be deleted by rollback");
|
||||
}
|
||||
|
||||
/**
|
||||
* rollbackCreatedResources skips any resource whose physicalId is still null, so identity has to
|
||||
* be recorded before the policy call — otherwise a malformed Policy leaves a live bus that
|
||||
* rollback cannot find, and it leaks permanently.
|
||||
*/
|
||||
@Test
|
||||
void busIsRollbackDeletableWhenThePolicyCallFails() {
|
||||
when(eventBridgeService.createEventBus(eq(BUS), any(), any(), eq(REGION)))
|
||||
.thenReturn(bus(Instant.parse("2026-01-01T00:00:00Z")));
|
||||
doThrow(new AwsException("MalformedPolicyDocumentException", "bad policy", 400))
|
||||
.when(eventBridgeService)
|
||||
.putPermission(anyString(), any(), any(), any(), any(), anyString(), anyString());
|
||||
|
||||
StackResource r = provisioner.provision("OrdersBus", "AWS::Events::EventBus", props(true),
|
||||
engine(), REGION, "000000000000", "my-stack", null, Map.of());
|
||||
|
||||
assertEquals("CREATE_FAILED", r.getStatus());
|
||||
assertEquals(BUS, r.getPhysicalId(), "physicalId must be recorded before the policy call");
|
||||
assertEquals("true", r.getAttributes().get(ROLLBACK_OWNED_ATTR));
|
||||
}
|
||||
|
||||
@Test
|
||||
void adoptedBusIsNotMarkedRollbackOwned() {
|
||||
when(eventBridgeService.createEventBus(eq(BUS), any(), any(), eq(REGION)))
|
||||
.thenThrow(new AwsException("ResourceAlreadyExistsException", "exists", 400));
|
||||
when(eventBridgeService.describeEventBus(BUS, REGION))
|
||||
.thenReturn(bus(Instant.parse("2026-01-01T00:00:00Z")));
|
||||
|
||||
StackResource r = provisionExisting(Map.of());
|
||||
|
||||
assertEquals("CREATE_COMPLETE", r.getStatus(), r.getStatusReason());
|
||||
assertNull(r.getAttributes().get(ROLLBACK_OWNED_ATTR),
|
||||
"a bus this stack did not create must not be deleted by rollback");
|
||||
}
|
||||
|
||||
private StackResource provisionExisting(Map<String, String> existingAttributes) {
|
||||
return provisionExisting(existingAttributes, props(false));
|
||||
}
|
||||
|
||||
private StackResource provisionExisting(Map<String, String> existingAttributes,
|
||||
JsonNode properties) {
|
||||
return provisioner.provision("OrdersBus", "AWS::Events::EventBus", properties,
|
||||
engine(), REGION, "000000000000", "my-stack", BUS, existingAttributes);
|
||||
}
|
||||
|
||||
private JsonNode props(boolean withPolicy) {
|
||||
var node = MAPPER.createObjectNode();
|
||||
node.put("Name", BUS);
|
||||
if (withPolicy) {
|
||||
node.set("Policy", MAPPER.createObjectNode().put("Version", "2012-10-17"));
|
||||
}
|
||||
return node;
|
||||
}
|
||||
|
||||
private CloudFormationTemplateEngine engine() {
|
||||
return new CloudFormationTemplateEngine("000000000000", REGION, "my-stack",
|
||||
"stack/id", Map.of(), Map.of(), Map.of(), Map.of(), Map.of(), MAPPER,
|
||||
(Function<String, String>) name -> null);
|
||||
}
|
||||
|
||||
private EventBus bus(Instant createdTime) {
|
||||
return new EventBus(BUS, "arn:aws:events:" + REGION + ":000000000000:event-bus/" + BUS,
|
||||
null, createdTime);
|
||||
}
|
||||
}
|
||||
+67
@@ -12,6 +12,8 @@ import io.github.hectorvent.floci.services.eventbridge.model.Target;
|
||||
import io.github.hectorvent.floci.services.resourcegroupstagging.ResourceGroupsTaggingService;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.ValueSource;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
@@ -77,6 +79,49 @@ class EventBridgeServiceTest {
|
||||
service.createEventBus("", null, null, REGION));
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(strings = {"default", "contains/slash", "contains space", "contains*star"})
|
||||
void createEventBusRejectsInvalidCustomNames(String name) {
|
||||
AwsException error = assertThrows(AwsException.class, () ->
|
||||
service.createEventBus(name, null, null, REGION));
|
||||
assertEquals("ValidationException", error.getErrorCode());
|
||||
assertEquals(400, error.getHttpStatus());
|
||||
}
|
||||
|
||||
@Test
|
||||
void createEventBusRejectsLongNameAndDescription() {
|
||||
assertThrows(AwsException.class, () ->
|
||||
service.createEventBus("n".repeat(257), null, null, REGION));
|
||||
assertThrows(AwsException.class, () ->
|
||||
service.createEventBus("valid-name", "d".repeat(513), null, REGION));
|
||||
}
|
||||
|
||||
@Test
|
||||
void updateEventBusRejectsLongDescription() {
|
||||
service.createEventBus("my-bus", null, null, REGION);
|
||||
assertThrows(AwsException.class, () ->
|
||||
service.updateEventBus(
|
||||
"my-bus", "d".repeat(513), null, null, null, REGION));
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(strings = {"", "contains space", "contains*star"})
|
||||
void updateEventBusRejectsInvalidExplicitNames(String name) {
|
||||
AwsException error = assertThrows(AwsException.class, () ->
|
||||
service.updateEventBus(name, "description", null, null, null, REGION));
|
||||
assertEquals("ValidationException", error.getErrorCode());
|
||||
assertEquals(400, error.getHttpStatus());
|
||||
}
|
||||
|
||||
@Test
|
||||
void updateEventBusRejectsLongExplicitName() {
|
||||
AwsException error = assertThrows(AwsException.class, () ->
|
||||
service.updateEventBus(
|
||||
"n".repeat(257), "description", null, null, null, REGION));
|
||||
assertEquals("ValidationException", error.getErrorCode());
|
||||
assertEquals(400, error.getHttpStatus());
|
||||
}
|
||||
|
||||
@Test
|
||||
void deleteEventBus() {
|
||||
service.createEventBus("my-bus", null, null, REGION);
|
||||
@@ -92,6 +137,28 @@ class EventBridgeServiceTest {
|
||||
service.deleteEventBus("default", REGION));
|
||||
}
|
||||
|
||||
@Test
|
||||
void deleteMissingEventBusIsIdempotent() {
|
||||
assertDoesNotThrow(() -> service.deleteEventBus("missing-bus", REGION));
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(strings = {"contains space", "contains*star"})
|
||||
void deleteEventBusRejectsInvalidNames(String name) {
|
||||
AwsException error = assertThrows(
|
||||
AwsException.class, () -> service.deleteEventBus(name, REGION));
|
||||
assertEquals("ValidationException", error.getErrorCode());
|
||||
assertEquals(400, error.getHttpStatus());
|
||||
}
|
||||
|
||||
@Test
|
||||
void deleteEventBusRejectsLongName() {
|
||||
AwsException error = assertThrows(
|
||||
AwsException.class, () -> service.deleteEventBus("n".repeat(257), REGION));
|
||||
assertEquals("ValidationException", error.getErrorCode());
|
||||
assertEquals(400, error.getHttpStatus());
|
||||
}
|
||||
|
||||
@Test
|
||||
void deleteEventBusWithRulesThrows() {
|
||||
service.createEventBus("my-bus", null, null, REGION);
|
||||
|
||||
+41
-2
@@ -4,6 +4,8 @@ import io.github.hectorvent.floci.testing.RestAssuredJsonUtils;
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import org.junit.jupiter.api.BeforeAll;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.ValueSource;
|
||||
|
||||
import static io.restassured.RestAssured.given;
|
||||
import static org.hamcrest.Matchers.containsString;
|
||||
@@ -53,6 +55,24 @@ class EventBridgeUpdateEventBusIntegrationTest {
|
||||
.body("Description", equalTo("hello world"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void emptyDescriptionClearsIt() {
|
||||
String bus = "update-test-bus-clear-description";
|
||||
createBus(bus);
|
||||
|
||||
given().contentType(CT).header("X-Amz-Target", UPDATE)
|
||||
.body("{\"Name\":\"" + bus + "\",\"Description\":\"set\"}")
|
||||
.when().post("/")
|
||||
.then().statusCode(200)
|
||||
.body("Description", equalTo("set"));
|
||||
|
||||
given().contentType(CT).header("X-Amz-Target", UPDATE)
|
||||
.body("{\"Name\":\"" + bus + "\",\"Description\":\"\"}")
|
||||
.when().post("/")
|
||||
.then().statusCode(200)
|
||||
.body("Description", equalTo(""));
|
||||
}
|
||||
|
||||
@Test
|
||||
void updateDefaultBus_nameOmitted() {
|
||||
given().contentType(CT).header("X-Amz-Target", UPDATE)
|
||||
@@ -91,14 +111,33 @@ class EventBridgeUpdateEventBusIntegrationTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
void updateNonExistentCustomBus_returns404() {
|
||||
void updateNonExistentCustomBusReturnsAws400() {
|
||||
given().contentType(CT).header("X-Amz-Target", UPDATE)
|
||||
.body("{\"Name\":\"this-bus-was-never-created\",\"Description\":\"x\"}")
|
||||
.when().post("/")
|
||||
.then().statusCode(404)
|
||||
.then().statusCode(400)
|
||||
.body("__type", containsString("ResourceNotFoundException"));
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(strings = {"", "contains space", "contains*star"})
|
||||
void updateRejectsInvalidExplicitName(String name) {
|
||||
given().contentType(CT).header("X-Amz-Target", UPDATE)
|
||||
.body("{\"Name\":\"" + name + "\",\"Description\":\"x\"}")
|
||||
.when().post("/")
|
||||
.then().statusCode(400)
|
||||
.body("__type", containsString("ValidationException"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void updateRejectsNameLongerThan256Characters() {
|
||||
given().contentType(CT).header("X-Amz-Target", UPDATE)
|
||||
.body("{\"Name\":\"" + "n".repeat(257) + "\",\"Description\":\"x\"}")
|
||||
.when().post("/")
|
||||
.then().statusCode(400)
|
||||
.body("__type", containsString("ValidationException"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void updateKmsKeyIdentifier() {
|
||||
String bus = "update-test-bus-kms";
|
||||
|
||||
Reference in new issue
Block a user