From c6361cab91c92eab039e4836d7febfa59f7efacd Mon Sep 17 00:00:00 2001 From: Tyler Webb <85189637+T-Webb1@users.noreply.github.com> Date: Thu, 12 Nov 2026 15:03:15 -0800 Subject: [PATCH] feat(eventbridge): create partner event buses from EventSourceName (#7968) * feat(eventbridge): create partner event buses from EventSourceName CreateEventBus and AWS::Events::EventBus now accept EventSourceName. The bus takes the source's name, so Name must equal it and must match aws.partner//. Floci does not model partner event sources, so any well-formed source name is accepted without one being created or activated first. A partner bus name contains slashes, so rule lookups for a bus no longer match the rules of a bus nested under its name, and a rule ARN on a partner bus resolves its bus and rule name from the last slash. * test(eventbridge): cover partner event buses Covers creating a partner bus from its EventSourceName, a name that differs from the source or is not a partner name, rules, targets, tags and PutEvents on the bus by name and by ARN, nested partner buses keeping their rules apart, deletion, and the CloudFormation resource. * refactor(eventbridge): resolve rule ARNs from the first slash again ruleKey joins the bus and rule name with a slash, so splitting a rule ARN at the first or the last slash finds the same stored rule. The original split is kept, and the test that only exercised the changed split goes with it; tagging a rule on a custom bus by ARN stays covered by the existing tag tests. * fix(eventbridge): validate rule names in PutRule PutRule accepted any name, so a name holding a slash was stored under a key that ListRules, PutEvents and DeleteEventBus no longer treat as a rule of that bus, and could collide with a rule on a nested partner bus. Rule names now match [\.\-_A-Za-z0-9]+ and are at most 64 characters, as AWS models them, and a missing or out-of-pattern name fails with ValidationException. The CloudFormation AWS::Events::Rule resource creates its rule through the same PutRule path. * fix(cloudformation): reject a Policy or malformed source on a partner event bus An AWS::Events::EventBus with EventSourceName now checks the source name against aws.partner// in the provisioner, so a malformed one fails with ValidationError like the resource's other checks rather than with the service's ValidationException. A Policy given with EventSourceName is rejected with ValidationError before the bus is created, since Floci never applies a resource policy to a bus whose name holds a slash. * fix(eventbridge): answer partner and rule name violations in AWS's shape CreateEventBus with EventSourceName and PutRule now report a bad name the way AWS's validation layer does, through SmithyValidationErrors: "1 validation error detected: Value '...' at 'name' failed to satisfy constraint: ...", naming the length, pattern or missing member that failed. A partner bus with no Name now gets the required-member error rather than a name mismatch. The partner source pattern is one public constant on EventBridgeService, which the CloudFormation provisioner now uses too. * fix(eventbridge): refuse PutPermission and RemovePermission on a partner bus Both operations model the bus as NonPartnerEventBusName, so AWS refuses a partner bus there. Floci stored the policy, but never applied a resource policy to a bus whose name holds a slash, so the statement had no effect. They now fail with ValidationException in AWS's validation shape, and an AWS::Events::EventBusPolicy on a partner bus fails the stack the same way. * fix(cloudformation): let an update change a partner bus's EventSourceName Once a bus exists its Name is fixed, and a Name change is already refused as a replacement, so EventSourceName carries nothing more on an update. An UpdateStack that drops, adds or changes it while keeping Name used to be validated as if it were creating the bus and failed; it now updates the bus in place. Whether the bus is a partner bus is read from its name, so a Policy on one is still refused when the template stops naming its source. * test(eventbridge): cover nested-bus PutEvents, partner rule tags and CFN rules PutEvents on a partner bus does not fire the rules of a bus nested under its name, a rule on a partner bus is tagged and listed by its ARN, and an AWS::Events::Rule names a partner bus in EventBusName and goes with the stack. * docs(eventbridge): note partner bus permissions, PutEvents and the rule-name upgrade * fix(cloudformation): validate a supplied EventSourceName on an event bus update An update that keeps the bus's Name skipped EventSourceName entirely, so a malformed source, one that does not match Name, or one newly added to a custom bus was accepted. When the template supplies EventSourceName it is now checked the way creation checks it; leaving it out still updates the bus in place. * fix(eventbridge): let a legacy slash-named rule block DeleteEventBus DeleteEventBus only counted rules whose name held no slash, so a bus whose only rule was a legacy slash-named one could be deleted, orphaning the rule; a scheduled one kept firing after a restart. Every rule stored under the bus now blocks the delete, except the rules of an existing nested partner bus, which share the key prefix but belong to that bus. * fix(eventbridge): validate rule names in the rule and target operations Only PutRule checked the rule name, so DeleteRule, EnableRule, DisableRule, PutTargets, RemoveTargets and ListTargetsByRule took a name like a/b and looked it up by key, which on a partner bus could reach a rule of a nested bus. They now answer a ValidationException the way PutRule does. A legacy slash-named rule that is stored on the bus named in the request is still reachable by its exact name, so it can have its targets removed and be deleted. * refactor(eventbridge): split a rule ARN at its last slash A rule name holds no slash, so the bus is everything before the last one. Splitting at the first slash found the same stored rule, since the key joins bus and rule with a slash, but left RuleRef's bus and rule wrong for a rule on a partner bus such as rule/aws.partner/example.com/acct/r1. * docs(eventbridge): describe legacy slash-named rules and EventSourceName updates A legacy slash-named rule is hidden from ListRules and PutEvents but still reachable by its exact name and blocks DeleteEventBus, and the other rule operations now validate the name. On a CloudFormation update a supplied EventSourceName is validated as on creation. * fix(eventbridge): keep every persisted rule reachable by its exact name PutRule did not validate rule names before, so a stored rule can be longer than 64 characters or contain a space, colon or at sign. Skip name validation whenever a rule with that exact name is stored on the requested bus, not only for slashed names, so such a rule can still have its targets removed, be disabled and be deleted, and no longer blocks DeleteEventBus forever. * fix(eventbridge): name the rule member in target operation validation errors PutTargets, RemoveTargets and ListTargetsByRule take the rule name in their Rule member, so report a rejected name at 'rule' as AWS does instead of at 'name'. * fix(eventbridge): validate the rule name in DescribeRule DescribeRule now applies the same rule name check as the other rule operations, so a malformed name fails with ValidationException instead of ResourceNotFoundException, while a persisted rule stays describable by its exact name. * fix(eventbridge): resolve a legacy slashed rule ARN on a custom bus Splitting a rule ARN at its last slash finds rules on partner buses but misses a rule persisted with a slash in its name on a custom bus, such as rule/foo/team/r1. When no rule is stored for the last-slash split, fall back to the first-slash split if the rule stored there belongs to that bus, so TagResource, UntagResource and ListTagsForResource reach it again. * refactor(eventbridge): decide DeleteEventBus by each rule's own bus Count a stored rule against the bus being deleted when its eventBusName is that bus, rather than inferring ownership from whether a nested bus exists under the rule key's prefix. * docs(cloudformation): note that AWS replaces a bus whose EventSourceName is dropped * test(eventbridge): cover legacy slashed rules on a custom bus Exercise the rule and target operations on a slash-named rule persisted on a custom bus, and check that a slashed name stored for a different bus is still rejected by every rule and target operation. * refactor(eventbridge): split a rule ARN at its last slash only A rule's store key joins the bus and rule name with a slash, so splitting rule/foo/team/r1 at its first or last slash names the same stored rule. The first-slash fallback could never find a rule the last-slash lookup missed; drop it and resolve the ARN without a store lookup. * test(eventbridge): pin the error a removed legacy slashed rule returns Once the stored rule is gone, DescribeRule validates its slashed name again and fails with ValidationException. Assert that code, and that the rule left the store, instead of any AwsException. * fix(cloudformation): treat a gone legacy-named rule as deleted A stack created before rule names were validated can hold a rule whose name PutRule now rejects. Once that rule is gone, ListTargetsByRule validates the name and fails with ValidationException, so DeleteStack ended DELETE_FAILED. Check whether the rule is stored first, through a new EventBridgeService.ruleExists that skips name validation, and treat a missing rule as already deleted. * docs(eventbridge): spell out what a legacy slashed rule can still do A slashed rule on the default bus can't be tagged by ARN, since rule/team/rule-1 reads as rule rule-1 on bus team; it stays reachable by exact name for the rule and target operations only. A stack holding a legacy-named rule can still be deleted, but an UpdateStack touching it fails because PutRule rejects the name. * fix(eventbridge): report the length violation of a long partner bus name on permission calls Signed-off-by: Tyler Webb * test(cloudformation): drop the section divider above the partner bus provisioner tests Signed-off-by: Tyler Webb * docs(eventbridge): ground the partner bus permission rejection in the API model Signed-off-by: Tyler Webb * fix(eventbridge): keep a partner bus off a legacy rule that shares its key A rule key joins the bus and rule name with a slash, so a slash-named rule persisted by an earlier version on a custom bus named aws.partner (for example example.com/orders/r1) has the same key as rule r1 on partner bus aws.partner/example.com/orders. Rule lookups, ListRules and PutEvents now check the stored rule's bus, so the partner bus neither lists, fires nor manages that rule, and PutRule on the partner bus is rejected rather than taking over the legacy rule's tags and targets. Signed-off-by: Tyler Webb * test(eventbridge): keep Step Functions target rule names within the 64 character limit PutRule now rejects rule names longer than 64 characters, as AWS does. The Step Functions integration test built names from a 16 character prefix, the suffix and a UUID, so the missing-target rule name reached 67 characters and PutRule rejected it before the test ran. Use a shorter prefix. Signed-off-by: Tyler Webb * fix(eventbridge): check a permission call's bus name against the modeled 256 character limit PutPermission and RemovePermission type EventBusName as NonPartnerEventBusName, which the model bounds at 1 to 256 characters with pattern [\.\-_A-Za-z0-9]+. The partner bus check used the 64 character rule name limit, so a partner bus name of 65 to 256 characters drew a length violation AWS does not report. Signed-off-by: Tyler Webb --------- Signed-off-by: Tyler Webb --- docs/services/cloudformation.md | 15 +- docs/services/eventbridge.md | 37 ++ .../provisioners/EventsCfnProvisioner.java | 35 +- .../eventbridge/EventBridgeHandler.java | 3 +- .../eventbridge/EventBridgeService.java | 148 ++++++- ...CloudFormationEventBusIntegrationTest.java | 217 +++++++++- .../EventBusDeleteOwnershipTest.java | 18 + .../EventBusProvisionOwnershipTest.java | 16 +- .../EventsCfnProvisionerTest.java | 29 ++ ...tBridgePartnerEventBusIntegrationTest.java | 189 +++++++++ .../eventbridge/EventBridgeServiceTest.java | 384 +++++++++++++++++- ...entBridgeStepFunctionsIntegrationTest.java | 2 +- .../cloudformation/writable-property-gaps.tsv | 1 - 13 files changed, 1055 insertions(+), 39 deletions(-) create mode 100644 src/test/java/io/floci/aws/services/eventbridge/EventBridgePartnerEventBusIntegrationTest.java diff --git a/docs/services/cloudformation.md b/docs/services/cloudformation.md index 975655dd97..7f9c770470 100644 --- a/docs/services/cloudformation.md +++ b/docs/services/cloudformation.md @@ -310,9 +310,18 @@ address. Dropping exhausted debt prevents later retries, but does not establish the bus name, and `Fn::GetAtt` supports `Arn` and `Name`. `Description` and `Tags` are applied when the bus is created. Rules that reference the bus are removed before stack deletion. -The current implementation is limited to custom buses with the `Name`, `Description`, `Tags`, and -`Policy` properties. `EventSourceName`, `KmsKeyIdentifier`, `DeadLetterConfig`, and `LogConfig` are -rejected with `ValidationError` instead of being silently ignored. AWS models a `Name` change as +The current implementation supports the `Name`, `EventSourceName`, `Description`, `Tags`, and +`Policy` properties. With `EventSourceName` the resource creates a +[partner event bus](eventbridge.md#partner-event-buses), whose `Name` must equal it, as AWS +requires; a template with a different `Name` fails with `ValidationError`. A partner bus takes no +`Policy` and fails with `ValidationError` when one is given; an `AWS::Events::EventBusPolicy` +on a partner bus fails its stack. AWS treats `Name` and `EventSourceName` as replacement-only, so +dropping `EventSourceName` makes AWS attempt to replace the bus; on `UpdateStack` with the same +`Name`, Floci keeps the bus as it is instead. An `EventSourceName` the template gives is checked as +on creation, so a malformed source, one that differs from `Name`, or one added to a custom bus fails +the update. +`KmsKeyIdentifier`, `DeadLetterConfig`, and `LogConfig` are rejected with `ValidationError` +instead of being silently ignored. AWS models a `Name` change as resource replacement; Floci currently rejects that update until generic replacement handling is available. `Policy` is applied when the bus is created. On `UpdateStack` the template's `Tags` are applied to the same bus in place: a key the stack recorded setting and the new template drops is diff --git a/docs/services/eventbridge.md b/docs/services/eventbridge.md index 3812941c20..8d38b8d863 100644 --- a/docs/services/eventbridge.md +++ b/docs/services/eventbridge.md @@ -152,6 +152,43 @@ aws events put-events \ --endpoint-url $AWS_ENDPOINT_URL ``` +## Partner Event Buses + +`CreateEventBus` with `EventSourceName` creates a partner event bus. As in AWS, the bus takes the +source's name, so `Name` must equal `EventSourceName`, and the name must match +`aws.partner//`. Floci does not model partner event sources, so any well-formed +source name is accepted without one being created or activated first. Once created, the bus works +like a custom bus: rules, targets, tags and `PutEvents` address it by name or ARN. A rule name +can't contain a slash on any bus: `PutRule` rejects a name outside `[\.\-_A-Za-z0-9]+` or longer +than 64 characters with `ValidationException`, as AWS does. + +Two calls differ from a custom bus. `PutPermission` and `RemovePermission` reject a partner bus +with `ValidationException`, since the API types their `EventBusName` as a non-partner bus name. +`PutEvents` to a partner bus is accepted and fans out to its rules, where AWS reserves that bus for +the partner's own events; this lets a test publish an event a partner would send. + +When upgrading, a rule persisted by an earlier Floci version under a name `PutRule` now rejects, +such as one with a slash or a space or longer than 64 characters, is still reachable by its exact +name on its own bus, and it keeps `DeleteEventBus` from deleting that bus. One with a slash in its +name is also no longer listed by `ListRules` or matched by `PutEvents`. On a custom bus it can still +be tagged by its ARN, but on the default bus it cannot: an ARN such as `rule/team/rule-1` reads as +rule `rule-1` on bus `team`, so that rule is reachable by its exact name for the rule and target +operations only. On a custom bus named `aws.partner`, a rule such as `example.com/orders/r1` shares +its storage key and ARN with rule `r1` on partner bus `aws.partner/example.com/orders`. That partner +bus does not list, match or manage the legacy rule, and `PutRule` of `r1` on it fails with +`ValidationException` until the legacy rule is deleted. A CloudFormation stack holding any of these legacy rules can still be deleted, but +an `UpdateStack` that touches the rule fails, since `PutRule` rejects its name. Remove its targets, +delete it and recreate it under a valid name. `DescribeRule`, `DeleteRule`, `EnableRule`, +`DisableRule`, `PutTargets`, `RemoveTargets` and `ListTargetsByRule` otherwise reject an invalid +rule name as `PutRule` does. + +```bash +aws events create-event-bus \ + --name aws.partner/example.com/123/orders \ + --event-source-name aws.partner/example.com/123/orders \ + --endpoint-url $AWS_ENDPOINT_URL +``` + ## Event Bus Targets A rule can target another event bus by ARN: the event is republished there, and that bus's own rules evaluate it and fan out normally. `Source`, `DetailType`, `Resources` and the originating `account`/`region` carry over, and each hop gets a new event id. diff --git a/src/main/java/io/floci/aws/services/cloudformation/provisioners/EventsCfnProvisioner.java b/src/main/java/io/floci/aws/services/cloudformation/provisioners/EventsCfnProvisioner.java index dcd8dc3a5a..cd594143d1 100644 --- a/src/main/java/io/floci/aws/services/cloudformation/provisioners/EventsCfnProvisioner.java +++ b/src/main/java/io/floci/aws/services/cloudformation/provisioners/EventsCfnProvisioner.java @@ -60,7 +60,7 @@ public class EventsCfnProvisioner implements CfnResourceProvisioner { private static final String EVENT_BUS_MANAGED_TAG_KEYS_ATTR = "FlociEventBusManagedTagKeys"; private static final String EVENT_BUS_MANAGED_POLICY_ATTR = "FlociEventBusManagedPolicy"; private static final Set EVENT_BUS_SUPPORTED_PROPERTIES = - Set.of("Name", "Description", "Tags", "Policy"); + Set.of("Name", "EventSourceName", "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\\-_]+"); @@ -406,7 +406,14 @@ public class EventsCfnProvisioner implements CfnResourceProvisioner { validateEventBusProperties(props); String existingBusName = ctx.isUpdate() ? ctx.priorPhysicalId() : null; String busName = ctx.resolveOptional(props, "Name"); - validateEventBusName(busName); + String eventSourceName = ctx.resolveOptional(props, "EventSourceName"); + boolean sameBus = existingBusName != null && existingBusName.equals(busName); + if (eventSourceName != null || !sameBus) { + validateEventBusName(busName, eventSourceName); + } + if (sameBus) { + eventSourceName = busName.indexOf('/') >= 0 ? busName : null; + } if (existingBusName != null && !existingBusName.equals(busName)) { throw new AwsException("ValidationError", "Updating EventBus Name requires resource replacement, which is not supported.", 400); @@ -418,11 +425,15 @@ public class EventsCfnProvisioner implements CfnResourceProvisioner { } Map tags = parseEventBusTags(props != null ? props.get("Tags") : null, ctx); JsonNode policy = resolveEventBusPolicy(props, ctx); + if (eventSourceName != null && !policy.isNull()) { + throw new AwsException("ValidationError", + "AWS::Events::EventBus Policy is not supported on a partner event bus.", 400); + } EventBus bus; boolean createdBus = false; try { - bus = eventBridgeService.createEventBus(busName, description, tags, ctx.region()); + bus = eventBridgeService.createEventBus(busName, eventSourceName, description, tags, ctx.region()); createdBus = true; r.getAttributes().put(CfnRollback.ROLLBACK_OWNED_ATTR, "true"); } catch (AwsException e) { @@ -485,11 +496,23 @@ public class EventsCfnProvisioner implements CfnResourceProvisioner { } } - private void validateEventBusName(String busName) { + private void validateEventBusName(String busName, String eventSourceName) { if (busName == null || busName.isBlank()) { throw new AwsException("ValidationError", "Name is required for AWS::Events::EventBus.", 400); } + if (eventSourceName != null) { + if (eventSourceName.length() > 256 + || !EventBridgeService.PARTNER_EVENT_SOURCE_NAME.matcher(eventSourceName).matches()) { + throw new AwsException("ValidationError", + "Invalid AWS::Events::EventBus EventSourceName: " + eventSourceName, 400); + } + if (!eventSourceName.equals(busName)) { + throw new AwsException("ValidationError", + "AWS::Events::EventBus Name must match EventSourceName: " + eventSourceName, 400); + } + return; + } if (busName.length() > 256 || !busName.matches("[.\\-_A-Za-z0-9]+") || "default".equals(busName)) { @@ -694,6 +717,10 @@ public class EventsCfnProvisioner implements CfnResourceProvisioner { private void deleteEventBridgeRuleSafe(String ruleName, String busName, String region) { try { + if (!eventBridgeService.ruleExists(ruleName, busName, region)) { + LOG.debugv("EventBridge rule already gone, treating as deleted: {0}", ruleName); + return; + } // Remove all targets before deleting the rule (busName scopes the lookup to the rule's bus). List targets = eventBridgeService.listTargetsByRule(ruleName, busName, region); if (!targets.isEmpty()) { diff --git a/src/main/java/io/floci/aws/services/eventbridge/EventBridgeHandler.java b/src/main/java/io/floci/aws/services/eventbridge/EventBridgeHandler.java index 89fb9cd3af..7747bb4d98 100644 --- a/src/main/java/io/floci/aws/services/eventbridge/EventBridgeHandler.java +++ b/src/main/java/io/floci/aws/services/eventbridge/EventBridgeHandler.java @@ -118,10 +118,11 @@ public class EventBridgeHandler { private Response handleCreateEventBus(JsonNode request, String region) { String name = request.path("Name").asText(null); + String eventSourceName = request.path("EventSourceName").asText(null); String description = request.path("Description").asText(null); String kmsKey = request.path("KmsKeyIdentifier").asText(null); Map tags = parseTagsArray(request.path("Tags")); - EventBus bus = eventBridgeService.createEventBus(name, description, kmsKey, + EventBus bus = eventBridgeService.createEventBus(name, eventSourceName, description, kmsKey, configJson(request.path("DeadLetterConfig")), configJson(request.path("LogConfig")), tags, region); // CreateEventBus answers with the bus's ARN and the configuration it was given. ObjectNode configuration = buildBusNode(bus); diff --git a/src/main/java/io/floci/aws/services/eventbridge/EventBridgeService.java b/src/main/java/io/floci/aws/services/eventbridge/EventBridgeService.java index d6fc8393e1..73701bfe34 100644 --- a/src/main/java/io/floci/aws/services/eventbridge/EventBridgeService.java +++ b/src/main/java/io/floci/aws/services/eventbridge/EventBridgeService.java @@ -182,18 +182,28 @@ public class EventBridgeService implements ResourceProvider, StoredResourceArns public EventBus createEventBus(String name, String description, Map tags, String region) { - return createEventBus(name, description, null, null, null, tags, region); + return createEventBus(name, null, description, tags, region); + } + + public EventBus createEventBus(String name, String eventSourceName, String description, + Map tags, String region) { + return createEventBus(name, eventSourceName, description, null, null, null, tags, region); } /** * Creates a custom bus with the KMS key, dead-letter queue and log configuration the request * gives, as {@code CreateEventBus} takes them; a null member leaves the bus without it. The * dead-letter and log configurations are stored as their JSON, as {@link #updateEventBus} does. + * A non-null {@code eventSourceName} makes it a partner bus, which takes the source's name. */ - public EventBus createEventBus(String name, String description, String kmsKeyIdentifier, - String deadLetterConfig, String logConfig, + public EventBus createEventBus(String name, String eventSourceName, String description, + String kmsKeyIdentifier, String deadLetterConfig, String logConfig, Map tags, String region) { - validateCustomEventBusName(name); + if (eventSourceName == null) { + validateCustomEventBusName(name); + } else { + validatePartnerEventBusName(name, eventSourceName); + } validateEventBusDescription(description); String key = busKey(region, name); if (busStore.get(key).isPresent()) { @@ -240,7 +250,8 @@ public class EventBridgeService implements ResourceProvider, StoredResourceArns return; } String rulePrefix = ruleKeyPrefix(region, effectiveName); - boolean hasRules = ruleStore.keys().stream().anyMatch(k -> k.startsWith(rulePrefix)); + boolean hasRules = ruleStore.scan(k -> k.startsWith(rulePrefix)).stream() + .anyMatch(rule -> effectiveName.equals(rule.getEventBusName())); if (hasRules) { throw new AwsException("ValidationException", "Cannot delete event bus with existing rules: " + name, 400); @@ -322,6 +333,22 @@ public class EventBridgeService implements ResourceProvider, StoredResourceArns } } + public static final Pattern PARTNER_EVENT_SOURCE_NAME = + Pattern.compile("aws\\.partner(/[\\.\\-_A-Za-z0-9]+){2,}"); + private static final Pattern EVENT_BUS_NAME = Pattern.compile("[/\\.\\-_A-Za-z0-9]+"); + + private void validatePartnerEventBusName(String name, String eventSourceName) { + List violations = new ArrayList<>(nameViolations("name", name, 256, EVENT_BUS_NAME)); + violations.addAll(nameViolations("eventSourceName", eventSourceName, 256, PARTNER_EVENT_SOURCE_NAME)); + if (!violations.isEmpty()) { + throw SmithyValidationErrors.validationException(violations); + } + if (!eventSourceName.equals(name)) { + throw new AwsException("ValidationException", + "Partner event bus name must match its event source name: " + eventSourceName, 400); + } + } + private void validateEventBusDescription(String description) { if (description != null && description.length() > 512) { throw new AwsException("ValidationException", @@ -355,6 +382,7 @@ public class EventBridgeService implements ResourceProvider, StoredResourceArns public Rule putRule(String name, String busName, String eventPattern, String scheduleExpression, RuleState state, String description, String roleArn, Map tags, String region) { + validateRuleName("name", name); if ((eventPattern == null || eventPattern.isBlank()) && (scheduleExpression == null || scheduleExpression.isBlank())) { throw new AwsException("ValidationException", @@ -374,7 +402,14 @@ public class EventBridgeService implements ResourceProvider, StoredResourceArns ensureBusExists(effectiveBus, region); String key = ruleKey(region, effectiveBus, name); - Rule rule = ruleStore.get(key).orElse(new Rule()); + Optional stored = ruleStore.get(key); + if (stored.isPresent() && !effectiveBus.equals(stored.get().getEventBusName())) { + throw new AwsException("ValidationException", + "Rule " + name + " on event bus " + effectiveBus + " conflicts with rule " + + stored.get().getName() + " on event bus " + stored.get().getEventBusName() + + ". Delete that rule first.", 400); + } + Rule rule = stored.orElse(new Rule()); rule.setAccountId(regionResolver.getAccountId()); rule.setName(name); rule.setArn(buildRuleArn(region, effectiveBus, name)); @@ -405,11 +440,46 @@ public class EventBridgeService implements ResourceProvider, StoredResourceArns return rule; } + private static final Pattern NON_PARTNER_NAME = Pattern.compile("[\\.\\-_A-Za-z0-9]+"); + + private static void validateRuleName(String member, String name) { + List violations = nameViolations(member, name, 64, NON_PARTNER_NAME); + if (!violations.isEmpty()) { + throw SmithyValidationErrors.validationException(violations); + } + } + + private void validateRuleReference(String member, String name, String busName, String region) { + boolean legacyRuleOfBus = name != null + && ruleStore.get(ruleKey(region, busName, name)) + .map(rule -> busName.equals(rule.getEventBusName())) + .orElse(false); + if (!legacyRuleOfBus) { + validateRuleName(member, name); + } + } + + private static List nameViolations(String path, String value, int maxLength, Pattern pattern) { + if (value == null) { + return List.of(SmithyValidationErrors.notNull(path)); + } + List violations = new ArrayList<>(); + String length = SmithyValidationErrors.lengthOutOfRange(path, value, 1, maxLength); + if (length != null) { + violations.add(length); + } + if (!pattern.matcher(value).matches()) { + violations.add(SmithyValidationErrors.pattern(path, value, pattern.pattern())); + } + return violations; + } + public void deleteRule(String name, String busName, String region) { String effectiveBus = resolvedBusName(busName); + validateRuleReference("name", name, effectiveBus, region); ensureBusExists(effectiveBus, region); String key = ruleKey(region, effectiveBus, name); - Rule rule = ruleStore.get(key).orElse(null); + Rule rule = ruleOfBus(key, effectiveBus).orElse(null); if (rule == null) { return; } @@ -428,9 +498,19 @@ public class EventBridgeService implements ResourceProvider, StoredResourceArns LOG.infov("Deleted rule: {0}", name); } + /** + * Whether a rule is stored under this exact name on the bus, without validating the name, so a + * caller can tell a rule persisted before name validation from one that is already gone. + */ + public boolean ruleExists(String name, String busName, String region) { + String effectiveBus = resolvedBusName(busName); + return name != null && ruleOfBus(ruleKey(region, effectiveBus, name), effectiveBus).isPresent(); + } + public Rule describeRule(String name, String busName, String region) { String effectiveBus = resolvedBusName(busName); - return ruleStore.get(ruleKey(region, effectiveBus, name)) + validateRuleReference("name", name, effectiveBus, region); + return ruleOfBus(ruleKey(region, effectiveBus, name), effectiveBus) .orElseThrow(() -> new AwsException("ResourceNotFoundException", "Rule not found: " + name, 400)); } @@ -439,11 +519,11 @@ public class EventBridgeService implements ResourceProvider, StoredResourceArns String effectiveBus = resolvedBusName(busName); String prefix = ruleKeyPrefix(region, effectiveBus); return ruleStore.scan(k -> { - if (!k.startsWith(prefix)) return false; + if (!isRuleKeyOfBus(k, prefix)) return false; if (namePrefix == null || namePrefix.isBlank()) return true; String ruleName = k.substring(prefix.length()); return ruleName.startsWith(namePrefix); - }); + }).stream().filter(rule -> effectiveBus.equals(rule.getEventBusName())).toList(); } /** @@ -478,8 +558,9 @@ public class EventBridgeService implements ResourceProvider, StoredResourceArns public void enableRule(String name, String busName, String region) { String effectiveBus = resolvedBusName(busName); + validateRuleReference("name", name, effectiveBus, region); String key = ruleKey(region, effectiveBus, name); - Rule rule = ruleStore.get(key) + Rule rule = ruleOfBus(key, effectiveBus) .orElseThrow(() -> new AwsException("ResourceNotFoundException", "Rule not found: " + name, 400)); rule.setState(RuleState.ENABLED); @@ -489,8 +570,9 @@ public class EventBridgeService implements ResourceProvider, StoredResourceArns public void disableRule(String name, String busName, String region) { String effectiveBus = resolvedBusName(busName); + validateRuleReference("name", name, effectiveBus, region); String key = ruleKey(region, effectiveBus, name); - Rule rule = ruleStore.get(key) + Rule rule = ruleOfBus(key, effectiveBus) .orElseThrow(() -> new AwsException("ResourceNotFoundException", "Rule not found: " + name, 400)); rule.setState(RuleState.DISABLED); @@ -520,8 +602,9 @@ public class EventBridgeService implements ResourceProvider, StoredResourceArns private int upsertTargets(String ruleName, String busName, List newTargets, String region) { String effectiveBus = resolvedBusName(busName); + validateRuleReference("rule", ruleName, effectiveBus, region); String key = ruleKey(region, effectiveBus, ruleName); - Rule rule = ruleStore.get(key) + Rule rule = ruleOfBus(key, effectiveBus) .orElseThrow(() -> new AwsException("ResourceNotFoundException", "Rule not found: " + ruleName, 400)); List existing = new ArrayList<>(targetStore.get(key).orElse(new ArrayList<>())); @@ -630,7 +713,11 @@ public class EventBridgeService implements ResourceProvider, StoredResourceArns public RemoveTargetsResult removeTargets(String ruleName, String busName, List ids, String region) { String effectiveBus = resolvedBusName(busName); + validateRuleReference("rule", ruleName, effectiveBus, region); String key = ruleKey(region, effectiveBus, ruleName); + if (ruleStore.get(key).filter(rule -> !effectiveBus.equals(rule.getEventBusName())).isPresent()) { + return new RemoveTargetsResult(0, ids.size()); + } List existing = new ArrayList<>(targetStore.get(key).orElse(new ArrayList<>())); int removed = 0; for (String id : ids) { @@ -645,8 +732,9 @@ public class EventBridgeService implements ResourceProvider, StoredResourceArns public List listTargetsByRule(String ruleName, String busName, String region) { String effectiveBus = resolvedBusName(busName); + validateRuleReference("rule", ruleName, effectiveBus, region); String key = ruleKey(region, effectiveBus, ruleName); - ruleStore.get(key) + ruleOfBus(key, effectiveBus) .orElseThrow(() -> new AwsException("ResourceNotFoundException", "Rule not found: " + ruleName, 400)); return targetStore.get(key).orElse(List.of()); @@ -708,7 +796,7 @@ public class EventBridgeService implements ResourceProvider, StoredResourceArns private static RuleRef parseRuleResource(String resource) { String afterRule = resource.substring("rule/".length()); - int slashIdx = afterRule.indexOf('/'); + int slashIdx = afterRule.lastIndexOf('/'); if (slashIdx >= 0) { // Custom bus: rule/{busName}/{ruleName} return new RuleRef(afterRule.substring(0, slashIdx), afterRule.substring(slashIdx + 1)); @@ -799,7 +887,7 @@ public class EventBridgeService implements ResourceProvider, StoredResourceArns public void putPermission(String busName, String action, String principal, String statementId, String conditionJson, String policyJson, String region) { - String effectiveBus = resolvedBusName(busName); + String effectiveBus = resolvedNonPartnerBusName(busName); if ("default".equals(effectiveBus)) { getOrCreateDefaultBus(region); } @@ -882,7 +970,7 @@ public class EventBridgeService implements ResourceProvider, StoredResourceArns } public void removePermission(String busName, String statementId, boolean removeAll, String region) { - String effectiveBus = resolvedBusName(busName); + String effectiveBus = resolvedNonPartnerBusName(busName); if ("default".equals(effectiveBus)) { getOrCreateDefaultBus(region); } @@ -1078,10 +1166,10 @@ public class EventBridgeService implements ResourceProvider, StoredResourceArns String eventId = UUID.randomUUID().toString(); String rulePrefix = ruleKeyPrefix(region, effectiveBus); - List candidateRules = accountScan(ruleStore, accountId, k -> k.startsWith(rulePrefix)); + List candidateRules = accountScan(ruleStore, accountId, k -> isRuleKeyOfBus(k, rulePrefix)); for (Rule rule : candidateRules) { - if (rule.getState() != RuleState.ENABLED) { + if (!effectiveBus.equals(rule.getEventBusName()) || rule.getState() != RuleState.ENABLED) { continue; } // A rule without an event pattern is a schedule rule: it never matches put events. @@ -1560,6 +1648,20 @@ public class EventBridgeService implements ResourceProvider, StoredResourceArns .filter(policy -> !policy.isBlank()); } + /** + * The bus a permission call addresses. {@code PutPermission} and {@code RemovePermission} model + * the name as {@code NonPartnerEventBusName}, so a partner bus, whose name holds a slash, is + * refused there as AWS refuses it rather than given a policy nothing would enforce. + */ + private static String resolvedNonPartnerBusName(String busName) { + String effectiveBus = resolvedBusName(busName); + if (effectiveBus.indexOf('/') >= 0) { + throw SmithyValidationErrors.validationException( + nameViolations("eventBusName", busName, 256, NON_PARTNER_NAME)); + } + return effectiveBus; + } + private static String resolvedBusName(String busName) { if (busName == null || busName.isBlank()) { return "default"; @@ -1605,6 +1707,14 @@ public class EventBridgeService implements ResourceProvider, StoredResourceArns return "rule:" + region + ":" + busName + "/"; } + private Optional ruleOfBus(String key, String busName) { + return ruleStore.get(key).filter(rule -> busName.equals(rule.getEventBusName())); + } + + private static boolean isRuleKeyOfBus(String key, String rulePrefix) { + return key.startsWith(rulePrefix) && key.indexOf('/', rulePrefix.length()) < 0; + } + private static String ruleKey(String region, String busName, String ruleName) { return ruleKeyPrefix(region, busName) + ruleName; } diff --git a/src/test/java/io/floci/aws/services/cloudformation/CloudFormationEventBusIntegrationTest.java b/src/test/java/io/floci/aws/services/cloudformation/CloudFormationEventBusIntegrationTest.java index 37f0b71e23..c379a03406 100644 --- a/src/test/java/io/floci/aws/services/cloudformation/CloudFormationEventBusIntegrationTest.java +++ b/src/test/java/io/floci/aws/services/cloudformation/CloudFormationEventBusIntegrationTest.java @@ -548,11 +548,226 @@ class CloudFormationEventBusIntegrationTest { } } + @Test + void partnerEventBusIsProvisionedFromItsEventSourceName() { + String suffix = Long.toString(System.nanoTime(), 36); + String busName = "aws.partner/example.com/cfn-" + suffix; + String stackName = "eventbus-partner-" + suffix; + + createStack(stackName, partnerEventBusTemplate(busName, busName)); + assertStackStatus(stackName, "CREATE_COMPLETE"); + + JsonPath bus = callEventBridge("AWSEvents.DescribeEventBus", "{\"Name\":\"" + busName + "\"}", 200); + assertEquals(busName, bus.getString("Name")); + if (!bus.getString("Arn").endsWith(":event-bus/" + busName)) { + throw new AssertionError("unexpected partner bus ARN: " + bus.getString("Arn")); + } + + deleteStack(stackName); + CfnStackWaits.awaitStackDeleted(stackName); + callEventBridge("AWSEvents.DescribeEventBus", "{\"Name\":\"" + busName + "\"}", 400); + } + + @Test + void ruleOnAPartnerEventBusIsProvisionedAndRemovedWithTheStack() { + String suffix = Long.toString(System.nanoTime(), 36); + String busName = "aws.partner/example.com/cfn-rule-" + suffix; + String stackName = "eventbus-partner-rule-" + suffix; + String template = """ + { + "Resources": { + "Bus": { + "Type": "AWS::Events::EventBus", + "Properties": { "Name": "%1$s", "EventSourceName": "%1$s" } + }, + "Rule": { + "Type": "AWS::Events::Rule", + "DependsOn": "Bus", + "Properties": { + "Name": "partner-rule", + "EventBusName": "%1$s", + "EventPattern": { "source": ["example.com"] } + } + } + } + } + """.formatted(busName); + + createStack(stackName, template); + assertStackStatus(stackName, "CREATE_COMPLETE"); + JsonPath rule = callEventBridge("AWSEvents.DescribeRule", + "{\"Name\":\"partner-rule\",\"EventBusName\":\"" + busName + "\"}", 200); + assertEquals(busName, rule.getString("EventBusName")); + if (!rule.getString("Arn").endsWith(":rule/" + busName + "/partner-rule")) { + throw new AssertionError("unexpected partner rule ARN: " + rule.getString("Arn")); + } + + deleteStack(stackName); + CfnStackWaits.awaitStackDeleted(stackName); + callEventBridge("AWSEvents.DescribeEventBus", "{\"Name\":\"" + busName + "\"}", 400); + } + + @Test + void partnerEventBusUpdateValidatesASuppliedEventSourceName() { + String suffix = Long.toString(System.nanoTime(), 36); + String busName = "aws.partner/example.com/cfn-update-" + suffix; + String stackName = "eventbus-partner-update-" + suffix; + + createStack(stackName, partnerEventBusTemplate(busName, busName)); + assertStackStatus(stackName, "CREATE_COMPLETE"); + String busArn = callEventBridge("AWSEvents.DescribeEventBus", + "{\"Name\":\"" + busName + "\"}", 200).getString("Arn"); + + updateStack(stackName, """ + { + "Resources": { + "Bus": { + "Type": "AWS::Events::EventBus", + "Properties": { "Name": "%s" } + } + } + } + """.formatted(busName)); + assertStackStatus(stackName, "UPDATE_COMPLETE"); + + updateStack(stackName, partnerEventBusTemplate(busName, busName)); + assertStackStatus(stackName, "UPDATE_COMPLETE"); + + updateStack(stackName, partnerEventBusTemplate(busName, "aws.partner/example.com/other-" + suffix)); + assertStackStatus(stackName, "UPDATE_ROLLBACK_COMPLETE"); + String events = describeStackEvents(stackName); + if (!events.contains("Name must match EventSourceName")) { + throw new AssertionError("partner-name mismatch on update was not preserved: " + events); + } + + assertEquals(busArn, callEventBridge("AWSEvents.DescribeEventBus", + "{\"Name\":\"" + busName + "\"}", 200).getString("Arn")); + + deleteStack(stackName); + CfnStackWaits.awaitStackDeleted(stackName); + } + + @Test + void partnerEventBusNameMustMatchItsEventSourceName() { + String suffix = Long.toString(System.nanoTime(), 36); + String stackName = "eventbus-partner-mismatch-" + suffix; + + createStack(stackName, partnerEventBusTemplate("aws.partner/example.com/a-" + suffix, + "aws.partner/example.com/b-" + suffix)); + assertStackStatus(stackName, "ROLLBACK_COMPLETE"); + String events = describeStackEvents(stackName); + if (!events.contains("Name must match EventSourceName")) { + throw new AssertionError("partner-name mismatch was not preserved: " + events); + } + } + + @Test + void malformedPartnerEventSourceNameIsAValidationError() { + String suffix = Long.toString(System.nanoTime(), 36); + String stackName = "eventbus-partner-malformed-" + suffix; + String sourceName = "aws.partner/cfn-" + suffix; + + createStack(stackName, partnerEventBusTemplate(sourceName, sourceName)); + assertStackStatus(stackName, "ROLLBACK_COMPLETE"); + String events = describeStackEvents(stackName); + if (!events.contains("Invalid AWS::Events::EventBus EventSourceName")) { + throw new AssertionError("malformed partner source name was not preserved: " + events); + } + } + + @Test + void partnerEventBusRejectsAPolicy() { + String suffix = Long.toString(System.nanoTime(), 36); + String busName = "aws.partner/example.com/cfn-policy-" + suffix; + String stackName = "eventbus-partner-policy-" + suffix; + String template = """ + { + "Resources": { + "Bus": { + "Type": "AWS::Events::EventBus", + "Properties": { + "Name": "%1$s", + "EventSourceName": "%1$s", + "Policy": { + "Version": "2012-10-17", + "Statement": [{ + "Sid": "AllowAccount", + "Effect": "Allow", + "Principal": {"AWS": "arn:aws:iam::111122223333:root"}, + "Action": "events:PutEvents", + "Resource": "*" + }] + } + } + } + } + } + """.formatted(busName); + + createStack(stackName, template); + assertStackStatus(stackName, "ROLLBACK_COMPLETE"); + String events = describeStackEvents(stackName); + if (!events.contains("Policy is not supported on a partner event bus")) { + throw new AssertionError("partner bus policy rejection was not preserved: " + events); + } + callEventBridge("AWSEvents.DescribeEventBus", "{\"Name\":\"" + busName + "\"}", 400); + } + + @Test + void eventBusPolicyOnAPartnerEventBusFails() { + String suffix = Long.toString(System.nanoTime(), 36); + String busName = "aws.partner/example.com/cfn-bus-policy-" + suffix; + String stackName = "eventbus-partner-bus-policy-" + suffix; + String template = """ + { + "Resources": { + "Bus": { + "Type": "AWS::Events::EventBus", + "Properties": { "Name": "%1$s", "EventSourceName": "%1$s" } + }, + "BusPolicy": { + "Type": "AWS::Events::EventBusPolicy", + "Properties": { + "EventBusName": { "Ref": "Bus" }, + "StatementId": "AllowAccount", + "Action": "events:PutEvents", + "Principal": "111122223333" + } + } + } + } + """.formatted(busName); + + createStack(stackName, template); + assertStackStatus(stackName, "ROLLBACK_COMPLETE"); + String events = describeStackEvents(stackName); + if (!events.contains("at 'eventBusName'")) { + throw new AssertionError("partner bus policy statement was not refused: " + events); + } + callEventBridge("AWSEvents.DescribeEventBus", "{\"Name\":\"" + busName + "\"}", 400); + } + + private static String partnerEventBusTemplate(String busName, String eventSourceName) { + return """ + { + "Resources": { + "Bus": { + "Type": "AWS::Events::EventBus", + "Properties": { + "Name": "%s", + "EventSourceName": "%s" + } + } + } + } + """.formatted(busName, eventSourceName); + } + // "Policy" is deliberately absent: an inline resource policy is supported (see // provisionEventBridgeEventBus), so rejecting it would regress templates main supports today. @ParameterizedTest @ValueSource(strings = { - "EventSourceName", "KmsKeyIdentifier", "DeadLetterConfig", "LogConfig" + "KmsKeyIdentifier", "DeadLetterConfig", "LogConfig" }) void unsupportedEventBusPropertiesFailInsteadOfBeingIgnored(String propertyName) { String suffix = Long.toString(System.nanoTime(), 36); diff --git a/src/test/java/io/floci/aws/services/cloudformation/EventBusDeleteOwnershipTest.java b/src/test/java/io/floci/aws/services/cloudformation/EventBusDeleteOwnershipTest.java index 179ff704ab..c154e02d42 100644 --- a/src/test/java/io/floci/aws/services/cloudformation/EventBusDeleteOwnershipTest.java +++ b/src/test/java/io/floci/aws/services/cloudformation/EventBusDeleteOwnershipTest.java @@ -95,6 +95,7 @@ class EventBusDeleteOwnershipTest { rule.setResourceType("AWS::Events::Rule"); rule.setPhysicalId("orders-rule"); rule.getAttributes().put("EventBusName", BUS); + when(eventBridgeService.ruleExists("orders-rule", BUS, REGION)).thenReturn(true); when(eventBridgeService.listTargetsByRule("orders-rule", BUS, REGION)) .thenThrow(new IllegalStateException("storage unavailable")); @@ -106,6 +107,23 @@ class EventBusDeleteOwnershipTest { verify(eventBridgeService, never()).deleteRule("orders-rule", BUS, REGION); } + @Test + void aRuleNamedBeforeValidationThatIsAlreadyGoneIsTreatedAsDeleted() { + StackResource rule = new StackResource(); + rule.setLogicalId("OrdersRule"); + rule.setResourceType("AWS::Events::Rule"); + rule.setPhysicalId("team/orders-rule"); + rule.getAttributes().put("EventBusName", BUS); + when(eventBridgeService.ruleExists("team/orders-rule", BUS, REGION)).thenReturn(false); + when(eventBridgeService.listTargetsByRule("team/orders-rule", BUS, REGION)) + .thenThrow(new AwsException("ValidationException", "invalid rule name", 400)); + + assertDoesNotThrow(() -> provisioner.delete(rule, REGION)); + + verify(eventBridgeService, never()).listTargetsByRule("team/orders-rule", BUS, REGION); + verify(eventBridgeService, never()).deleteRule("team/orders-rule", BUS, REGION); + } + private StackResource resource(String createdTimeAttr) { StackResource r = new StackResource(); r.setLogicalId("OrdersBus"); diff --git a/src/test/java/io/floci/aws/services/cloudformation/EventBusProvisionOwnershipTest.java b/src/test/java/io/floci/aws/services/cloudformation/EventBusProvisionOwnershipTest.java index 469ca3ba3e..ef5586ae98 100644 --- a/src/test/java/io/floci/aws/services/cloudformation/EventBusProvisionOwnershipTest.java +++ b/src/test/java/io/floci/aws/services/cloudformation/EventBusProvisionOwnershipTest.java @@ -66,7 +66,7 @@ class EventBusProvisionOwnershipTest { */ @Test void updateOfBusProvisionedBeforeOwnershipTrackingAdoptsItInsteadOfFailing() { - when(eventBridgeService.createEventBus(eq(BUS), any(), any(), eq(REGION))) + when(eventBridgeService.createEventBus(eq(BUS), any(), any(), any(), eq(REGION))) .thenThrow(new AwsException("ResourceAlreadyExistsException", "exists", 400)); when(eventBridgeService.describeEventBus(BUS, REGION)) .thenReturn(bus(Instant.parse("2026-01-01T00:00:00Z"))); @@ -81,7 +81,7 @@ class EventBusProvisionOwnershipTest { @Test void updateOfTaggedBusProvisionedBeforeTagTrackingAdoptsItInsteadOfFailing() { - when(eventBridgeService.createEventBus(eq(BUS), any(), any(), eq(REGION))) + when(eventBridgeService.createEventBus(eq(BUS), any(), any(), any(), eq(REGION))) .thenThrow(new AwsException("ResourceAlreadyExistsException", "exists", 400)); EventBus existingBus = bus(Instant.parse("2026-01-01T00:00:00Z")); existingBus.setTags(Map.of("environment", "test")); @@ -101,7 +101,7 @@ class EventBusProvisionOwnershipTest { @Test void updateOfBusProvisionedBeforePolicyTrackingAdoptsUnchangedPolicyWithoutReapplyingIt() throws Exception { - when(eventBridgeService.createEventBus(eq(BUS), any(), any(), eq(REGION))) + when(eventBridgeService.createEventBus(eq(BUS), any(), any(), any(), eq(REGION))) .thenThrow(new AwsException("ResourceAlreadyExistsException", "exists", 400)); EventBus existingBus = bus(Instant.parse("2026-01-01T00:00:00Z")); existingBus.setPolicy("{\"Version\":\"2012-10-17\"}"); @@ -119,7 +119,7 @@ class EventBusProvisionOwnershipTest { @Test void changedTrackedPolicyFailsWithoutMutatingTheOwnedBus() { - when(eventBridgeService.createEventBus(eq(BUS), any(), any(), eq(REGION))) + when(eventBridgeService.createEventBus(eq(BUS), any(), any(), any(), eq(REGION))) .thenThrow(new AwsException("ResourceAlreadyExistsException", "exists", 400)); EventBus existingBus = bus(Instant.parse("2026-01-01T00:00:00Z")); existingBus.setPolicy("{\"Version\":\"2008-10-17\"}"); @@ -154,7 +154,7 @@ class EventBusProvisionOwnershipTest { */ @Test void failedTagUpdateKeepsItsSnapshotForTheRollbackWalker() { - when(eventBridgeService.createEventBus(eq(BUS), any(), any(), eq(REGION))) + when(eventBridgeService.createEventBus(eq(BUS), any(), any(), any(), eq(REGION))) .thenThrow(new AwsException("ResourceAlreadyExistsException", "exists", 400)); EventBus existingBus = bus(Instant.parse("2026-01-01T00:00:00Z")); existingBus.setTags(Map.of("version", "0.1.5")); @@ -211,7 +211,7 @@ class EventBusProvisionOwnershipTest { @Test void updateOfBusRecreatedOutOfBandStillFails() { - when(eventBridgeService.createEventBus(eq(BUS), any(), any(), eq(REGION))) + when(eventBridgeService.createEventBus(eq(BUS), any(), any(), any(), eq(REGION))) .thenThrow(new AwsException("ResourceAlreadyExistsException", "exists", 400)); when(eventBridgeService.describeEventBus(BUS, REGION)) .thenReturn(bus(Instant.parse("2026-02-02T00:00:00Z"))); @@ -230,7 +230,7 @@ class EventBusProvisionOwnershipTest { */ @Test void busIsRollbackDeletableWhenThePolicyCallFails() { - when(eventBridgeService.createEventBus(eq(BUS), any(), any(), eq(REGION))) + when(eventBridgeService.createEventBus(eq(BUS), any(), any(), any(), eq(REGION))) .thenReturn(bus(Instant.parse("2026-01-01T00:00:00Z"))); doThrow(new AwsException("MalformedPolicyDocumentException", "bad policy", 400)) .when(eventBridgeService) @@ -246,7 +246,7 @@ class EventBusProvisionOwnershipTest { @Test void adoptedBusIsNotMarkedRollbackOwned() { - when(eventBridgeService.createEventBus(eq(BUS), any(), any(), eq(REGION))) + when(eventBridgeService.createEventBus(eq(BUS), any(), any(), any(), eq(REGION))) .thenThrow(new AwsException("ResourceAlreadyExistsException", "exists", 400)); when(eventBridgeService.describeEventBus(BUS, REGION)) .thenReturn(bus(Instant.parse("2026-01-01T00:00:00Z"))); diff --git a/src/test/java/io/floci/aws/services/cloudformation/provisioners/EventsCfnProvisionerTest.java b/src/test/java/io/floci/aws/services/cloudformation/provisioners/EventsCfnProvisionerTest.java index 7991bcab4d..3962663f9c 100644 --- a/src/test/java/io/floci/aws/services/cloudformation/provisioners/EventsCfnProvisionerTest.java +++ b/src/test/java/io/floci/aws/services/cloudformation/provisioners/EventsCfnProvisionerTest.java @@ -17,6 +17,7 @@ import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.MethodSource; +import org.junit.jupiter.params.provider.ValueSource; import org.mockito.ArgumentCaptor; import org.mockito.ArgumentMatchers; import org.mockito.Mockito; @@ -495,6 +496,34 @@ class EventsCfnProvisionerTest { assertTrue(thrown.getMessage().contains("requires resource replacement")); } + @ParameterizedTest + @ValueSource(strings = {"aws.partner/example.com", "partner/example.com/orders", "aws.partner/example.com/x y"}) + void aMalformedEventSourceNameIsAValidationError(String eventSourceName) { + AwsException thrown = assertThrows(AwsException.class, () -> provisioner.provision( + resource("AWS::Events::EventBus", "Bus"), + mapper.createObjectNode().put("Name", eventSourceName).put("EventSourceName", eventSourceName), + ctx(null))); + + assertEquals("ValidationError", thrown.getErrorCode()); + assertTrue(thrown.getMessage().contains("Invalid AWS::Events::EventBus EventSourceName")); + verify(events, never()).createEventBus(any(), any(), any(), any(), any()); + } + + @Test + void aPolicyOnAPartnerEventBusIsAValidationError() { + String name = "aws.partner/example.com/orders"; + ObjectNode props = mapper.createObjectNode().put("Name", name).put("EventSourceName", name); + props.putObject("Policy").put("Version", "2012-10-17"); + + AwsException thrown = assertThrows(AwsException.class, () -> provisioner.provision( + resource("AWS::Events::EventBus", "Bus"), props, ctx(null))); + + assertEquals("ValidationError", thrown.getErrorCode()); + assertTrue(thrown.getMessage().contains("Policy is not supported on a partner event bus")); + verify(events, never()).createEventBus(any(), any(), any(), any(), any()); + verify(events, never()).putPermission(any(), any(), any(), any(), any(), any(), any()); + } + // ── the policy statement id is held to the modeled pattern ──────────────── @Test diff --git a/src/test/java/io/floci/aws/services/eventbridge/EventBridgePartnerEventBusIntegrationTest.java b/src/test/java/io/floci/aws/services/eventbridge/EventBridgePartnerEventBusIntegrationTest.java new file mode 100644 index 0000000000..0882200cee --- /dev/null +++ b/src/test/java/io/floci/aws/services/eventbridge/EventBridgePartnerEventBusIntegrationTest.java @@ -0,0 +1,189 @@ +package io.floci.aws.services.eventbridge; + +import io.floci.aws.testing.RestAssuredJsonUtils; +import io.quarkus.test.junit.QuarkusTest; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; + +import java.net.URI; + +import static io.restassured.RestAssured.given; +import static org.hamcrest.Matchers.containsString; +import static org.hamcrest.Matchers.endsWith; +import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.hasSize; +import static org.hamcrest.Matchers.nullValue; + +/** + * A partner event bus is created from its {@code EventSourceName}, takes that name, and then works + * like any custom bus: it is described and deleted by name or ARN, and a rule on it delivers the + * events put on it. + */ +@QuarkusTest +class EventBridgePartnerEventBusIntegrationTest { + + private static final String EB_CT = "application/x-amz-json-1.1"; + private static final String SQS_CT = "application/x-amz-json-1.0"; + + @BeforeAll + static void configure() { + RestAssuredJsonUtils.configureAwsContentTypes(); + } + + @Test + void aPartnerBusDeliversEventsPutOnItByArn() { + String suffix = Long.toString(System.nanoTime(), 36); + String bus = "aws.partner/example.com/" + suffix + "/orders"; + String queue = "partner-sink-" + suffix; + + String busArn = given().contentType(EB_CT).header("X-Amz-Target", "AWSEvents.CreateEventBus") + .body("{\"Name\":\"" + bus + "\",\"EventSourceName\":\"" + bus + "\"}") + .when().post("/") + .then().statusCode(200) + .body("EventBusArn", endsWith(":event-bus/" + bus)) + .extract().jsonPath().getString("EventBusArn"); + + given().contentType(EB_CT).header("X-Amz-Target", "AWSEvents.DescribeEventBus") + .body("{\"Name\":\"" + busArn + "\"}") + .when().post("/") + .then().statusCode(200) + .body("Name", equalTo(bus)) + .body("Arn", equalTo(busArn)); + + String queueUrl = given().contentType(SQS_CT).header("X-Amz-Target", "AmazonSQS.CreateQueue") + .body("{\"QueueName\":\"" + queue + "\"}") + .when().post("/").then().statusCode(200) + .extract().jsonPath().getString("QueueUrl"); + String queuePath = URI.create(queueUrl).getPath(); + String queueArn = given().contentType(SQS_CT).header("X-Amz-Target", "AmazonSQS.GetQueueAttributes") + .body("{\"QueueUrl\":\"" + queueUrl + "\",\"AttributeNames\":[\"All\"]}") + .when().post(queuePath).then().statusCode(200) + .extract().jsonPath().getString("Attributes.QueueArn"); + + given().contentType(EB_CT).header("X-Amz-Target", "AWSEvents.PutRule") + .body("{\"Name\":\"partner-rule\",\"EventBusName\":\"" + busArn + "\"," + + "\"EventPattern\":\"{\\\"source\\\":[\\\"example.com\\\"]}\"}") + .when().post("/") + .then().statusCode(200) + .body("RuleArn", endsWith(":rule/" + bus + "/partner-rule")); + + given().contentType(EB_CT).header("X-Amz-Target", "AWSEvents.PutTargets") + .body("{\"Rule\":\"partner-rule\",\"EventBusName\":\"" + bus + "\"," + + "\"Targets\":[{\"Id\":\"sink\",\"Arn\":\"" + queueArn + "\"}]}") + .when().post("/") + .then().statusCode(200) + .body("FailedEntryCount", equalTo(0)); + + given().contentType(EB_CT).header("X-Amz-Target", "AWSEvents.PutEvents") + .body(""" + {"Entries":[{"EventBusName":"%s","Source":"example.com", + "DetailType":"Order Created","Detail":"{\\"orderId\\":\\"o-1\\"}"}]} + """.formatted(busArn)) + .when().post("/") + .then().statusCode(200) + .body("FailedEntryCount", equalTo(0)); + + given().contentType(SQS_CT).header("X-Amz-Target", "AmazonSQS.ReceiveMessage") + .body("{\"QueueUrl\":\"" + queueUrl + "\",\"MaxNumberOfMessages\":1,\"WaitTimeSeconds\":2}") + .when().post(queuePath) + .then().statusCode(200) + .body("Messages", hasSize(1)) + .body("Messages[0].Body", containsString("\"event-bus-name\":\"" + bus + "\"")); + + given().contentType(EB_CT).header("X-Amz-Target", "AWSEvents.RemoveTargets") + .body("{\"Rule\":\"partner-rule\",\"EventBusName\":\"" + bus + "\",\"Ids\":[\"sink\"]}") + .when().post("/").then().statusCode(200); + given().contentType(EB_CT).header("X-Amz-Target", "AWSEvents.DeleteRule") + .body("{\"Name\":\"partner-rule\",\"EventBusName\":\"" + bus + "\"}") + .when().post("/").then().statusCode(200); + given().contentType(EB_CT).header("X-Amz-Target", "AWSEvents.DeleteEventBus") + .body("{\"Name\":\"" + busArn + "\"}") + .when().post("/").then().statusCode(200); + + given().contentType(EB_CT).header("X-Amz-Target", "AWSEvents.DescribeEventBus") + .body("{\"Name\":\"" + bus + "\"}") + .when().post("/") + .then().statusCode(400) + .body("__type", containsString("ResourceNotFoundException")); + } + + @Test + void aPartnerBusNameMustMatchItsEventSourceName() { + given().contentType(EB_CT).header("X-Amz-Target", "AWSEvents.CreateEventBus") + .body("{\"Name\":\"aws.partner/example.com/a\",\"EventSourceName\":\"aws.partner/example.com/b\"}") + .when().post("/") + .then().statusCode(400) + .body("__type", containsString("ValidationException")); + } + + @Test + void aRuleNameWithASlashIsRejected() { + String suffix = Long.toString(System.nanoTime(), 36); + String bus = "aws.partner/example.com/" + suffix; + given().contentType(EB_CT).header("X-Amz-Target", "AWSEvents.CreateEventBus") + .body("{\"Name\":\"" + bus + "\",\"EventSourceName\":\"" + bus + "\"}") + .when().post("/").then().statusCode(200); + + given().contentType(EB_CT).header("X-Amz-Target", "AWSEvents.PutRule") + .body("{\"Name\":\"eu/rule\",\"EventBusName\":\"" + bus + "\"," + + "\"EventPattern\":\"{\\\"source\\\":[\\\"example.com\\\"]}\"}") + .when().post("/") + .then().statusCode(400) + .body("__type", containsString("ValidationException")) + .body("message", containsString("Value 'eu/rule' at 'name' failed to satisfy constraint")); + + given().contentType(EB_CT).header("X-Amz-Target", "AWSEvents.ListRules") + .body("{\"EventBusName\":\"" + bus + "\"}") + .when().post("/") + .then().statusCode(200) + .body("Rules", hasSize(0)); + + given().contentType(EB_CT).header("X-Amz-Target", "AWSEvents.DeleteEventBus") + .body("{\"Name\":\"" + bus + "\"}") + .when().post("/").then().statusCode(200); + } + + @Test + void aPartnerBusTakesNoPermission() { + String suffix = Long.toString(System.nanoTime(), 36); + String bus = "aws.partner/example.com/" + suffix; + given().contentType(EB_CT).header("X-Amz-Target", "AWSEvents.CreateEventBus") + .body("{\"Name\":\"" + bus + "\",\"EventSourceName\":\"" + bus + "\"}") + .when().post("/").then().statusCode(200); + + given().contentType(EB_CT).header("X-Amz-Target", "AWSEvents.PutPermission") + .body("{\"EventBusName\":\"" + bus + "\",\"Action\":\"events:PutEvents\"," + + "\"Principal\":\"111122223333\",\"StatementId\":\"allow\"}") + .when().post("/") + .then().statusCode(400) + .body("__type", containsString("ValidationException")) + .body("message", equalTo("1 validation error detected: Value '" + bus + "' at 'eventBusName' " + + "failed to satisfy constraint: Member must satisfy regular expression pattern: " + + "[\\.\\-_A-Za-z0-9]+")); + + given().contentType(EB_CT).header("X-Amz-Target", "AWSEvents.RemovePermission") + .body("{\"EventBusName\":\"" + bus + "\",\"RemoveAllPermissions\":true}") + .when().post("/") + .then().statusCode(400) + .body("__type", containsString("ValidationException")); + + given().contentType(EB_CT).header("X-Amz-Target", "AWSEvents.DescribeEventBus") + .body("{\"Name\":\"" + bus + "\"}") + .when().post("/") + .then().statusCode(200) + .body("Policy", nullValue()); + + given().contentType(EB_CT).header("X-Amz-Target", "AWSEvents.DeleteEventBus") + .body("{\"Name\":\"" + bus + "\"}") + .when().post("/").then().statusCode(200); + } + + @Test + void aNameWithASlashButNoEventSourceNameIsStillRejected() { + given().contentType(EB_CT).header("X-Amz-Target", "AWSEvents.CreateEventBus") + .body("{\"Name\":\"aws.partner/example.com/no-source\"}") + .when().post("/") + .then().statusCode(400) + .body("__type", containsString("ValidationException")); + } +} diff --git a/src/test/java/io/floci/aws/services/eventbridge/EventBridgeServiceTest.java b/src/test/java/io/floci/aws/services/eventbridge/EventBridgeServiceTest.java index 43918c6732..6d9d79165a 100644 --- a/src/test/java/io/floci/aws/services/eventbridge/EventBridgeServiceTest.java +++ b/src/test/java/io/floci/aws/services/eventbridge/EventBridgeServiceTest.java @@ -22,6 +22,7 @@ import io.floci.aws.services.resourcegroupstagging.ResourceGroupsTaggingService; import io.floci.aws.testing.PartitionMatrix; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.function.Executable; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.CsvSource; @@ -55,17 +56,19 @@ class EventBridgeServiceTest { private EventBridgeService service; private TargetDispatcher dispatcherMock; + private StorageBackend ruleStore; private StorageBackend replayStore; private ReplayDispatcher replayDispatcherMock; @BeforeEach void setUp() { dispatcherMock = mock(TargetDispatcher.class); + ruleStore = new InMemoryStorage<>(); replayStore = new InMemoryStorage<>(); replayDispatcherMock = mock(ReplayDispatcher.class); service = new EventBridgeService( new InMemoryStorage<>(), - new InMemoryStorage<>(), + ruleStore, new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(), @@ -204,6 +207,140 @@ class EventBridgeServiceTest { service.createEventBus("valid-name", "d".repeat(513), null, REGION)); } + @Test + void createPartnerEventBusTakesItsEventSourceName() { + String name = "aws.partner/example.com/123/orders"; + EventBus bus = service.createEventBus(name, name, "Partner bus", null, REGION); + + assertEquals(name, bus.getName()); + assertTrue(bus.getArn().endsWith(":event-bus/" + name)); + assertEquals(bus.getArn(), service.describeEventBus(name, REGION).getArn()); + assertEquals(name, service.describeEventBus(bus.getArn(), REGION).getName()); + } + + @Test + void createPartnerEventBusRejectsANameOtherThanItsEventSourceName() { + AwsException error = assertThrows(AwsException.class, () -> + service.createEventBus("aws.partner/example.com/a", "aws.partner/example.com/b", + null, null, REGION)); + assertEquals("ValidationException", error.getErrorCode()); + assertEquals(400, error.getHttpStatus()); + } + + @ParameterizedTest + @ValueSource(strings = {"aws.partner/example.com", "partner/example.com/x", "aws.partner/example.com/x y"}) + void createPartnerEventBusRejectsAnInvalidEventSourceName(String name) { + AwsException error = assertThrows(AwsException.class, () -> + service.createEventBus(name, name, null, null, REGION)); + assertEquals("ValidationException", error.getErrorCode()); + assertTrue(error.getMessage().contains("Value '" + name + "' at 'eventSourceName' failed to " + + "satisfy constraint: Member must satisfy regular expression pattern: " + + "aws\\.partner(/[\\.\\-_A-Za-z0-9]+){2,}"), error.getMessage()); + } + + @Test + void createPartnerEventBusRequiresAName() { + AwsException error = assertThrows(AwsException.class, () -> + service.createEventBus(null, "aws.partner/example.com/orders", null, null, REGION)); + assertEquals("ValidationException", error.getErrorCode()); + assertEquals("1 validation error detected: Value null at 'name' failed to satisfy constraint: " + + "Member must not be null", error.getMessage()); + } + + @Test + void putPermissionOnALongPartnerBusNameReportsOnlyThePattern() { + String name = "aws.partner/example.com/" + "o".repeat(200); + service.createEventBus(name, name, null, null, REGION); + + AwsException error = assertThrows(AwsException.class, () -> + service.putPermission(name, "events:PutEvents", "111122223333", "allow", null, null, REGION)); + assertEquals("ValidationException", error.getErrorCode()); + assertEquals("1 validation error detected: Value '" + name + "' at 'eventBusName' failed to satisfy " + + "constraint: Member must satisfy regular expression pattern: [\\.\\-_A-Za-z0-9]+", + error.getMessage()); + } + + @Test + void putPermissionOnAPartnerBusNameBeyondTheModeledLengthReportsBothConstraints() { + String name = "aws.partner/example.com/" + "o".repeat(240); + + AwsException error = assertThrows(AwsException.class, () -> + service.putPermission(name, "events:PutEvents", "111122223333", "allow", null, null, REGION)); + assertEquals("ValidationException", error.getErrorCode()); + assertTrue(error.getMessage().startsWith("2 validation errors detected: "), error.getMessage()); + assertTrue(error.getMessage().contains("at 'eventBusName' failed to satisfy constraint: " + + "Member must have length less than or equal to 256"), error.getMessage()); + } + + @Test + void putEventsOnAPartnerBusByArnReachesTheRuleOnIt() { + String name = "aws.partner/example.com/123/orders"; + EventBus bus = service.createEventBus(name, name, null, null, REGION); + Rule rule = service.putRule("partner-rule", name, "{\"source\":[\"example.com\"]}", null, + RuleState.ENABLED, null, null, null, REGION); + Target target = new Target("t1", "arn:aws:sqs:us-east-1:000000000000:queue-1", null, null); + service.putTargets("partner-rule", bus.getArn(), List.of(target), REGION); + + service.putEvents(List.of(Map.of("EventBusName", bus.getArn(), "Source", "example.com", + "DetailType", "Order", "Detail", "{}")), REGION); + + assertTrue(rule.getArn().endsWith(":rule/" + name + "/partner-rule")); + verify(dispatcherMock).dispatch(eq(rule.getArn()), eq(target), anyString(), eq(REGION), any()); + } + + @Test + void nestedPartnerBusesKeepTheirRulesApart() { + String parent = "aws.partner/example.com/orders"; + String child = parent + "/eu"; + service.createEventBus(parent, parent, null, null, REGION); + service.createEventBus(child, child, null, null, REGION); + service.putRule("child-rule", child, "{\"source\":[\"example.com\"]}", null, + RuleState.ENABLED, null, null, null, REGION); + + assertTrue(service.listRules(parent, null, REGION).isEmpty()); + assertEquals(1, service.listRules(child, null, REGION).size()); + assertDoesNotThrow(() -> service.deleteEventBus(parent, REGION)); + } + + @Test + void putEventsOnAParentPartnerBusDoesNotFireTheNestedBusRules() { + String parent = "aws.partner/example.com/orders"; + String child = parent + "/eu"; + service.createEventBus(parent, parent, null, null, REGION); + service.createEventBus(child, child, null, null, REGION); + service.putRule("child-rule", child, "{\"source\":[\"example.com\"]}", null, + RuleState.ENABLED, null, null, null, REGION); + Target target = new Target("t1", "arn:aws:sqs:us-east-1:000000000000:queue-1", null, null); + service.putTargets("child-rule", child, List.of(target), REGION); + + service.putEvents(List.of(Map.of("EventBusName", parent, "Source", "example.com", + "DetailType", "Order", "Detail", "{}")), REGION); + + verify(dispatcherMock, never()).dispatch(anyString(), any(), anyString(), anyString(), any()); + } + + @Test + void ruleOnAPartnerBusIsTaggableByItsArn() { + String name = "aws.partner/example.com/123/orders"; + service.createEventBus(name, name, null, null, REGION); + Rule rule = service.putRule("partner-rule", name, "{\"source\":[\"example.com\"]}", null, + RuleState.ENABLED, null, null, null, REGION); + + service.tagResource(rule.getArn(), Map.of("team", "orders"), REGION); + + assertEquals(Map.of("team", "orders"), service.listTagsForResource(rule.getArn(), REGION)); + } + + @Test + void deletePartnerEventBusByArn() { + String name = "aws.partner/example.com/123/orders"; + EventBus bus = service.createEventBus(name, name, null, null, REGION); + + service.deleteEventBus(bus.getArn(), REGION); + + assertThrows(AwsException.class, () -> service.describeEventBus(name, REGION)); + } + @Test void updateEventBusRejectsLongDescription() { service.createEventBus("my-bus", null, null, REGION); @@ -277,6 +414,18 @@ class EventBridgeServiceTest { service.deleteEventBus("my-bus", REGION)); } + @Test + void deleteEventBusWithALegacySlashNamedRuleThrows() { + service.createEventBus("my-bus", null, null, REGION); + Rule legacy = new Rule(); + legacy.setName("team/rule-1"); + legacy.setEventBusName("my-bus"); + ruleStore.put("rule:" + REGION + ":my-bus/team/rule-1", legacy); + + assertThrows(AwsException.class, () -> + service.deleteEventBus("my-bus", REGION)); + } + @Test void listEventBuses() { service.createEventBus("bus-a", null, null, REGION); @@ -482,6 +631,239 @@ class EventBridgeServiceTest { assertTrue(service.listRules(null, null, REGION).isEmpty()); } + @ParameterizedTest + @ValueSource(strings = {"a/b", "rule name", "rule:1"}) + void putRuleRejectsANameOutsideThePattern(String name) { + AwsException error = assertThrows(AwsException.class, () -> + service.putRule(name, null, "{\"source\":[\"my.app\"]}", null, RuleState.ENABLED, + null, null, null, REGION)); + assertEquals("ValidationException", error.getErrorCode()); + assertEquals(400, error.getHttpStatus()); + assertEquals("1 validation error detected: Value '" + name + "' at 'name' failed to satisfy " + + "constraint: Member must satisfy regular expression pattern: [\\.\\-_A-Za-z0-9]+", + error.getMessage()); + assertTrue(service.listRules(null, null, REGION).isEmpty()); + } + + @Test + void putRuleRejectsANameLongerThan64Characters() { + AwsException error = assertThrows(AwsException.class, () -> + service.putRule("r".repeat(65), null, "{\"source\":[\"my.app\"]}", null, + RuleState.ENABLED, null, null, null, REGION)); + assertEquals("ValidationException", error.getErrorCode()); + assertTrue(error.getMessage().endsWith("Member must have length less than or equal to 64")); + assertDoesNotThrow(() -> service.putRule("r".repeat(64), null, "{\"source\":[\"my.app\"]}", + null, RuleState.ENABLED, null, null, null, REGION)); + } + + @Test + void putRuleRequiresAName() { + AwsException error = assertThrows(AwsException.class, () -> + service.putRule(null, null, "{\"source\":[\"my.app\"]}", null, RuleState.ENABLED, + null, null, null, REGION)); + assertEquals("ValidationException", error.getErrorCode()); + assertEquals("1 validation error detected: Value null at 'name' failed to satisfy constraint: " + + "Member must not be null", error.getMessage()); + } + + @Test + void aRuleNameCannotReachIntoANestedPartnerBus() { + String parent = "aws.partner/example.com/orders"; + service.createEventBus(parent, parent, null, null, REGION); + service.createEventBus(parent + "/eu", parent + "/eu", null, null, REGION); + + assertThrows(AwsException.class, () -> service.putRule("eu/child-rule", parent, + "{\"source\":[\"example.com\"]}", null, RuleState.ENABLED, null, null, null, REGION)); + assertTrue(service.listRules(parent + "/eu", null, REGION).isEmpty()); + } + + @Test + void ruleAndTargetOperationsRejectANameOutsideThePattern() { + Target target = new Target("t1", "arn:aws:sqs:us-east-1:000000000000:queue-1", null, null); + + assertRuleNameRejected(() -> service.deleteRule("a/b", null, REGION), "name"); + assertRuleNameRejected(() -> service.describeRule("a/b", null, REGION), "name"); + assertRuleNameRejected(() -> service.enableRule("a/b", null, REGION), "name"); + assertRuleNameRejected(() -> service.disableRule("a/b", null, REGION), "name"); + assertRuleNameRejected(() -> service.putTargets("a/b", null, List.of(target), REGION), "rule"); + assertRuleNameRejected(() -> service.removeTargets("a/b", null, List.of("t1"), REGION), "rule"); + assertRuleNameRejected(() -> service.listTargetsByRule("a/b", null, REGION), "rule"); + } + + private static void assertRuleNameRejected(Executable call) { + AwsException error = assertThrows(AwsException.class, call); + assertEquals("ValidationException", error.getErrorCode()); + assertEquals(400, error.getHttpStatus()); + } + + private static void assertRuleNameRejected(Executable call, String member) { + AwsException error = assertThrows(AwsException.class, call); + assertEquals("ValidationException", error.getErrorCode()); + assertEquals(400, error.getHttpStatus()); + assertEquals("1 validation error detected: Value 'a/b' at '" + member + "' failed to satisfy " + + "constraint: Member must satisfy regular expression pattern: [\\.\\-_A-Za-z0-9]+", + error.getMessage()); + } + + @Test + void aRuleOperationCannotReachIntoANestedPartnerBus() { + String parent = "aws.partner/example.com/orders"; + service.createEventBus(parent, parent, null, null, REGION); + service.createEventBus(parent + "/eu", parent + "/eu", null, null, REGION); + service.putRule("child-rule", parent + "/eu", "{\"source\":[\"example.com\"]}", null, + RuleState.ENABLED, null, null, null, REGION); + + assertRuleNameRejected(() -> service.deleteRule("eu/child-rule", parent, REGION)); + assertEquals(1, service.listRules(parent + "/eu", null, REGION).size()); + } + + @Test + void aLegacySlashNamedRuleStaysRemovableByItsExactName() { + Rule legacy = new Rule(); + legacy.setName("team/rule-1"); + legacy.setArn("arn:aws:events:us-east-1:000000000000:rule/team/rule-1"); + legacy.setEventBusName("default"); + legacy.setState(RuleState.ENABLED); + ruleStore.put("rule:" + REGION + ":default/team/rule-1", legacy); + + assertTrue(service.listTargetsByRule("team/rule-1", null, REGION).isEmpty()); + service.deleteRule("team/rule-1", null, REGION); + + assertTrue(ruleStore.get("rule:" + REGION + ":default/team/rule-1").isEmpty()); + AwsException error = assertThrows(AwsException.class, + () -> service.describeRule("team/rule-1", null, REGION)); + assertEquals("ValidationException", error.getErrorCode()); + } + + @ParameterizedTest + @MethodSource("legacyRuleNamesOutsideThePattern") + void aLegacyRuleNamedOutsideThePatternStaysManageableByItsExactName(String name) { + Rule legacy = new Rule(); + legacy.setName(name); + legacy.setArn("arn:aws:events:us-east-1:000000000000:rule/" + name); + legacy.setEventBusName("default"); + legacy.setState(RuleState.ENABLED); + ruleStore.put("rule:" + REGION + ":default/" + name, legacy); + Target target = new Target("t1", "arn:aws:sqs:us-east-1:000000000000:queue-1", null, null); + service.putTargets(name, null, List.of(target), REGION); + + assertEquals(1, service.listTargetsByRule(name, null, REGION).size()); + assertEquals(1, service.removeTargets(name, null, List.of("t1"), REGION).successfulCount()); + service.disableRule(name, null, REGION); + assertEquals(RuleState.DISABLED, ruleStore.get("rule:" + REGION + ":default/" + name).orElseThrow().getState()); + service.deleteRule(name, null, REGION); + + assertTrue(ruleStore.get("rule:" + REGION + ":default/" + name).isEmpty()); + } + + static Stream legacyRuleNamesOutsideThePattern() { + return Stream.of("r".repeat(65), "team rule"); + } + + @Test + void ruleExistsLooksUpAnInvalidNameWithoutRejectingIt() { + Rule legacy = new Rule(); + legacy.setName("team/rule-1"); + legacy.setEventBusName("default"); + legacy.setState(RuleState.ENABLED); + ruleStore.put("rule:" + REGION + ":default/team/rule-1", legacy); + + assertTrue(service.ruleExists("team/rule-1", null, REGION)); + assertFalse(service.ruleExists("team/rule-2", null, REGION)); + } + + @Test + void aLegacySlashNamedRuleOnACustomBusIsTaggableByItsArn() { + service.createEventBus("foo", null, null, REGION); + String arn = "arn:aws:events:us-east-1:000000000000:rule/foo/team/r1"; + Rule legacy = new Rule(); + legacy.setName("team/r1"); + legacy.setArn(arn); + legacy.setEventBusName("foo"); + legacy.setState(RuleState.ENABLED); + ruleStore.put("rule:" + REGION + ":foo/team/r1", legacy); + + service.tagResource(arn, Map.of("team", "orders", "env", "test"), REGION); + service.untagResource(arn, List.of("env"), REGION); + + assertEquals(Map.of("team", "orders"), service.listTagsForResource(arn, REGION)); + } + + @Test + void aLegacySlashNamedRuleOnACustomBusStaysManageableByItsExactName() { + service.createEventBus("foo", null, null, REGION); + Rule legacy = new Rule(); + legacy.setName("team/r1"); + legacy.setArn("arn:aws:events:us-east-1:000000000000:rule/foo/team/r1"); + legacy.setEventBusName("foo"); + legacy.setState(RuleState.ENABLED); + ruleStore.put("rule:" + REGION + ":foo/team/r1", legacy); + Target target = new Target("t1", "arn:aws:sqs:us-east-1:000000000000:queue-1", null, null); + + service.putTargets("team/r1", "foo", List.of(target), REGION); + assertEquals(1, service.listTargetsByRule("team/r1", "foo", REGION).size()); + service.disableRule("team/r1", "foo", REGION); + assertEquals(RuleState.DISABLED, service.describeRule("team/r1", "foo", REGION).getState()); + service.enableRule("team/r1", "foo", REGION); + assertEquals(1, service.removeTargets("team/r1", "foo", List.of("t1"), REGION).successfulCount()); + service.deleteRule("team/r1", "foo", REGION); + + assertTrue(ruleStore.get("rule:" + REGION + ":foo/team/r1").isEmpty()); + assertDoesNotThrow(() -> service.deleteEventBus("foo", REGION)); + } + + @Test + void aPartnerBusDoesNotTakeOverALegacyRuleStoredUnderTheSameKey() { + String partner = "aws.partner/example.com/orders"; + service.createEventBus("aws.partner", null, null, REGION); + Rule legacy = new Rule(); + legacy.setName("example.com/orders/r1"); + legacy.setArn("arn:aws:events:us-east-1:000000000000:rule/aws.partner/example.com/orders/r1"); + legacy.setEventBusName("aws.partner"); + legacy.setEventPattern("{\"source\":[\"example.com\"]}"); + legacy.setState(RuleState.ENABLED); + ruleStore.put("rule:" + REGION + ":" + partner + "/r1", legacy); + Target target = new Target("t1", "arn:aws:sqs:us-east-1:000000000000:queue-1", null, null); + service.putTargets("example.com/orders/r1", "aws.partner", List.of(target), REGION); + service.createEventBus(partner, partner, null, null, REGION); + + assertTrue(service.listRules(partner, null, REGION).isEmpty()); + assertEquals("ResourceNotFoundException", assertThrows(AwsException.class, + () -> service.describeRule("r1", partner, REGION)).getErrorCode()); + assertEquals(0, service.removeTargets("r1", partner, List.of("t1"), REGION).successfulCount()); + assertEquals("ValidationException", assertThrows(AwsException.class, + () -> service.putRule("r1", partner, "{\"source\":[\"example.com\"]}", null, + RuleState.ENABLED, null, null, null, REGION)).getErrorCode()); + service.putEvents(List.of(Map.of("EventBusName", partner, "Source", "example.com", + "DetailType", "Order", "Detail", "{}")), REGION); + + verify(dispatcherMock, never()).dispatch(anyString(), any(), anyString(), anyString(), any()); + assertEquals("aws.partner", service.describeRule("example.com/orders/r1", "aws.partner", REGION) + .getEventBusName()); + assertEquals(1, service.listTargetsByRule("example.com/orders/r1", "aws.partner", REGION).size()); + } + + @Test + void aSlashNamedRuleStoredForAnotherBusIsRejected() { + service.createEventBus("foo", null, null, REGION); + Rule nested = new Rule(); + nested.setName("b"); + nested.setArn("arn:aws:events:us-east-1:000000000000:rule/foo/a/b"); + nested.setEventBusName("foo/a"); + nested.setState(RuleState.ENABLED); + ruleStore.put("rule:" + REGION + ":foo/a/b", nested); + Target target = new Target("t1", "arn:aws:sqs:us-east-1:000000000000:queue-1", null, null); + + assertRuleNameRejected(() -> service.describeRule("a/b", "foo", REGION), "name"); + assertRuleNameRejected(() -> service.deleteRule("a/b", "foo", REGION), "name"); + assertRuleNameRejected(() -> service.enableRule("a/b", "foo", REGION), "name"); + assertRuleNameRejected(() -> service.disableRule("a/b", "foo", REGION), "name"); + assertRuleNameRejected(() -> service.putTargets("a/b", "foo", List.of(target), REGION), "rule"); + assertRuleNameRejected(() -> service.removeTargets("a/b", "foo", List.of("t1"), REGION), "rule"); + assertRuleNameRejected(() -> service.listTargetsByRule("a/b", "foo", REGION), "rule"); + assertTrue(ruleStore.get("rule:" + REGION + ":foo/a/b").isPresent()); + } + @Test void deleteRuleIsIdempotent() { service.putRule("my-rule", null, null, "rate(1 minute)", RuleState.ENABLED, diff --git a/src/test/java/io/floci/aws/services/eventbridge/EventBridgeStepFunctionsIntegrationTest.java b/src/test/java/io/floci/aws/services/eventbridge/EventBridgeStepFunctionsIntegrationTest.java index dfb175a829..d39a8cd4d1 100644 --- a/src/test/java/io/floci/aws/services/eventbridge/EventBridgeStepFunctionsIntegrationTest.java +++ b/src/test/java/io/floci/aws/services/eventbridge/EventBridgeStepFunctionsIntegrationTest.java @@ -138,7 +138,7 @@ class EventBridgeStepFunctionsIntegrationTest { } private String createRule(String suffix, String eventPattern) { - String name = "eventbridge-sfn-" + suffix + "-" + UUID.randomUUID(); + String name = "eb-sfn-" + suffix + "-" + UUID.randomUUID(); eventBridgeService.putRule( name, null, eventPattern, null, RuleState.ENABLED, null, null, null, SOURCE_REGION); ruleNames.add(name); diff --git a/src/test/resources/cloudformation/writable-property-gaps.tsv b/src/test/resources/cloudformation/writable-property-gaps.tsv index 6ac37979d0..b9e9ec92ac 100644 --- a/src/test/resources/cloudformation/writable-property-gaps.tsv +++ b/src/test/resources/cloudformation/writable-property-gaps.tsv @@ -353,7 +353,6 @@ AWS::ElasticLoadBalancingV2::TargetGroup TargetGroupAttributes accepted and igno AWS::ElasticLoadBalancingV2::TargetGroup Targets accepted and ignored AWS::Events::Archive KmsKeyIdentifier documented as ignored (docs/services/cloudformation.md, EventBridge) AWS::Events::EventBus DeadLetterConfig rejected with a ValidationError, not supported by Floci -AWS::Events::EventBus EventSourceName rejected with a ValidationError, not supported by Floci AWS::Events::EventBus KmsKeyIdentifier rejected with a ValidationError, not supported by Floci AWS::Events::EventBus LogConfig rejected with a ValidationError, not supported by Floci AWS::IAM::ManagedPolicy Description accepted and ignored