feat(cloudformation): provision AWS::Events::EventBus as a real custom bus (#1807)

* feat(cloudformation): provision EventBridge event buses

* fix(cloudformation): restore main's provisioner changes lost in the EventBus merge

The previous conflict resolution took this branch's whole
CloudFormationResourceProvisioner, which silently reverted five commits main had
landed on that file since the merge base — including the DynamoDB/Lambda delete
idempotency from #1803 and AWS::EC2::LaunchTemplate from #1973.

Re-resolve from main's file and apply only this branch's EventBus additions on
top: the ownership-tracking provisioner, its validation helpers, and the typed
rethrow in deleteEventBridgeRuleSafe. main's provisionEventBusPolicy and inline
Policy support are kept, with Policy added to EVENT_BUS_SUPPORTED_PROPERTIES so
the inline form is no longer rejected.

* fix(cloudformation): delete EventBus resources created before ownership tracking

deleteEventBusSafe(StackResource) refused to delete whenever the
FlociEventBusCreatedTime attribute was absent, treating "ownership not tracked"
the same as "ownership changed". Stacks provisioned by an earlier Floci build are
restored from cloudformation-stacks.json without that attribute, so the first
DeleteStack after upgrading left them permanently in DELETE_FAILED.

Only refuse when a recorded created-time actually disagrees with the live bus.
A missing attribute falls back to the pre-tracking behaviour of deleting what the
stack recorded it created.

* fix(cloudformation): adopt untracked EventBus on update and record identity before the policy call

Two provision-side defects, both surfaced in review:

UpdateStack broke for stacks provisioned before FlociEventBusCreatedTime existed.
Those resources are restored without the attribute, so the adoption guard's
'existingCreatedTime == null' arm re-threw ResourceAlreadyExists on every update,
including no-ops. Same inverted guard the delete path already uses: only a recorded
time that actually disagrees means the bus was recreated out of band.

The bus also leaked when Policy application failed. r.setPhysicalId ran after
putPermission, and rollbackCreatedResources skips resources whose physicalId is
null, so a malformed policy left a live bus rollback could not find. Identity and
ROLLBACK_OWNED_ATTR are now recorded before the policy call, matching how
provisionIamRole marks a freshly created role. The attribute is cleared on the
adoption path so rollback never deletes a bus this stack did not create.

* chore: re-run CI

Build and Test failed on RuntimeApiServerTest's extension/stop race, a pre-existing
flake unrelated to this change (no CloudFormation test failed). Root-caused separately:
test-timing half in #2141, server-side shutdown-ordering half filed as an issue.

* fix(cloudformation): adopt tagged pre-tracking event buses

* test(dynamodb): retain Quarkus port for cleanup

* chore: rerun CI after download outage

* fix(cloudformation): reject unsafe EventBus policy updates

---------

Co-authored-by: Alexander Banna <abanna@users.noreply.github.com>
This commit is contained in:
Alex BannaandAlexander Banna authored and GitHub committed 2026-08-12 16:38:17 -04:00
1 parent 33ba5ac59c
commit bc21367cc4
10 files changed
+1824 -69

No files matched your search

@@ -102,6 +102,7 @@ import java.nio.charset.StandardCharsets;
import java.time.Duration;
import java.util.*;
import java.util.concurrent.TimeoutException;
import java.util.regex.Pattern;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
@@ -120,6 +121,13 @@ public class CloudFormationResourceProvisioner {
private static final String INLINE_CLEANUP_ROLE_TARGETS_ATTR = "__FlociInlineCleanupRoleTargets";
private static final String INLINE_CLEANUP_USER_TARGETS_ATTR = "__FlociInlineCleanupUserTargets";
private static final String INLINE_CLEANUP_GROUP_TARGETS_ATTR = "__FlociInlineCleanupGroupTargets";
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 String LOG_GROUP_NAME_MODE_ATTR = "FlociLogGroupNameMode";
@@ -306,7 +314,7 @@ public class CloudFormationResourceProvisioner {
case "AWS::Route53::HostedZone" -> provisionRoute53HostedZone(resource, properties, engine);
case "AWS::Route53::RecordSet" -> provisionRoute53RecordSet(resource, properties, engine);
case "AWS::Events::Rule" -> provisionEventBridgeRule(resource, properties, engine, region, stackName);
case "AWS::Events::EventBus" -> provisionEventBus(resource, properties, engine, region, stackName);
case "AWS::Events::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);
@@ -465,6 +473,18 @@ public class CloudFormationResourceProvisioner {
deleteManagedPolicy(resource);
return;
}
// A Rule on a custom bus is keyed by that bus; the physical id is only the rule name, so the
// type/physicalId path resolves to the "default" bus and never finds it — leaving the rule (and
// then its bus) undeletable. Pass the bus name captured at provision time.
if ("AWS::Events::Rule".equals(resourceType)) {
deleteEventBridgeRuleSafe(resource.getPhysicalId(),
resource.getAttributes().get("EventBusName"), region);
return;
}
if ("AWS::Events::EventBus".equals(resourceType)) {
deleteEventBusSafe(resource, region);
return;
}
delete(resourceType, resource.getPhysicalId(), region);
}
@@ -503,6 +523,7 @@ public class CloudFormationResourceProvisioner {
"ValidationError",
"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);
@@ -2810,6 +2831,8 @@ public class CloudFormationResourceProvisioner {
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);
}
@@ -2857,71 +2880,322 @@ public class CloudFormationResourceProvisioner {
}
}
/**
* 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
// 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 (Exception e) {
LOG.debugv("Could not delete EventBridge rule {0}: {1}", ruleName, e.getMessage());
}
}
private void provisionEventBus(StackResource r, JsonNode props, CloudFormationTemplateEngine engine,
String region, String stackName) {
String name = resolveOptional(props, "Name", engine);
if (name == null || name.isBlank()) {
name = generatePhysicalName(stackName, r.getLogicalId(), 256, false);
}
String description = resolveOptional(props, "Description", engine);
Map<String, String> tags = new HashMap<>();
if (props != null && props.has("Tags") && props.get("Tags").isArray()) {
for (JsonNode tag : props.get("Tags")) {
String key = engine.resolve(tag.path("Key"));
if (!key.isEmpty()) {
tags.put(key, engine.resolve(tag.path("Value")));
}
}
}
EventBus bus;
try {
bus = eventBridgeService.createEventBus(name, description, tags, region);
} catch (AwsException e) {
if ("ResourceAlreadyExistsException".equals(e.getErrorCode())) {
bus = eventBridgeService.describeEventBus(name, region);
} else {
// 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;
}
}
// Optional inline resource policy (rare for CDK EventBus constructs).
if (props != null && props.has("Policy") && !props.get("Policy").isNull()) {
String policyJson = engine.resolveNode(props.get("Policy")).toString();
eventBridgeService.putPermission(name, null, null, null, null, policyJson, region);
}
r.setPhysicalId(name);
r.getAttributes().put("Arn", bus.getArn());
r.getAttributes().put("Name", name);
}
private void deleteEventBusSafe(String name, String region) {
try {
eventBridgeService.deleteEventBus(name, region);
LOG.debugv("EventBridge rule already gone, treating as deleted: {0}", ruleName);
} catch (Exception e) {
// Warn (not debug): the stack still records the resource as DELETE_COMPLETE, so a bus
// left alive here (e.g. rules deleted out of dependency order) is a silent divergence
// that must stay diagnosable.
LOG.warnv("Could not delete event bus {0}: {1}", name, e.getMessage());
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");
@@ -407,6 +407,7 @@ public class CloudFormationService {
private void executeTemplate(Stack stack, String templateBody, Map<String, String> params,
boolean isCreate, String region, String accountId) {
String previousTemplateBody = stack.getTemplateBody();
try {
JsonNode template = parseTemplate(templateBody);
@@ -459,6 +460,7 @@ public class CloudFormationService {
name -> exports.get(exportKey(region, name)));
StackResource resource = stack.getResources().get(logicalId);
StackResource previousResource = resource;
if (resource == null) {
resource = new StackResource();
resource.setLogicalId(logicalId);
@@ -490,6 +492,12 @@ public class CloudFormationService {
if ("CREATE_FAILED".equals(resource.getStatus())
|| "UPDATE_FAILED".equals(resource.getStatus())) {
failedResource = resource;
if (!isCreate && previousResource != null) {
// Provisioners work on a copy of the stored resource metadata. Keep the
// last known-good identity and status when an update attempt fails so a
// later retry or stack deletion still manages the original resource.
stack.getResources().put(logicalId, previousResource);
}
break;
}
}
@@ -498,6 +506,9 @@ public class CloudFormationService {
// A resource failed to provision: stop, and (on create) roll back what we built so a
// corrected re-deploy starts from a clean slate (acceptance criterion #9).
if (failedResource != null) {
if (!isCreate) {
stack.setTemplateBody(previousTemplateBody);
}
rollbackFailedExecution(stack, region, isCreate, failedResource);
return;
}
@@ -556,6 +567,9 @@ public class CloudFormationService {
} catch (Exception e) {
LOG.errorv("Stack {0} execution failed: {1}", stack.getStackName(), e.getMessage());
if (!isCreate) {
stack.setTemplateBody(previousTemplateBody);
}
String failStatus = isCreate ? "CREATE_FAILED" : "UPDATE_FAILED";
stack.setStatus(failStatus);
stack.setStatusReason(e.getMessage());
@@ -570,9 +584,10 @@ public class CloudFormationService {
*
* <p>On a <b>create</b>, rolls back by deleting the resources that were successfully created in
* this execution, leaving a clean slate ({@code ROLLBACK_COMPLETE}) so a corrected re-deploy can
* start from scratch. On an <b>update</b>, marks {@code UPDATE_ROLLBACK_COMPLETE} and keeps the
* prior physical IDs so a corrected re-deploy proceeds (full prior-template restoration is out
* of scope — see plan Part 7).
* start from scratch. On an <b>update</b>, marks {@code UPDATE_ROLLBACK_COMPLETE}; the caller
* restores the prior template and failed-resource metadata so retries and deletion continue to
* manage the last known-good physical resource. Rolling back side effects from resources that
* completed earlier in the failed update remains out of scope.
*/
private void rollbackFailedExecution(Stack stack, String region, boolean isCreate,
StackResource failedResource) {
@@ -137,9 +137,8 @@ public class EventBridgeService {
public EventBus createEventBus(String name, String description,
Map<String, String> tags, String region) {
if (name == null || name.isBlank()) {
throw new AwsException("ValidationException", "EventBus name is required.", 400);
}
validateCustomEventBusName(name);
validateEventBusDescription(description);
String key = busKey(region, name);
if (busStore.get(key).isPresent()) {
throw new AwsException("ResourceAlreadyExistsException",
@@ -166,13 +165,15 @@ public class EventBridgeService {
throw new AwsException("ValidationException", "EventBus name is required.", 400);
}
String effectiveName = resolvedBusName(name);
validateEventBusNameForMutation(effectiveName);
if ("default".equals(effectiveName)) {
throw new AwsException("ValidationException", "Cannot delete the default event bus.", 400);
}
String key = busKey(region, effectiveName);
EventBus bus = busStore.get(key)
.orElseThrow(() -> new AwsException("ResourceNotFoundException",
"EventBus not found: " + effectiveName, 404));
EventBus bus = busStore.get(key).orElse(null);
if (bus == null) {
return;
}
String rulePrefix = ruleKeyPrefix(region, effectiveName);
boolean hasRules = ruleStore.keys().stream().anyMatch(k -> k.startsWith(rulePrefix));
if (hasRules) {
@@ -192,7 +193,7 @@ public class EventBridgeService {
}
return busStore.get(busKey(region, effectiveName))
.orElseThrow(() -> new AwsException("ResourceNotFoundException",
"EventBus not found: " + name, 404));
"EventBus not found: " + name, 400));
}
public EventBus updateEventBus(String name,
@@ -201,19 +202,22 @@ public class EventBridgeService {
String deadLetterConfig,
String logConfig,
String region) {
validateEventBusDescription(description);
if (name != null) {
validateEventBusNameForMutation(name);
}
// Name identifies the bus; never mutated (AWS does not support rename).
String effectiveName = name == null || name.isBlank() ? "default" : name;
String effectiveName = name == null ? "default" : name;
EventBus bus = "default".equals(effectiveName)
? getOrCreateDefaultBus(region)
: busStore.get(busKey(region, effectiveName))
.orElseThrow(() -> new AwsException("ResourceNotFoundException",
"EventBus not found: " + effectiveName, 404));
"EventBus not found: " + effectiveName, 400));
// Only mark dirty when a field is both non-blank AND different from
// the value currently on the bus — re-sending the same value is a no-op.
// Description accepts an explicit empty string so callers can clear it. A null value means
// the field was omitted and must remain unchanged.
boolean dirty = false;
if (description != null && !description.isBlank()
&& !description.equals(bus.getDescription())) {
if (description != null && !description.equals(bus.getDescription())) {
bus.setDescription(description);
dirty = true;
}
@@ -241,6 +245,34 @@ public class EventBridgeService {
return bus;
}
private void validateCustomEventBusName(String name) {
if (name == null || name.isBlank()) {
throw new AwsException("ValidationException", "EventBus name is required.", 400);
}
if (name.length() > 256
|| !name.matches("[.\\-_A-Za-z0-9]+")
|| "default".equals(name)) {
throw new AwsException("ValidationException",
"Invalid custom event bus name: " + name, 400);
}
}
private void validateEventBusDescription(String description) {
if (description != null && description.length() > 512) {
throw new AwsException("ValidationException",
"EventBus description must not exceed 512 characters.", 400);
}
}
private void validateEventBusNameForMutation(String name) {
if (name.isEmpty()
|| name.length() > 256
|| !name.matches("[/\\.\\-_A-Za-z0-9]+")) {
throw new AwsException("ValidationException",
"Invalid event bus name: " + name, 400);
}
}
public List<EventBus> listEventBuses(String namePrefix, String region) {
getOrCreateDefaultBus(region);
String storagePrefix = "bus:" + region + ":";