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 bf7d1c0c85..85710990bd 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 @@ -20,9 +20,7 @@ import io.github.hectorvent.floci.services.cloudformation.provisioners.CfnResour import io.github.hectorvent.floci.services.cloudformation.provisioners.Ec2SecurityGroupRuleCfnProvisioner; import io.github.hectorvent.floci.services.cloudformation.provisioners.UpdateCleanupResult; 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.InputTransformer; import io.github.hectorvent.floci.services.eventbridge.model.RuleState; import io.github.hectorvent.floci.services.eventbridge.model.SqsParameters; @@ -126,13 +124,6 @@ public class CloudFormationResourceProvisioner { private static final String INLINE_CLEANUP_GROUP_TARGETS_ATTR = "__FlociInlineCleanupGroupTargets"; private static final String SFN_NAME_MODE_ATTR = "FlociStepFunctionsNameMode"; static final String SFN_UPDATE_SNAPSHOT_ATTR = "__FlociStepFunctionsUpdateSnapshot"; - private static final String EVENT_BUS_CREATED_TIME_ATTR = "FlociEventBusCreatedTime"; - private static final String EVENT_BUS_MANAGED_TAG_KEYS_ATTR = "FlociEventBusManagedTagKeys"; - private static final String EVENT_BUS_MANAGED_POLICY_ATTR = "FlociEventBusManagedPolicy"; - private static final Set EVENT_BUS_SUPPORTED_PROPERTIES = - Set.of("Name", "Description", "Tags", "Policy"); - private static final Pattern EVENT_BUS_TAG_PATTERN = - Pattern.compile("[\\p{L}\\p{N}\\p{Z}_.:/=+\\-@]*"); private static final String NAME_MODE_EXPLICIT = "explicit"; private static final String NAME_MODE_GENERATED = "generated"; private static final int GENERATED_NAME_SUFFIX_LENGTH = 12; @@ -177,8 +168,6 @@ public class CloudFormationResourceProvisioner { "AWS::ApiGatewayV2::Authorizer", "AWS::CloudFormation::CustomResource", "AWS::EKS::Nodegroup", - "AWS::Events::EventBus", - "AWS::Events::Rule", "AWS::IAM::ManagedPolicy", "AWS::IAM::Policy", "AWS::SecretsManager::SecretTargetAttachment", @@ -210,9 +199,6 @@ public class CloudFormationResourceProvisioner { "AWS::EC2::SecurityGroup", "AWS::EKS::Cluster", "AWS::EKS::Nodegroup", - "AWS::Events::EventBus", - "AWS::Events::EventBusPolicy", - "AWS::Events::Rule", "AWS::IAM::AccessKey", "AWS::IAM::InstanceProfile", "AWS::IAM::ManagedPolicy", @@ -247,7 +233,6 @@ public class CloudFormationResourceProvisioner { private final LambdaService lambdaService; private final IamService iamService; private final SecretsManagerService secretsManagerService; - private final EventBridgeService eventBridgeService; private final ApiGatewayService apiGatewayService; private final ApiGatewayV2Service apiGatewayV2Service; private final LambdaLayerService lambdaLayerService; @@ -275,7 +260,6 @@ public class CloudFormationResourceProvisioner { LambdaService lambdaService, IamService iamService, SsmService ssmService, KmsService kmsService, SecretsManagerService secretsManagerService, - EventBridgeService eventBridgeService, ApiGatewayService apiGatewayService, ApiGatewayV2Service apiGatewayV2Service, EcrService ecrService, @@ -305,7 +289,6 @@ public class CloudFormationResourceProvisioner { this.lambdaService = lambdaService; this.iamService = iamService; this.secretsManagerService = secretsManagerService; - this.eventBridgeService = eventBridgeService; this.apiGatewayService = apiGatewayService; this.apiGatewayV2Service = apiGatewayV2Service; this.lambdaLayerService = lambdaLayerService; @@ -379,9 +362,6 @@ public class CloudFormationResourceProvisioner { case "AWS::SecretsManager::SecretTargetAttachment" -> provisionSecretTargetAttachment(resource, properties, engine, region, stackName); case "AWS::Route53::RecordSet" -> provisionRoute53RecordSet(resource, properties, engine); - case "AWS::Events::Rule" -> provisionEventBridgeRule(resource, properties, engine, region, stackName); - case "AWS::Events::EventBus" -> provisionEventBridgeEventBus(resource, properties, engine, region); - 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); @@ -600,14 +580,6 @@ 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; - } // Authorizer deletion needs the api id (a stored attribute, not the physical id, which is // the authorizer id) — same shape as the Nodegroup case above. Without this, the generic // type/physicalId delete path has no case for this type at all and silently no-ops, @@ -635,10 +607,6 @@ public class CloudFormationResourceProvisioner { deleteManagedPolicy(resource); return; } - if ("AWS::Events::EventBus".equals(resourceType)) { - deleteEventBusSafe(resource, region); - return; - } throw new IllegalStateException("DELETE_NEEDS_STACK_RESOURCE lists " + resourceType + " but no branch here deletes it — deleting it by physical id alone would " + "silently no-op and leave the resource live."); @@ -673,9 +641,6 @@ public class CloudFormationResourceProvisioner { "SecretTargetAttachment deletion requires the StackResource metadata that records its managed fields.", 400); // No bus context on the type/physicalId path (e.g. CREATE-rollback); targets the default bus. - 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::StepFunctions::StateMachine" -> stepFunctionsService.deleteStateMachine(physicalId); @@ -3306,474 +3271,6 @@ public class CloudFormationResourceProvisioner { return password; } - // ── EventBridge ───────────────────────────────────────────────────────── - - private void provisionEventBridgeRule(StackResource r, JsonNode props, CloudFormationTemplateEngine engine, - String region, String stackName) { - String ruleName = resolveOptional(props, "Name", engine); - if (ruleName == null || ruleName.isBlank()) { - ruleName = generatePhysicalName(stackName, r.getLogicalId(), 64, false); - } - - String busName = resolveOptional(props, "EventBusName", engine); - String description = resolveOptional(props, "Description", engine); - String roleArn = resolveOptional(props, "RoleArn", engine); - String scheduleExpression = resolveOptional(props, "ScheduleExpression", engine); - - String eventPattern = null; - if (props != null && props.has("EventPattern") && !props.get("EventPattern").isNull()) { - JsonNode patternNode = engine.resolveNode(props.get("EventPattern")); - eventPattern = patternNode.toString(); - } - - String stateStr = resolveOptional(props, "State", engine); - RuleState state = "DISABLED".equals(stateStr) ? RuleState.DISABLED : RuleState.ENABLED; - - var rule = eventBridgeService.putRule(ruleName, busName, eventPattern, scheduleExpression, - state, description, roleArn, Map.of(), region); - r.setPhysicalId(ruleName); - r.getAttributes().put("Arn", rule.getArn()); - // A rule on a custom bus is keyed by that bus; remember it so the resource delete can target - // the right bus (the physical id is only the rule name, which resolves to the default bus). - if (busName != null && !busName.isBlank()) { - r.getAttributes().put("EventBusName", busName); - } - - // Provision inline targets - if (props != null && props.has("Targets")) { - List targets = new ArrayList<>(); - for (JsonNode targetNode : props.get("Targets")) { - JsonNode resolved = engine.resolveNode(targetNode); - String targetId = resolved.path("Id").asText(null); - String targetArn = resolved.path("Arn").asText(null); - String input = resolved.path("Input").asText(null); - String inputPath = resolved.path("InputPath").asText(null); - if (targetId != null && targetArn != null) { - Target target = new Target(targetId, targetArn, input, inputPath); - target.setInputTransformer(InputTransformer.fromJson(resolved.path("InputTransformer"))); - JsonNode sqsParamsNode = resolved.path("SqsParameters"); - if (!sqsParamsNode.isMissingNode() && sqsParamsNode.isObject()) { - String messageGroupId = sqsParamsNode.path("MessageGroupId").asText(null); - if (messageGroupId != null) { - SqsParameters sqsParameters = new SqsParameters(); - sqsParameters.setMessageGroupId(messageGroupId); - target.setSqsParameters(sqsParameters); - } - } - JsonNode batchParamsNode = resolved.path("BatchParameters"); - if (!batchParamsNode.isMissingNode() && batchParamsNode.isObject()) { - JsonNode arrayProperties = batchParamsNode.path("ArrayProperties"); - BatchParameters batchParameters = new BatchParameters(); - batchParameters.setJobDefinition(batchParamsNode.path("JobDefinition").asText(null)); - batchParameters.setJobName(batchParamsNode.path("JobName").asText(null)); - if (arrayProperties.isObject()) { - batchParameters.setArrayProperties(jsonObjectToMap(arrayProperties)); - } - if (batchParamsNode.has("RetryStrategy")) { - batchParameters.setRetryStrategy(batchParamsNode.get("RetryStrategy")); - } - target.setBatchParameters(batchParameters); - } - targets.add(target); - } - } - if (!targets.isEmpty()) { - eventBridgeService.putTargets(ruleName, busName, targets, region); - } - } - } - - /** - * Provisions an {@code AWS::Events::EventBus} (a custom EventBridge event bus). Without this the - * resource would fall through to the generic stub, which assigns a physical id but never registers - * the bus with the EventBridge service — so any {@code AWS::Events::Rule} (or PutEvents) targeting - * the bus fails "EventBus not found". Per the AWS spec, {@code Ref} returns the bus name - * (not the ARN), so the physical id is the name; {@code Fn::GetAtt "Arn"} exposes the ARN. - */ - private void provisionEventBridgeEventBus(StackResource r, JsonNode props, - CloudFormationTemplateEngine engine, String region) { - validateEventBusProperties(props); - String existingBusName = r.getPhysicalId(); - String busName = resolveOptional(props, "Name", engine); - validateEventBusName(busName); - if (existingBusName != null && !existingBusName.equals(busName)) { - throw new AwsException("ValidationError", - "Updating EventBus Name requires resource replacement, which is not supported.", 400); - } - String description = resolveOptional(props, "Description", engine); - if (description != null && description.length() > 512) { - throw new AwsException("ValidationError", - "AWS::Events::EventBus Description must not exceed 512 characters.", 400); - } - Map tags = parseEventBusTags( - props != null ? props.get("Tags") : null, engine); - JsonNode policy = resolveEventBusPolicy(props, engine); - - EventBus bus; - boolean createdBus = false; - try { - bus = eventBridgeService.createEventBus(busName, description, tags, region); - createdBus = true; - r.getAttributes().put(CfnRollback.ROLLBACK_OWNED_ATTR, "true"); - } catch (AwsException e) { - boolean stackAlreadyOwnsBus = existingBusName != null && existingBusName.equals(busName); - if (!stackAlreadyOwnsBus || !"ResourceAlreadyExistsException".equals(e.getErrorCode())) { - throw e; - } - bus = eventBridgeService.describeEventBus(busName, region); - // A missing created-time means ownership was never tracked, not that it changed: stacks - // provisioned before this attribute existed are restored without it. Refusing there would - // wedge every later UpdateStack, including no-op ones. Only a recorded time that actually - // disagrees means the bus was recreated out of band and belongs to its new owner. - String existingCreatedTime = r.getAttributes().get(EVENT_BUS_CREATED_TIME_ATTR); - String actualCreatedTime = eventBusCreatedTime(bus); - if (existingCreatedTime != null && !existingCreatedTime.equals(actualCreatedTime)) { - r.getAttributes().remove(CfnRollback.ROLLBACK_OWNED_ATTR); - throw e; - } - validateEventBusMutablePropertiesUnchanged(r, bus, description, tags, policy); - } - - // Record identity before applying the policy: rollbackCreatedResources skips any resource - // whose physicalId is still null, so a putPermission failure after the bus exists would - // otherwise orphan it with no way for rollback to find it. - r.setPhysicalId(busName); // Ref → EventBus name (AWS-faithful) - r.getAttributes().put("Arn", bus.getArn()); - r.getAttributes().put("Name", busName); - r.getAttributes().put(EVENT_BUS_CREATED_TIME_ATTR, eventBusCreatedTime(bus)); - recordEventBusManagedTagKeys(r, tags.keySet()); - recordEventBusManagedPolicy(r, policy); - - // Apply an optional inline resource policy only during creation. Updating it is rejected by - // validateEventBusMutablePropertiesUnchanged until stack updates can roll back live resource - // mutations transactionally. - if (createdBus && !policy.isNull()) { - eventBridgeService.putPermission(busName, null, null, null, null, policy.toString(), region); - } - } - - private void validateEventBusProperties(JsonNode props) { - if (props == null || props.isNull()) { - return; - } - if (!props.isObject()) { - throw new AwsException("ValidationError", - "AWS::Events::EventBus Properties must be an object.", 400); - } - List unsupported = new ArrayList<>(); - props.fieldNames().forEachRemaining(name -> { - if (!EVENT_BUS_SUPPORTED_PROPERTIES.contains(name)) { - unsupported.add(name); - } - }); - if (!unsupported.isEmpty()) { - Collections.sort(unsupported); - throw new AwsException("ValidationError", - "Unsupported AWS::Events::EventBus properties: " - + String.join(", ", unsupported), 400); - } - } - - private void validateEventBusName(String busName) { - if (busName == null || busName.isBlank()) { - throw new AwsException("ValidationError", - "Name is required for AWS::Events::EventBus.", 400); - } - if (busName.length() > 256 - || !busName.matches("[.\\-_A-Za-z0-9]+") - || "default".equals(busName)) { - throw new AwsException("ValidationError", - "Invalid custom event bus Name: " + busName, 400); - } - } - - private Map parseEventBusTags( - JsonNode tagsNode, CloudFormationTemplateEngine engine) { - if (tagsNode == null || tagsNode.isNull()) { - return Map.of(); - } - JsonNode resolvedTags = engine.resolveNode(tagsNode); - if (!resolvedTags.isArray()) { - throw new AwsException("ValidationError", - "AWS::Events::EventBus Tags must be an array.", 400); - } - if (resolvedTags.size() > 50) { - throw new AwsException("ValidationError", - "AWS::Events::EventBus supports at most 50 tags.", 400); - } - Map tags = new LinkedHashMap<>(); - for (JsonNode entry : resolvedTags) { - if (!entry.isObject()) { - throw new AwsException("ValidationError", - "Each AWS::Events::EventBus tag must be an object.", 400); - } - String key = entry.path("Key").asText(null); - String value = entry.path("Value").asText(null); - if (key == null || key.isEmpty() || key.length() > 128) { - throw new AwsException("ValidationError", - "Event bus tag Key must contain 1 to 128 characters.", 400); - } - if (key.regionMatches(true, 0, "aws:", 0, 4)) { - throw new AwsException("ValidationError", - "Event bus tag Key must not use the reserved aws: prefix.", 400); - } - if (!EVENT_BUS_TAG_PATTERN.matcher(key).matches()) { - throw new AwsException("ValidationError", - "Event bus tag Key contains unsupported characters.", 400); - } - if (value == null || value.length() > 256) { - throw new AwsException("ValidationError", - "Event bus tag Value must contain at most 256 characters.", 400); - } - if (!EVENT_BUS_TAG_PATTERN.matcher(value).matches()) { - throw new AwsException("ValidationError", - "Event bus tag Value contains unsupported characters.", 400); - } - if (tags.putIfAbsent(key, value) != null) { - throw new AwsException("ValidationError", - "Duplicate event bus tag Key: " + key, 400); - } - } - return tags; - } - - private void validateEventBusMutablePropertiesUnchanged( - StackResource resource, EventBus bus, String requestedDescription, - Map requestedTags, JsonNode requestedPolicy) { - if (!Objects.equals(bus.getDescription(), requestedDescription)) { - throw unsupportedEventBusMutableUpdate(); - } - - // Stacks persisted by the older EventBus provisioner have no managed-key metadata. There - // is no reliable way to distinguish their CloudFormation tags from tags added out of band, - // so allow this one-time adoption and start tracking the requested keys afterwards. - if (resource.getAttributes().containsKey(EVENT_BUS_MANAGED_TAG_KEYS_ATTR)) { - Map currentManagedTags = new LinkedHashMap<>(); - for (String key : eventBusManagedTagKeys(resource)) { - if (bus.getTags().containsKey(key)) { - currentManagedTags.put(key, bus.getTags().get(key)); - } - } - if (!currentManagedTags.equals(requestedTags)) { - throw unsupportedEventBusMutableUpdate(); - } - } - - String managedPolicy = resource.getAttributes().get(EVENT_BUS_MANAGED_POLICY_ATTR); - JsonNode policyToCompare = managedPolicy != null - ? parseEventBusPolicy(managedPolicy, "stored CloudFormation metadata") - : parseEventBusPolicy(bus.getPolicy(), "the existing event bus"); - if (managedPolicy != null || !requestedPolicy.isNull()) { - if (!policyToCompare.equals(requestedPolicy)) { - throw unsupportedEventBusMutableUpdate(); - } - } - } - - private JsonNode resolveEventBusPolicy(JsonNode props, CloudFormationTemplateEngine engine) { - if (props == null || !props.has("Policy") || props.get("Policy").isNull()) { - return JsonNodeFactory.instance.nullNode(); - } - return engine.resolveNode(props.get("Policy")); - } - - private JsonNode parseEventBusPolicy(String policy, String source) { - if (policy == null) { - return JsonNodeFactory.instance.nullNode(); - } - try { - JsonNode parsed = objectMapper.readTree(policy); - return parsed != null ? parsed : JsonNodeFactory.instance.nullNode(); - } catch (Exception e) { - throw new AwsException("InternalFailure", - "Invalid EventBus policy in " + source + ": " + e.getMessage(), 500); - } - } - - private void recordEventBusManagedPolicy(StackResource resource, JsonNode policy) { - try { - resource.getAttributes().put(EVENT_BUS_MANAGED_POLICY_ATTR, - objectMapper.writeValueAsString(policy)); - } catch (Exception e) { - throw new AwsException("InternalFailure", - "Failed to store EventBus managed-policy metadata: " + e.getMessage(), 500); - } - } - - private AwsException unsupportedEventBusMutableUpdate() { - return new AwsException("ValidationError", - "Updating AWS::Events::EventBus Description, Tags, or Policy is not supported " - + "until transactional rollback is available.", 400); - } - - private Set eventBusManagedTagKeys(StackResource resource) { - String value = resource.getAttributes().get(EVENT_BUS_MANAGED_TAG_KEYS_ATTR); - if (value == null || value.isBlank()) { - return Set.of(); - } - try { - JsonNode keys = objectMapper.readTree(value); - if (!keys.isArray()) { - throw new IllegalArgumentException("managed tag keys are not an array"); - } - Set result = new HashSet<>(); - keys.forEach(key -> result.add(key.asText())); - return result; - } catch (Exception e) { - throw new AwsException("InternalFailure", - "Invalid stored EventBus managed-tag metadata: " + e.getMessage(), 500); - } - } - - private void recordEventBusManagedTagKeys(StackResource resource, Set keys) { - try { - resource.getAttributes().put( - EVENT_BUS_MANAGED_TAG_KEYS_ATTR, - objectMapper.writeValueAsString(new TreeSet<>(keys))); - } catch (Exception e) { - throw new AwsException("InternalFailure", - "Failed to store EventBus managed-tag metadata: " + e.getMessage(), 500); - } - } - - private String eventBusCreatedTime(EventBus bus) { - return bus.getCreatedTime() != null ? bus.getCreatedTime().toString() : ""; - } - - private void deleteEventBridgeRuleSafe(String ruleName, String busName, String region) { - try { - // Remove all targets before deleting the rule (busName scopes the lookup to the rule's bus). - var targets = eventBridgeService.listTargetsByRule(ruleName, busName, region); - if (!targets.isEmpty()) { - List targetIds = targets.stream().map(Target::getId).toList(); - eventBridgeService.removeTargets(ruleName, busName, targetIds, region); - } - eventBridgeService.deleteRule(ruleName, busName, region); - } catch (AwsException e) { - // An already-deleted rule is the one failure that genuinely means "done". Anything else - // is a real error worth surfacing rather than hiding behind a debug line. - if (!"ResourceNotFoundException".equals(e.getErrorCode())) { - throw e; - } - LOG.debugv("EventBridge rule already gone, treating as deleted: {0}", ruleName); - } catch (Exception e) { - throw new AwsException("InternalFailure", - "Could not delete EventBridge rule " + ruleName + ": " + e.getMessage(), 500); - } - } - - private void deleteEventBusSafe(String busName, String region) { - try { - eventBridgeService.deleteEventBus(busName, region); - } catch (AwsException e) { - if (!"ResourceNotFoundException".equals(e.getErrorCode())) { - throw e; - } - LOG.debugv("Event bus already gone, treating as deleted: {0}", busName); - } - } - - private void deleteEventBusSafe(StackResource resource, String region) { - String busName = resource.getPhysicalId(); - EventBus bus; - try { - bus = eventBridgeService.describeEventBus(busName, region); - } catch (AwsException e) { - if ("ResourceNotFoundException".equals(e.getErrorCode())) { - LOG.debugv("Event bus already gone, treating as deleted: {0}", busName); - return; - } - throw e; - } - - // A missing attribute means ownership was never tracked, not that it changed: stacks - // provisioned before this attribute existed are restored from cloudformation-stacks.json - // without it. Refusing there would leave every such stack permanently in DELETE_FAILED, so - // fall back to the pre-tracking behaviour of deleting what the stack recorded it created. - String expectedCreatedTime = resource.getAttributes().get(EVENT_BUS_CREATED_TIME_ATTR); - if (expectedCreatedTime != null && !expectedCreatedTime.equals(eventBusCreatedTime(bus))) { - throw new AwsException("ValidationError", - "EventBus ownership changed; refusing to delete: " + busName, 400); - } - deleteEventBusSafe(busName, region); - } - - - 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 ──────────────────────────────────────────────────────────────── diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/CfnRollback.java b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/CfnRollback.java index 45b8ea29a7..78d05a9078 100644 --- a/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/CfnRollback.java +++ b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/CfnRollback.java @@ -44,6 +44,15 @@ public final class CfnRollback { */ public static final String PIPE_UPDATE_SNAPSHOT_ATTR = "__FlociPipeUpdateSnapshot"; + /** + * Holds the targets an EventBridge rule carried before the update in flight reconciled them, + * with the rule name, bus and region needed to address them again, so a failed stack update can + * put them back. Written by {@code EventsCfnProvisioner} before its first target call and spent + * by its {@code rollbackUpdate}. The rule name alone does not address a target: a rule on a + * custom bus is keyed by that bus, and the rollback hook is handed the stack resource alone. + */ + public static final String RULE_TARGETS_SNAPSHOT_ATTR = "__FlociRuleTargetsSnapshot"; + /** * Holds the settings an event invoke configuration carried before an in-place update changed * them, in the request shape a put takes, so a failed stack update can put them back. Written diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/EventsCfnProvisioner.java b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/EventsCfnProvisioner.java new file mode 100644 index 0000000000..558079a3e6 --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/EventsCfnProvisioner.java @@ -0,0 +1,766 @@ +package io.github.hectorvent.floci.services.cloudformation.provisioners; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.core.type.TypeReference; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.node.ArrayNode; +import com.fasterxml.jackson.databind.node.JsonNodeFactory; +import com.fasterxml.jackson.databind.node.ObjectNode; +import io.github.hectorvent.floci.core.common.AwsException; +import io.github.hectorvent.floci.services.cloudformation.model.StackResource; +import io.github.hectorvent.floci.services.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.InputTransformer; +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; +import jakarta.enterprise.context.ApplicationScoped; +import jakarta.inject.Inject; +import org.jboss.logging.Logger; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashSet; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Set; +import java.util.stream.Collectors; +import java.util.TreeSet; +import java.util.regex.Pattern; + +/** + * CloudFormation provisioning for EventBridge: {@code AWS::Events::Rule}, + * {@code AWS::Events::EventBus} and {@code AWS::Events::EventBusPolicy}. Extracted from + * {@code CloudFormationResourceProvisioner}. + * + *

Two of these types need the resource's stored attributes to delete, not just the physical + * id, so they are served by the {@link #delete(StackResource, String)} override rather than the + * id-only form: a rule remembers the custom bus it lives on, and an event bus remembers the + * creation time that proves the stack still owns it. + */ +@ApplicationScoped +public class EventsCfnProvisioner implements CfnResourceProvisioner { + + private static final Logger LOG = Logger.getLogger(EventsCfnProvisioner.class); + private static final ObjectMapper MAPPER = new ObjectMapper(); + + private static final String EVENT_BUS_CREATED_TIME_ATTR = "FlociEventBusCreatedTime"; + private static final String EVENT_BUS_MANAGED_TAG_KEYS_ATTR = "FlociEventBusManagedTagKeys"; + private static final String EVENT_BUS_MANAGED_POLICY_ATTR = "FlociEventBusManagedPolicy"; + private static final Set EVENT_BUS_SUPPORTED_PROPERTIES = + Set.of("Name", "Description", "Tags", "Policy"); + private static final Pattern EVENT_BUS_TAG_PATTERN = + Pattern.compile("[\\p{L}\\p{N}\\p{Z}_.:/=+\\-@]*"); + private static final Pattern STATEMENT_ID_PATTERN = Pattern.compile("[a-zA-Z0-9\\-_]+"); + private static final int STATEMENT_ID_MAX_LENGTH = 64; + + private final EventBridgeService eventBridgeService; + + @Inject + public EventsCfnProvisioner(EventBridgeService eventBridgeService) { + this.eventBridgeService = eventBridgeService; + } + + @Override + public Set resourceTypes() { + return Set.of("AWS::Events::Rule", "AWS::Events::EventBus", "AWS::Events::EventBusPolicy"); + } + + @Override + public void provision(StackResource r, JsonNode props, ProvisionContext ctx) { + switch (r.getResourceType()) { + case "AWS::Events::Rule" -> provisionRule(r, props, ctx); + case "AWS::Events::EventBus" -> provisionEventBus(r, props, ctx); + case "AWS::Events::EventBusPolicy" -> provisionEventBusPolicy(r, props, ctx); + default -> throw new IllegalStateException( + "EventsCfnProvisioner cannot handle " + r.getResourceType()); + } + } + + /** + * A rule and an event bus both need attributes the physical id cannot carry: the rule's custom + * bus, and the bus's recorded creation time. Deleting either by id alone would silently target + * the default bus or skip the ownership check. + */ + @Override + public void delete(StackResource resource, String region) { + switch (resource.getResourceType()) { + case "AWS::Events::Rule" -> deleteEventBridgeRuleSafe(resource.getPhysicalId(), + resource.getAttributes() != null ? resource.getAttributes().get("EventBusName") : null, + region); + case "AWS::Events::EventBus" -> deleteEventBusSafe(resource, region); + default -> delete(resource.getResourceType(), resource.getPhysicalId(), region); + } + } + + @Override + public void delete(String resourceType, String physicalId, String region) { + if (physicalId == null || physicalId.isBlank()) { + return; + } + switch (resourceType) { + case "AWS::Events::Rule" -> deleteEventBridgeRuleSafe(physicalId, null, region); + case "AWS::Events::EventBus" -> deleteEventBusSafe(physicalId, region); + case "AWS::Events::EventBusPolicy" -> removeEventBusPolicySafe(physicalId, region); + default -> { + // no other type reaches this provisioner + } + } + } + + private void provisionRule(StackResource r, JsonNode props, ProvisionContext ctx) { + // A snapshot describes the update in flight. The one an earlier update left behind goes + // before this run touches a target, so a rollback never puts back a target the rule stopped + // carrying two updates ago. + r.getAttributes().remove(CfnRollback.RULE_TARGETS_SNAPSHOT_ATTR); + // Name is createOnly and the physical id is the rule name, so ctx.stablePhysicalName + // applies directly: without it an unnamed rule was given a fresh random name on every + // UpdateStack, creating a second rule and leaving the first behind with its targets. + String ruleName = ctx.stablePhysicalName( + ctx.resolveOptional(props, "Name"), r.getLogicalId(), 64, false); + + String busName = ctx.resolveOptional(props, "EventBusName"); + String description = ctx.resolveOptional(props, "Description"); + String roleArn = ctx.resolveOptional(props, "RoleArn"); + String scheduleExpression = ctx.resolveOptional(props, "ScheduleExpression"); + + String eventPattern = null; + if (props != null && props.has("EventPattern") && !props.get("EventPattern").isNull()) { + JsonNode patternNode = ctx.engine().resolveNode(props.get("EventPattern")); + eventPattern = patternNode.toString(); + } + + String stateStr = ctx.resolveOptional(props, "State"); + RuleState state = "DISABLED".equals(stateStr) ? RuleState.DISABLED : RuleState.ENABLED; + + var rule = eventBridgeService.putRule(ruleName, busName, eventPattern, scheduleExpression, + state, description, roleArn, Map.of(), ctx.region()); + r.setPhysicalId(ruleName); + r.getAttributes().put("Arn", rule.getArn()); + // A rule on a custom bus is keyed by that bus; remember it so the resource delete can target + // the right bus (the physical id is only the rule name, which resolves to the default bus). + if (busName != null && !busName.isBlank()) { + r.getAttributes().put("EventBusName", busName); + } + + // Provision inline targets + List targets = new ArrayList<>(); + if (props != null && props.has("Targets") && props.get("Targets").isArray()) { + for (JsonNode targetNode : props.get("Targets")) { + JsonNode resolved = ctx.engine().resolveNode(targetNode); + String targetId = resolved.path("Id").asText(null); + String targetArn = resolved.path("Arn").asText(null); + String input = resolved.path("Input").asText(null); + String inputPath = resolved.path("InputPath").asText(null); + if (targetId != null && targetArn != null) { + Target target = new Target(targetId, targetArn, input, inputPath); + target.setInputTransformer(InputTransformer.fromJson(resolved.path("InputTransformer"))); + JsonNode sqsParamsNode = resolved.path("SqsParameters"); + if (!sqsParamsNode.isMissingNode() && sqsParamsNode.isObject()) { + String messageGroupId = sqsParamsNode.path("MessageGroupId").asText(null); + if (messageGroupId != null) { + SqsParameters sqsParameters = new SqsParameters(); + sqsParameters.setMessageGroupId(messageGroupId); + target.setSqsParameters(sqsParameters); + } + } + JsonNode batchParamsNode = resolved.path("BatchParameters"); + if (!batchParamsNode.isMissingNode() && batchParamsNode.isObject()) { + JsonNode arrayProperties = batchParamsNode.path("ArrayProperties"); + BatchParameters batchParameters = new BatchParameters(); + batchParameters.setJobDefinition(batchParamsNode.path("JobDefinition").asText(null)); + batchParameters.setJobName(batchParamsNode.path("JobName").asText(null)); + if (arrayProperties.isObject()) { + batchParameters.setArrayProperties(jsonObjectToMap(arrayProperties)); + } + if (batchParamsNode.has("RetryStrategy")) { + batchParameters.setRetryStrategy(batchParamsNode.get("RetryStrategy")); + } + target.setBatchParameters(batchParameters); + } + targets.add(target); + } + } + } + if (ctx.isUpdate()) { + snapshotTargetsBeforeUpdate(r, ruleName, busName, ctx.region()); + } + try { + if (!targets.isEmpty()) { + eventBridgeService.putTargets(ruleName, busName, targets, ctx.region()); + } + removeStaleTargets(ruleName, busName, targets, ctx.region()); + } catch (RuntimeException updateFailure) { + restoreTargetsAfterFailedUpdate(r, updateFailure); + throw updateFailure; + } + } + + /** + * Records the targets the rule carries before this update reconciles them, so they can be put + * back when the stack update fails: by {@link #restoreTargetsAfterFailedUpdate} when this + * rule's own reconciliation is what failed, and by {@link #rollbackUpdate} when a later + * resource is. Only taken on an update, because a create has nothing to restore to. + * + *

The rule name, its bus and the region travel with the targets because the rollback hook is + * handed the stack resource alone, and those three are how targets are addressed. + */ + private void snapshotTargetsBeforeUpdate(StackResource r, String ruleName, String busName, String region) { + ObjectNode snapshot = MAPPER.createObjectNode(); + snapshot.put("ruleName", ruleName); + snapshot.put("busName", busName); + snapshot.put("region", region); + snapshot.set("targets", MAPPER.valueToTree( + eventBridgeService.listTargetsByRule(ruleName, busName, region))); + r.getAttributes().put(CfnRollback.RULE_TARGETS_SNAPSHOT_ATTR, snapshot.toString()); + } + + /** + * Puts the rule's targets back from the snapshot this update took, while the failure that + * interrupted the reconciliation is on its way out of the provisioner. The snapshot is spent + * here, so the rollback hook finds nothing left to act on for a rule already restored. + * + *

A restore that fails itself leaves the rule delivering to a set of targets nobody + * recorded. Its reason goes on the resource under + * {@link CfnRollback#UPDATE_ROLLBACK_FAILURE_ATTR}, which is what makes the stack report + * UPDATE_ROLLBACK_FAILED naming this resource instead of a clean rollback, and it is attached + * to the update failure as suppressed so neither is lost. The restore repeats the calls the + * update just made, so it can come back carrying the very exception that interrupted the + * update; suppressing a throwable under itself is rejected by the JDK, and that one is already + * the failure being reported. + */ + private void restoreTargetsAfterFailedUpdate(StackResource r, RuntimeException updateFailure) { + String rawSnapshot = r.getAttributes().get(CfnRollback.RULE_TARGETS_SNAPSHOT_ATTR); + if (rawSnapshot == null) { + return; + } + try { + restoreSnapshottedTargets(r, MAPPER.readTree(rawSnapshot)); + } catch (RuntimeException | JsonProcessingException restoreFailure) { + if (restoreFailure != updateFailure) { + updateFailure.addSuppressed(restoreFailure); + } + String reason = restoreFailure.getMessage() != null + ? restoreFailure.getMessage() + : restoreFailure.getClass().getSimpleName(); + LOG.errorv("Could not restore the targets of rule {0} after a failed update: {1}", + r.getPhysicalId(), reason); + r.getAttributes().put(CfnRollback.UPDATE_ROLLBACK_FAILURE_ATTR, reason); + } + } + + /** + * Puts the rule's targets back to what the snapshot holds and spends it. Exact rather than + * additive: a target the failed update added is removed, and every snapshotted target is put + * again, so one the update modified goes back to the configuration it was found with. + * + *

This is the hook for an update a later resource failed: this rule's own + * reconciliation committed, so its snapshot is still unspent. When the rule's own + * reconciliation is what failed, {@link #restoreTargetsAfterFailedUpdate} has already restored + * it inside {@code provision} and spent the snapshot there, and a rule this run never touched + * carries no snapshot at all, which is the false this returns so the stack keeps reporting that + * rollback is not implemented rather than silently clearing its targets. + */ + @Override + public boolean rollbackUpdate(StackResource resource) { + String rawSnapshot = resource.getAttributes().get(CfnRollback.RULE_TARGETS_SNAPSHOT_ATTR); + if (rawSnapshot == null) { + return false; + } + try { + restoreSnapshottedTargets(resource, MAPPER.readTree(rawSnapshot)); + } catch (JsonProcessingException unreadableSnapshot) { + throw new IllegalStateException("Could not read the rule target snapshot for " + + resource.getLogicalId(), unreadableSnapshot); + } + return true; + } + + private void restoreSnapshottedTargets(StackResource resource, JsonNode snapshot) { + String ruleName = snapshotText(snapshot, "ruleName"); + String busName = snapshotText(snapshot, "busName"); + String region = snapshot.get("region").asText(); + List restored = MAPPER.convertValue( + snapshot.path("targets"), new TypeReference>() { }); + Set restoredIds = restored.stream().map(Target::getId).collect(Collectors.toSet()); + List added = eventBridgeService.listTargetsByRule(ruleName, busName, region).stream() + .map(Target::getId) + .filter(id -> !restoredIds.contains(id)) + .toList(); + if (!added.isEmpty()) { + eventBridgeService.removeTargets(ruleName, busName, added, region); + } + if (!restored.isEmpty()) { + eventBridgeService.putTargets(ruleName, busName, restored, region); + } + resource.getAttributes().remove(CfnRollback.RULE_TARGETS_SNAPSHOT_ATTR); + } + + /** A snapshotted string, or null when the rule carried none. */ + private static String snapshotText(JsonNode snapshot, String property) { + JsonNode value = snapshot.get(property); + return value == null || value.isNull() ? null : value.asText(); + } + + /** + * Drives the rule's targets to the template's desired state. PutTargets only upserts by id, + * so a target dropped from the template stayed on the rule forever, still delivering events. + * A template that declares no Targets at all means no targets, so the sweep runs either way. + */ + private void removeStaleTargets(String ruleName, String busName, List desired, String region) { + Set desiredIds = desired.stream().map(Target::getId).collect(Collectors.toSet()); + List stale = eventBridgeService.listTargetsByRule(ruleName, busName, region).stream() + .map(Target::getId) + .filter(id -> !desiredIds.contains(id)) + .toList(); + if (!stale.isEmpty()) { + eventBridgeService.removeTargets(ruleName, busName, stale, region); + } + } + + /** + * Provisions an {@code AWS::Events::EventBus} (a custom EventBridge event bus). Without this the + * resource would fall through to the generic stub, which assigns a physical id but never registers + * the bus with the EventBridge service, so any {@code AWS::Events::Rule} (or PutEvents) targeting + * the bus fails "EventBus not found". Per the AWS spec, {@code Ref} returns the bus name + * (not the ARN), so the physical id is the name; {@code Fn::GetAtt "Arn"} exposes the ARN. + */ + private void provisionEventBus(StackResource r, JsonNode props, ProvisionContext ctx) { + validateEventBusProperties(props); + String existingBusName = ctx.isUpdate() ? ctx.priorPhysicalId() : null; + String busName = ctx.resolveOptional(props, "Name"); + validateEventBusName(busName); + if (existingBusName != null && !existingBusName.equals(busName)) { + throw new AwsException("ValidationError", + "Updating EventBus Name requires resource replacement, which is not supported.", 400); + } + String description = ctx.resolveOptional(props, "Description"); + if (description != null && description.length() > 512) { + throw new AwsException("ValidationError", + "AWS::Events::EventBus Description must not exceed 512 characters.", 400); + } + Map tags = parseEventBusTags(props != null ? props.get("Tags") : null, ctx); + JsonNode policy = resolveEventBusPolicy(props, ctx); + + EventBus bus; + boolean createdBus = false; + try { + bus = eventBridgeService.createEventBus(busName, description, tags, ctx.region()); + createdBus = true; + r.getAttributes().put(CfnRollback.ROLLBACK_OWNED_ATTR, "true"); + } catch (AwsException e) { + boolean stackAlreadyOwnsBus = existingBusName != null && existingBusName.equals(busName); + if (!stackAlreadyOwnsBus || !"ResourceAlreadyExistsException".equals(e.getErrorCode())) { + throw e; + } + bus = eventBridgeService.describeEventBus(busName, ctx.region()); + // A missing created-time means ownership was never tracked, not that it changed: stacks + // provisioned before this attribute existed are restored without it. Refusing there would + // wedge every later UpdateStack, including no-op ones. Only a recorded time that actually + // disagrees means the bus was recreated out of band and belongs to its new owner. + String existingCreatedTime = r.getAttributes().get(EVENT_BUS_CREATED_TIME_ATTR); + String actualCreatedTime = eventBusCreatedTime(bus); + if (existingCreatedTime != null && !existingCreatedTime.equals(actualCreatedTime)) { + r.getAttributes().remove(CfnRollback.ROLLBACK_OWNED_ATTR); + throw e; + } + validateEventBusMutablePropertiesUnchanged(r, bus, description, tags, policy); + } + + // Record identity before applying the policy: rollbackCreatedResources skips any resource + // whose physicalId is still null, so a putPermission failure after the bus exists would + // otherwise orphan it with no way for rollback to find it. + r.setPhysicalId(busName); // Ref → EventBus name (AWS-faithful) + r.getAttributes().put("Arn", bus.getArn()); + r.getAttributes().put("Name", busName); + r.getAttributes().put(EVENT_BUS_CREATED_TIME_ATTR, eventBusCreatedTime(bus)); + recordEventBusManagedTagKeys(r, tags.keySet()); + recordEventBusManagedPolicy(r, policy); + + // Apply an optional inline resource policy only during creation. Updating it is rejected by + // validateEventBusMutablePropertiesUnchanged until stack updates can roll back live resource + // mutations transactionally. + if (createdBus && !policy.isNull()) { + eventBridgeService.putPermission(busName, null, null, null, null, policy.toString(), ctx.region()); + } + } + + private void validateEventBusProperties(JsonNode props) { + if (props == null || props.isNull()) { + return; + } + if (!props.isObject()) { + throw new AwsException("ValidationError", + "AWS::Events::EventBus Properties must be an object.", 400); + } + List unsupported = new ArrayList<>(); + props.fieldNames().forEachRemaining(name -> { + if (!EVENT_BUS_SUPPORTED_PROPERTIES.contains(name)) { + unsupported.add(name); + } + }); + if (!unsupported.isEmpty()) { + Collections.sort(unsupported); + throw new AwsException("ValidationError", + "Unsupported AWS::Events::EventBus properties: " + + String.join(", ", unsupported), 400); + } + } + + private void validateEventBusName(String busName) { + if (busName == null || busName.isBlank()) { + throw new AwsException("ValidationError", + "Name is required for AWS::Events::EventBus.", 400); + } + if (busName.length() > 256 + || !busName.matches("[.\\-_A-Za-z0-9]+") + || "default".equals(busName)) { + throw new AwsException("ValidationError", + "Invalid custom event bus Name: " + busName, 400); + } + } + + private Map parseEventBusTags(JsonNode tagsNode, ProvisionContext ctx) { + if (tagsNode == null || tagsNode.isNull()) { + return Map.of(); + } + JsonNode resolvedTags = ctx.engine().resolveNode(tagsNode); + if (!resolvedTags.isArray()) { + throw new AwsException("ValidationError", + "AWS::Events::EventBus Tags must be an array.", 400); + } + if (resolvedTags.size() > 50) { + throw new AwsException("ValidationError", + "AWS::Events::EventBus supports at most 50 tags.", 400); + } + Map tags = new LinkedHashMap<>(); + for (JsonNode entry : resolvedTags) { + if (!entry.isObject()) { + throw new AwsException("ValidationError", + "Each AWS::Events::EventBus tag must be an object.", 400); + } + String key = entry.path("Key").asText(null); + String value = entry.path("Value").asText(null); + if (key == null || key.isEmpty() || key.length() > 128) { + throw new AwsException("ValidationError", + "Event bus tag Key must contain 1 to 128 characters.", 400); + } + if (key.regionMatches(true, 0, "aws:", 0, 4)) { + throw new AwsException("ValidationError", + "Event bus tag Key must not use the reserved aws: prefix.", 400); + } + if (!EVENT_BUS_TAG_PATTERN.matcher(key).matches()) { + throw new AwsException("ValidationError", + "Event bus tag Key contains unsupported characters.", 400); + } + if (value == null || value.length() > 256) { + throw new AwsException("ValidationError", + "Event bus tag Value must contain at most 256 characters.", 400); + } + if (!EVENT_BUS_TAG_PATTERN.matcher(value).matches()) { + throw new AwsException("ValidationError", + "Event bus tag Value contains unsupported characters.", 400); + } + if (tags.putIfAbsent(key, value) != null) { + throw new AwsException("ValidationError", + "Duplicate event bus tag Key: " + key, 400); + } + } + return tags; + } + + private void validateEventBusMutablePropertiesUnchanged( + StackResource resource, EventBus bus, String requestedDescription, + Map requestedTags, JsonNode requestedPolicy) { + if (!Objects.equals(bus.getDescription(), requestedDescription)) { + throw unsupportedEventBusMutableUpdate(); + } + + // Stacks persisted by the older EventBus provisioner have no managed-key metadata. There + // is no reliable way to distinguish their CloudFormation tags from tags added out of band, + // so allow this one-time adoption and start tracking the requested keys afterwards. + if (resource.getAttributes().containsKey(EVENT_BUS_MANAGED_TAG_KEYS_ATTR)) { + Map currentManagedTags = new LinkedHashMap<>(); + for (String key : eventBusManagedTagKeys(resource)) { + if (bus.getTags().containsKey(key)) { + currentManagedTags.put(key, bus.getTags().get(key)); + } + } + if (!currentManagedTags.equals(requestedTags)) { + throw unsupportedEventBusMutableUpdate(); + } + } + + String managedPolicy = resource.getAttributes().get(EVENT_BUS_MANAGED_POLICY_ATTR); + JsonNode policyToCompare = managedPolicy != null + ? parseEventBusPolicy(managedPolicy, "stored CloudFormation metadata") + : parseEventBusPolicy(bus.getPolicy(), "the existing event bus"); + if (managedPolicy != null || !requestedPolicy.isNull()) { + if (!policyToCompare.equals(requestedPolicy)) { + throw unsupportedEventBusMutableUpdate(); + } + } + } + + private JsonNode resolveEventBusPolicy(JsonNode props, ProvisionContext ctx) { + if (props == null || !props.has("Policy") || props.get("Policy").isNull()) { + return JsonNodeFactory.instance.nullNode(); + } + return ctx.engine().resolveNode(props.get("Policy")); + } + + private JsonNode parseEventBusPolicy(String policy, String source) { + if (policy == null) { + return JsonNodeFactory.instance.nullNode(); + } + try { + JsonNode parsed = MAPPER.readTree(policy); + return parsed != null ? parsed : JsonNodeFactory.instance.nullNode(); + } catch (Exception e) { + throw new AwsException("InternalFailure", + "Invalid EventBus policy in " + source + ": " + e.getMessage(), 500); + } + } + + private void recordEventBusManagedPolicy(StackResource resource, JsonNode policy) { + try { + resource.getAttributes().put(EVENT_BUS_MANAGED_POLICY_ATTR, + MAPPER.writeValueAsString(policy)); + } catch (Exception e) { + throw new AwsException("InternalFailure", + "Failed to store EventBus managed-policy metadata: " + e.getMessage(), 500); + } + } + + private AwsException unsupportedEventBusMutableUpdate() { + return new AwsException("ValidationError", + "Updating AWS::Events::EventBus Description, Tags, or Policy is not supported " + + "until transactional rollback is available.", 400); + } + + private Set eventBusManagedTagKeys(StackResource resource) { + String value = resource.getAttributes().get(EVENT_BUS_MANAGED_TAG_KEYS_ATTR); + if (value == null || value.isBlank()) { + return Set.of(); + } + try { + JsonNode keys = MAPPER.readTree(value); + if (!keys.isArray()) { + throw new IllegalArgumentException("managed tag keys are not an array"); + } + Set result = new HashSet<>(); + keys.forEach(key -> result.add(key.asText())); + return result; + } catch (Exception e) { + throw new AwsException("InternalFailure", + "Invalid stored EventBus managed-tag metadata: " + e.getMessage(), 500); + } + } + + private void recordEventBusManagedTagKeys(StackResource resource, Set keys) { + try { + resource.getAttributes().put( + EVENT_BUS_MANAGED_TAG_KEYS_ATTR, + MAPPER.writeValueAsString(new TreeSet<>(keys))); + } catch (Exception e) { + throw new AwsException("InternalFailure", + "Failed to store EventBus managed-tag metadata: " + e.getMessage(), 500); + } + } + + private String eventBusCreatedTime(EventBus bus) { + return bus.getCreatedTime() != null ? bus.getCreatedTime().toString() : ""; + } + + private void deleteEventBridgeRuleSafe(String ruleName, String busName, String region) { + try { + // Remove all targets before deleting the rule (busName scopes the lookup to the rule's bus). + var targets = eventBridgeService.listTargetsByRule(ruleName, busName, region); + if (!targets.isEmpty()) { + List targetIds = targets.stream().map(Target::getId).toList(); + eventBridgeService.removeTargets(ruleName, busName, targetIds, region); + } + eventBridgeService.deleteRule(ruleName, busName, region); + } catch (AwsException e) { + // An already-deleted rule is the one failure that genuinely means "done". Anything else + // is a real error worth surfacing rather than hiding behind a debug line. + if (!"ResourceNotFoundException".equals(e.getErrorCode())) { + throw e; + } + LOG.debugv("EventBridge rule already gone, treating as deleted: {0}", ruleName); + } catch (Exception e) { + throw new AwsException("InternalFailure", + "Could not delete EventBridge rule " + ruleName + ": " + e.getMessage(), 500); + } + } + + private void deleteEventBusSafe(String busName, String region) { + try { + eventBridgeService.deleteEventBus(busName, region); + } catch (AwsException e) { + if (!"ResourceNotFoundException".equals(e.getErrorCode())) { + throw e; + } + LOG.debugv("Event bus already gone, treating as deleted: {0}", busName); + } + } + + private void deleteEventBusSafe(StackResource resource, String region) { + String busName = resource.getPhysicalId(); + EventBus bus; + try { + bus = eventBridgeService.describeEventBus(busName, region); + } catch (AwsException e) { + if ("ResourceNotFoundException".equals(e.getErrorCode())) { + LOG.debugv("Event bus already gone, treating as deleted: {0}", busName); + return; + } + throw e; + } + + // A missing attribute means ownership was never tracked, not that it changed: stacks + // provisioned before this attribute existed are restored from cloudformation-stacks.json + // without it. Refusing there would leave every such stack permanently in DELETE_FAILED, so + // fall back to the pre-tracking behaviour of deleting what the stack recorded it created. + String expectedCreatedTime = resource.getAttributes().get(EVENT_BUS_CREATED_TIME_ATTR); + if (expectedCreatedTime != null && !expectedCreatedTime.equals(eventBusCreatedTime(bus))) { + throw new AwsException("ValidationError", + "EventBus ownership changed; refusing to delete: " + busName, 400); + } + deleteEventBusSafe(busName, region); + } + + + private void provisionEventBusPolicy(StackResource r, JsonNode props, ProvisionContext ctx) { + String busName = resolveOrDefault(props, "EventBusName", ctx, "default"); + String statementId = ctx.resolveOptional(props, "StatementId"); + if (statementId == null || statementId.isBlank()) { + throw new AwsException("ValidationException", "EventBusPolicy StatementId is required.", 400); + } + validateStatementId(statementId); + + 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) ctx.engine().resolveNode(props.get("Statement")).deepCopy(); + statement.put("Sid", statementId); + + EventBus bus = eventBridgeService.describeEventBus(busName, ctx.region()); + ObjectNode policy; + String current = bus.getPolicy(); + if (current != null && !current.isBlank()) { + policy = (ObjectNode) MAPPER.readTree(current); + } else { + policy = MAPPER.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, + MAPPER.writeValueAsString(policy), ctx.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 = ctx.resolveOptional(props, "Action"); + String principal = ctx.resolveOptional(props, "Principal"); + String conditionJson = null; + if (props != null && props.has("Condition") && !props.get("Condition").isNull()) { + JsonNode c = ctx.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 = MAPPER.createObjectNode(); + condition.set(type, MAPPER.createObjectNode().put(key, value)); + conditionJson = condition.toString(); + } + } + eventBridgeService.putPermission(busName, action, principal, statementId, conditionJson, null, ctx.region()); + + r.setPhysicalId(busName + "|" + statementId); + } + + /** + * Holds a policy statement id to what the registry schema for {@code AWS::Events::EventBusPolicy} + * models: {@code [a-zA-Z0-9-_]+}, 1 to 64 characters. Rejecting here is parity first, since AWS + * refuses the same values, and it also keeps the physical id unambiguous: the id this + * provisioner assigns is {@code |}, and neither the modeled bus-name + * pattern nor this one admits the separator, so {@link #removeEventBusPolicySafe} can always + * split it back into the pair it was built from. + */ + private void validateStatementId(String statementId) { + if (statementId.length() > STATEMENT_ID_MAX_LENGTH + || !STATEMENT_ID_PATTERN.matcher(statementId).matches()) { + throw new AwsException("ValidationException", + "Invalid EventBusPolicy StatementId: " + statementId, 400); + } + } + + private void removeEventBusPolicySafe(String physicalId, String region) { + int sep = physicalId.lastIndexOf('|'); + String busName = sep >= 0 ? physicalId.substring(0, sep) : "default"; + String statementId = sep >= 0 ? physicalId.substring(sep + 1) : physicalId; + // Only an already-gone bus or statement means "done"; RemovePermission raises + // ResourceNotFoundException for both. Anything else is a real failure and must reach the + // stack as DELETE_FAILED rather than being logged away, which is what the previous + // catch-all did: the statement stayed on the bus and the stack still reported deleted. + CfnDeletes.safeDelete("Event bus policy statement", physicalId, + () -> eventBridgeService.removePermission(busName, statementId, false, region), + "ResourceNotFoundException"); + } + private static String resolveOrDefault(JsonNode props, String name, ProvisionContext ctx, String defaultValue) { + String value = ctx.resolveOptional(props, name); + return (value != null && !value.isBlank()) ? value : defaultValue; + } + + /** Copied from the monolith: the shared original serves six other callers and stays there. */ + private Map jsonObjectToMap(JsonNode node) { + Map out = new LinkedHashMap<>(); + node.fields().forEachRemaining(e -> out.put(e.getKey(), jsonNodeToValue(e.getValue()))); + return out; + } + + private Object jsonNodeToValue(JsonNode node) { + if (node == null || node.isNull()) { + return null; + } + if (node.isObject()) { + return jsonObjectToMap(node); + } + if (node.isArray()) { + List values = new ArrayList<>(); + node.forEach(v -> values.add(jsonNodeToValue(v))); + return values; + } + if (node.isBoolean()) { + return node.asBoolean(); + } + if (node.isIntegralNumber()) { + return node.asLong(); + } + if (node.isFloatingPointNumber()) { + return node.asDouble(); + } + return node.asText(); + } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/CfnProvisionerFixture.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CfnProvisionerFixture.java index a8abae3c7e..c82b53520f 100644 --- a/src/test/java/io/github/hectorvent/floci/services/cloudformation/CfnProvisionerFixture.java +++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CfnProvisionerFixture.java @@ -30,6 +30,7 @@ import io.github.hectorvent.floci.services.cloudformation.provisioners.ApiGatewa import io.github.hectorvent.floci.services.cloudformation.provisioners.AutoScalingLifecycleHookCfnProvisioner; import io.github.hectorvent.floci.services.cloudformation.provisioners.AutoScalingScalingPolicyCfnProvisioner; import io.github.hectorvent.floci.services.cloudformation.provisioners.BackupVaultCfnProvisioner; +import io.github.hectorvent.floci.services.cloudformation.provisioners.EventsCfnProvisioner; import io.github.hectorvent.floci.services.cloudformation.provisioners.CdkMetadataCfnProvisioner; import io.github.hectorvent.floci.services.cloudformation.provisioners.CloudTrailCfnProvisioner; import io.github.hectorvent.floci.services.cloudformation.provisioners.CloudWatchCfnProvisioner; @@ -298,6 +299,9 @@ final class CfnProvisionerFixture { if (backupService != null) { discovered.add(new BackupVaultCfnProvisioner(backupService)); } + if (eventBridgeService != null) { + discovered.add(new EventsCfnProvisioner(eventBridgeService)); + } if (wafV2Service != null) { discovered.add(new WafV2CfnProvisioner(wafV2Service)); } @@ -590,7 +594,6 @@ final class CfnProvisionerFixture { ssmService, kmsService, secretsManagerService, - eventBridgeService, apiGatewayService, apiGatewayV2Service, ecrService, diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/EventsCfnProvisionerTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/EventsCfnProvisionerTest.java new file mode 100644 index 0000000000..8ac521a72e --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/EventsCfnProvisionerTest.java @@ -0,0 +1,356 @@ +package io.github.hectorvent.floci.services.cloudformation.provisioners; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.node.ArrayNode; +import com.fasterxml.jackson.databind.node.ObjectNode; +import io.github.hectorvent.floci.core.common.AwsException; +import io.github.hectorvent.floci.services.cloudformation.CloudFormationTemplateEngine; +import io.github.hectorvent.floci.services.cloudformation.model.StackResource; +import io.github.hectorvent.floci.services.eventbridge.EventBridgeService; +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.mockito.ArgumentCaptor; + +import java.util.HashMap; +import java.util.List; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.doThrow; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +/** The Events CFN provisioner in isolation, with only {@link EventBridgeService} mocked. */ +class EventsCfnProvisionerTest { + + private static final String REGION = "us-east-1"; + private static final String RULE_ARN = "arn:aws:events:us-east-1:000000000000:rule/my-stack-Rule-ab12cd"; + + private final EventBridgeService events = mock(EventBridgeService.class); + private final ObjectMapper mapper = new ObjectMapper(); + private final EventsCfnProvisioner provisioner = new EventsCfnProvisioner(events); + + private ProvisionContext ctx(String priorPhysicalId) { + CloudFormationTemplateEngine engine = mock(CloudFormationTemplateEngine.class); + when(engine.resolve(any())).thenAnswer(inv -> { + JsonNode node = inv.getArgument(0); + return node == null ? null : node.asText(); + }); + when(engine.resolveNode(any())).thenAnswer(inv -> inv.getArgument(0)); + return new ProvisionContext(engine, REGION, "000000000000", "my-stack", priorPhysicalId); + } + + private StackResource resource(String type, String logicalId) { + StackResource r = new StackResource(); + r.setResourceType(type); + r.setLogicalId(logicalId); + r.setAttributes(new HashMap<>()); + return r; + } + + private void stubPutRule() { + Rule rule = new Rule(); + rule.setArn(RULE_ARN); + when(events.putRule(anyString(), any(), any(), any(), any(), any(), any(), any(), anyString())) + .thenReturn(rule); + } + + private ObjectNode target(String id, String arn) { + return mapper.createObjectNode().put("Id", id).put("Arn", arn); + } + + private static Target storedTarget(String id) { + return new Target(id, "arn:aws:sqs:us-east-1:000000000000:q-" + id, null, null); + } + + // ── the rule keeps its identity across an update ────────────────────────── + + @Test + void anUnnamedRuleKeepsItsGeneratedNameAcrossUpdates() { + // The defect: generating unconditionally gave an unnamed rule a fresh random name on every + // UpdateStack, creating a second rule and leaving the first behind still matching events. + stubPutRule(); + StackResource r = resource("AWS::Events::Rule", "Rule"); + + provisioner.provision(r, mapper.createObjectNode(), ctx("my-stack-Rule-ab12cd")); + + assertEquals("my-stack-Rule-ab12cd", r.getPhysicalId()); + verify(events).putRule(eq("my-stack-Rule-ab12cd"), any(), any(), any(), any(), any(), any(), + any(), anyString()); + } + + @Test + void anExplicitlyNamedRuleStillUsesTheTemplateName() { + stubPutRule(); + StackResource r = resource("AWS::Events::Rule", "Rule"); + + provisioner.provision(r, mapper.createObjectNode().put("Name", "orders"), ctx(null)); + + assertEquals("orders", r.getPhysicalId()); + assertEquals(RULE_ARN, r.getAttributes().get("Arn")); + } + + // ── targets are driven to the template's desired state ─────────────────── + + @Test + void aTargetDroppedFromTheTemplateIsRemovedFromTheRule() { + // PutTargets only upserts by id, so without the sweep a dropped target stayed on the rule + // and kept receiving events after the template stopped declaring it. + stubPutRule(); + when(events.listTargetsByRule(anyString(), any(), anyString())) + .thenReturn(List.of(storedTarget("keep"), storedTarget("gone"))); + ObjectNode props = mapper.createObjectNode().put("Name", "orders"); + props.putArray("Targets").add(target("keep", "arn:aws:sqs:us-east-1:000000000000:q-keep")); + + provisioner.provision(resource("AWS::Events::Rule", "Rule"), props, ctx("orders")); + + ArgumentCaptor> removed = ArgumentCaptor.forClass(List.class); + verify(events).removeTargets(eq("orders"), any(), removed.capture(), anyString()); + assertEquals(List.of("gone"), removed.getValue()); + } + + @Test + void aTemplateThatDeclaresNoTargetsClearsThem() { + stubPutRule(); + when(events.listTargetsByRule(anyString(), any(), anyString())) + .thenReturn(List.of(storedTarget("stale"))); + + provisioner.provision(resource("AWS::Events::Rule", "Rule"), + mapper.createObjectNode().put("Name", "orders"), ctx("orders")); + + ArgumentCaptor> removed = ArgumentCaptor.forClass(List.class); + verify(events).removeTargets(eq("orders"), any(), removed.capture(), anyString()); + assertEquals(List.of("stale"), removed.getValue()); + verify(events, never()).putTargets(anyString(), any(), any(), anyString()); + } + + @Test + void anUnchangedTargetSetRemovesNothing() { + stubPutRule(); + when(events.listTargetsByRule(anyString(), any(), anyString())) + .thenReturn(List.of(storedTarget("keep"))); + ObjectNode props = mapper.createObjectNode().put("Name", "orders"); + props.putArray("Targets").add(target("keep", "arn:aws:sqs:us-east-1:000000000000:q-keep")); + + provisioner.provision(resource("AWS::Events::Rule", "Rule"), props, ctx("orders")); + + verify(events).putTargets(eq("orders"), any(), any(), anyString()); + verify(events, never()).removeTargets(anyString(), any(), any(), anyString()); + } + + // ── a failed policy removal is not swallowed ───────────────────────────── + + @Test + void anAlreadyGonePolicyStatementCountsAsDeleted() { + doThrowOnRemovePermission(new AwsException("ResourceNotFoundException", + "Statement not found: sid-1", 400)); + + provisioner.delete("AWS::Events::EventBusPolicy", "orders-bus|sid-1", REGION); + + verify(events).removePermission("orders-bus", "sid-1", false, REGION); + } + + @Test + void aFailedPolicyRemovalReachesTheStack() { + // The previous catch-all logged every failure at debug and returned, so the statement + // stayed on the bus while the stack still reported DELETE_COMPLETE. + doThrowOnRemovePermission(new AwsException("ValidationException", "StatementId is required.", 400)); + + AwsException thrown = assertThrows(AwsException.class, + () -> provisioner.delete("AWS::Events::EventBusPolicy", "orders-bus|sid-1", REGION)); + + assertEquals("ValidationException", thrown.getErrorCode()); + assertTrue(thrown.getMessage().contains("StatementId")); + } + + // ── the event bus reads its prior identity from the provision context ───── + + @Test + void anEventBusUpdateComparesAgainstThePriorIdFromTheContext() { + // provision assigns the new id as it runs, so the prior name has to come from the context. + // Reading it off the resource made a rename look like a create and silently switched buses. + StackResource r = resource("AWS::Events::EventBus", "Bus"); + + AwsException thrown = assertThrows(AwsException.class, () -> provisioner.provision( + r, mapper.createObjectNode().put("Name", "renamed"), ctx("orders-bus"))); + + assertTrue(thrown.getMessage().contains("requires resource replacement")); + } + + // ── the policy statement id is held to the modeled pattern ──────────────── + + @Test + void aStatementIdCarryingTheIdSeparatorIsRejected() { + // AWS models StatementId as [a-zA-Z0-9-_]+, so a pipe cannot reach the service. Refusing it + // is parity first, and it also keeps "|" splittable back into the pair. + AwsException thrown = assertThrows(AwsException.class, () -> provisioner.provision( + resource("AWS::Events::EventBusPolicy", "Policy"), + policyProps("orders-bus|sid"), ctx(null))); + + assertEquals("ValidationException", thrown.getErrorCode()); + assertTrue(thrown.getMessage().contains("StatementId")); + } + + @Test + void aStatementIdBeyondTheModeledLengthIsRejected() { + AwsException thrown = assertThrows(AwsException.class, () -> provisioner.provision( + resource("AWS::Events::EventBusPolicy", "Policy"), + policyProps("s".repeat(65)), ctx(null))); + + assertEquals("ValidationException", thrown.getErrorCode()); + verify(events, never()).putPermission(anyString(), any(), any(), anyString(), any(), any(), anyString()); + } + + private ObjectNode policyProps(String statementId) { + return mapper.createObjectNode() + .put("EventBusName", "orders-bus") + .put("StatementId", statementId) + .put("Action", "events:PutEvents") + .put("Principal", "111122223333"); + } + + private void doThrowOnRemovePermission(AwsException e) { + org.mockito.Mockito.doThrow(e).when(events) + .removePermission(anyString(), anyString(), org.mockito.ArgumentMatchers.anyBoolean(), anyString()); + } + + // ── a failed stack update puts the rule's targets back ──────────────────── + + private static final String RULE_TARGETS_SNAPSHOT_ATTR = CfnRollback.RULE_TARGETS_SNAPSHOT_ATTR; + + @Test + void aRollbackPutsBackATargetTheUpdateDropped() { + // Before the snapshot, the reconciliation sweep could delete a live target and a later + // resource's failure left it deleted: the rule stopped delivering to it for good. + stubPutRule(); + stubTargetSequence(List.of(storedTarget("keep"), storedTarget("gone")), + List.of(storedTarget("keep"), storedTarget("gone")), + List.of(storedTarget("keep"))); + StackResource r = updatedRuleWithTargets("keep"); + + assertTrue(provisioner.rollbackUpdate(r)); + + assertEquals(List.of("keep", "gone"), idsOfPutTargets(2).get(1)); + assertNull(r.getAttributes().get(RULE_TARGETS_SNAPSHOT_ATTR)); + } + + @Test + void aRollbackRemovesATargetTheUpdateAdded() { + // The restore is exact, not additive: what the failed update added does not survive it. + stubPutRule(); + stubTargetSequence(List.of(storedTarget("keep")), + List.of(storedTarget("keep"), storedTarget("added")), + List.of(storedTarget("keep"), storedTarget("added"))); + StackResource r = updatedRuleWithTargets("keep", "added"); + + assertTrue(provisioner.rollbackUpdate(r)); + + ArgumentCaptor> removed = ArgumentCaptor.forClass(List.class); + verify(events).removeTargets(eq("orders"), any(), removed.capture(), anyString()); + assertEquals(List.of("added"), removed.getValue()); + assertEquals(List.of("keep"), idsOfPutTargets(2).get(1)); + } + + @Test + void aRuleThisRunNeverTouchedIsNotRolledBack() { + // Answering true here would clear the targets of a rule the update never reconciled. False + // is what makes the stack keep reporting that rollback is not implemented for it. + StackResource r = resource("AWS::Events::Rule", "Rule"); + r.setPhysicalId("orders"); + + assertFalse(provisioner.rollbackUpdate(r)); + + verify(events, never()).putTargets(anyString(), any(), any(), anyString()); + verify(events, never()).removeTargets(anyString(), any(), any(), anyString()); + } + + @Test + void aFailedReconciliationRestoresTheTargetsAndRethrowsTheFailure() { + stubPutRule(); + stubTargetSequence(List.of(storedTarget("keep"), storedTarget("gone")), + List.of(storedTarget("keep"), storedTarget("gone"))); + AwsException putFailure = new AwsException("ValidationException", "Too many targets", 400); + when(events.putTargets(anyString(), any(), any(), anyString())).thenThrow(putFailure).thenReturn(1); + StackResource r = resource("AWS::Events::Rule", "Rule"); + + AwsException thrown = assertThrows(AwsException.class, + () -> provisioner.provision(r, ruleProps("keep"), ctx("orders"))); + + assertSame(putFailure, thrown); + assertEquals(List.of("keep", "gone"), idsOfPutTargets(2).get(1)); + assertNull(r.getAttributes().get(CfnRollback.UPDATE_ROLLBACK_FAILURE_ATTR)); + assertNull(r.getAttributes().get(RULE_TARGETS_SNAPSHOT_ATTR)); + } + + @Test + void aRestoreThatAlsoFailsIsRecordedOnTheResource() { + // The stack has to report UPDATE_ROLLBACK_FAILED naming this rule rather than claiming the + // prior targets are live, so the restore failure goes on the resource instead of being + // thrown over the failure that is already on its way out. + stubPutRule(); + stubTargetSequence(List.of(storedTarget("keep"), storedTarget("gone")), + List.of(storedTarget("keep"), storedTarget("gone"))); + AwsException putFailure = new AwsException("ValidationException", "Too many targets", 400); + doThrow(putFailure).when(events).putTargets(anyString(), any(), any(), anyString()); + StackResource r = resource("AWS::Events::Rule", "Rule"); + + assertThrows(AwsException.class, () -> provisioner.provision(r, ruleProps("keep"), ctx("orders"))); + + assertEquals("Too many targets", r.getAttributes().get(CfnRollback.UPDATE_ROLLBACK_FAILURE_ATTR)); + } + + @Test + void aCreateTakesNoSnapshotToRollBack() { + stubPutRule(); + + StackResource r = resource("AWS::Events::Rule", "Rule"); + provisioner.provision(r, ruleProps("keep"), ctx(null)); + + assertNull(r.getAttributes().get(RULE_TARGETS_SNAPSHOT_ATTR)); + assertFalse(provisioner.rollbackUpdate(r)); + } + + /** Runs an update that reconciles the rule down to {@code desiredIds}, and returns the resource. */ + private StackResource updatedRuleWithTargets(String... desiredIds) { + StackResource r = resource("AWS::Events::Rule", "Rule"); + provisioner.provision(r, ruleProps(desiredIds), ctx("orders")); + return r; + } + + private ObjectNode ruleProps(String... targetIds) { + ObjectNode props = mapper.createObjectNode().put("Name", "orders"); + ArrayNode declared = props.putArray("Targets"); + for (String id : targetIds) { + declared.add(target(id, "arn:aws:sqs:us-east-1:000000000000:q-" + id)); + } + return props; + } + + /** Successive answers from ListTargetsByRule, in the order the run asks for them. */ + @SafeVarargs + private void stubTargetSequence(List first, List... rest) { + var stub = when(events.listTargetsByRule(anyString(), any(), anyString())).thenReturn(first); + for (List answer : rest) { + stub = stub.thenReturn(answer); + } + } + + /** The target ids of each PutTargets call, in order, asserting there were exactly {@code n}. */ + private List> idsOfPutTargets(int n) { + ArgumentCaptor> put = ArgumentCaptor.forClass(List.class); + verify(events, times(n)).putTargets(eq("orders"), any(), put.capture(), anyString()); + return put.getAllValues().stream().map(call -> call.stream().map(Target::getId).toList()).toList(); + } +} diff --git a/src/test/resources/cloudformation/supported-resource-types.tsv b/src/test/resources/cloudformation/supported-resource-types.tsv index 9ef1d3caf2..60308dcd7c 100644 --- a/src/test/resources/cloudformation/supported-resource-types.tsv +++ b/src/test/resources/cloudformation/supported-resource-types.tsv @@ -71,9 +71,9 @@ AWS::ElasticLoadBalancingV2::Listener ElbV2CfnProvisioner AWS::ElasticLoadBalancingV2::ListenerRule ElbV2CfnProvisioner AWS::ElasticLoadBalancingV2::LoadBalancer ElbV2CfnProvisioner AWS::ElasticLoadBalancingV2::TargetGroup ElbV2CfnProvisioner -AWS::Events::EventBus LEGACY_SWITCH -AWS::Events::EventBusPolicy LEGACY_SWITCH -AWS::Events::Rule LEGACY_SWITCH +AWS::Events::EventBus EventsCfnProvisioner +AWS::Events::EventBusPolicy EventsCfnProvisioner +AWS::Events::Rule EventsCfnProvisioner AWS::IAM::AccessKey LEGACY_SWITCH AWS::IAM::InstanceProfile LEGACY_SWITCH AWS::IAM::ManagedPolicy LEGACY_SWITCH