mirror of
https://github.com/floci-io/floci.git
synced 2026-11-24 06:20:24 -05:00
refactor(cloudformation): move the Events types into EventsCfnProvisioner (#3286)
* refactor(cloudformation): move the Events types into a per-service provisioner AWS::Events::Rule, EventBus and EventBusPolicy move out of the legacy monolith into EventsCfnProvisioner, continuing the decomposition. The block was already contiguous and self-contained: 18 methods and five constants, none of them referenced from outside, and EventBridgeService was the monolith's only user, so the field, its constructor parameter and both imports go too. Behaviour preserving. The event bus arm in particular already carried real logic worth keeping intact: rollback ownership, the created-time check that refuses to delete a bus recreated out of band, managed tag and policy tracking, and the rejection of an unsupported mutable update. All of it moves unchanged. Rule and EventBus were listed in DELETE_NEEDS_STACK_RESOURCE because deleting them needs stored attributes rather than the physical id alone: a rule remembers the custom bus it lives on, and a bus remembers the creation time proving the stack still owns it. That logic moves into the provisioner's delete(StackResource, String) override and both entries leave the set, which is what CfnDeletePrecedenceTest gates. EventBusPolicy keeps the id-only form, its composite busName|statementId id being enough. The four existing Events test classes needed no changes: they build the provisioner through CfnProvisionerFixture, so wiring the new provisioner there is all it took for them to exercise it. 40 tests across them still pass, and the schema-coverage gate finds no new attribute gaps. Monolith 6,457 to 5,954 lines, legacy types 47 to 44. * fix(cloudformation): keep an Events rule's identity and targets across an update provision runs again on every UpdateStack, and the rule arm got both halves of that wrong. An unnamed rule generated a fresh physical name each time, so the second update created a second rule and left the first behind, still matching events and still delivering to its targets. Name is createOnly and a rule's physical id is its name, so ctx.stablePhysicalName applies directly here, unlike the Batch types whose physical id is an ARN and which need the name read from a stored attribute. Targets were never driven to the template's desired state. PutTargets upserts by id and removes nothing, so a target dropped from the template stayed on the rule and kept receiving events indefinitely. The desired set is now reconciled after the put, which also covers a template that declares no Targets at all: that means no targets, so the sweep runs either way. The Targets property is checked for being an array before it is iterated. Five unit tests: an unnamed rule keeping its name, an explicit name still winning, a dropped target being removed, a cleared Targets list removing all of them, and an unchanged set removing nothing. * fix(cloudformation): surface a failed Events policy removal instead of hiding it Deleting an AWS::Events::EventBusPolicy wrapped the whole removal in a bare catch (Exception) that logged at debug and returned. Every failure was hidden: the statement stayed on the bus while the stack reported DELETE_COMPLETE, which is the outcome AGENTS.md rules out for deletes, since a real failure has to reach the stack as DELETE_FAILED. RemovePermission distinguishes its failures, unlike the Batch services where a single ClientException covers everything. It raises ResourceNotFoundException both when the bus is gone and when the statement is not on it, and those are the two cases that genuinely mean "already deleted". So the removal now goes through the shared CfnDeletes.safeDelete tolerating only that code, and anything else, a malformed statement id for instance, propagates. Two unit tests: an already-gone statement counting as deleted, and a ValidationException reaching the caller rather than being swallowed. * fix(cloudformation): drop the em dash from the moved Events javadoc The javadoc came across from CloudFormationResourceProvisioner verbatim. That file holds 30 em dashes but is an existing file, and the doc-style gate only scans the files a PR adds, so moving the prose into a new file is what surfaced a violation that was always there. * fix(cloudformation): read the prior event bus id from the provision context provision serves create and update, and it assigns the new physical id as it runs, so a resource-derived identity check can flip mid-method. The moved code read the prior bus name off the resource. It was captured before the assignment so the behaviour was right, but the convention exists precisely so the next edit cannot quietly break it. * fix(cloudformation): validate the Events policy StatementId The registry schema for AWS::Events::EventBusPolicy and the botocore model agree that StatementId is [a-zA-Z0-9-_]+, 1 to 64 characters, but nothing checked it, so an AWS-invalid value was accepted. It also made the physical id ambiguous. This provisioner keys a policy statement as "<bus name>|<statement id>" and the delete splits on the last separator. Neither the modeled bus-name pattern nor the statement-id one admits a pipe, so holding the value to the model closes that at source rather than by guessing at the split. * fix(cloudformation): restore rule targets when a stack update rolls back The reconciliation sweep this branch added can delete a live target, which nothing could put back: without a rollbackUpdate hook the resource fell to "Rollback is not implemented for AWS::Events::Rule", so a failed stack update left the rule no longer delivering to it and the stack reported UPDATE_ROLLBACK_FAILED. Before the sweep, targets were only ever upserted and there was nothing to restore. Snapshot the rule's targets before the first target call of an update and put them back on failure, following PipesCfnProvisioner: the snapshot is spent by whichever end the update reaches, restoring inside provision when this rule's own reconciliation failed and through rollbackUpdate when a later resource did. The restore is exact rather than additive, so a target the failed update added does not survive it. A restore that fails itself is recorded on the resource instead of thrown, so the stack reports the original failure. The snapshot carries the rule name, its bus and the region because the rollback hook is handed the stack resource alone, and a rule on a custom bus is keyed by that bus. This restores targets, not the rule's own properties, which putRule overwrites on the same path. That gap predates this branch. * refactor(cloudformation): hold the Events provisioner to a single injected service AGENTS.md requires a CloudFormation provisioner to inject only the service it wraps. This one also took an ObjectMapper, carried over from PipesCfnProvisioner when its rollback snapshot was modelled on that class. The package already has a second convention for exactly this job, and it is the one that satisfies the rule: LambdaEventInvokeConfigCfnProvisioner, the other snapshot-based rollback provisioner, holds a private static mapper and injects only its service, as do LambdaEventSourceMappingCfnProvisioner, Ec2NetworkCfnProvisioner and ReplacementCleanup. The configured mapper adds a 100 MB string limit and lenient empty-bean serialization. Neither reaches this code: EventBridge caps a bus policy near 10 KB and a target's Input at 8192 characters, both far under Jackson's default, and every type serialized here has real properties. No behaviour changes, so the existing tests are what prove the swap is inert.
This commit is contained in:
1 parent
ca435aeb50
commit
3218d2404e
6 files changed
+1138
-507
No files matched your search
-503
@@ -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<String> 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<Target> 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 <em>name</em>
|
||||
* (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<String, String> 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<String> 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<String, String> 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<String, String> 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<String, String> 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<String, String> 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<String> 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<String> 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<String> 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<String> 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 ────────────────────────────────────────────────────────────────
|
||||
|
||||
|
||||
+9
@@ -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
|
||||
|
||||
+766
@@ -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}.
|
||||
*
|
||||
* <p>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<String> 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<String> 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<Target> 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.
|
||||
*
|
||||
* <p>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.
|
||||
*
|
||||
* <p>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.
|
||||
*
|
||||
* <p>This is the hook for an update a <em>later</em> 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<Target> restored = MAPPER.convertValue(
|
||||
snapshot.path("targets"), new TypeReference<List<Target>>() { });
|
||||
Set<String> restoredIds = restored.stream().map(Target::getId).collect(Collectors.toSet());
|
||||
List<String> 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<Target> desired, String region) {
|
||||
Set<String> desiredIds = desired.stream().map(Target::getId).collect(Collectors.toSet());
|
||||
List<String> 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 <em>name</em>
|
||||
* (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<String, String> 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<String> 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<String, String> 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<String, String> 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<String, String> 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<String, String> 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<String> 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<String> 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<String> 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<String> 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 <bus name>|<statement id>}, 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<String, Object> jsonObjectToMap(JsonNode node) {
|
||||
Map<String, Object> 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<Object> 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();
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user