diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationResourceProvisioner.java b/src/main/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationResourceProvisioner.java index e6e6e60deb..3ee7e1d206 100644 --- a/src/main/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationResourceProvisioner.java +++ b/src/main/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationResourceProvisioner.java @@ -11,6 +11,7 @@ import io.github.hectorvent.floci.services.cloudformation.provisioners.CfnResour import io.github.hectorvent.floci.services.dynamodb.DynamoDbService; import io.github.hectorvent.floci.services.eventbridge.EventBridgeService; import io.github.hectorvent.floci.services.eventbridge.model.BatchParameters; +import io.github.hectorvent.floci.services.eventbridge.model.EventBus; import io.github.hectorvent.floci.services.eventbridge.model.RuleState; import io.github.hectorvent.floci.services.eventbridge.model.SqsParameters; import io.github.hectorvent.floci.services.eventbridge.model.Target; @@ -293,6 +294,8 @@ public class CloudFormationResourceProvisioner { case "AWS::Route53::HostedZone" -> provisionRoute53HostedZone(resource, properties, engine); case "AWS::Route53::RecordSet" -> provisionRoute53RecordSet(resource, properties, engine); case "AWS::Events::Rule" -> provisionEventBridgeRule(resource, properties, engine, region, stackName); + case "AWS::Events::EventBus" -> provisionEventBus(resource, properties, engine, region, stackName); + case "AWS::Events::EventBusPolicy" -> provisionEventBusPolicy(resource, properties, engine, region); case "AWS::ApiGateway::RestApi" -> provisionApiGatewayRestApi(resource, properties, engine, region, accountId, stackName); case "AWS::ApiGateway::Resource" -> provisionApiGatewayResource(resource, properties, engine, region); case "AWS::ApiGateway::Authorizer" -> provisionApiGatewayAuthorizer(resource, properties, engine, region); @@ -411,6 +414,14 @@ public class CloudFormationResourceProvisioner { } return; } + // Rule deletion needs the rule's event bus (stored as an attribute at provision time), + // which the type/physicalId delete path can't provide; a custom-bus rule looked up under + // the default bus would silently no-op and leave the rule (and its bus) live. + if ("AWS::Events::Rule".equals(resourceType)) { + deleteEventBridgeRuleSafe(resource.getPhysicalId(), + resource.getAttributes().get("EventBusName"), region); + return; + } // AWS::IAM::Policy is an inline policy; detaching it needs the principals it was attached to, // which the type/physicalId delete path can't provide (only the delete-stack path has them). if ("AWS::IAM::Policy".equals(resourceType)) { @@ -458,7 +469,9 @@ public class CloudFormationResourceProvisioner { } // KMS keys can't be immediately deleted; skip case "AWS::KMS::Alias" -> kmsService.deleteAlias(physicalId, region); case "AWS::SecretsManager::Secret" -> deleteSecretSafe(physicalId, region); - case "AWS::Events::Rule" -> deleteEventBridgeRuleSafe(physicalId, region); + case "AWS::Events::Rule" -> deleteEventBridgeRuleSafe(physicalId, null, region); + case "AWS::Events::EventBus" -> deleteEventBusSafe(physicalId, region); + case "AWS::Events::EventBusPolicy" -> removeEventBusPolicySafe(physicalId, region); case "AWS::ApiGateway::RestApi" -> apiGatewayService.deleteRestApi(region, physicalId); case "AWS::ApiGatewayV2::Api" -> apiGatewayV2Service.deleteApi(region, physicalId); case "AWS::ECR::Repository" -> @@ -2366,6 +2379,9 @@ public class CloudFormationResourceProvisioner { state, description, roleArn, Map.of(), region); r.setPhysicalId(ruleName); r.getAttributes().put("Arn", rule.getArn()); + if (busName != null && !busName.isBlank()) { + r.getAttributes().put("EventBusName", busName); + } // Provision inline targets if (props != null && props.has("Targets")) { @@ -2410,20 +2426,147 @@ public class CloudFormationResourceProvisioner { } } - private void deleteEventBridgeRuleSafe(String ruleName, String region) { + private void deleteEventBridgeRuleSafe(String ruleName, String busName, String region) { try { // Remove all targets before deleting the rule - var targets = eventBridgeService.listTargetsByRule(ruleName, null, region); + var targets = eventBridgeService.listTargetsByRule(ruleName, busName, region); if (!targets.isEmpty()) { List targetIds = targets.stream().map(Target::getId).toList(); - eventBridgeService.removeTargets(ruleName, null, targetIds, region); + eventBridgeService.removeTargets(ruleName, busName, targetIds, region); } - eventBridgeService.deleteRule(ruleName, null, region); + eventBridgeService.deleteRule(ruleName, busName, region); } catch (Exception e) { LOG.debugv("Could not delete EventBridge rule {0}: {1}", ruleName, e.getMessage()); } } + private void provisionEventBus(StackResource r, JsonNode props, CloudFormationTemplateEngine engine, + String region, String stackName) { + String name = resolveOptional(props, "Name", engine); + if (name == null || name.isBlank()) { + name = generatePhysicalName(stackName, r.getLogicalId(), 256, false); + } + String description = resolveOptional(props, "Description", engine); + + Map tags = new HashMap<>(); + if (props != null && props.has("Tags") && props.get("Tags").isArray()) { + for (JsonNode tag : props.get("Tags")) { + String key = engine.resolve(tag.path("Key")); + if (!key.isEmpty()) { + tags.put(key, engine.resolve(tag.path("Value"))); + } + } + } + + EventBus bus; + try { + bus = eventBridgeService.createEventBus(name, description, tags, region); + } catch (AwsException e) { + if ("ResourceAlreadyExistsException".equals(e.getErrorCode())) { + bus = eventBridgeService.describeEventBus(name, region); + } else { + throw e; + } + } + + // Optional inline resource policy (rare for CDK EventBus constructs). + if (props != null && props.has("Policy") && !props.get("Policy").isNull()) { + String policyJson = engine.resolveNode(props.get("Policy")).toString(); + eventBridgeService.putPermission(name, null, null, null, null, policyJson, region); + } + + r.setPhysicalId(name); + r.getAttributes().put("Arn", bus.getArn()); + r.getAttributes().put("Name", name); + } + + private void deleteEventBusSafe(String name, String region) { + try { + eventBridgeService.deleteEventBus(name, region); + } catch (Exception e) { + // Warn (not debug): the stack still records the resource as DELETE_COMPLETE, so a bus + // left alive here (e.g. rules deleted out of dependency order) is a silent divergence + // that must stay diagnosable. + LOG.warnv("Could not delete event bus {0}: {1}", name, e.getMessage()); + } + } + + private void provisionEventBusPolicy(StackResource r, JsonNode props, CloudFormationTemplateEngine engine, + String region) { + String busName = resolveOrDefault(props, "EventBusName", engine, "default"); + String statementId = resolveOptional(props, "StatementId", engine); + if (statementId == null || statementId.isBlank()) { + throw new AwsException("ValidationException", "EventBusPolicy StatementId is required.", 400); + } + + if (props != null && props.has("Statement") && props.get("Statement").isObject()) { + // Statement form: merge the full statement into the bus policy, keyed by Sid, + // so multiple EventBusPolicy resources on the same bus coexist. + try { + ObjectNode statement = (ObjectNode) engine.resolveNode(props.get("Statement")).deepCopy(); + statement.put("Sid", statementId); + + EventBus bus = eventBridgeService.describeEventBus(busName, region); + ObjectNode policy; + String current = bus.getPolicy(); + if (current != null && !current.isBlank()) { + policy = (ObjectNode) objectMapper.readTree(current); + } else { + policy = objectMapper.createObjectNode(); + policy.put("Version", "2012-10-17"); + policy.putArray("Statement"); + } + ArrayNode statements = policy.withArray("Statement"); + for (int i = 0; i < statements.size(); i++) { + if (statementId.equals(statements.get(i).path("Sid").asText(null))) { + statements.remove(i); + break; + } + } + statements.add(statement); + eventBridgeService.putPermission(busName, null, null, statementId, null, + objectMapper.writeValueAsString(policy), region); + } catch (AwsException e) { + throw e; + } catch (Exception e) { + throw new AwsException("ValidationException", + "Invalid EventBusPolicy Statement: " + e.getMessage(), 400); + } + r.setPhysicalId(busName + "|" + statementId); + return; + } + + // Individual form: Action + Principal (+ optional Condition {Type, Key, Value}). + String action = resolveOptional(props, "Action", engine); + String principal = resolveOptional(props, "Principal", engine); + String conditionJson = null; + if (props != null && props.has("Condition") && !props.get("Condition").isNull()) { + JsonNode c = engine.resolveNode(props.get("Condition")); + String type = c.path("Type").asText(null); + String key = c.path("Key").asText(null); + String value = c.path("Value").asText(null); + if (type != null && key != null && value != null) { + ObjectNode condition = objectMapper.createObjectNode(); + condition.set(type, objectMapper.createObjectNode().put(key, value)); + conditionJson = condition.toString(); + } + } + eventBridgeService.putPermission(busName, action, principal, statementId, conditionJson, null, region); + + r.setPhysicalId(busName + "|" + statementId); + } + + private void removeEventBusPolicySafe(String physicalId, String region) { + try { + int sep = physicalId.lastIndexOf('|'); + String busName = sep >= 0 ? physicalId.substring(0, sep) : "default"; + String statementId = sep >= 0 ? physicalId.substring(sep + 1) : physicalId; + eventBridgeService.removePermission(busName, statementId, false, region); + } catch (Exception e) { + LOG.debugv("Could not remove event bus policy {0}: {1}", physicalId, e.getMessage()); + } + } + // ── Batch ──────────────────────────────────────────────────────────────── private void provisionBatchComputeEnvironment(StackResource r, JsonNode props, diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationIntegrationTest.java index a922624a22..19e7187372 100644 --- a/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationIntegrationTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationIntegrationTest.java @@ -6819,6 +6819,69 @@ class CloudFormationIntegrationTest { .statusCode(200); } + @Test + void rollbackStack_customBusWithRule_rollsBackBusAndRule() { + // RbBus provisions first, RbRule (on that custom bus) second, then BadSecret fails + // (SecretString + GenerateSecretString is invalid), forcing a CREATE rollback. The rule + // and its custom bus must both be cleaned up, not leaked. + String failingTemplate = """ + { + "Resources": { + "RbBus": { + "Type": "AWS::Events::EventBus", + "Properties": { "Name": "cfn-rb-bus" } + }, + "RbRule": { + "Type": "AWS::Events::Rule", + "DependsOn": "RbBus", + "Properties": { + "Name": "cfn-rb-rule", + "EventBusName": { "Ref": "RbBus" }, + "EventPattern": { "source": ["rb.test"] } + } + }, + "BadSecret": { + "Type": "AWS::SecretsManager::Secret", + "DependsOn": "RbRule", + "Properties": { + "Name": "cfn-rb-secret", + "SecretString": "explicit", + "GenerateSecretString": { "PasswordLength": 32 } + } + } + } + } + """; + + given() + .contentType("application/x-www-form-urlencoded") + .formParam("Action", "CreateStack") + .formParam("StackName", "cfn-rb-stack") + .formParam("TemplateBody", failingTemplate) + .when().post("/").then().statusCode(200); + + given() + .contentType("application/x-www-form-urlencoded") + .formParam("Action", "DescribeStacks") + .formParam("StackName", "cfn-rb-stack") + .when().post("/") + .then().statusCode(200).body(containsString("ROLLBACK_COMPLETE")); + + // The rule created on the custom bus was rolled back... + given() + .contentType("application/x-amz-json-1.1") + .header("X-Amz-Target", "AWSEvents.DescribeRule") + .body("{\"Name\":\"cfn-rb-rule\",\"EventBusName\":\"cfn-rb-bus\"}") + .when().post("/").then().body(containsString("ResourceNotFoundException")); + + // ...and so was the custom bus. + given() + .contentType("application/x-amz-json-1.1") + .header("X-Amz-Target", "AWSEvents.DescribeEventBus") + .body("{\"Name\":\"cfn-rb-bus\"}") + .when().post("/").then().body(containsString("ResourceNotFoundException")); + } + @Test void createStack_resourceFailure_setsRollbackComplete_singleResource() { // A lone failing resource still moves the stack to ROLLBACK_COMPLETE (no orphaned state). @@ -6923,4 +6986,338 @@ class CloudFormationIntegrationTest { .body("endpointConfiguration.vpcEndpointIds", contains("vpce-12345678")); } + @Test + void createStack_withEventBus_createsRealBusAndResolvesRefAndGetAtt() { + String template = """ + { + "Resources": { + "MyBus": { + "Type": "AWS::Events::EventBus", + "Properties": { + "Name": "cfn-custom-bus", + "Description": "Custom bus created via CloudFormation", + "Tags": [ { "Key": "env", "Value": "test" } ] + } + } + }, + "Outputs": { + "BusRef": { "Value": { "Ref": "MyBus" } }, + "BusArn": { "Value": { "Fn::GetAtt": ["MyBus", "Arn"] } }, + "BusName": { "Value": { "Fn::GetAtt": ["MyBus", "Name"] } } + } + } + """; + + given() + .contentType("application/x-www-form-urlencoded") + .formParam("Action", "CreateStack") + .formParam("StackName", "cfn-eventbus-stack") + .formParam("TemplateBody", template) + .when().post("/") + .then().statusCode(200).body(containsString("")); + + given() + .contentType("application/x-www-form-urlencoded") + .formParam("Action", "DescribeStacks") + .formParam("StackName", "cfn-eventbus-stack") + .when().post("/") + .then().statusCode(200) + .body(containsString("CREATE_COMPLETE")) + .body(containsString("BusRef")) + .body(containsString("cfn-custom-bus")) + .body(containsString("event-bus/cfn-custom-bus")); + + // The bus really exists in EventBridge, not a stub. + given() + .contentType("application/x-amz-json-1.1") + .header("X-Amz-Target", "AWSEvents.DescribeEventBus") + .body("{\"Name\":\"cfn-custom-bus\"}") + .when().post("/") + .then().statusCode(200) + .body("Name", equalTo("cfn-custom-bus")) + .body("Arn", containsString("event-bus/cfn-custom-bus")); + } + + @Test + void deleteStack_withEventBus_removesBus() { + String template = """ + { "Resources": { "MyBus": { "Type": "AWS::Events::EventBus", + "Properties": { "Name": "cfn-bus-to-delete" } } } } + """; + + given() + .contentType("application/x-www-form-urlencoded") + .formParam("Action", "CreateStack") + .formParam("StackName", "cfn-eventbus-delete-stack") + .formParam("TemplateBody", template) + .when().post("/").then().statusCode(200); + + given() + .contentType("application/x-www-form-urlencoded") + .formParam("Action", "DeleteStack") + .formParam("StackName", "cfn-eventbus-delete-stack") + .when().post("/").then().statusCode(200); + + // The bus is gone. + given() + .contentType("application/x-amz-json-1.1") + .header("X-Amz-Target", "AWSEvents.DescribeEventBus") + .body("{\"Name\":\"cfn-bus-to-delete\"}") + .when().post("/") + .then().body(containsString("ResourceNotFoundException")); + } + + @Test + void deleteStack_customBusWithRule_removesBusAndRule() { + String template = """ + { + "Resources": { + "MyBus": { + "Type": "AWS::Events::EventBus", + "Properties": { "Name": "cfn-teardown-bus" } + }, + "MyRule": { + "Type": "AWS::Events::Rule", + "Properties": { + "Name": "cfn-teardown-rule", + "EventBusName": { "Ref": "MyBus" }, + "EventPattern": { "source": ["teardown.test"] } + } + } + } + } + """; + + given() + .contentType("application/x-www-form-urlencoded") + .formParam("Action", "CreateStack") + .formParam("StackName", "cfn-teardown-stack") + .formParam("TemplateBody", template) + .when().post("/").then().statusCode(200).body(containsString("")); + + // Sanity: the rule exists on the custom bus before teardown. + given() + .contentType("application/x-amz-json-1.1") + .header("X-Amz-Target", "AWSEvents.DescribeRule") + .body("{\"Name\":\"cfn-teardown-rule\",\"EventBusName\":\"cfn-teardown-bus\"}") + .when().post("/").then().statusCode(200).body("Name", equalTo("cfn-teardown-rule")); + + given() + .contentType("application/x-www-form-urlencoded") + .formParam("Action", "DeleteStack") + .formParam("StackName", "cfn-teardown-stack") + .when().post("/").then().statusCode(200); + + // The rule is gone from the custom bus... + given() + .contentType("application/x-amz-json-1.1") + .header("X-Amz-Target", "AWSEvents.DescribeRule") + .body("{\"Name\":\"cfn-teardown-rule\",\"EventBusName\":\"cfn-teardown-bus\"}") + .when().post("/").then().body(containsString("ResourceNotFoundException")); + + // ...and so is the bus. + given() + .contentType("application/x-amz-json-1.1") + .header("X-Amz-Target", "AWSEvents.DescribeEventBus") + .body("{\"Name\":\"cfn-teardown-bus\"}") + .when().post("/").then().body(containsString("ResourceNotFoundException")); + } + + @Test + void createStack_customBusRuleDeliversEventToSqs() { + String template = """ + { + "Resources": { + "MyBus": { + "Type": "AWS::Events::EventBus", + "Properties": { "Name": "cfn-e2e-bus" } + }, + "TargetQueue": { + "Type": "AWS::SQS::Queue", + "Properties": { "QueueName": "cfn-e2e-queue" } + }, + "MyRule": { + "Type": "AWS::Events::Rule", + "Properties": { + "Name": "cfn-e2e-rule", + "EventBusName": { "Ref": "MyBus" }, + "EventPattern": { "source": ["my.e2e.app"] }, + "Targets": [ + { "Id": "Target0", "Arn": { "Fn::GetAtt": ["TargetQueue", "Arn"] } } + ] + } + } + } + } + """; + + given() + .contentType("application/x-www-form-urlencoded") + .formParam("Action", "CreateStack") + .formParam("StackName", "cfn-e2e-stack") + .formParam("TemplateBody", template) + .when().post("/").then().statusCode(200).body(containsString("")); + + given() + .contentType("application/x-www-form-urlencoded") + .formParam("Action", "DescribeStacks") + .formParam("StackName", "cfn-e2e-stack") + .when().post("/") + .then().statusCode(200).body(containsString("CREATE_COMPLETE")); + + // The rule is attached to the custom bus. + given() + .contentType("application/x-amz-json-1.1") + .header("X-Amz-Target", "AWSEvents.ListTargetsByRule") + .body("{\"Rule\":\"cfn-e2e-rule\",\"EventBusName\":\"cfn-e2e-bus\"}") + .when().post("/") + .then().statusCode(200) + .body("Targets[0].Arn", equalTo("arn:aws:sqs:us-east-1:000000000000:cfn-e2e-queue")); + + // Send a matching event to the custom bus. + given() + .contentType("application/x-amz-json-1.1") + .header("X-Amz-Target", "AWSEvents.PutEvents") + .body(""" + {"Entries":[{"Source":"my.e2e.app","DetailType":"t", + "Detail":"{\\"hello\\":\\"world\\"}","EventBusName":"cfn-e2e-bus"}]} + """) + .when().post("/") + .then().statusCode(200).body("FailedEntryCount", equalTo(0)); + + // Resolve the queue URL, then confirm the message was delivered. + String getUrlXml = given() + .contentType("application/x-www-form-urlencoded") + .formParam("Action", "GetQueueUrl") + .formParam("QueueName", "cfn-e2e-queue") + .when().post("/") + .then().statusCode(200).extract().body().asString(); + String queueUrl = getUrlXml.substring( + getUrlXml.indexOf("") + "".length(), + getUrlXml.indexOf("")); + + given() + .contentType("application/x-www-form-urlencoded") + .formParam("Action", "ReceiveMessage") + .formParam("QueueUrl", queueUrl) + .formParam("MaxNumberOfMessages", "1") + .formParam("WaitTimeSeconds", "0") + .when().post("/") + .then().statusCode(200) + .body(containsString("my.e2e.app")) + .body(containsString("hello")); + } + + @Test + void createStack_withEventBusPolicyIndividualForm_writesStatement() { + String template = """ + { + "Resources": { + "MyBus": { + "Type": "AWS::Events::EventBus", + "Properties": { "Name": "cfn-policy-bus" } + }, + "MyPolicy": { + "Type": "AWS::Events::EventBusPolicy", + "Properties": { + "EventBusName": { "Ref": "MyBus" }, + "StatementId": "AllowAcct", + "Action": "events:PutEvents", + "Principal": "111122223333" + } + } + } + } + """; + + given() + .contentType("application/x-www-form-urlencoded") + .formParam("Action", "CreateStack") + .formParam("StackName", "cfn-eventbuspolicy-stack") + .formParam("TemplateBody", template) + .when().post("/").then().statusCode(200).body(containsString("")); + + given() + .contentType("application/x-www-form-urlencoded") + .formParam("Action", "DescribeStacks") + .formParam("StackName", "cfn-eventbuspolicy-stack") + .when().post("/") + .then().statusCode(200).body(containsString("CREATE_COMPLETE")); + + given() + .contentType("application/x-amz-json-1.1") + .header("X-Amz-Target", "AWSEvents.DescribeEventBus") + .body("{\"Name\":\"cfn-policy-bus\"}") + .when().post("/") + .then().statusCode(200) + .body("Policy", containsString("AllowAcct")) + .body("Policy", containsString("111122223333")); + } + + @Test + void createStack_withEventBusPolicyStatementForm_mergesMultipleStatements() { + String template = """ + { + "Resources": { + "MyBus": { + "Type": "AWS::Events::EventBus", + "Properties": { "Name": "cfn-stmt-bus" } + }, + "PolicyA": { + "Type": "AWS::Events::EventBusPolicy", + "Properties": { + "EventBusName": { "Ref": "MyBus" }, + "StatementId": "StmtA", + "Statement": { + "Effect": "Allow", + "Principal": { "AWS": "arn:aws:iam::111111111111:root" }, + "Action": "events:PutEvents", + "Resource": { "Fn::GetAtt": ["MyBus", "Arn"] } + } + } + }, + "PolicyB": { + "Type": "AWS::Events::EventBusPolicy", + "Properties": { + "EventBusName": { "Ref": "MyBus" }, + "StatementId": "StmtB", + "Statement": { + "Effect": "Allow", + "Principal": { "AWS": "arn:aws:iam::222222222222:root" }, + "Action": "events:PutEvents", + "Resource": { "Fn::GetAtt": ["MyBus", "Arn"] } + } + } + } + } + } + """; + + given() + .contentType("application/x-www-form-urlencoded") + .formParam("Action", "CreateStack") + .formParam("StackName", "cfn-stmt-stack") + .formParam("TemplateBody", template) + .when().post("/").then().statusCode(200).body(containsString("")); + + given() + .contentType("application/x-www-form-urlencoded") + .formParam("Action", "DescribeStacks") + .formParam("StackName", "cfn-stmt-stack") + .when().post("/") + .then().statusCode(200).body(containsString("CREATE_COMPLETE")); + + // Both statements must be present — a naive whole-policy replace would keep only one. + given() + .contentType("application/x-amz-json-1.1") + .header("X-Amz-Target", "AWSEvents.DescribeEventBus") + .body("{\"Name\":\"cfn-stmt-bus\"}") + .when().post("/") + .then().statusCode(200) + .body("Policy", containsString("StmtA")) + .body("Policy", containsString("StmtB")) + .body("Policy", containsString("111111111111")) + .body("Policy", containsString("222222222222")); + } + }