diff --git a/docs/services/eventbridge.md b/docs/services/eventbridge.md index e56d1704df..fc1bbcdd72 100644 --- a/docs/services/eventbridge.md +++ b/docs/services/eventbridge.md @@ -83,6 +83,14 @@ key, bus, account and ARN. Explicit account records take precedence. Persisted l remain discoverable even if they no longer pass creation-time validation. The lookup does not provide an atomic snapshot across concurrent rule and target updates. +## Managed rules + +A rule that another service manages, such as the rule of an EventBridge V2 AWS service event source, answers +`ManagedBy` in `DescribeRule` and `ListRules`. +`PutRule`, `PutTargets`, `EnableRule` and `DisableRule` on it fail with `ManagedRuleException`. +So do `TagResource` and `UntagResource`. `DeleteRule` and `RemoveTargets` fail with it unless the request sets +`Force` to `true`. A rule with targets still cannot be deleted. `ListTagsForResource` answers no tags. + ## Numeric event patterns `TestEventPattern` and `PutEvents` rule routing support `numeric` comparisons on diff --git a/docs/services/eventbridgev2.md b/docs/services/eventbridgev2.md index 2f98a27c2a..740fe8bf0c 100644 --- a/docs/services/eventbridgev2.md +++ b/docs/services/eventbridgev2.md @@ -102,7 +102,7 @@ not retained. `DescribeSubscriber` and `ListSubscribers` return `Revoked` once t ## Revoking a resource -`RevokeResource` takes the ARN of a webhook event source or of a subscriber and answers it back. A revoke cannot be +`RevokeResource` takes the ARN of an event source or of a subscriber and answers it back. A revoke cannot be undone. A second revoke answers `200` and changes nothing. - A revoked source answers `403` on its webhook URL for every POST that reaches authentication. Its secret stays @@ -118,12 +118,12 @@ undone. A second revoke answers `200` and changes nothing. `Description` reads `*** Not accessible: event bus deleted ***`. A new bus of the same name does not take it over. It can have a subscriber of the orphan's name, but a source name stays taken. - The ARN of a webhook source or subscriber that does not exist is answered `403` as access denied. A source ARN of - type `aws.service` or `aws.partner` is answered `404`. + type `aws.service` or `aws.partner` that does not exist is answered `404`. ## Webhook event sources -Floci serves event sources of the `WebhookEventsConfiguration` kind. A request with an -`AwsServiceEventsConfiguration` or `PartnerEventsConfiguration` is refused with `InvalidInputException`. +Floci serves event sources of the `WebhookEventsConfiguration` and `AwsServiceEventsConfiguration` kinds. This +section covers the webhook kind. A `PartnerEventsConfiguration` always fails, as described below. - A source is `ACTIVE` at once. Its ARN is `arn:aws:events:::event-sourcev2/webhook//`. @@ -191,6 +191,37 @@ A `400` also sends `Connection: close` and closes the connection. - The host of the request decides the source. The Region in the host is not checked. - Not emulated: `429` throttling and `LogConfiguration` delivery. +## AWS service event sources + +An `AwsServiceEventsConfiguration` source forwards the events of one AWS service, such as `aws.ssm`, to its bus. + +- A source is `ACTIVE` at once. Its ARN is + `arn:aws:events:::event-sourcev2/aws.service//`. It has no `EventSourceDetails`, and + `ListEventSources` answers `Type` `AWS_SERVICE_EVENTS`. +- `DescribeEventSource` returns `Configuration` as given. `Pattern` is the exact string that was sent. +- Floci creates a managed rule on the default bus of the account and Region. It is named by the id in the source + ARN and has `ManagedBy` `events.amazonaws.com`. Its pattern sets `source`, `account` and `region`, then the members + of `Pattern` in their own order. Its one target is the bus of the source. `OnFailureConfiguration.Arn` becomes the + target's `DeadLetterConfig`. +- `Pattern` may not set `source`, `account` or `region`. The dead-letter queue must be a standard queue of the + caller's account and Region. A queue that does not exist is accepted. +- An event of the service that matches the managed rule reaches the bus. `Data` is the event of the default bus + as it is. `Metadata` is empty. `SystemMetadata` has `EventGroupId` and `DeduplicationId`, both the event id, + then `ContentType`, `aws:IngestionTime`, `aws:Source`, `aws:DetailType`, `aws:EventId`, `aws:SequenceNumber` and + `aws:DeliveryType`. A bus takes one event per event id, however many sources of the service it has. +- `UpdateEventSource` replaces the whole configuration and rewrites the rule. A `Description` alone leaves the rule + alone. The type of a source cannot change. +- A `Pattern` that is no event pattern on its own, such as `{}`, is answered `400` with + `EventSource forwarding could not be provisioned: InvalidEventPatternException`. The source is still kept. After + a create it is `CREATE_FAILED` with no rule. After an update it is `UPDATE_FAILED`, holds the new configuration, + and keeps the rule it had. A later valid update makes it `ACTIVE` and writes the rule. +- `DeleteEventSource` removes the managed rule. A revoked source keeps its rule and takes no more events. +- `DeleteEventBus` is blocked by a source that is not revoked, but not by one that is `CREATE_FAILED`. +- `RotateWebhookCredentials` does not take the ARN of a service source. + +A `PartnerEventsConfiguration` always fails with `InvalidInputException`, as AWS does for a partner event source +that does not exist, since Floci models no partner event sources. + ## IAM Under IAM enforcement, EventBridge V2 operations are authorized as the `events` actions of the same diff --git a/src/main/java/io/floci/aws/services/eventbridge/EventBridgeErrors.java b/src/main/java/io/floci/aws/services/eventbridge/EventBridgeErrors.java index 77df84c5f2..3191eff2fb 100644 --- a/src/main/java/io/floci/aws/services/eventbridge/EventBridgeErrors.java +++ b/src/main/java/io/floci/aws/services/eventbridge/EventBridgeErrors.java @@ -77,11 +77,27 @@ final class EventBridgeErrors { return validation("Rule can't be deleted since it has targets."); } + static AwsException managedRule(String rule) { + return managed(rule + " is a managed rule."); + } + + static AwsException managedRuleNeedsForce(String rule) { + return managed(rule + " is a managed rule. Set 'force' parameter to true to override."); + } + + static AwsException managedRuleTags(String rule) { + return managed("Tag related operations on the managed rule " + rule + " is not allowed."); + } + static AwsException replaySourceArchiveNotFound(String archive) { return validation("Parameter EventSourceArn is not valid. Reason: Archive " + archive + " does not exist."); } + private static AwsException managed(String message) { + return new AwsException("ManagedRuleException", message, 400); + } + private static AwsException validation(String message) { return new AwsException("ValidationException", message, 400); } 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 073b67a8aa..beceb5a204 100644 --- a/src/main/java/io/floci/aws/services/eventbridge/EventBridgeHandler.java +++ b/src/main/java/io/floci/aws/services/eventbridge/EventBridgeHandler.java @@ -192,7 +192,7 @@ public class EventBridgeHandler { private Response handleDeleteRule(JsonNode request, String region) { String name = request.path("Name").asText(null); String busName = request.path("EventBusName").asText(null); - eventBridgeService.deleteRule(name, busName, region); + eventBridgeService.deleteRule(name, busName, request.path("Force").asBoolean(false), region); return Response.ok(objectMapper.createObjectNode()).build(); } @@ -335,7 +335,8 @@ public class EventBridgeHandler { } } EventBridgeService.RemoveTargetsResult result = - eventBridgeService.removeTargets(ruleName, busName, ids, region); + eventBridgeService.removeTargets(ruleName, busName, ids, request.path("Force").asBoolean(false), + region); ObjectNode response = objectMapper.createObjectNode(); response.put("SuccessfulEntryCount", result.successfulCount()); response.put("FailedEntryCount", result.failedCount()); @@ -876,6 +877,9 @@ public class EventBridgeHandler { if (rule.getRoleArn() != null) { node.put("RoleArn", rule.getRoleArn()); } + if (rule.getManagedBy() != null) { + node.put("ManagedBy", rule.getManagedBy()); + } return node; } diff --git a/src/main/java/io/floci/aws/services/eventbridge/EventBridgeInvoker.java b/src/main/java/io/floci/aws/services/eventbridge/EventBridgeInvoker.java index cd0b0e7605..85d7be87a4 100644 --- a/src/main/java/io/floci/aws/services/eventbridge/EventBridgeInvoker.java +++ b/src/main/java/io/floci/aws/services/eventbridge/EventBridgeInvoker.java @@ -26,6 +26,7 @@ import io.floci.aws.services.eventbridge.model.HttpParameters; import io.floci.aws.services.eventbridge.model.InputTransformer; import io.floci.aws.services.eventbridge.model.RedshiftDataParameters; import io.floci.aws.services.eventbridge.model.Target; +import io.floci.aws.services.eventbridgev2.EventBridgeV2Service; import io.floci.aws.services.firehose.FirehoseService; import io.floci.aws.services.firehose.model.Record; import io.floci.aws.services.kinesis.KinesisService; @@ -94,6 +95,7 @@ public class EventBridgeInvoker { private final RedshiftTargetAuthorizer redshiftTargetAuthorizer; private final RedshiftDataTargetSubmitter redshiftSubmitter; private final AppSyncTargetInvoker appSyncTargetInvoker; + private final EventBridgeV2Service eventBridgeV2Service; private final ServiceRegistry serviceRegistry; private final RegionResolver regionResolver; private final ObjectMapper objectMapper; @@ -108,11 +110,13 @@ public class EventBridgeInvoker { EcsJsonHandler ecsJsonHandler, StepFunctionsService stepFunctionsService, RedshiftDataService redshiftDataService, RedshiftTargetAuthorizer redshiftTargetAuthorizer, ServiceRegistry serviceRegistry, RegionResolver regionResolver, ObjectMapper objectMapper, - EmulatorConfig config, AppSyncTargetInvoker appSyncTargetInvoker) { + EmulatorConfig config, AppSyncTargetInvoker appSyncTargetInvoker, + EventBridgeV2Service eventBridgeV2Service) { this(lambdaService, sqsService, snsService, batchService, firehoseService, kinesisService, eventBridgeService, ecsService, ecsJsonHandler, stepFunctionsService, redshiftDataService, redshiftTargetAuthorizer, serviceRegistry, regionResolver, objectMapper, config, - apiDestinationClient(ContainerCaBundle.sslContext(config).orElse(null)), appSyncTargetInvoker); + apiDestinationClient(ContainerCaBundle.sslContext(config).orElse(null)), appSyncTargetInvoker, + eventBridgeV2Service); } public EventBridgeInvoker(LambdaService lambdaService, SqsService sqsService, SnsService snsService, @@ -124,7 +128,7 @@ public class EventBridgeInvoker { EmulatorConfig config, AppSyncTargetInvoker appSyncTargetInvoker) { this(lambdaService, sqsService, snsService, batchService, firehoseService, null, eventBridgeService, ecsService, ecsJsonHandler, stepFunctionsService, redshiftDataService, redshiftTargetAuthorizer, - serviceRegistry, regionResolver, objectMapper, config, appSyncTargetInvoker); + serviceRegistry, regionResolver, objectMapper, config, appSyncTargetInvoker, null); } private static HttpClient apiDestinationClient(SSLContext sslContext) { @@ -181,7 +185,7 @@ public class EventBridgeInvoker { EmulatorConfig config, HttpClient httpClient, AppSyncTargetInvoker appSyncTargetInvoker) { this(lambdaService, sqsService, snsService, batchService, firehoseService, null, eventBridgeService, ecsService, ecsJsonHandler, stepFunctionsService, redshiftDataService, redshiftTargetAuthorizer, - serviceRegistry, regionResolver, objectMapper, config, httpClient, appSyncTargetInvoker); + serviceRegistry, regionResolver, objectMapper, config, httpClient, appSyncTargetInvoker, null); } private EventBridgeInvoker(LambdaService lambdaService, SqsService sqsService, SnsService snsService, @@ -190,7 +194,8 @@ public class EventBridgeInvoker { EcsJsonHandler ecsJsonHandler, StepFunctionsService stepFunctionsService, RedshiftDataService redshiftDataService, RedshiftTargetAuthorizer redshiftTargetAuthorizer, ServiceRegistry serviceRegistry, RegionResolver regionResolver, ObjectMapper objectMapper, - EmulatorConfig config, HttpClient httpClient, AppSyncTargetInvoker appSyncTargetInvoker) { + EmulatorConfig config, HttpClient httpClient, AppSyncTargetInvoker appSyncTargetInvoker, + EventBridgeV2Service eventBridgeV2Service) { this.lambdaService = lambdaService; this.sqsService = sqsService; this.snsService = snsService; @@ -205,6 +210,7 @@ public class EventBridgeInvoker { this.redshiftTargetAuthorizer = redshiftTargetAuthorizer; this.redshiftSubmitter = new RedshiftDataTargetSubmitter(redshiftDataService, objectMapper); this.appSyncTargetInvoker = appSyncTargetInvoker; + this.eventBridgeV2Service = eventBridgeV2Service; this.serviceRegistry = serviceRegistry; this.regionResolver = regionResolver; this.objectMapper = objectMapper; @@ -240,6 +246,15 @@ public class EventBridgeInvoker { objectMapper, config); } + private void forwardToEventBusV2(String busArn, String ruleArn, String eventJson) { + if (eventBridgeV2Service == null || ruleArn == null) { + LOG.warnv("EventBridge V2 event bus target {0} cannot take the event: no V2 service or rule", busArn); + return; + } + eventBridgeV2Service.forwardServiceEvent(busArn, ruleArn, eventJson); + LOG.debugv("EventBridge delivered to EventBridge V2 bus: {0}", busArn); + } + public void invokeTarget(Target target, String eventJson, String region) { invokeTarget(target, eventJson, region, null); } @@ -346,6 +361,8 @@ public class EventBridgeInvoker { RequestScopes.runAs(targetAccount, () -> stepFunctionsService.startExecution(arn, null, payload, targetRegion)); LOG.debugv("EventBridge started Step Functions execution: {0}", arn); + } else if (arn.contains(":events:") && arn.contains(":event-busv2/")) { + forwardToEventBusV2(arn, ruleArn, eventJson); } else if (arn.contains(":events:") && arn.contains(":event-bus/")) { if (eventBridgeService == null) { LOG.warnv("EventBridge event-bus target missing EventBridge service: {0}", arn); 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 af1f804026..4bf1c40eb0 100644 --- a/src/main/java/io/floci/aws/services/eventbridge/EventBridgeService.java +++ b/src/main/java/io/floci/aws/services/eventbridge/EventBridgeService.java @@ -413,6 +413,9 @@ public class EventBridgeService implements ResourceProvider, StoredResourceArns + stored.get().getName() + " on event bus " + stored.get().getEventBusName() + ". Delete that rule first.", 400); } + if (stored.isPresent() && stored.get().getManagedBy() != null) { + throw EventBridgeErrors.managedRule(name); + } Rule rule = stored.orElse(new Rule()); rule.setAccountId(regionResolver.getAccountId()); rule.setName(name); @@ -444,6 +447,42 @@ public class EventBridgeService implements ResourceProvider, StoredResourceArns return rule; } + /** + * Creates or replaces a rule another AWS service manages on the default bus, with the one target it + * forwards to. It bypasses the managed-rule refusals a caller of the public operations meets. + */ + public Rule putManagedRule(String name, String managedBy, String eventPattern, Target target, String region) { + getOrCreateDefaultBus(region); + String key = ruleKey(region, "default", name); + Rule rule = ruleStore.get(key).orElse(new Rule()); + rule.setAccountId(regionResolver.getAccountId()); + rule.setName(name); + rule.setArn(buildRuleArn(region, "default", name)); + rule.setEventBusName("default"); + rule.setEventPattern(eventPattern); + rule.setState(RuleState.ENABLED); + rule.setManagedBy(managedBy); + if (rule.getCreatedAt() == null) { + rule.setCreatedAt(Instant.now()); + } + ruleStore.put(key, rule); + targetStore.put(key, new ArrayList<>(List.of(target))); + return rule; + } + + /** Whether the default bus has a rule of this name that another service manages. */ + public boolean isManagedRule(String name, String region) { + return ruleStore.get(ruleKey(region, "default", name)).filter(rule -> rule.getManagedBy() != null).isPresent(); + } + + /** Removes a managed rule and its targets. A rule that is already gone is not an error. */ + public void deleteManagedRule(String name, String region) { + String key = ruleKey(region, "default", name); + ruleStore.get(key).ifPresent(rule -> dispatcher.dropPendingRetries(rule.getArn(), List.of(name))); + ruleStore.delete(key); + targetStore.delete(key); + } + private static final Pattern NON_PARTNER_NAME = Pattern.compile("[\\.\\-_A-Za-z0-9]+"); private static void validateRuleName(String member, String name) { @@ -479,6 +518,10 @@ public class EventBridgeService implements ResourceProvider, StoredResourceArns } public void deleteRule(String name, String busName, String region) { + deleteRule(name, busName, false, region); + } + + public void deleteRule(String name, String busName, boolean force, String region) { String effectiveBus = resolvedBusName(busName); validateRuleReference("name", name, effectiveBus, region); ensureBusExists(effectiveBus, region); @@ -487,6 +530,9 @@ public class EventBridgeService implements ResourceProvider, StoredResourceArns if (rule == null) { return; } + if (rule.getManagedBy() != null && !force) { + throw EventBridgeErrors.managedRuleNeedsForce(name); + } List targets = targetStore.get(key).orElse(List.of()); if (!targets.isEmpty()) { throw EventBridgeErrors.ruleHasTargets(); @@ -576,6 +622,7 @@ public class EventBridgeService implements ResourceProvider, StoredResourceArns String key = ruleKey(region, effectiveBus, name); Rule rule = ruleOfBus(key, effectiveBus) .orElseThrow(() -> EventBridgeErrors.ruleNotFound(name, effectiveBus)); + requireNotManaged(rule); rule.setState(RuleState.ENABLED); ruleStore.put(key, rule); startSchedulerIfNeeded(rule); @@ -587,6 +634,7 @@ public class EventBridgeService implements ResourceProvider, StoredResourceArns String key = ruleKey(region, effectiveBus, name); Rule rule = ruleOfBus(key, effectiveBus) .orElseThrow(() -> EventBridgeErrors.ruleNotFound(name, effectiveBus)); + requireNotManaged(rule); rule.setState(RuleState.DISABLED); ruleStore.put(key, rule); @@ -618,6 +666,7 @@ public class EventBridgeService implements ResourceProvider, StoredResourceArns String key = ruleKey(region, effectiveBus, ruleName); Rule rule = ruleOfBus(key, effectiveBus) .orElseThrow(() -> EventBridgeErrors.ruleNotFound(ruleName, effectiveBus)); + requireNotManaged(rule); List existing = new ArrayList<>(targetStore.get(key).orElse(new ArrayList<>())); for (Target newTarget : newTargets) { EcsParameters ecs = newTarget.getEcsParameters(); @@ -733,12 +782,20 @@ public class EventBridgeService implements ResourceProvider, StoredResourceArns public RemoveTargetsResult removeTargets(String ruleName, String busName, List ids, String region) { + return removeTargets(ruleName, busName, ids, false, region); + } + + public RemoveTargetsResult removeTargets(String ruleName, String busName, + List ids, boolean force, 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()); } + if (!force && ruleStore.get(key).filter(rule -> rule.getManagedBy() != null).isPresent()) { + throw EventBridgeErrors.managedRuleNeedsForce(ruleName); + } List existing = new ArrayList<>(targetStore.get(key).orElse(new ArrayList<>())); int removed = 0; for (String id : ids) { @@ -900,10 +957,29 @@ public class EventBridgeService implements ResourceProvider, StoredResourceArns return new RuleRef("default", afterRule); } + private void requireTaggable(String resource, String region) { + if (!resource.startsWith("rule/")) { + return; + } + RuleRef ref = parseRuleResource(resource); + boolean managed = ruleStore.get(ruleKey(region, ref.busName(), ref.ruleName())) + .filter(rule -> rule.getManagedBy() != null).isPresent(); + if (managed) { + throw EventBridgeErrors.managedRuleTags(ref.ruleName()); + } + } + + private static void requireNotManaged(Rule rule) { + if (rule.getManagedBy() != null) { + throw EventBridgeErrors.managedRule(rule.getName()); + } + } + public void tagResource(String resourceArn, Map tags, String region) { validateTagResourceArn(resourceArn, region); String resource = AwsArnUtils.parse(resourceArn).resource(); TagResource target = requireTagResource(resourceArn, region, resource); + requireTaggable(resource, region); target.tags().putAll(tags); target.save().run(); resourceGroupsTaggingService.tagResources(List.of(resourceArn), tags, region); @@ -913,6 +989,7 @@ public class EventBridgeService implements ResourceProvider, StoredResourceArns validateTagResourceArn(resourceArn, region); String resource = AwsArnUtils.parse(resourceArn).resource(); TagResource target = requireTagResource(resourceArn, region, resource); + requireTaggable(resource, region); tagKeys.forEach(target.tags()::remove); target.save().run(); resourceGroupsTaggingService.untagResources(List.of(resourceArn), tagKeys, region); @@ -1322,7 +1399,7 @@ public class EventBridgeService implements ResourceProvider, StoredResourceArns return matchesPattern(entry, eventPattern); } - private void validateEventPattern(String eventPattern) { + public void validateEventPattern(String eventPattern) { JsonNode pattern; try { pattern = objectMapper.readTree(eventPattern); diff --git a/src/main/java/io/floci/aws/services/eventbridge/model/Rule.java b/src/main/java/io/floci/aws/services/eventbridge/model/Rule.java index fede11f96f..610bab9ebc 100644 --- a/src/main/java/io/floci/aws/services/eventbridge/model/Rule.java +++ b/src/main/java/io/floci/aws/services/eventbridge/model/Rule.java @@ -22,6 +22,7 @@ public class Rule { private RuleState state = RuleState.ENABLED; private String description; private String roleArn; + private String managedBy; private Map tags = new HashMap<>(); private Instant createdAt; @@ -54,6 +55,9 @@ public class Rule { public String getRoleArn() { return roleArn; } public void setRoleArn(String roleArn) { this.roleArn = roleArn; } + public String getManagedBy() { return managedBy; } + public void setManagedBy(String managedBy) { this.managedBy = managedBy; } + public Map getTags() { return tags; } public void setTags(Map tags) { this.tags = tags; } diff --git a/src/main/java/io/floci/aws/services/eventbridgev2/EventBridgeV2EventSources.java b/src/main/java/io/floci/aws/services/eventbridgev2/EventBridgeV2EventSources.java index c7a58bc7d9..2bb4c8ca44 100644 --- a/src/main/java/io/floci/aws/services/eventbridgev2/EventBridgeV2EventSources.java +++ b/src/main/java/io/floci/aws/services/eventbridgev2/EventBridgeV2EventSources.java @@ -15,8 +15,11 @@ import io.floci.aws.core.common.PaginatedResult; import io.floci.aws.core.common.Pagination; import io.floci.aws.core.common.RegionResolver; import io.floci.aws.core.common.Resettable; +import io.floci.aws.core.common.ServicePrincipals; import io.floci.aws.core.storage.AccountAwareStorageBackend; import io.floci.aws.core.storage.StorageFactory; +import io.floci.aws.services.eventbridge.EventBridgeService; +import io.floci.aws.services.eventbridge.model.Target; import io.floci.aws.services.eventbridgev2.model.EventBusV2; import io.floci.aws.services.eventbridgev2.model.EventSourceV2; import io.floci.aws.services.eventbridgev2.model.RotationRequest; @@ -47,6 +50,9 @@ import java.util.function.Function; @ApplicationScoped public class EventBridgeV2EventSources implements Resettable { private static final String OWNING_SERVICE = "events-webhook"; + private static final String EVENTS_PRINCIPAL = ServicePrincipals.of("events"); + private static final String CREATE_FAILED = "CREATE_FAILED"; + private static final String UPDATE_FAILED = "UPDATE_FAILED"; private static final String WEBHOOK_HOST_LABELS = "c01.events-webhook."; private static final Logger LOG = Logger.getLogger(EventBridgeV2EventSources.class); @@ -67,32 +73,35 @@ public class EventBridgeV2EventSources implements Resettable { private final SecureRandom random = new SecureRandom(); private final WebhookDeduplication deduplication; private final TlsCertificateManager certificateManager; + private final EventBridgeService eventBridge; @Inject public EventBridgeV2EventSources(StorageFactory storageFactory, SecretsManagerService secrets, RegionResolver regionResolver, EmulatorConfig config, - TlsCertificateManager certificateManager) { + TlsCertificateManager certificateManager, EventBridgeService eventBridge) { this(storageFactory.create("eventbridgev2", "eventbridgev2-event-sources.json", new TypeReference>() {}), - secrets, regionResolver, Clock.systemUTC(), config.effectiveBaseUrl(), certificateManager); + secrets, regionResolver, Clock.systemUTC(), config.effectiveBaseUrl(), certificateManager, + eventBridge); } EventBridgeV2EventSources(AccountAwareStorageBackend sources, SecretsManagerService secrets, RegionResolver regionResolver, Clock clock, String baseUrl, - TlsCertificateManager certificateManager) { + TlsCertificateManager certificateManager, EventBridgeService eventBridge) { this.sources = sources; this.secrets = secrets; this.regionResolver = regionResolver; this.clock = clock; this.baseUrl = URI.create(baseUrl); this.certificateManager = certificateManager; + this.eventBridge = eventBridge; this.deduplication = new WebhookDeduplication(clock); } /** - * Creates a webhook event source on a bus of the caller's, {@code ACTIVE} at once, with the secret that holds - * its credential. A retry with the {@code ClientToken} of an earlier create returns that source when it repeats - * the request, and fails when it changes it. + * Creates an event source on a bus of the caller's. A webhook source is {@code ACTIVE} at once, with the secret + * that holds its credential. A retry with the {@code ClientToken} of an earlier create returns that source when + * it repeats the request, and fails when it changes it. */ EventSourceV2 create(JsonNode request, String region, Function> findBusByName) { EventBridgeV2RequestShapes.check("CreateEventSource", request); @@ -110,14 +119,20 @@ public class EventBridgeV2EventSources implements Resettable { if (clientToken == null) { throw EventBridgeV2Service.invalidInput("ClientToken is required"); } + Map.Entry variant = WebhookEventsConfigurations.onlyVariant(configuration); + if (ServiceEventsConfigurations.PARTNER.equals(variant.getKey())) { + checkPartnerSource(variant.getValue(), region); + requireBus(eventBusArn, findBusByName); + throw ServiceEventsConfigurations.partnerSourceMissing(variant.getValue()); + } + if (ServiceEventsConfigurations.AWS_SERVICE.equals(variant.getKey())) { + return createServiceSource(request, region, clientToken, variant.getValue(), findBusByName); + } JsonNode webhook = WebhookEventsConfigurations.validateForCreate(configuration); // The request carries credentials, so only its hash is kept. String requestHash = Digests.sha256Hex(EventBridgeV2Service.withoutClientToken(request)); - Optional retried = EventBridgeV2Service.retried(() -> inRegion(region), - clientToken, requestHash, EventSourceV2::getClientToken, EventSourceV2::getCreateRequestHash, - () -> new AwsException("IdempotentParameterMismatchException", - "ClientToken was used by a previous request with different parameters", 409)); + Optional retried = retriedSource(region, clientToken, requestHash); if (retried.isPresent()) { return retried.get(); } @@ -131,8 +146,7 @@ public class EventBridgeV2EventSources implements Resettable { Instant now = clock.instant(); EventSourceV2 source = new EventSourceV2(); source.setName(name); - source.setArn(regionResolver.buildArn("events", region, - "event-sourcev2/webhook/" + name + "/" + EventBridgeV2Service.newId(random))); + source.setArn(sourceArn(region, "webhook", name)); source.setEventBusArn(eventBusArn); source.setDescription(request.path("Description").textValue()); source.setConfiguration(WebhookEventsConfigurations.echo(webhook)); @@ -154,11 +168,121 @@ public class EventBridgeV2EventSources implements Resettable { return source; } + private Optional retriedSource(String region, String clientToken, String requestHash) { + return EventBridgeV2Service.retried(() -> inRegion(region), + clientToken, requestHash, EventSourceV2::getClientToken, EventSourceV2::getCreateRequestHash, + () -> new AwsException("IdempotentParameterMismatchException", + "ClientToken was used by a previous request with different parameters", 409)); + } + + private String sourceArn(String region, String kind, String name) { + return regionResolver.buildArn("events", region, + "event-sourcev2/" + kind + "/" + name + "/" + EventBridgeV2Service.newId(random)); + } + + private void checkPartnerSource(JsonNode partner, String region) { + ServiceEventsConfigurations.checkPattern(partner, false); + ServiceEventsConfigurations.checkOnFailure(partner, region, regionResolver.getAccountId()); + ServiceEventsConfigurations.checkPartnerRegion(partner, region); + } + + private void checkServiceSource(JsonNode service, String region) { + ServiceEventsConfigurations.checkPattern(service, true); + ServiceEventsConfigurations.checkOnFailure(service, region, regionResolver.getAccountId()); + } + + /** + * Creates a source of AWS service events. A pattern the forwarding rule cannot use still leaves the source + * behind, as {@code CREATE_FAILED}, with no rule. + */ + private EventSourceV2 createServiceSource(JsonNode request, String region, String clientToken, JsonNode service, + Function> findBusByName) { + String eventBusArn = request.get("EventBusArn").textValue(); + checkServiceSource(service, region); + String requestHash = Digests.sha256Hex(EventBridgeV2Service.withoutClientToken(request)); + Optional retried = retriedSource(region, clientToken, requestHash); + if (retried.isPresent()) { + if (CREATE_FAILED.equals(retried.get().getState())) { + throw ServiceEventsConfigurations.provisioningFailed(); + } + return retried.get(); + } + requireBus(eventBusArn, findBusByName); + String name = request.get("Name").textValue(); + String key = EventBridgeV2Service.storageKey(region, name); + if (sources.get(key).isPresent()) { + throw new AwsException("ResourceAlreadyExistsException", "Resource already exists", 409); + } + + Instant now = clock.instant(); + EventSourceV2 source = new EventSourceV2(); + source.setName(name); + source.setArn(sourceArn(region, "aws.service", name)); + source.setEventBusArn(eventBusArn); + source.setDescription(request.path("Description").textValue()); + source.setConfiguration(ServiceEventsConfigurations.echo(service)); + source.setCreationTime(now); + source.setLastModifiedTime(now); + source.setTags(tags(request.get("Tags"))); + source.setClientToken(clientToken); + source.setCreateRequestHash(requestHash); + boolean provisioned = provisionRule(source, service, region); + source.setState(provisioned ? EventBridgeV2Service.ACTIVE : CREATE_FAILED); + try { + sources.put(key, source); + } catch (RuntimeException e) { + if (provisioned) { + eventBridge.deleteManagedRule(id(source), region); + } + throw e; + } + if (!provisioned) { + throw ServiceEventsConfigurations.provisioningFailed(); + } + return source; + } + + /** + * Puts the rule on the default bus that forwards the service's events to the source's bus. False when the + * source's own pattern is not one an event rule can use, and then no rule is touched. + */ + private boolean provisionRule(EventSourceV2 source, JsonNode service, String region) { + if (ServiceEventsConfigurations.givesPattern(service)) { + JsonNode own = ServiceEventsConfigurations.ownPattern(service); + if (!ServiceEventsConfigurations.isUsablePattern(own) || !acceptedByEventBridge(own)) { + return false; + } + } + String ruleName = id(source); + Target target = new Target(ruleName, source.getEventBusArn(), null, null); + String deadLetterQueue = service.path("OnFailureConfiguration").path("Arn").textValue(); + if (deadLetterQueue != null) { + target.setDeadLetterConfig(new Target.DeadLetterConfig(deadLetterQueue)); + } + eventBridge.putManagedRule(ruleName, EVENTS_PRINCIPAL, + ServiceEventsConfigurations.forwardingPattern(service, regionResolver.getAccountId(), region), + target, region); + return true; + } + + private boolean acceptedByEventBridge(JsonNode pattern) { + try { + eventBridge.validateEventPattern(pattern.toString()); + return true; + } catch (AwsException e) { + if (!"InvalidEventPatternException".equals(e.getErrorCode())) { + throw e; + } + LOG.debugv("The pattern of an event source was refused: {0}", e.getMessage()); + return false; + } + } + /** * Replaces the description the request gives and the whole webhook configuration. The credentials, the URL and * the secret stay as they are. A refused update changes nothing. */ - EventSourceV2 update(JsonNode request, String region) { + EventSourceV2 update(JsonNode request, String region, Function> findBusByName) { EventBridgeV2RequestShapes.check("UpdateEventSource", request); String arn = request.get("EventSourceArn").textValue(); checkArn(arn, region); @@ -169,6 +293,9 @@ public class EventBridgeV2EventSources implements Resettable { requireOwnAccount(roleArn); } EventSourceV2 source = require(arn, region); + if (ServiceEventsConfigurations.isAwsService(source)) { + return updateServiceSource(request, region, source, configuration, findBusByName); + } JsonNode webhook = configuration == null ? null : WebhookEventsConfigurations.validateForUpdate( configuration, WebhookEventsConfigurations.authType( source.getConfiguration().get(WebhookEventsConfigurations.WEBHOOK))); @@ -185,6 +312,43 @@ public class EventBridgeV2EventSources implements Resettable { return changed; } + /** + * Replaces the description and the whole configuration of a source of AWS service events, and the forwarding + * rule with it. A pattern the rule cannot use still stores the new configuration, as {@code UPDATE_FAILED}, + * and leaves the rule as it was. + */ + private EventSourceV2 updateServiceSource(JsonNode request, String region, EventSourceV2 source, + JsonNode configuration, + Function> findBusByName) { + JsonNode service = null; + if (configuration != null) { + Map.Entry variant = WebhookEventsConfigurations.onlyVariant(configuration); + if (!ServiceEventsConfigurations.AWS_SERVICE.equals(variant.getKey())) { + throw WebhookEventsConfigurations.variantImmutable(ServiceEventsConfigurations.AWS_SERVICE_TYPE); + } + service = variant.getValue(); + checkServiceSource(service, region); + } + requireNotRevoked(source, "EventSource is revoked and cannot be updated"); + requireBus(source.getEventBusArn(), findBusByName); + + EventSourceV2 changed = copyOf(source); + changed.setDescription(request.hasNonNull("Description") ? request.get("Description").textValue() + : source.getDescription()); + changed.setLastModifiedTime(clock.instant()); + boolean provisioned = true; + if (service != null) { + changed.setConfiguration(ServiceEventsConfigurations.echo(service)); + provisioned = provisionRule(changed, service, region); + changed.setState(provisioned ? EventBridgeV2Service.ACTIVE : UPDATE_FAILED); + } + sources.put(EventBridgeV2Service.storageKey(region, source.getName()), changed); + if (!provisioned) { + throw ServiceEventsConfigurations.provisioningFailed(); + } + return changed; + } + /** * Replaces the credential in the source's secret, with the one the request gives or a generated one, and * returns the secret's ARN. The URL and the secret stay, and so does the time the source was modified. A @@ -323,6 +487,16 @@ public class EventBridgeV2EventSources implements Resettable { /** Deletes the source and schedules its secret for deletion, unless the secret is already scheduled. */ void delete(JsonNode request, String region) { EventSourceV2 source = find("DeleteEventSource", request, region); + if (ServiceEventsConfigurations.isAwsService(source)) { + eventBridge.deleteManagedRule(id(source), region); + } else { + deleteSecret(source, region); + } + sources.delete(EventBridgeV2Service.storageKey(region, source.getName())); + deduplication.forget(source.getArn()); + } + + private void deleteSecret(EventSourceV2 source, String region) { try { if (secrets.describeSecret(source.getSecretArn(), region).getDeletedDate() == null) { secrets.deleteSecret(source.getSecretArn(), null, false, region); @@ -333,8 +507,6 @@ public class EventBridgeV2EventSources implements Resettable { } LOG.warnv("The secret {0} of event source {1} is already gone", source.getSecretArn(), source.getArn()); } - sources.delete(EventBridgeV2Service.storageKey(region, source.getName())); - deduplication.forget(source.getArn()); } /** @@ -378,7 +550,25 @@ public class EventBridgeV2EventSources implements Resettable { boolean hasSourcesOn(String eventBusArn, String region) { return inRegion(region).stream() - .anyMatch(source -> eventBusArn.equals(source.getEventBusArn()) && !source.isRevoked()); + .anyMatch(source -> eventBusArn.equals(source.getEventBusArn()) && !source.isRevoked() + && !CREATE_FAILED.equals(source.getState())); + } + + /** + * Whether {@code ruleArn} is the managed rule of a source of AWS service events that is on the bus and takes + * events: the rule of that id on the default bus of the bus's own account and Region. + */ + boolean takesServiceEvents(String eventBusArn, String region, String ruleArn) { + String sourceId = ruleArn.substring(ruleArn.lastIndexOf('/') + 1); + String managedRuleArn = regionResolver.buildArn("events", region, + AwsArnUtils.parse(eventBusArn).accountId(), "rule/" + sourceId); + if (!managedRuleArn.equals(ruleArn) || !eventBridge.isManagedRule(sourceId, region)) { + return false; + } + return inRegion(region).stream() + .anyMatch(source -> eventBusArn.equals(source.getEventBusArn()) + && ServiceEventsConfigurations.isAwsService(source) && !source.isRevoked() + && sourceId.equals(id(source))); } /** The URL a source receives its events at, in the scheme of Floci's own base URL. */ @@ -469,7 +659,7 @@ public class EventBridgeV2EventSources implements Resettable { } } - private static AwsException busMissing() { + static AwsException busMissing() { return new AwsException("ResourceNotFoundException", "Resource does not exist", 404); } diff --git a/src/main/java/io/floci/aws/services/eventbridgev2/EventBridgeV2Handler.java b/src/main/java/io/floci/aws/services/eventbridgev2/EventBridgeV2Handler.java index 3557db5234..e9f8bf734b 100644 --- a/src/main/java/io/floci/aws/services/eventbridgev2/EventBridgeV2Handler.java +++ b/src/main/java/io/floci/aws/services/eventbridgev2/EventBridgeV2Handler.java @@ -216,7 +216,7 @@ public class EventBridgeV2Handler { private Response handleCreateEventSource(JsonNode request, String region) { EventSourceV2 source = service.createEventSource(request, region); ObjectNode response = eventSourceIdentity(source); - response.set("EventSourceDetails", eventSourceDetails(source)); + putEventSourceDetails(response, source); response.put("CreationTime", epochSeconds(source.getCreationTime())); return Response.ok(response).build(); } @@ -237,7 +237,7 @@ public class EventBridgeV2Handler { if (source.isRevoked()) { response.put("Revoked", true); } - response.set("EventSourceDetails", eventSourceDetails(source)); + putEventSourceDetails(response, source); response.put("CreationTime", epochSeconds(source.getCreationTime())); response.put("LastModifiedTime", epochSeconds(source.getLastModifiedTime())); return Response.ok(response).build(); @@ -276,7 +276,7 @@ public class EventBridgeV2Handler { summary.put("EventSourceArn", source.getArn()); summary.put("Name", source.getName()); summary.put("EventBusArn", source.getEventBusArn()); - summary.put("Type", "WEBHOOK_EVENTS"); + summary.put("Type", ServiceEventsConfigurations.typeOf(source)); summary.put("State", source.getState()); if (source.isRevoked()) { summary.put("Revoked", true); @@ -301,6 +301,12 @@ public class EventBridgeV2Handler { return response; } + private void putEventSourceDetails(ObjectNode response, EventSourceV2 source) { + if (!ServiceEventsConfigurations.isAwsService(source)) { + response.set("EventSourceDetails", eventSourceDetails(source)); + } + } + private ObjectNode eventSourceDetails(EventSourceV2 source) { ObjectNode details = objectMapper.createObjectNode(); ObjectNode webhook = details.putObject("WebhookDetails"); diff --git a/src/main/java/io/floci/aws/services/eventbridgev2/EventBridgeV2Service.java b/src/main/java/io/floci/aws/services/eventbridgev2/EventBridgeV2Service.java index 7512abdbf0..4299026293 100644 --- a/src/main/java/io/floci/aws/services/eventbridgev2/EventBridgeV2Service.java +++ b/src/main/java/io/floci/aws/services/eventbridgev2/EventBridgeV2Service.java @@ -14,6 +14,7 @@ import io.floci.aws.core.common.AwsJsonTimestamp; import io.floci.aws.core.common.PaginatedResult; import io.floci.aws.core.common.Pagination; import io.floci.aws.core.common.RegionResolver; +import io.floci.aws.core.common.RequestScopes; import io.floci.aws.core.common.Resettable; import io.floci.aws.core.storage.AccountAwareStorageBackend; import io.floci.aws.core.storage.StorageFactory; @@ -89,6 +90,7 @@ public class EventBridgeV2Service implements Resettable { private final boolean enabled; private final SecureRandom random = new SecureRandom(); private final ConcurrentMap deliveriesByBus = new ConcurrentHashMap<>(); + private final WebhookDeduplication serviceEventDeduplication; @Inject public EventBridgeV2Service(StorageFactory storageFactory, RegionResolver regionResolver, @@ -112,6 +114,7 @@ public class EventBridgeV2Service implements Resettable { this.eventSources = eventSources; this.clock = clock; this.enabled = enabled; + this.serviceEventDeduplication = new WebhookDeduplication(clock); } /** Whether {@code floci.services.eventbridgev2.enabled} turns the service off. */ @@ -227,6 +230,7 @@ public class EventBridgeV2Service implements Resettable { } buses.delete(storageKey(region, bus.getName())); deliveriesByBus.remove(bus.getArn()); + serviceEventDeduplication.forget(bus.getArn()); } /** @@ -416,7 +420,9 @@ public class EventBridgeV2Service implements Resettable { public EventSourceV2 createEventSource(JsonNode request, String region) { EventSourceV2 source = storeEventSource(request, region); - eventSources.coverWebhookHosts(region); + if (source.getWebhookHostId() != null) { + eventSources.coverWebhookHosts(region); + } return source; } @@ -426,16 +432,22 @@ public class EventBridgeV2Service implements Resettable { public EventSourceV2 describeEventSource(JsonNode request, String region) { EventSourceV2 source = findEventSource(request, region); - eventSources.coverWebhookHosts(region); + if (source.getWebhookHostId() != null) { + eventSources.coverWebhookHosts(region); + } return source; } private synchronized EventSourceV2 findEventSource(JsonNode request, String region) { - return eventSources.describe(request, region); + EventSourceV2 source = eventSources.describe(request, region); + if ("CREATE_FAILED".equals(source.getState()) && findEventBus(source.getEventBusArn(), region).isEmpty()) { + throw EventBridgeV2EventSources.busMissing(); + } + return source; } public synchronized EventSourceV2 updateEventSource(JsonNode request, String region) { - return eventSources.update(request, region); + return eventSources.update(request, region, name -> buses.get(storageKey(region, name))); } public synchronized String rotateWebhookCredentials(JsonNode request, String region) { @@ -586,6 +598,55 @@ public class EventBridgeV2Service implements Resettable { return event; } + /** + * Accepts an event that an AWS service sent to the default bus and that the managed rule of the event source + * {@code ruleArn} names forwards here. A source that is gone or revoked takes nothing, and a bus takes one event per + * event id, as AWS delivered one when several sources of a service shared a bus. + */ + public void forwardServiceEvent(String eventBusArn, String ruleArn, String eventJson) { + AwsArnUtils.Arn bus = AwsArnUtils.parse(eventBusArn); + RequestScopes.runAs(bus.accountId(), bus.region(), () -> { + if (!eventSources.takesServiceEvents(eventBusArn, bus.region(), ruleArn)) { + LOG.debugv("Rule {0} is not the managed rule of an event source of {1}", ruleArn, eventBusArn); + return; + } + JsonNode data = parseServiceEvent(eventJson); + String eventId = data.path("id").asText(); + if (!serviceEventDeduplication.firstSeen(eventBusArn, eventId)) { + return; + } + try { + publishWebhookEvent(eventBusArn, bus.region(), sequenceNumber -> serviceEvent(data, sequenceNumber)); + } catch (RuntimeException e) { + serviceEventDeduplication.forget(eventBusArn, eventId); + throw e; + } + }); + } + + private static JsonNode parseServiceEvent(String eventJson) { + try { + return MAPPER.readTree(eventJson); + } catch (JsonProcessingException e) { + throw new IllegalStateException("The event a rule forwards is not JSON", e); + } + } + + private PublishedEvent serviceEvent(JsonNode data, String sequenceNumber) { + String eventId = data.path("id").asText(); + ObjectNode system = JsonNodeFactory.instance.objectNode(); + system.put("EventGroupId", eventId); + system.put("DeduplicationId", eventId); + system.put("ContentType", PUT_EVENTS_CONTENT_TYPE); + system.put("aws:IngestionTime", WebhookEvents.INGESTION_TIME.format(clock.instant())); + system.put("aws:Source", data.path("source").asText()); + system.put("aws:DetailType", data.path("detail-type").asText()); + system.put("aws:EventId", UUID.randomUUID().toString()); + system.put("aws:SequenceNumber", sequenceNumber); + system.put("aws:DeliveryType", "LIVE"); + return new PublishedEvent(data, JsonNodeFactory.instance.objectNode(), system); + } + private PublishedEvent accept(EventBusV2 bus, List running, List> deliveries, Function build) { @@ -687,6 +748,7 @@ public class EventBridgeV2Service implements Resettable { buses.clear(); subscribers.clear(); deliveriesByBus.clear(); + serviceEventDeduplication.clear(); } // ──────────────────────────── Subscriber settings ──────────────────────────── diff --git a/src/main/java/io/floci/aws/services/eventbridgev2/ServiceEventsConfigurations.java b/src/main/java/io/floci/aws/services/eventbridgev2/ServiceEventsConfigurations.java new file mode 100644 index 0000000000..4002f8e418 --- /dev/null +++ b/src/main/java/io/floci/aws/services/eventbridgev2/ServiceEventsConfigurations.java @@ -0,0 +1,180 @@ +package io.floci.aws.services.eventbridgev2; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.DeserializationFeature; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.json.JsonMapper; +import com.fasterxml.jackson.databind.node.JsonNodeFactory; +import com.fasterxml.jackson.databind.node.ObjectNode; +import io.floci.aws.core.common.AwsArnUtils; +import io.floci.aws.core.common.AwsException; +import io.floci.aws.services.eventbridgev2.model.EventSourceV2; + +import java.util.Iterator; +import java.util.List; +import java.util.Map; + +import static io.floci.aws.services.eventbridgev2.EventBridgeV2Service.invalidInput; + +/** + * The request rules of the AWS service and partner event sources that AWS checks after the constraints of its + * model, and the forms their configurations take. + */ +final class ServiceEventsConfigurations { + static final String AWS_SERVICE = "AwsServiceEventsConfiguration"; + static final String PARTNER = "PartnerEventsConfiguration"; + static final String WEBHOOK_TYPE = "WEBHOOK_EVENTS"; + static final String AWS_SERVICE_TYPE = "AWS_SERVICE_EVENTS"; + + private static final List RESERVED_PATTERN_KEYS = List.of("source", "account", "region"); + private static final ObjectMapper STRICT = JsonMapper.builder() + .enable(DeserializationFeature.FAIL_ON_TRAILING_TOKENS) + .build(); + + private ServiceEventsConfigurations() { + } + + /** The {@code Type} of the source in a listing, from the one configuration member it holds. */ + static String typeOf(EventSourceV2 source) { + return source.getConfiguration().has(AWS_SERVICE) ? AWS_SERVICE_TYPE : WEBHOOK_TYPE; + } + + static boolean isAwsService(EventSourceV2 source) { + return source.getConfiguration().has(AWS_SERVICE); + } + + /** + * Checks the {@code Pattern} of a source's configuration. A service source may not set the keys its forwarding + * rule sets itself, and a partner source may. + */ + static void checkPattern(JsonNode variant, boolean refuseReservedKeys) { + String text = variant.path("Pattern").textValue(); + if (text == null || text.isEmpty()) { + return; + } + JsonNode pattern; + try { + pattern = STRICT.readTree(text); + } catch (JsonProcessingException e) { + throw invalidInput("Pattern is not valid JSON"); + } + if (pattern == null || !pattern.isObject()) { + throw invalidInput("Pattern must be a JSON object"); + } + if (!refuseReservedKeys) { + return; + } + Iterator keys = pattern.fieldNames(); + while (keys.hasNext()) { + String key = keys.next(); + if (RESERVED_PATTERN_KEYS.contains(key)) { + throw invalidInput("Pattern must not set the key '" + key + "'; the forwarding rule sets it from " + + "the requested AwsService and the source account and region"); + } + } + } + + /** Checks that the dead-letter queue lives in the caller's Region and account and is a standard queue. */ + static void checkOnFailure(JsonNode variant, String region, String accountId) { + String arn = variant.path("OnFailureConfiguration").path("Arn").textValue(); + if (arn == null) { + return; + } + AwsArnUtils.Arn queue = AwsArnUtils.parse(arn); + if (!queue.region().equals(region)) { + throw invalidInput("OnFailureConfiguration.Arn region '" + queue.region() + + "' must match the caller's region '" + region + "'"); + } + if (!queue.accountId().equals(accountId)) { + throw invalidInput("OnFailureConfiguration.Arn account '" + queue.accountId() + + "' must match the caller's account '" + accountId + "'"); + } + if (queue.resource().endsWith(".fifo")) { + throw invalidInput("OnFailureConfiguration.Arn must name a standard SQS queue: FIFO queues are not " + + "supported as EventSource dead-letter queues"); + } + } + + static void checkPartnerRegion(JsonNode variant, String region) { + String arn = variant.path("PartnerEventSourceArn").textValue(); + String arnRegion = AwsArnUtils.parse(arn).region(); + if (!arnRegion.equals(region)) { + throw invalidInput("PartnerEventSourceArn region '" + arnRegion + "' must match the caller's region '" + + region + "'"); + } + } + + /** The error for a partner source that Floci does not model, named as AWS words it. */ + static AwsException partnerSourceMissing(JsonNode variant) { + String arn = variant.path("PartnerEventSourceArn").textValue(); + String name = AwsArnUtils.parse(arn).resource().substring("event-source/".length()); + return invalidInput("The partner event source " + name + " could not be described: Event source " + name + + " does not exist."); + } + + static AwsException provisioningFailed() { + return invalidInput("EventSource forwarding could not be provisioned: InvalidEventPatternException"); + } + + /** + * The pattern of the forwarding rule: the service, account and Region first, then the members of the + * source's own pattern in the order it gives them. + */ + static String forwardingPattern(JsonNode variant, String accountId, String region) { + ObjectNode pattern = JsonNodeFactory.instance.objectNode(); + pattern.putArray("source").add(variant.get("AwsService").textValue()); + pattern.putArray("account").add(accountId); + pattern.putArray("region").add(region); + JsonNode own = ownPattern(variant); + for (Map.Entry member : own.properties()) { + pattern.set(member.getKey(), member.getValue()); + } + return pattern.toString(); + } + + static boolean givesPattern(JsonNode variant) { + String text = variant.path("Pattern").textValue(); + return text != null && !text.isEmpty(); + } + + /** The source's own pattern, empty when it gives none. */ + static JsonNode ownPattern(JsonNode variant) { + String text = variant.path("Pattern").textValue(); + if (text == null || text.isEmpty()) { + return JsonNodeFactory.instance.objectNode(); + } + try { + return STRICT.readTree(text); + } catch (JsonProcessingException e) { + throw new IllegalStateException("The pattern of a checked event source is not JSON", e); + } + } + + /** + * Whether a pattern the source gave can stand as an event pattern on its own: it names at least one member, + * and every member is an array or an object. + */ + static boolean isUsablePattern(JsonNode pattern) { + return !pattern.isEmpty() && membersAreFilters(pattern); + } + + private static boolean membersAreFilters(JsonNode pattern) { + for (JsonNode member : pattern) { + if (member.isObject() ? !membersAreFilters(member) : !member.isArray()) { + return false; + } + } + return true; + } + + /** The {@code Configuration} a describe returns: as given, less the members the model does not declare. */ + static JsonNode echo(JsonNode variant) { + ObjectNode copy = (ObjectNode) EventBridgeV2RequestShapes.modeled("AwsServiceEventsSourceConfiguration", + variant); + WebhookEventsConfigurations.dropNulls(copy); + ObjectNode configuration = copy.objectNode(); + configuration.set(AWS_SERVICE, copy); + return configuration; + } +} diff --git a/src/main/java/io/floci/aws/services/eventbridgev2/WebhookEvents.java b/src/main/java/io/floci/aws/services/eventbridgev2/WebhookEvents.java index 411a272fb7..4c9e42f265 100644 --- a/src/main/java/io/floci/aws/services/eventbridgev2/WebhookEvents.java +++ b/src/main/java/io/floci/aws/services/eventbridgev2/WebhookEvents.java @@ -33,7 +33,7 @@ final class WebhookEvents { private static final int MAX_METADATA_VALUE_BYTES = 1024; private static final byte[] UTF8_BOM = {(byte) 0xEF, (byte) 0xBB, (byte) 0xBF}; - private static final DateTimeFormatter INGESTION_TIME = + static final DateTimeFormatter INGESTION_TIME = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'").withZone(ZoneOffset.UTC); private static final ObjectMapper STRICT = JsonMapper.builder() .enable(StreamReadFeature.STRICT_DUPLICATE_DETECTION) diff --git a/src/main/java/io/floci/aws/services/eventbridgev2/WebhookEventsConfigurations.java b/src/main/java/io/floci/aws/services/eventbridgev2/WebhookEventsConfigurations.java index be6406f1ee..44ff4f8800 100644 --- a/src/main/java/io/floci/aws/services/eventbridgev2/WebhookEventsConfigurations.java +++ b/src/main/java/io/floci/aws/services/eventbridgev2/WebhookEventsConfigurations.java @@ -32,7 +32,6 @@ final class WebhookEventsConfigurations { private static final String WHSEC = "whsec_"; private static final int MIN_HMAC_SECRET_BYTES = 16; private static final int MAX_HMAC_SECRET_BYTES = 512; - private static final String ONLY_WEBHOOK = "Only WebhookEventsConfiguration event sources are supported."; private static final List SECRET_MEMBERS = List.of("SecretValue", "Username", "Password"); private static final List AUTH_MEMBERS = List.of(STATIC_TOKEN, BASIC, HMAC); @@ -46,17 +45,11 @@ final class WebhookEventsConfigurations { private WebhookEventsConfigurations() { } - /** - * Checks a create request's {@code Configuration} and returns its webhook configuration. A configuration of - * another variant is refused, as Floci serves webhook event sources only. - */ + /** Checks the webhook configuration of a create request's {@code Configuration} and returns it. */ static JsonNode validateForCreate(JsonNode configuration) { - Map.Entry variant = onlyVariant(configuration); - if (!WEBHOOK.equals(variant.getKey())) { - throw invalidInput(ONLY_WEBHOOK); - } - validateWebhook(variant.getValue()); - return variant.getValue(); + JsonNode webhook = onlyVariant(configuration).getValue(); + validateWebhook(webhook); + return webhook; } /** @@ -66,8 +59,7 @@ final class WebhookEventsConfigurations { static JsonNode validateForUpdate(JsonNode configuration, String storedAuthType) { Map.Entry variant = onlyVariant(configuration); if (!WEBHOOK.equals(variant.getKey())) { - throw invalidInput("EventSource type is immutable: the configuration variant must remain " - + "WEBHOOK_EVENTS"); + throw variantImmutable(ServiceEventsConfigurations.WEBHOOK_TYPE); } JsonNode webhook = variant.getValue(); JsonNode auth = webhook.path("AuthConfiguration"); @@ -97,7 +89,12 @@ final class WebhookEventsConfigurations { return members; } - private static Map.Entry onlyVariant(JsonNode configuration) { + static AwsException variantImmutable(String eventSourceType) { + return invalidInput("EventSource type is immutable: the configuration variant must remain " + + eventSourceType); + } + + static Map.Entry onlyVariant(JsonNode configuration) { List> members = variants(configuration); if (members.size() != 1) { throw invalidInput("Exactly one Configuration sub-field must be provided"); @@ -309,7 +306,7 @@ final class WebhookEventsConfigurations { return configuration; } - private static void dropNulls(JsonNode node) { + static void dropNulls(JsonNode node) { if (node instanceof ObjectNode object) { Iterator> fields = object.properties().iterator(); while (fields.hasNext()) { diff --git a/src/test/java/io/floci/aws/services/eventbridge/EventBridgeInvokerTest.java b/src/test/java/io/floci/aws/services/eventbridge/EventBridgeInvokerTest.java index dadb91d283..dd722f0471 100644 --- a/src/test/java/io/floci/aws/services/eventbridge/EventBridgeInvokerTest.java +++ b/src/test/java/io/floci/aws/services/eventbridge/EventBridgeInvokerTest.java @@ -18,6 +18,7 @@ import io.floci.aws.services.eventbridge.model.EcsParameters; import io.floci.aws.services.eventbridge.model.InputTransformer; import io.floci.aws.services.eventbridge.model.NetworkConfiguration; import io.floci.aws.services.eventbridge.model.Target; +import io.floci.aws.services.eventbridgev2.EventBridgeV2Service; import io.floci.aws.services.firehose.FirehoseService; import io.floci.aws.services.firehose.model.Record; import io.floci.aws.services.lambda.LambdaService; @@ -767,4 +768,38 @@ class EventBridgeInvokerTest { verify(eventBridgeService, never()).putEvents(anyList(), anyString(), any()); } + + @Test + void invokeTarget_eventBusV2Target_forwardsTheEventNamedByTheRule() { + EventBridgeV2Service eventBridgeV2Service = mock(EventBridgeV2Service.class); + EventBridgeInvoker forwarding = invokerWith(eventBridgeV2Service); + String busArn = "arn:aws:events:us-east-1:000000000000:event-busv2/orders/zzzzzzzzzzzzzzzzzzzzzzzzz"; + String event = "{\"id\":\"e1\",\"source\":\"aws.ssm\",\"detail-type\":\"x\",\"detail\":{}}"; + + forwarding.invokeTarget(new Target("abcdefghijklmnopqrstuvwxy", busArn, null, null), event, "us-east-1", + "arn:aws:events:us-east-1:000000000000:rule/abcdefghijklmnopqrstuvwxy"); + + verify(eventBridgeV2Service).forwardServiceEvent(busArn, + "arn:aws:events:us-east-1:000000000000:rule/abcdefghijklmnopqrstuvwxy", event); + verify(eventBridgeService, never()).putEvents(anyList(), anyString(), any()); + } + + @Test + void invokeTarget_eventBusV2TargetWithoutTheRuleDeliversNothing() { + EventBridgeV2Service eventBridgeV2Service = mock(EventBridgeV2Service.class); + + invokerWith(eventBridgeV2Service).invokeTarget(new Target("id1", + "arn:aws:events:us-east-1:000000000000:event-busv2/orders/zzzzzzzzzzzzzzzzzzzzzzzzz", null, null), + "{}", "us-east-1"); + + verifyNoInteractions(eventBridgeV2Service); + } + + private EventBridgeInvoker invokerWith(EventBridgeV2Service eventBridgeV2Service) { + EmulatorConfig config = mock(EmulatorConfig.class, Mockito.RETURNS_DEEP_STUBS); + return new EventBridgeInvoker(lambdaService, sqsService, mock(SnsService.class), batchService, + firehoseService, null, eventBridgeService, ecsService, null, stepFunctionsService, + mock(RedshiftDataService.class), null, mock(ServiceRegistry.class), regionResolver, + new ObjectMapper(), config, null, eventBridgeV2Service); + } } diff --git a/src/test/java/io/floci/aws/services/eventbridge/EventBridgeManagedRuleTest.java b/src/test/java/io/floci/aws/services/eventbridge/EventBridgeManagedRuleTest.java new file mode 100644 index 0000000000..8ba8e5acc4 --- /dev/null +++ b/src/test/java/io/floci/aws/services/eventbridge/EventBridgeManagedRuleTest.java @@ -0,0 +1,186 @@ +package io.floci.aws.services.eventbridge; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import io.floci.aws.core.common.AwsErrorResponse; +import io.floci.aws.core.common.AwsException; +import io.floci.aws.core.common.RegionResolver; +import io.floci.aws.core.storage.InMemoryStorage; +import io.floci.aws.services.eventbridge.model.Rule; +import io.floci.aws.services.eventbridge.model.RuleState; +import io.floci.aws.services.eventbridge.model.Target; +import io.floci.aws.services.resourcegroupstagging.ResourceGroupsTaggingService; +import jakarta.ws.rs.core.Response; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import java.util.List; +import java.util.Map; + +import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.Mockito.mock; + +class EventBridgeManagedRuleTest { + private static final String REGION = "us-east-1"; + private static final ObjectMapper MAPPER = new ObjectMapper(); + private static final String PRINCIPAL = "events.amazonaws.com"; + private static final String RULE = "abcdefghijklmnopqrstuvwxy"; + private static final String RULE_ARN = "arn:aws:events:us-east-1:000000000000:rule/" + RULE; + private static final String BUS_ARN = "arn:aws:events:us-east-1:000000000000:event-busv2/orders/zzzzzzzzzzzzzzzzzzzzzzzzz"; + + private EventBridgeService service; + private EventBridgeHandler handler; + + @BeforeEach + void setUp() { + service = new EventBridgeService(new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(), + new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(), + new InMemoryStorage<>(), new RegionResolver(REGION, "000000000000"), MAPPER, null, + mock(TargetDispatcher.class), mock(ReplayDispatcher.class), new ResourceGroupsTaggingService(null), + mock(AppSyncTargetValidator.class)); + handler = new EventBridgeHandler(service, MAPPER); + service.putManagedRule(RULE, PRINCIPAL, "{\"source\":[\"aws.ssm\"]}", new Target(RULE, BUS_ARN, null, null), + REGION); + } + + @Test + void describeAndListAnswerManagedBy() throws Exception { + JsonNode described = call("DescribeRule", "{\"Name\":\"" + RULE + "\"}"); + assertEquals(PRINCIPAL, described.path("ManagedBy").textValue()); + assertEquals("{\"source\":[\"aws.ssm\"]}", described.path("EventPattern").textValue()); + + JsonNode listed = call("ListRules", "{}"); + assertEquals(PRINCIPAL, listed.path("Rules").get(0).path("ManagedBy").textValue()); + } + + @Test + void aRuleThatIsNotManagedAnswersNoManagedBy() throws Exception { + service.putRule("plain", null, "{\"source\":[\"x\"]}", null, RuleState.ENABLED, null, null, null, REGION); + + JsonNode described = call("DescribeRule", "{\"Name\":\"plain\"}"); + + assertTrue(described.path("ManagedBy").isMissingNode()); + } + + @Test + void theManagedRuleHasOneEnabledTargetOnTheDefaultBus() { + Rule rule = service.describeRule(RULE, null, REGION); + + assertEquals(RuleState.ENABLED, rule.getState()); + assertEquals("default", rule.getEventBusName()); + List targets = service.listTargetsByRule(RULE, null, REGION); + assertEquals(1, targets.size()); + assertEquals(RULE, targets.getFirst().getId()); + assertEquals(BUS_ARN, targets.getFirst().getArn()); + } + + @Test + void deleteRuleNeedsForce() { + AwsException e = assertThrows(AwsException.class, () -> service.deleteRule(RULE, null, REGION)); + + assertManaged(e, RULE + " is a managed rule. Set 'force' parameter to true to override."); + } + + @Test + void removeTargetsNeedsForce() { + AwsException e = assertThrows(AwsException.class, + () -> service.removeTargets(RULE, null, List.of(RULE), REGION)); + + assertManaged(e, RULE + " is a managed rule. Set 'force' parameter to true to override."); + assertEquals(1, service.listTargetsByRule(RULE, null, REGION).size()); + } + + @Test + void disableEnablePutRuleAndPutTargetsRefuseAManagedRule() { + String message = RULE + " is a managed rule."; + assertManaged(assertThrows(AwsException.class, () -> service.disableRule(RULE, null, REGION)), message); + assertManaged(assertThrows(AwsException.class, () -> service.enableRule(RULE, null, REGION)), message); + assertManaged(assertThrows(AwsException.class, () -> service.putRule(RULE, null, "{\"source\":[\"x\"]}", null, + RuleState.ENABLED, null, null, null, REGION)), message); + assertManaged(assertThrows(AwsException.class, () -> service.putTargets(RULE, null, + List.of(new Target("t", "arn:aws:sqs:us-east-1:000000000000:q", null, null)), REGION)), message); + } + + @Test + void tagAndUntagRefuseAManagedRuleButListTagsAnswersNone() { + String message = "Tag related operations on the managed rule " + RULE + " is not allowed."; + assertManaged(assertThrows(AwsException.class, + () -> service.tagResource(RULE_ARN, Map.of("k", "v"), REGION)), message); + assertManaged(assertThrows(AwsException.class, + () -> service.untagResource(RULE_ARN, List.of("k"), REGION)), message); + + assertTrue(service.listTagsForResource(RULE_ARN, REGION).isEmpty()); + } + + @Test + void removeTargetsWithForceThenDeleteRuleWithForceWorks() throws Exception { + assertEquals(0, call("RemoveTargets", "{\"Rule\":\"" + RULE + "\",\"Ids\":[\"" + RULE + "\"],\"Force\":true}") + .path("FailedEntryCount").asInt()); + call("DeleteRule", "{\"Name\":\"" + RULE + "\",\"Force\":true}"); + + assertTrue(service.listRules(null, null, REGION).isEmpty()); + } + + @Test + void deleteRuleWithForceStillFailsWhileTheRuleHasTargets() { + AwsException e = assertThrows(AwsException.class, () -> service.deleteRule(RULE, null, true, REGION)); + + assertEquals("ValidationException", e.getErrorCode()); + assertEquals("Rule can't be deleted since it has targets.", e.getMessage()); + } + + @Test + void deleteRuleWithNoForceInTheRequestIsRefused() throws Exception { + try (Response response = handler.handle("DeleteRule", MAPPER.readTree("{\"Name\":\"" + RULE + "\"}"), + REGION)) { + assertEquals(400, response.getStatus()); + AwsErrorResponse error = (AwsErrorResponse) response.getEntity(); + assertEquals("ManagedRuleException", error.type()); + } + } + + @Test + void listRuleNamesByTargetFindsTheManagedRuleByTheBusArn() { + assertEquals(List.of(RULE), service.listRuleNamesByTarget(BUS_ARN, null, null, null, REGION).items()); + } + + @Test + void deleteManagedRuleRemovesTheRuleAndItsTargetsAndToleratesAMissingRule() { + service.deleteManagedRule(RULE, REGION); + + assertTrue(service.listRules(null, null, REGION).isEmpty()); + assertDoesNotThrow(() -> service.deleteManagedRule(RULE, REGION)); + } + + @Test + void putManagedRuleRewritesTheRuleAndReplacesTheTarget() { + Target target = new Target(RULE, BUS_ARN, null, null); + target.setDeadLetterConfig(new Target.DeadLetterConfig("arn:aws:sqs:us-east-1:000000000000:dead")); + + service.putManagedRule(RULE, PRINCIPAL, "{\"source\":[\"aws.s3\"]}", target, REGION); + + assertEquals("{\"source\":[\"aws.s3\"]}", service.describeRule(RULE, null, REGION).getEventPattern()); + assertEquals("arn:aws:sqs:us-east-1:000000000000:dead", + service.listTargetsByRule(RULE, null, REGION).getFirst().getDeadLetterConfig().arn()); + service.putManagedRule(RULE, PRINCIPAL, "{\"source\":[\"aws.s3\"]}", new Target(RULE, BUS_ARN, null, null), + REGION); + assertNull(service.listTargetsByRule(RULE, null, REGION).getFirst().getDeadLetterConfig()); + } + + private JsonNode call(String action, String body) throws Exception { + try (Response response = handler.handle(action, MAPPER.readTree(body), REGION)) { + assertEquals(200, response.getStatus(), String.valueOf(response.getEntity())); + return (JsonNode) response.getEntity(); + } + } + + private static void assertManaged(AwsException e, String message) { + assertEquals("ManagedRuleException", e.getErrorCode()); + assertEquals(400, e.getHttpStatus()); + assertEquals(message, e.getMessage()); + } +} diff --git a/src/test/java/io/floci/aws/services/eventbridge/RulePersistenceTest.java b/src/test/java/io/floci/aws/services/eventbridge/RulePersistenceTest.java index cfea759914..cb97e44ef8 100644 --- a/src/test/java/io/floci/aws/services/eventbridge/RulePersistenceTest.java +++ b/src/test/java/io/floci/aws/services/eventbridge/RulePersistenceTest.java @@ -31,6 +31,7 @@ class RulePersistenceTest { rule.setEventBusName("default"); rule.setScheduleExpression("rate(5 minutes)"); rule.setState(RuleState.ENABLED); + rule.setManagedBy("events.amazonaws.com"); PersistentStorage writer = new PersistentStorage<>( filePath, new TypeReference>() {}); @@ -47,6 +48,7 @@ class RulePersistenceTest { assertEquals("arn:aws:events:us-east-1:000000000000:rule/my-rule", loaded.get().getArn()); assertEquals("rate(5 minutes)", loaded.get().getScheduleExpression()); assertEquals(RuleState.ENABLED, loaded.get().getState()); + assertEquals("events.amazonaws.com", loaded.get().getManagedBy()); } @Test diff --git a/src/test/java/io/floci/aws/services/eventbridgev2/AwsServiceEventSourcesTest.java b/src/test/java/io/floci/aws/services/eventbridgev2/AwsServiceEventSourcesTest.java new file mode 100644 index 0000000000..4858e548a3 --- /dev/null +++ b/src/test/java/io/floci/aws/services/eventbridgev2/AwsServiceEventSourcesTest.java @@ -0,0 +1,789 @@ +package io.floci.aws.services.eventbridgev2; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import io.floci.aws.config.TlsCertificateManager; +import io.floci.aws.core.common.AwsException; +import io.floci.aws.core.common.PaginatedResult; +import io.floci.aws.core.common.RegionResolver; +import io.floci.aws.core.storage.AccountAwareStorageBackend; +import io.floci.aws.services.eventbridge.EventBridgeService; +import io.floci.aws.services.eventbridge.model.Target; +import io.floci.aws.services.eventbridgev2.model.EventSourceV2; +import io.floci.aws.services.secretsmanager.SecretsManagerService; +import io.floci.aws.services.secretsmanager.model.Secret; +import io.floci.aws.testing.ManualClock; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.mockito.ArgumentCaptor; + +import java.time.Duration; +import java.time.Instant; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.stream.Collectors; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.atLeastOnce; +import static org.mockito.Mockito.doThrow; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +class AwsServiceEventSourcesTest { + private static final String REGION = "us-east-1"; + private static final String ACCOUNT = "000000000000"; + private static final Instant NOW = Instant.parse("2026-11-27T12:00:00Z"); + private static final ObjectMapper MAPPER = new ObjectMapper(); + private static final String QUEUE = "arn:aws:sqs:us-east-1:000000000000:dead"; + private static final String ROLE = "arn:aws:iam::000000000000:role/Delivery"; + private static final String PARTNER = "arn:aws:events:us-east-1:111111111111:event-source/aws.partner/" + + "example.com/123/orders"; + private static final String RULE_ARN_PREFIX = "arn:aws:events:us-east-1:000000000000:rule/"; + private static final String PROVISIONING_FAILED = + "EventSource forwarding could not be provisioned: InvalidEventPatternException"; + + private EventBridgeService eventBridge; + private EventBridgeV2Delivery delivery; + private EventBridgeV2Service service; + private ManualClock clock; + private TlsCertificateManager certificateManager; + private String bus; + + @BeforeEach + void setUp() { + eventBridge = mock(EventBridgeService.class); + when(eventBridge.isManagedRule(any(), any())).thenReturn(true); + delivery = mock(EventBridgeV2Delivery.class); + certificateManager = mock(TlsCertificateManager.class); + clock = new ManualClock(NOW); + RegionResolver regionResolver = new RegionResolver(REGION, ACCOUNT); + SecretsManagerService secrets = mock(SecretsManagerService.class); + Secret secret = new Secret(); + secret.setArn("arn:aws:secretsmanager:us-east-1:000000000000:secret:events-webhook!x-AbCdEf"); + when(secrets.createSecret(any(), any(), any(), any(), any(), any(), any(), any())).thenReturn(secret); + EventBridgeV2EventSources eventSources = new EventBridgeV2EventSources( + AccountAwareStorageBackend.inMemory(ACCOUNT), secrets, regionResolver, clock, + "http://floci.test:4566", certificateManager, eventBridge); + service = new EventBridgeV2Service(AccountAwareStorageBackend.inMemory(ACCOUNT), + AccountAwareStorageBackend.inMemory(ACCOUNT), regionResolver, delivery, eventSources, clock, true); + bus = service.createEventBus(json("{\"Name\":\"orders\"}"), REGION).getArn(); + } + + // ──────────────────────────── Create ──────────────────────────── + + @Test + void createMintsAnActiveSourceWithNoWebhookDetails() { + EventSourceV2 source = service.createEventSource(create("svc", "{\"AwsService\":\"aws.ssm\"}"), REGION); + + assertTrue(source.getArn().matches( + "arn:aws:events:us-east-1:000000000000:event-sourcev2/aws.service/svc/[a-z0-9]{25}"), source.getArn()); + assertEquals("ACTIVE", source.getState()); + assertEquals("AWS_SERVICE_EVENTS", ServiceEventsConfigurations.typeOf(source)); + assertNull(source.getWebhookHostId()); + assertNull(source.getSecretArn()); + verify(certificateManager, never()).ensureHost(any()); + } + + @Test + void describeEchoesTheConfigurationAndThePatternAsSent() { + String pattern = "{ \"detail-type\" : [\"Parameter Store Change\"] }"; + EventSourceV2 source = service.createEventSource(create("svc", + "{\"AwsService\":\"aws.ssm\",\"Pattern\":\"" + escaped(pattern) + "\"," + + "\"OnFailureConfiguration\":{}}"), REGION); + + EventSourceV2 described = service.describeEventSource(arn(source.getArn()), REGION); + + assertEquals(json("{\"AwsServiceEventsConfiguration\":{\"AwsService\":\"aws.ssm\",\"Pattern\":\"" + + escaped(pattern) + "\",\"OnFailureConfiguration\":{}}}"), described.getConfiguration()); + } + + @Test + void describeKeepsAnEmptyPattern() { + EventSourceV2 source = service.createEventSource(create("svc", + "{\"AwsService\":\"aws.ssm\",\"Pattern\":\"\"}"), REGION); + + assertEquals("", service.describeEventSource(arn(source.getArn()), REGION).getConfiguration() + .path("AwsServiceEventsConfiguration").path("Pattern").textValue()); + assertEquals("{\"source\":[\"aws.ssm\"],\"account\":[\"000000000000\"],\"region\":[\"us-east-1\"]}", + lastPutRule().pattern()); + } + + @Test + void createPutsTheManagedRuleOnTheDefaultBusWithOneTarget() { + EventSourceV2 source = service.createEventSource(create("svc", "{\"AwsService\":\"aws.ssm\"}"), REGION); + + PutRule rule = lastPutRule(); + String id = source.getArn().substring(source.getArn().length() - 25); + assertEquals(id, rule.name()); + assertEquals("events.amazonaws.com", rule.managedBy()); + assertEquals("{\"source\":[\"aws.ssm\"],\"account\":[\"000000000000\"],\"region\":[\"us-east-1\"]}", + rule.pattern()); + assertEquals(id, rule.target().getId()); + assertEquals(bus, rule.target().getArn()); + assertNull(rule.target().getRoleArn()); + assertNull(rule.target().getDeadLetterConfig()); + assertEquals(REGION, rule.region()); + } + + @Test + void thePatternMembersFollowTheForwardingKeysInTheirOwnOrder() { + service.createEventSource(create("svc", "{\"AwsService\":\"aws.ssm\",\"Pattern\":\"" + + escaped("{\"detail\":{\"name\":[\"/a\"]},\"detail-type\":[\"Parameter Store Change\"]}") + "\"}"), + REGION); + + assertEquals("{\"source\":[\"aws.ssm\"],\"account\":[\"000000000000\"],\"region\":[\"us-east-1\"]," + + "\"detail\":{\"name\":[\"/a\"]},\"detail-type\":[\"Parameter Store Change\"]}", + lastPutRule().pattern()); + } + + @Test + void theOnFailureQueueBecomesTheDeadLetterConfigOfTheTarget() { + service.createEventSource(create("svc", + "{\"AwsService\":\"aws.ssm\",\"OnFailureConfiguration\":{\"Arn\":\"" + QUEUE + "\"}}"), REGION); + + assertEquals(QUEUE, lastPutRule().target().getDeadLetterConfig().arn()); + } + + @Test + void anOnFailureConfigurationWithNoArnLeavesNoDeadLetterConfig() { + service.createEventSource(create("svc", "{\"AwsService\":\"aws.ssm\",\"OnFailureConfiguration\":{}}"), REGION); + + assertNull(lastPutRule().target().getDeadLetterConfig()); + } + + @Test + void twoSourcesOfOneServiceShareABus() { + service.createEventSource(create("one", "{\"AwsService\":\"aws.ssm\"}"), REGION); + service.createEventSource(create("two", "{\"AwsService\":\"aws.ssm\"}"), REGION); + + verify(eventBridge, times(2)).putManagedRule(any(), any(), any(), any(), eq(REGION)); + } + + @Test + void listTellsTheTypeOfEachSource() { + service.createEventSource(create("svc", "{\"AwsService\":\"aws.ssm\"}"), REGION); + service.createEventSource(json("{\"ClientToken\":\"w\",\"Name\":\"hook\",\"EventBusArn\":\"" + bus + "\"," + + "\"Configuration\":{\"WebhookEventsConfiguration\":{\"AuthConfiguration\":" + + "{\"StaticTokenAuthConfiguration\":{\"TokenHttpHeader\":\"X-Token\"}},\"RoleArn\":\"" + ROLE + + "\"}}}"), REGION); + + PaginatedResult page = service.listEventSources(json("{}"), REGION); + + assertEquals(Set.of("AWS_SERVICE_EVENTS", "WEBHOOK_EVENTS"), page.items().stream() + .map(ServiceEventsConfigurations::typeOf).collect(Collectors.toSet())); + } + + // ──────────────────────────── Checks ──────────────────────────── + + @Test + void aPatternThatIsNotJsonIsRefused() { + assertEquals("Pattern is not valid JSON", refusal("{\"AwsService\":\"aws.ssm\",\"Pattern\":\"{oops\"}")); + } + + @Test + void aPatternThatIsNotAnObjectIsRefused() { + assertEquals("Pattern must be a JSON object", refusal("{\"AwsService\":\"aws.ssm\",\"Pattern\":\"[]\"}")); + } + + @Test + void aPatternMayNotSetTheKeysTheForwardingRuleSets() { + for (String key : List.of("source", "account", "region")) { + assertEquals("Pattern must not set the key '" + key + "'; the forwarding rule sets it from the requested " + + "AwsService and the source account and region", refusal("{\"AwsService\":\"aws.ssm\"," + + "\"Pattern\":\"{\\\"" + key + "\\\":[\\\"x\\\"]}\"}")); + } + } + + @Test + void theFirstReservedKeyInThePatternsOwnOrderIsNamed() { + assertEquals("Pattern must not set the key 'region'; the forwarding rule sets it from the requested " + + "AwsService and the source account and region", refusal("{\"AwsService\":\"aws.ssm\"," + + "\"Pattern\":\"{\\\"region\\\":[\\\"x\\\"],\\\"source\\\":[\\\"y\\\"]}\"}")); + } + + @Test + void onlyTheTopLevelKeysAreReserved() { + service.createEventSource(create("svc", "{\"AwsService\":\"aws.ssm\",\"Pattern\":\"" + + escaped("{\"detail\":{\"source\":[\"x\"]}}") + "\"}"), REGION); + + verify(eventBridge).putManagedRule(any(), any(), any(), any(), eq(REGION)); + } + + @Test + void theDeadLetterQueueMustBeInTheCallersRegion() { + assertEquals("OnFailureConfiguration.Arn region 'us-west-2' must match the caller's region 'us-east-1'", + refusal("{\"AwsService\":\"aws.ssm\",\"OnFailureConfiguration\":{\"Arn\":" + + "\"arn:aws:sqs:us-west-2:000000000000:dead\"}}")); + } + + @Test + void theDeadLetterQueueMustBeInTheCallersAccount() { + assertEquals("OnFailureConfiguration.Arn account '111111111111' must match the caller's account " + + "'000000000000'", refusal("{\"AwsService\":\"aws.ssm\",\"OnFailureConfiguration\":{\"Arn\":" + + "\"arn:aws:sqs:us-east-1:111111111111:dead\"}}")); + } + + @Test + void theDeadLetterQueueMayNotBeFifo() { + assertEquals("OnFailureConfiguration.Arn must name a standard SQS queue: FIFO queues are not supported as " + + "EventSource dead-letter queues", refusal("{\"AwsService\":\"aws.ssm\"," + + "\"OnFailureConfiguration\":{\"Arn\":\"arn:aws:sqs:us-east-1:000000000000:dead.fifo\"}}")); + } + + @Test + void theRegionOfTheQueueIsCheckedBeforeItsAccountAndItsAccountBeforeFifo() { + assertEquals("OnFailureConfiguration.Arn region 'us-west-2' must match the caller's region 'us-east-1'", + refusal("{\"AwsService\":\"aws.ssm\",\"OnFailureConfiguration\":{\"Arn\":" + + "\"arn:aws:sqs:us-west-2:111111111111:dead.fifo\"}}")); + assertEquals("OnFailureConfiguration.Arn account '111111111111' must match the caller's account " + + "'000000000000'", refusal("{\"AwsService\":\"aws.ssm\",\"OnFailureConfiguration\":{\"Arn\":" + + "\"arn:aws:sqs:us-east-1:111111111111:dead.fifo\"}}")); + } + + @Test + void thePatternIsCheckedBeforeTheDeadLetterQueue() { + assertEquals("Pattern is not valid JSON", refusal("{\"AwsService\":\"aws.ssm\",\"Pattern\":\"{oops\"," + + "\"OnFailureConfiguration\":{\"Arn\":\"arn:aws:sqs:us-west-2:000000000000:dead\"}}")); + } + + @Test + void theChecksComeBeforeTheBusLookup() { + AwsException e = assertThrows(AwsException.class, () -> service.createEventSource(request("svc", + missingBus(), "{\"AwsService\":\"aws.ssm\",\"Pattern\":\"[]\"}"), REGION)); + assertEquals("Pattern must be a JSON object", e.getMessage()); + } + + @Test + void theBusLookupComesBeforeProvisioning() { + AwsException e = assertThrows(AwsException.class, () -> service.createEventSource(request("svc", + missingBus(), "{\"AwsService\":\"aws.ssm\",\"Pattern\":\"{}\"}"), REGION)); + assertEquals("ResourceNotFoundException", e.getErrorCode()); + assertEquals("Resource does not exist", e.getMessage()); + } + + @Test + void aRefusalOtherThanProvisioningStoresNothing() { + refusal("{\"AwsService\":\"aws.ssm\",\"Pattern\":\"[]\"}"); + + assertTrue(service.listEventSources(json("{}"), REGION).items().isEmpty()); + verify(eventBridge, never()).putManagedRule(any(), any(), any(), any(), any()); + } + + // ──────────────────────────── CREATE_FAILED ──────────────────────────── + + @Test + void aPatternNoRuleCanUseLeavesACreateFailedSource() { + for (String pattern : List.of("{}", "{\"detail-type\":\"Object Created\"}")) { + String name = "f" + Math.abs(pattern.hashCode()); + AwsException e = assertThrows(AwsException.class, () -> service.createEventSource(create(name, + "{\"AwsService\":\"aws.s3\",\"Pattern\":\"" + escaped(pattern) + "\"}"), REGION)); + + assertEquals("InvalidInputException", e.getErrorCode()); + assertEquals(400, e.getHttpStatus()); + assertEquals(PROVISIONING_FAILED, e.getMessage()); + } + + List listed = service.listEventSources(json("{}"), REGION).items(); + assertEquals(2, listed.size()); + assertTrue(listed.stream().allMatch(source -> "CREATE_FAILED".equals(source.getState()))); + verify(eventBridge, never()).putManagedRule(any(), any(), any(), any(), any()); + } + + @Test + void aPatternEventBridgeRefusesLeavesACreateFailedSource() { + doThrow(new AwsException("InvalidEventPatternException", "refused", 400)) + .when(eventBridge).validateEventPattern(any()); + + AwsException e = assertThrows(AwsException.class, () -> service.createEventSource(create("svc", + "{\"AwsService\":\"aws.s3\",\"Pattern\":\"" + escaped("{\"detail-type\":[\"x\"]}") + "\"}"), REGION)); + + assertEquals(PROVISIONING_FAILED, e.getMessage()); + assertEquals("CREATE_FAILED", service.listEventSources(json("{}"), REGION).items().getFirst().getState()); + } + + @Test + void aCreateFailedSourceIsDescribedAndKeepsItsNameTaken() { + failCreate("svc"); + EventSourceV2 stored = service.listEventSources(json("{}"), REGION).items().getFirst(); + + assertEquals("CREATE_FAILED", service.describeEventSource(arn(stored.getArn()), REGION).getState()); + AwsException e = assertThrows(AwsException.class, () -> service.createEventSource( + create("svc", "{\"AwsService\":\"aws.s3\"}", "other"), REGION)); + assertEquals("ResourceAlreadyExistsException", e.getErrorCode()); + } + + @Test + void aRetryOfACreateFailedSourceAnswersTheSame400() { + JsonNode request = create("svc", "{\"AwsService\":\"aws.s3\",\"Pattern\":\"{}\"}"); + assertThrows(AwsException.class, () -> service.createEventSource(request, REGION)); + + AwsException e = assertThrows(AwsException.class, () -> service.createEventSource(request, REGION)); + + assertEquals(PROVISIONING_FAILED, e.getMessage()); + assertEquals(1, service.listEventSources(json("{}"), REGION).items().size()); + } + + @Test + void aCreateFailedSourceDoesNotBlockDeletingItsBus() { + failCreate("svc"); + + service.deleteEventBus(bus, REGION); + } + + @Test + void aCreateFailedSourceIsNotFoundOnceItsBusIsGoneButStaysListedAndDeletable() { + failCreate("svc"); + EventSourceV2 stored = service.listEventSources(json("{}"), REGION).items().getFirst(); + service.deleteEventBus(bus, REGION); + + AwsException e = assertThrows(AwsException.class, + () -> service.describeEventSource(arn(stored.getArn()), REGION)); + + assertEquals("ResourceNotFoundException", e.getErrorCode()); + assertEquals(404, e.getHttpStatus()); + assertEquals("Resource does not exist", e.getMessage()); + assertEquals(1, service.listEventSources(json("{}"), REGION).items().size()); + service.deleteEventSource(arn(stored.getArn()), REGION); + assertTrue(service.listEventSources(json("{}"), REGION).items().isEmpty()); + } + + // ──────────────────────────── Update ──────────────────────────── + + @Test + void updateReplacesTheConfigurationAndRewritesTheRule() { + EventSourceV2 source = service.createEventSource(create("svc", "{\"AwsService\":\"aws.ssm\",\"Pattern\":\"" + + escaped("{\"detail-type\":[\"x\"]}") + "\",\"OnFailureConfiguration\":{\"Arn\":\"" + QUEUE + + "\"}}"), REGION); + + EventSourceV2 updated = service.updateEventSource(update(source, "{\"AwsService\":\"aws.s3\"}"), REGION); + + assertEquals("ACTIVE", updated.getState()); + assertEquals(json("{\"AwsServiceEventsConfiguration\":{\"AwsService\":\"aws.s3\"}}"), + updated.getConfiguration()); + PutRule rule = lastPutRule(); + assertEquals("{\"source\":[\"aws.s3\"],\"account\":[\"000000000000\"],\"region\":[\"us-east-1\"]}", + rule.pattern()); + assertNull(rule.target().getDeadLetterConfig()); + } + + @Test + void aDescriptionOnlyUpdateLeavesTheRuleAlone() { + EventSourceV2 source = service.createEventSource(create("svc", "{\"AwsService\":\"aws.ssm\"}"), REGION); + clock.advance(Duration.ofMinutes(1)); + + EventSourceV2 updated = service.updateEventSource(json("{\"EventSourceArn\":\"" + source.getArn() + + "\",\"Description\":\"d\"}"), REGION); + + assertEquals("d", updated.getDescription()); + assertEquals(NOW.plus(Duration.ofMinutes(1)), updated.getLastModifiedTime()); + verify(eventBridge, times(1)).putManagedRule(any(), any(), any(), any(), any()); + } + + @Test + void updateRefusesAnotherVariantWithTheTypeOfTheSource() { + EventSourceV2 source = service.createEventSource(create("svc", "{\"AwsService\":\"aws.ssm\"}"), REGION); + + AwsException e = assertThrows(AwsException.class, () -> service.updateEventSource(json( + "{\"EventSourceArn\":\"" + source.getArn() + "\",\"Configuration\":{\"PartnerEventsConfiguration\":" + + "{\"PartnerEventSourceArn\":\"" + PARTNER + "\"}}}"), REGION)); + + assertEquals("EventSource type is immutable: the configuration variant must remain AWS_SERVICE_EVENTS", + e.getMessage()); + } + + @Test + void updateRunsTheChecksOfCreate() { + EventSourceV2 source = service.createEventSource(create("svc", "{\"AwsService\":\"aws.ssm\"}"), REGION); + + AwsException e = assertThrows(AwsException.class, () -> service.updateEventSource(update(source, + "{\"AwsService\":\"aws.ssm\",\"Pattern\":\"{\\\"account\\\":[\\\"1\\\"]}\"}"), REGION)); + + assertEquals("Pattern must not set the key 'account'; the forwarding rule sets it from the requested " + + "AwsService and the source account and region", e.getMessage()); + } + + @Test + void aFailedUpdateStoresTheNewConfigurationAndLeavesTheRule() { + EventSourceV2 source = service.createEventSource(create("svc", "{\"AwsService\":\"aws.ssm\"}"), REGION); + clock.advance(Duration.ofMinutes(1)); + + AwsException e = assertThrows(AwsException.class, () -> service.updateEventSource(update(source, + "{\"AwsService\":\"aws.s3\",\"Pattern\":\"{}\"}", "new"), REGION)); + + assertEquals(PROVISIONING_FAILED, e.getMessage()); + EventSourceV2 stored = service.describeEventSource(arn(source.getArn()), REGION); + assertEquals("UPDATE_FAILED", stored.getState()); + assertEquals("new", stored.getDescription()); + assertEquals("aws.s3", stored.getConfiguration().path("AwsServiceEventsConfiguration").path("AwsService") + .textValue()); + assertEquals(NOW.plus(Duration.ofMinutes(1)), stored.getLastModifiedTime()); + verify(eventBridge, times(1)).putManagedRule(any(), any(), any(), any(), any()); + } + + @Test + void aValidUpdateAfterAFailedOneMakesTheSourceActiveAndRewritesTheRule() { + EventSourceV2 source = service.createEventSource(create("svc", "{\"AwsService\":\"aws.ssm\"}"), REGION); + assertThrows(AwsException.class, () -> service.updateEventSource(update(source, + "{\"AwsService\":\"aws.s3\",\"Pattern\":\"{}\"}"), REGION)); + + EventSourceV2 updated = service.updateEventSource(update(source, "{\"AwsService\":\"aws.s3\"}"), REGION); + + assertEquals("ACTIVE", updated.getState()); + assertEquals("{\"source\":[\"aws.s3\"],\"account\":[\"000000000000\"],\"region\":[\"us-east-1\"]}", + lastPutRule().pattern()); + } + + @Test + void aValidUpdateOfACreateFailedSourceMakesItActiveAndCreatesTheRule() { + failCreate("svc"); + EventSourceV2 source = service.listEventSources(json("{}"), REGION).items().getFirst(); + + EventSourceV2 updated = service.updateEventSource(update(source, "{\"AwsService\":\"aws.s3\"}"), REGION); + + assertEquals("ACTIVE", updated.getState()); + assertEquals(ruleArn(source).substring(RULE_ARN_PREFIX.length()), lastPutRule().name()); + } + + @Test + void aSourceWhoseBusIsGoneAnswersEveryUpdateWithNotFound() { + failCreate("svc"); + EventSourceV2 stored = service.listEventSources(json("{}"), REGION).items().getFirst(); + service.deleteEventBus(bus, REGION); + + for (JsonNode request : List.of(update(stored, "{\"AwsService\":\"aws.s3\"}"), + json("{\"EventSourceArn\":\"" + stored.getArn() + "\",\"Description\":\"d\"}"))) { + AwsException e = assertThrows(AwsException.class, () -> service.updateEventSource(request, REGION)); + assertEquals("ResourceNotFoundException", e.getErrorCode()); + assertEquals(404, e.getHttpStatus()); + assertEquals("Resource does not exist", e.getMessage()); + } + AwsException json = assertThrows(AwsException.class, () -> service.updateEventSource(update(stored, + "{\"AwsService\":\"aws.s3\",\"Pattern\":\"{oops\"}"), REGION)); + assertEquals("Pattern is not valid JSON", json.getMessage()); + verify(eventBridge, never()).putManagedRule(any(), any(), any(), any(), any()); + assertEquals("CREATE_FAILED", service.listEventSources(json("{}"), REGION).items().getFirst().getState()); + } + + @Test + void aRevokedSourceCannotBeUpdated() { + EventSourceV2 source = service.createEventSource(create("svc", "{\"AwsService\":\"aws.ssm\"}"), REGION); + service.revokeResource(json("{\"Arn\":\"" + source.getArn() + "\"}"), REGION); + + AwsException e = assertThrows(AwsException.class, () -> service.updateEventSource(update(source, + "{\"AwsService\":\"aws.s3\"}"), REGION)); + + assertEquals("InvalidStateException", e.getErrorCode()); + assertEquals(409, e.getHttpStatus()); + assertEquals("EventSource is revoked and cannot be updated", e.getMessage()); + } + + // ──────────────────────────── Delete, revoke and the bus ──────────────────────────── + + @Test + void deleteRemovesTheManagedRule() { + EventSourceV2 source = service.createEventSource(create("svc", "{\"AwsService\":\"aws.ssm\"}"), REGION); + + service.deleteEventSource(arn(source.getArn()), REGION); + + verify(eventBridge).deleteManagedRule(ruleArn(source).substring(RULE_ARN_PREFIX.length()), REGION); + assertTrue(service.listEventSources(json("{}"), REGION).items().isEmpty()); + } + + @Test + void revokeKeepsTheRuleAndTheState() { + EventSourceV2 source = service.createEventSource(create("svc", "{\"AwsService\":\"aws.ssm\"}"), REGION); + + service.revokeResource(json("{\"Arn\":\"" + source.getArn() + "\"}"), REGION); + + EventSourceV2 described = service.describeEventSource(arn(source.getArn()), REGION); + assertTrue(described.isRevoked()); + assertEquals("ACTIVE", described.getState()); + verify(eventBridge, never()).deleteManagedRule(any(), any()); + } + + @Test + void anActiveSourceBlocksDeletingItsBusAndARevokedOneDoesNot() { + EventSourceV2 source = service.createEventSource(create("svc", "{\"AwsService\":\"aws.ssm\"}"), REGION); + + AwsException e = assertThrows(AwsException.class, () -> service.deleteEventBus(bus, REGION)); + assertEquals("ResourceInUseException", e.getErrorCode()); + assertEquals("The event bus cannot be deleted because it has one or more event sources that are not " + + "revoked. Delete or revoke them and retry.", e.getMessage()); + + service.revokeResource(json("{\"Arn\":\"" + source.getArn() + "\"}"), REGION); + service.deleteEventBus(bus, REGION); + } + + @Test + void rotatingTheCredentialsOfAServiceSourceFailsTheArnPattern() { + EventSourceV2 source = service.createEventSource(create("svc", "{\"AwsService\":\"aws.ssm\"}"), REGION); + + AwsException e = assertThrows(AwsException.class, () -> service.rotateWebhookCredentials(json( + "{\"EventSourceArn\":\"" + source.getArn() + "\",\"ClientToken\":\"t\"}"), REGION)); + + assertEquals("InvalidInputException", e.getErrorCode()); + assertTrue(e.getMessage().contains("Value '" + source.getArn() + "' at 'eventSourceArn'"), e.getMessage()); + } + + // ──────────────────────────── Partner sources ──────────────────────────── + + @Test + void aPartnerSourceFailsAsAMissingPartnerSource() { + AwsException e = assertThrows(AwsException.class, () -> service.createEventSource( + partner("{\"PartnerEventSourceArn\":\"" + PARTNER + "\"}"), REGION)); + + assertEquals("InvalidInputException", e.getErrorCode()); + assertEquals(400, e.getHttpStatus()); + assertEquals("The partner event source aws.partner/example.com/123/orders could not be described: Event " + + "source aws.partner/example.com/123/orders does not exist.", e.getMessage()); + assertTrue(service.listEventSources(json("{}"), REGION).items().isEmpty()); + } + + @Test + void thePartnerSourceMustBeInTheCallersRegion() { + assertEquals("PartnerEventSourceArn region 'us-west-2' must match the caller's region 'us-east-1'", + partnerRefusal("{\"PartnerEventSourceArn\":\"" + PARTNER.replace("us-east-1", "us-west-2") + "\"}")); + } + + @Test + void aPartnerPatternGetsTheJsonChecksButNotTheReservedKeyCheck() { + assertEquals("Pattern is not valid JSON", partnerRefusal("{\"PartnerEventSourceArn\":\"" + PARTNER + + "\",\"Pattern\":\"{oops\"}")); + assertEquals("Pattern must be a JSON object", partnerRefusal("{\"PartnerEventSourceArn\":\"" + PARTNER + + "\",\"Pattern\":\"[]\"}")); + assertTrue(partnerRefusal("{\"PartnerEventSourceArn\":\"" + PARTNER + + "\",\"Pattern\":\"{\\\"source\\\":[\\\"x\\\"]}\"}").contains("does not exist")); + } + + @Test + void aPartnerSourceRunsTheDeadLetterChecksBeforeTheRegionAndTheBusLookup() { + assertEquals("OnFailureConfiguration.Arn must name a standard SQS queue: FIFO queues are not supported as " + + "EventSource dead-letter queues", partnerRefusal("{\"PartnerEventSourceArn\":\"" + + PARTNER.replace("us-east-1", "us-west-2") + "\",\"OnFailureConfiguration\":{\"Arn\":" + + "\"arn:aws:sqs:us-east-1:000000000000:dead.fifo\"}}")); + } + + @Test + void aPartnerSourceLooksUpTheBusBeforeThePartnerSource() { + AwsException e = assertThrows(AwsException.class, () -> service.createEventSource(json( + "{\"ClientToken\":\"t\",\"Name\":\"p\",\"EventBusArn\":\"" + missingBus() + "\",\"Configuration\":" + + "{\"PartnerEventsConfiguration\":{\"PartnerEventSourceArn\":\"" + PARTNER + "\"}}}"), + REGION)); + + assertEquals("ResourceNotFoundException", e.getErrorCode()); + } + + // ──────────────────────────── Forwarding ──────────────────────────── + + @Test + void aServiceEventReachesTheSubscribersOfTheBusOnce() { + EventSourceV2 source = service.createEventSource(create("svc", "{\"AwsService\":\"aws.ssm\"}"), REGION); + subscribe(); + String ruleName = ruleArn(source); + String event = "{\"version\":\"0\",\"id\":\"11111111-2222-3333-4444-555555555555\"," + + "\"detail-type\":\"Parameter Store Change\",\"source\":\"aws.ssm\",\"account\":\"000000000000\"," + + "\"time\":\"2026-11-27T12:00:00Z\",\"region\":\"us-east-1\",\"resources\":[],\"detail\":{}}"; + + service.forwardServiceEvent(bus, ruleName, event); + service.forwardServiceEvent(bus, ruleName, event); + + ArgumentCaptor delivered = ArgumentCaptor.forClass(PublishedEvent.class); + verify(delivery, times(1)).deliver(any(), delivered.capture()); + PublishedEvent published = delivered.getValue(); + assertEquals(json(event), published.data()); + assertEquals(json("{}"), published.metadata()); + assertEquals(List.of("EventGroupId", "DeduplicationId", "ContentType", "aws:IngestionTime", "aws:Source", + "aws:DetailType", "aws:EventId", "aws:SequenceNumber", "aws:DeliveryType"), + published.systemMetadata().propertyStream().map(Map.Entry::getKey).toList()); + assertEquals("11111111-2222-3333-4444-555555555555", published.systemMetadata().path("EventGroupId") + .textValue()); + assertEquals("11111111-2222-3333-4444-555555555555", published.systemMetadata().path("DeduplicationId") + .textValue()); + assertEquals("application/eventbridge+json", published.systemMetadata().path("ContentType").textValue()); + assertEquals("aws.ssm", published.systemMetadata().path("aws:Source").textValue()); + assertEquals("Parameter Store Change", published.systemMetadata().path("aws:DetailType").textValue()); + assertEquals("LIVE", published.systemMetadata().path("aws:DeliveryType").textValue()); + assertEquals("1", published.systemMetadata().path("aws:SequenceNumber").textValue()); + } + + @Test + void anUpdateFailedSourceStillTakesEventsThroughItsEarlierRule() { + EventSourceV2 source = service.createEventSource(create("svc", "{\"AwsService\":\"aws.ssm\"}"), REGION); + subscribe(); + assertThrows(AwsException.class, () -> service.updateEventSource(update(source, + "{\"AwsService\":\"aws.ssm\",\"Pattern\":\"{}\"}"), REGION)); + assertEquals("UPDATE_FAILED", service.describeEventSource(arn(source.getArn()), REGION).getState()); + + service.forwardServiceEvent(bus, ruleArn(source), + "{\"id\":\"e1\",\"source\":\"aws.ssm\",\"detail-type\":\"x\",\"detail\":{}}"); + + verify(delivery, times(1)).deliver(any(), any()); + } + + @Test + void aUserRuleNamedLikeASourceDeliversNothing() { + failCreate("svc"); + EventSourceV2 failed = service.listEventSources(json("{}"), REGION).items().getFirst(); + subscribe(); + String event = "{\"id\":\"e1\",\"source\":\"x\",\"detail-type\":\"x\",\"detail\":{}}"; + when(eventBridge.isManagedRule(any(), any())).thenReturn(false); + + service.forwardServiceEvent(bus, ruleArn(failed), event); + + verify(delivery, never()).deliver(any(), any()); + } + + @Test + void aRuleOnACustomBusOrInAnotherAccountDeliversNothing() { + EventSourceV2 source = service.createEventSource(create("svc", "{\"AwsService\":\"aws.ssm\"}"), REGION); + subscribe(); + String id = ruleArn(source).substring(RULE_ARN_PREFIX.length()); + String event = "{\"id\":\"e1\",\"source\":\"aws.ssm\",\"detail-type\":\"x\",\"detail\":{}}"; + + service.forwardServiceEvent(bus, RULE_ARN_PREFIX + "custom/" + id, event); + service.forwardServiceEvent(bus, "arn:aws:events:us-east-1:111111111111:rule/" + id, event); + service.forwardServiceEvent(bus, "arn:aws:events:us-west-2:000000000000:rule/" + id, event); + + verify(delivery, never()).deliver(any(), any()); + } + + @Test + void aRevokedSourceTakesNoEvents() { + EventSourceV2 source = service.createEventSource(create("svc", "{\"AwsService\":\"aws.ssm\"}"), REGION); + subscribe(); + service.revokeResource(json("{\"Arn\":\"" + source.getArn() + "\"}"), REGION); + + service.forwardServiceEvent(bus, ruleArn(source), + "{\"id\":\"e1\",\"source\":\"aws.ssm\",\"detail-type\":\"x\",\"detail\":{}}"); + + verify(delivery, never()).deliver(any(), any()); + } + + @Test + void aRuleWithNoSourceTakesNoEvents() { + subscribe(); + + service.forwardServiceEvent(bus, RULE_ARN_PREFIX + "abcdefghijklmnopqrstuvwxy", + "{\"id\":\"e1\",\"source\":\"aws.ssm\",\"detail-type\":\"x\",\"detail\":{}}"); + + verify(delivery, never()).deliver(any(), any()); + } + + @Test + void oneEventPerEventIdIsDeliveredWhenTwoSourcesShareABus() { + EventSourceV2 one = service.createEventSource(create("one", "{\"AwsService\":\"aws.ssm\"}"), REGION); + EventSourceV2 two = service.createEventSource(create("two", "{\"AwsService\":\"aws.ssm\"}"), REGION); + subscribe(); + String event = "{\"id\":\"e1\",\"source\":\"aws.ssm\",\"detail-type\":\"x\",\"detail\":{}}"; + + service.forwardServiceEvent(bus, ruleArn(one), event); + service.forwardServiceEvent(bus, ruleArn(two), event); + + verify(delivery, times(1)).deliver(any(), any()); + } + + // ──────────────────────────── Helpers ──────────────────────────── + + private record PutRule(String name, String managedBy, String pattern, Target target, String region) { + } + + private PutRule lastPutRule() { + ArgumentCaptor name = ArgumentCaptor.forClass(String.class); + ArgumentCaptor managedBy = ArgumentCaptor.forClass(String.class); + ArgumentCaptor pattern = ArgumentCaptor.forClass(String.class); + ArgumentCaptor target = ArgumentCaptor.forClass(Target.class); + ArgumentCaptor region = ArgumentCaptor.forClass(String.class); + verify(eventBridge, atLeastOnce()).putManagedRule(name.capture(), managedBy.capture(), + pattern.capture(), target.capture(), region.capture()); + int last = name.getAllValues().size() - 1; + return new PutRule(name.getAllValues().get(last), managedBy.getAllValues().get(last), + pattern.getAllValues().get(last), target.getAllValues().get(last), region.getAllValues().get(last)); + } + + private static String ruleArn(EventSourceV2 source) { + return RULE_ARN_PREFIX + source.getArn().substring(source.getArn().length() - 25); + } + + private void subscribe() { + service.createSubscriber(json("{\"Name\":\"s\",\"EventBusArn\":\"" + bus + "\",\"InvokeConfiguration\":" + + "{\"TargetArn\":\"arn:aws:sqs:us-east-1:000000000000:q\",\"RoleArn\":\"" + ROLE + "\"}}"), REGION); + } + + private void failCreate(String name) { + assertThrows(AwsException.class, () -> service.createEventSource(create(name, + "{\"AwsService\":\"aws.s3\",\"Pattern\":\"{}\"}"), REGION)); + } + + private String refusal(String awsServiceConfiguration) { + return assertThrows(AwsException.class, () -> service.createEventSource( + create("svc", awsServiceConfiguration), REGION)).getMessage(); + } + + private String partnerRefusal(String partnerConfiguration) { + return assertThrows(AwsException.class, () -> service.createEventSource(partner(partnerConfiguration), + REGION)).getMessage(); + } + + private String missingBus() { + return bus.substring(0, bus.lastIndexOf('/') + 1).replace("orders", "gone") + "abcdefghijklmnopqrstuvwxy"; + } + + private JsonNode create(String name, String awsServiceConfiguration) { + return create(name, awsServiceConfiguration, null); + } + + private JsonNode create(String name, String awsServiceConfiguration, String description) { + return request(name, bus, awsServiceConfiguration, description); + } + + private JsonNode request(String name, String busArn, String awsServiceConfiguration) { + return request(name, busArn, awsServiceConfiguration, null); + } + + private JsonNode request(String name, String busArn, String awsServiceConfiguration, String description) { + String token = "t" + Integer.toHexString((name + busArn + awsServiceConfiguration).hashCode()); + return json("{\"ClientToken\":\"" + token + "\",\"Name\":\"" + name + "\",\"EventBusArn\":\"" + busArn + + "\",\"Configuration\":{\"AwsServiceEventsConfiguration\":" + awsServiceConfiguration + "}" + + (description == null ? "" : ",\"Description\":\"" + description + "\"") + "}"); + } + + private JsonNode partner(String partnerConfiguration) { + return json("{\"ClientToken\":\"p\",\"Name\":\"p\",\"EventBusArn\":\"" + bus + "\",\"Configuration\":" + + "{\"PartnerEventsConfiguration\":" + partnerConfiguration + "}}"); + } + + private static JsonNode update(EventSourceV2 source, String awsServiceConfiguration) { + return update(source, awsServiceConfiguration, null); + } + + private static JsonNode update(EventSourceV2 source, String awsServiceConfiguration, String description) { + return json("{\"EventSourceArn\":\"" + source.getArn() + "\",\"Configuration\":" + + "{\"AwsServiceEventsConfiguration\":" + awsServiceConfiguration + "}" + + (description == null ? "" : ",\"Description\":\"" + description + "\"") + "}"); + } + + private static JsonNode arn(String arn) { + return json("{\"EventSourceArn\":\"" + arn + "\"}"); + } + + private static String escaped(String json) { + return json.replace("\\", "\\\\").replace("\"", "\\\""); + } + + private static JsonNode json(String json) { + try { + return MAPPER.readTree(json); + } catch (Exception e) { + throw new IllegalArgumentException(json, e); + } + } +} diff --git a/src/test/java/io/floci/aws/services/eventbridgev2/EventBridgeV2EventSourcesTest.java b/src/test/java/io/floci/aws/services/eventbridgev2/EventBridgeV2EventSourcesTest.java index 0563c39002..510277c37c 100644 --- a/src/test/java/io/floci/aws/services/eventbridgev2/EventBridgeV2EventSourcesTest.java +++ b/src/test/java/io/floci/aws/services/eventbridgev2/EventBridgeV2EventSourcesTest.java @@ -8,19 +8,18 @@ import io.floci.aws.core.common.AwsException; import io.floci.aws.core.common.PaginatedResult; import io.floci.aws.core.common.RegionResolver; import io.floci.aws.core.storage.AccountAwareStorageBackend; +import io.floci.aws.services.eventbridge.EventBridgeService; import io.floci.aws.services.eventbridgev2.model.EventBusV2; import io.floci.aws.services.eventbridgev2.model.EventSourceV2; import io.floci.aws.services.secretsmanager.SecretsManagerService; import io.floci.aws.services.secretsmanager.model.Secret; +import io.floci.aws.testing.ManualClock; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.mockito.ArgumentCaptor; -import java.time.Clock; import java.time.Duration; import java.time.Instant; -import java.time.ZoneId; -import java.time.ZoneOffset; import java.util.Base64; import java.util.List; import java.util.Map; @@ -57,7 +56,8 @@ class EventBridgeV2EventSourcesTest { private SecretsManagerService secrets; private TlsCertificateManager certificateManager; private EventBridgeV2Service service; - private TestClock clock; + private ManualClock clock; + private EventBridgeService eventBridge; private String bus; @BeforeEach @@ -69,12 +69,13 @@ class EventBridgeV2EventSourcesTest { return secret; }); when(secrets.describeSecret(any(), any())).thenReturn(new Secret()); - clock = new TestClock(NOW); + clock = new ManualClock(NOW); RegionResolver regionResolver = new RegionResolver(REGION, ACCOUNT); certificateManager = mock(TlsCertificateManager.class); + eventBridge = mock(EventBridgeService.class); EventBridgeV2EventSources eventSources = new EventBridgeV2EventSources( AccountAwareStorageBackend.inMemory(ACCOUNT), secrets, regionResolver, clock, "http://floci.test:4566", - certificateManager); + certificateManager, eventBridge); service = new EventBridgeV2Service(AccountAwareStorageBackend.inMemory(ACCOUNT), AccountAwareStorageBackend.inMemory(ACCOUNT), regionResolver, mock(EventBridgeV2Delivery.class), eventSources, clock, true); @@ -262,14 +263,6 @@ class EventBridgeV2EventSourcesTest { assertEquals("Event bus not found: orders", e.getMessage()); } - @Test - void createRefusesAnotherVariantWithFlociOwnWording() { - AwsException e = assertThrows(AwsException.class, () -> service.createEventSource(json( - "{\"Name\":\"hook\",\"ClientToken\":\"t\",\"EventBusArn\":\"" + bus + "\",\"Configuration\":" - + "{\"AwsServiceEventsConfiguration\":{\"AwsService\":\"aws.s3\"}}}"), REGION)); - assertEquals("Only WebhookEventsConfiguration event sources are supported.", e.getMessage()); - } - @Test void createWithoutAClientTokenIsRefusedBeforeTheSemanticRules() { ObjectNode request = create("hook", bus, "{\"BasicHttpAuthConfiguration\":{\"Username\":\"u\"}}"); @@ -401,7 +394,7 @@ class EventBridgeV2EventSourcesTest { doThrow(failure).when(failing).put(any(), any()); EventBridgeV2EventSources eventSources = new EventBridgeV2EventSources(failing, secrets, new RegionResolver(REGION, ACCOUNT), clock, "http://floci.test:4566", - certificateManager); + certificateManager, eventBridge); EventBusV2 existing = new EventBusV2(); existing.setArn(bus); @@ -855,31 +848,4 @@ class EventBridgeV2EventSourcesTest { throw new IllegalArgumentException(json, e); } } - - private static final class TestClock extends Clock { - private Instant now; - - TestClock(Instant now) { - this.now = now; - } - - void advance(Duration duration) { - now = now.plus(duration); - } - - @Override - public ZoneId getZone() { - return ZoneOffset.UTC; - } - - @Override - public Clock withZone(ZoneId zone) { - return this; - } - - @Override - public Instant instant() { - return now; - } - } } diff --git a/src/test/java/io/floci/aws/services/eventbridgev2/EventBridgeV2ServiceEventSourceIntegrationTest.java b/src/test/java/io/floci/aws/services/eventbridgev2/EventBridgeV2ServiceEventSourceIntegrationTest.java new file mode 100644 index 0000000000..852b45a2c1 --- /dev/null +++ b/src/test/java/io/floci/aws/services/eventbridgev2/EventBridgeV2ServiceEventSourceIntegrationTest.java @@ -0,0 +1,130 @@ +package io.floci.aws.services.eventbridgev2; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import io.floci.aws.testing.AwsTestClients; +import io.quarkus.test.junit.QuarkusTest; +import org.junit.jupiter.api.Test; +import software.amazon.awssdk.regions.Region; +import software.amazon.awssdk.services.eventbridge.EventBridgeClient; +import software.amazon.awssdk.services.eventbridge.model.DescribeRuleResponse; +import software.amazon.awssdk.services.eventbridge.model.ManagedRuleException; +import software.amazon.awssdk.services.eventbridge.model.ResourceNotFoundException; +import software.amazon.awssdk.services.eventbridgev2.EventBridgeV2Client; +import software.amazon.awssdk.services.eventbridgev2.model.CreateEventSourceResponse; +import software.amazon.awssdk.services.eventbridgev2.model.EventSourceConfiguration; +import software.amazon.awssdk.services.eventbridgev2.model.InvalidInputException; +import software.amazon.awssdk.services.eventbridgev2.model.TransformerType; +import software.amazon.awssdk.services.sqs.SqsClient; +import software.amazon.awssdk.services.sqs.model.Message; +import software.amazon.awssdk.services.sqs.model.QueueAttributeName; +import software.amazon.awssdk.services.ssm.SsmClient; +import software.amazon.awssdk.services.ssm.model.ParameterType; + +import java.time.Duration; +import java.util.ArrayList; +import java.util.List; + +import static org.awaitility.Awaitility.await; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +/** An AWS service event source forwards the service's events to its bus through a managed rule, through the SDKs. */ +@QuarkusTest +class EventBridgeV2ServiceEventSourceIntegrationTest { + + private static final ObjectMapper MAPPER = new ObjectMapper(); + private static final String ACCOUNT = "000000000000"; + private static final String ROLE = "arn:aws:iam::000000000000:role/EventBusDelivery"; + + @Test + void aServiceSourceDeliversTheServicesEventsToASubscriber() throws Exception { + String suffix = Long.toString(System.nanoTime(), 36); + try (EventBridgeV2Client events = AwsTestClients.create(EventBridgeV2Client.builder(), ACCOUNT, Region.US_EAST_1); + EventBridgeClient rules = AwsTestClients.create(EventBridgeClient.builder(), ACCOUNT, Region.US_EAST_1); + SqsClient sqs = AwsTestClients.create(SqsClient.builder(), ACCOUNT, Region.US_EAST_1); + SsmClient ssm = AwsTestClients.create(SsmClient.builder(), ACCOUNT, Region.US_EAST_1)) { + String queueUrl = sqs.createQueue(request -> request.queueName("v2-svc-" + suffix)).queueUrl(); + String queueArn = sqs.getQueueAttributes(request -> request.queueUrl(queueUrl) + .attributeNames(QueueAttributeName.QUEUE_ARN)).attributes().get(QueueAttributeName.QUEUE_ARN); + String bus = events.createEventBus(request -> request.name("v2-svc-" + suffix)).eventBusArn(); + String subscriber = events.createSubscriber(request -> request.name("all").eventBusArn(bus) + .invokeConfiguration(invoke -> invoke.targetArn(queueArn).roleArn(ROLE)) + .transformer(transformer -> transformer.type(TransformerType.WITH_METADATA))).subscriberArn(); + + CreateEventSourceResponse created = events.createEventSource(request -> request.name("ssm-" + suffix) + .eventBusArn(bus).configuration(EventSourceConfiguration.fromAwsServiceEventsConfiguration( + service -> service.awsService("aws.ssm") + .pattern("{\"detail-type\":[\"Parameter Store Change\"]}")))); + String sourceArn = created.eventSourceArn(); + assertTrue(sourceArn.contains(":event-sourcev2/aws.service/ssm-" + suffix + "/"), sourceArn); + assertEquals("ACTIVE", created.stateAsString()); + assertNull(created.eventSourceDetails()); + String ruleName = sourceArn.substring(sourceArn.length() - 25); + + DescribeRuleResponse rule = rules.describeRule(request -> request.name(ruleName)); + assertEquals("events.amazonaws.com", rule.managedBy()); + assertEquals("{\"source\":[\"aws.ssm\"],\"account\":[\"" + ACCOUNT + "\"],\"region\":[\"us-east-1\"]," + + "\"detail-type\":[\"Parameter Store Change\"]}", rule.eventPattern()); + assertEquals(bus, rules.listTargetsByRule(request -> request.rule(ruleName)).targets().getFirst().arn()); + assertEquals(ruleName, rules.listRuleNamesByTarget(request -> request.targetArn(bus)).ruleNames() + .getFirst()); + assertThrows(ManagedRuleException.class, () -> rules.deleteRule(request -> request.name(ruleName))); + + ssm.putParameter(request -> request.name("/svc-" + suffix).value("v").type(ParameterType.STRING)); + + List received = new ArrayList<>(); + await().atMost(Duration.ofSeconds(10)).untilAsserted(() -> { + received.addAll(sqs.receiveMessage(request -> request.queueUrl(queueUrl).maxNumberOfMessages(10) + .waitTimeSeconds(1)).messages()); + assertEquals(1, received.size(), received.toString()); + }); + JsonNode body = MAPPER.readTree(received.getFirst().body()); + JsonNode data = body.path("Data"); + assertEquals("aws.ssm", data.path("source").asText()); + assertEquals("Parameter Store Change", data.path("detail-type").asText()); + assertTrue(body.path("Metadata").isObject() && body.path("Metadata").isEmpty(), body.toString()); + JsonNode system = body.path("SystemMetadata"); + List keys = new ArrayList<>(); + system.fieldNames().forEachRemaining(keys::add); + assertEquals(List.of("EventGroupId", "DeduplicationId", "ContentType", "aws:IngestionTime", "aws:Source", + "aws:DetailType", "aws:EventId", "aws:SequenceNumber", "aws:DeliveryType"), keys); + assertEquals(data.path("id").asText(), system.path("EventGroupId").asText()); + assertEquals(data.path("id").asText(), system.path("DeduplicationId").asText()); + assertEquals("application/eventbridge+json", system.path("ContentType").asText()); + assertTrue(system.path("aws:IngestionTime").asText().matches("\\d{4}-\\d\\d-\\d\\dT\\d\\d:\\d\\d:\\d\\d\\.\\d{3}Z"), + system.toString()); + assertEquals("aws.ssm", system.path("aws:Source").asText()); + assertEquals("Parameter Store Change", system.path("aws:DetailType").asText()); + assertEquals("LIVE", system.path("aws:DeliveryType").asText()); + + events.deleteEventSource(request -> request.eventSourceArn(sourceArn)); + assertThrows(ResourceNotFoundException.class, + () -> rules.describeRule(request -> request.name(ruleName))); + events.deleteSubscriber(request -> request.subscriberArn(subscriber)); + events.deleteEventBus(request -> request.eventBusArn(bus)); + ssm.deleteParameter(request -> request.name("/svc-" + suffix)); + sqs.deleteQueue(request -> request.queueUrl(queueUrl)); + } + } + + @Test + void aPartnerSourceFailsAsAMissingPartnerSource() { + String suffix = Long.toString(System.nanoTime(), 36); + try (EventBridgeV2Client events = AwsTestClients.create(EventBridgeV2Client.builder(), ACCOUNT, Region.US_EAST_1)) { + String bus = events.createEventBus(request -> request.name("v2-partner-" + suffix)).eventBusArn(); + + InvalidInputException e = assertThrows(InvalidInputException.class, () -> events.createEventSource( + request -> request.name("partner-" + suffix).eventBusArn(bus) + .configuration(EventSourceConfiguration.fromPartnerEventsConfiguration(partner -> partner + .partnerEventSourceArn("arn:aws:events:us-east-1:111111111111:event-source/" + + "aws.partner/example.com/123/orders"))))); + + assertEquals("The partner event source aws.partner/example.com/123/orders could not be described: Event " + + "source aws.partner/example.com/123/orders does not exist.", e.awsErrorDetails().errorMessage()); + events.deleteEventBus(request -> request.eventBusArn(bus)); + } + } +} diff --git a/src/test/java/io/floci/aws/services/eventbridgev2/EventBridgeV2ServiceTest.java b/src/test/java/io/floci/aws/services/eventbridgev2/EventBridgeV2ServiceTest.java index 80a4729d14..22d97c0b34 100644 --- a/src/test/java/io/floci/aws/services/eventbridgev2/EventBridgeV2ServiceTest.java +++ b/src/test/java/io/floci/aws/services/eventbridgev2/EventBridgeV2ServiceTest.java @@ -9,6 +9,7 @@ import io.floci.aws.core.common.AwsException; import io.floci.aws.core.common.PaginatedResult; import io.floci.aws.core.common.RegionResolver; import io.floci.aws.core.storage.AccountAwareStorageBackend; +import io.floci.aws.services.eventbridge.EventBridgeService; import io.floci.aws.services.eventbridgev2.model.EventBusV2; import io.floci.aws.services.eventbridgev2.model.SubscriberV2; import io.floci.aws.services.secretsmanager.SecretsManagerService; @@ -65,7 +66,7 @@ class EventBridgeV2ServiceTest { Clock clock = Clock.fixed(NOW, ZoneOffset.UTC); EventBridgeV2EventSources eventSources = new EventBridgeV2EventSources( AccountAwareStorageBackend.inMemory(ACCOUNT), mock(SecretsManagerService.class), regionResolver, clock, - "http://floci.test:4566", mock(TlsCertificateManager.class)); + "http://floci.test:4566", mock(TlsCertificateManager.class), mock(EventBridgeService.class)); service = new EventBridgeV2Service(AccountAwareStorageBackend.inMemory(ACCOUNT), AccountAwareStorageBackend.inMemory(ACCOUNT), regionResolver, delivery, eventSources, clock, true); } diff --git a/src/test/java/io/floci/aws/services/eventbridgev2/EventBridgeV2WebhooksTest.java b/src/test/java/io/floci/aws/services/eventbridgev2/EventBridgeV2WebhooksTest.java index cd5650ae11..3a43beea12 100644 --- a/src/test/java/io/floci/aws/services/eventbridgev2/EventBridgeV2WebhooksTest.java +++ b/src/test/java/io/floci/aws/services/eventbridgev2/EventBridgeV2WebhooksTest.java @@ -6,6 +6,7 @@ import io.floci.aws.config.TlsCertificateManager; import io.floci.aws.core.common.AwsException; import io.floci.aws.core.common.RegionResolver; import io.floci.aws.core.storage.AccountAwareStorageBackend; +import io.floci.aws.services.eventbridge.EventBridgeService; import io.floci.aws.services.eventbridgev2.EventBridgeV2Webhooks.Answer; import io.floci.aws.services.eventbridgev2.EventBridgeV2Webhooks.Request; import io.floci.aws.services.eventbridgev2.model.EventSourceV2; @@ -88,7 +89,7 @@ class EventBridgeV2WebhooksTest { RegionResolver regionResolver = new RegionResolver(REGION, ACCOUNT); sources = new EventBridgeV2EventSources( AccountAwareStorageBackend.inMemory(ACCOUNT), secrets, regionResolver, clock, "http://floci.test:4566", - mock(TlsCertificateManager.class)); + mock(TlsCertificateManager.class), mock(EventBridgeService.class)); service = new EventBridgeV2Service(AccountAwareStorageBackend.inMemory(ACCOUNT), AccountAwareStorageBackend.inMemory(ACCOUNT), regionResolver, delivery, sources, clock, true); webhooks = new EventBridgeV2Webhooks(service, sources, secrets, clock); diff --git a/src/test/java/io/floci/aws/services/eventbridgev2/WebhookEventsConfigurationsTest.java b/src/test/java/io/floci/aws/services/eventbridgev2/WebhookEventsConfigurationsTest.java index d9f3d7dd63..6889f9a50c 100644 --- a/src/test/java/io/floci/aws/services/eventbridgev2/WebhookEventsConfigurationsTest.java +++ b/src/test/java/io/floci/aws/services/eventbridgev2/WebhookEventsConfigurationsTest.java @@ -217,13 +217,6 @@ class WebhookEventsConfigurationsTest { createRefusal("{\"WebhookEventsConfiguration\":{},\"PartnerEventsConfiguration\":{}}")); } - @ParameterizedTest - @ValueSource(strings = {"AwsServiceEventsConfiguration", "PartnerEventsConfiguration"}) - void otherVariantsAreNotSupported(String variant) { - assertEquals("Only WebhookEventsConfiguration event sources are supported.", - createRefusal("{\"" + variant + "\":{}}")); - } - @Test void authConfigurationMustSetExactlyOneMember() { String message = "WebhookEventsConfiguration.AuthConfiguration must set exactly one of " diff --git a/src/test/java/io/floci/aws/services/eventbridgev2/WebhookSourceFixture.java b/src/test/java/io/floci/aws/services/eventbridgev2/WebhookSourceFixture.java index 9bb13c9079..2643dafefe 100644 --- a/src/test/java/io/floci/aws/services/eventbridgev2/WebhookSourceFixture.java +++ b/src/test/java/io/floci/aws/services/eventbridgev2/WebhookSourceFixture.java @@ -8,6 +8,7 @@ import io.floci.aws.config.TlsCertificateManager; import io.floci.aws.core.common.RegionResolver; import io.floci.aws.core.storage.AccountAwareStorageBackend; import io.floci.aws.core.storage.StorageFactory; +import io.floci.aws.services.eventbridge.EventBridgeService; import io.floci.aws.services.eventbridgev2.model.EventSourceV2; import io.floci.aws.services.secretsmanager.SecretsManagerService; import io.floci.aws.services.secretsmanager.model.Secret; @@ -51,7 +52,7 @@ final class WebhookSourceFixture { clock = new ManualClock(NOW); EventBridgeV2EventSources sources = new EventBridgeV2EventSources( AccountAwareStorageBackend.inMemory(ACCOUNT), secrets, regionResolver, clock, "http://floci.test:4566", - mock(TlsCertificateManager.class)); + mock(TlsCertificateManager.class), mock(EventBridgeService.class)); service = new EventBridgeV2Service(AccountAwareStorageBackend.inMemory(ACCOUNT), AccountAwareStorageBackend.inMemory(ACCOUNT), regionResolver, delivery, sources, clock, true); webhooks = new EventBridgeV2Webhooks(service, sources, secrets, clock);