From c24cb128115d0dbb5b451dbbe8ceedd97e03ce93 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?TATSUNO=20=E2=80=9CTaz=E2=80=9D=20Yasuhiro?= Date: Fri, 27 Nov 2026 07:47:36 +0900 Subject: [PATCH] feat(eventbridgev2): revoke event sources and subscribers (#9528) RevokeResource answered UnsupportedOperation. It now revokes a webhook event source or a subscriber for good. A revoked source answers 403 on its webhook URL and refuses UpdateEventSource and RotateWebhookCredentials with InvalidStateException. A revoked subscriber receives no more events and refuses UpdateSubscriber the same way. Both can still be described, listed and deleted, and report Revoked once revoked while leaving the member out before. DeleteEventBus ignores revoked sources and subscribers, which outlive their bus under a key a new bus of the same name cannot reach. ListSubscribers pages by bus name, subscriber name and ARN, so an orphan and its namesake on the recreated bus both show. --- docs/services/eventbridgev2.md | 29 +- docs/services/index.md | 2 +- .../EventBridgeV2EventSources.java | 61 +- .../eventbridgev2/EventBridgeV2Handler.java | 49 +- .../eventbridgev2/EventBridgeV2Service.java | 104 ++- .../eventbridgev2/EventBridgeV2Webhooks.java | 2 +- .../eventbridgev2/model/EventSourceV2.java | 9 + .../eventbridgev2/model/SubscriberV2.java | 9 + .../aws/eventbridgev2-request-shapes.json | 16 + .../EventBridgeV2RequestShapesTest.java | 48 ++ .../EventBridgeV2RevokeResourceTest.java | 778 ++++++++++++++++++ .../EventBridgeV2RotateCredentialsTest.java | 138 ++-- ...ventBridgeV2SubscriberIntegrationTest.java | 3 +- .../EventBridgeV2WebhookIntegrationTest.java | 111 +++ .../EventBridgeV2WebhooksTest.java | 73 ++ .../eventbridgev2/WebhookSourceFixture.java | 72 ++ tools/aws/regen_eventbridgev2_shapes.py | 2 +- tools/aws/test_request_shapes.py | 6 +- 18 files changed, 1381 insertions(+), 131 deletions(-) create mode 100644 src/test/java/io/floci/aws/services/eventbridgev2/EventBridgeV2RevokeResourceTest.java create mode 100644 src/test/java/io/floci/aws/services/eventbridgev2/WebhookSourceFixture.java diff --git a/docs/services/eventbridgev2.md b/docs/services/eventbridgev2.md index 849320779e..a78cffa47b 100644 --- a/docs/services/eventbridgev2.md +++ b/docs/services/eventbridgev2.md @@ -18,7 +18,7 @@ The AWS CLI calls it `aws eventsv2` and the SDKs `EventBridgeV2`. | --- | --- | | `CreateEventBus` | Create an event bus, with an optional description, KMS key, retention period, and tags | | `DescribeEventBus` | Return an event bus's name, description, configuration, state and times | -| `DeleteEventBus` | Delete an event bus that has no subscribers or event sources | +| `DeleteEventBus` | Delete an event bus that has no subscribers or event sources that are not revoked | | `ListEventBuses` | List the Region's event buses in name order, filtered by name prefix, a page at a time | | `CreateSubscriber` | Create a subscriber that delivers the events its filters match to an Amazon SQS queue | | `DescribeSubscriber` | Return a subscriber's target, filters, transformer, delivery settings, state and times | @@ -30,6 +30,7 @@ The AWS CLI calls it `aws eventsv2` and the SDKs `EventBridgeV2`. | `ListEventSources` | List the Region's event sources, or one event bus's, filtered by name prefix, a page at a time | | `UpdateEventSource` | Replace a webhook event source's configuration and description | | `RotateWebhookCredentials` | Replace the credential in a webhook event source's secret, with a given or a generated one | +| `RevokeResource` | Revoke a webhook event source or a subscriber for good, keeping it but ending its use | | `DeleteEventSource` | Delete a webhook event source and schedule its secret for deletion | | `PutEvents` | Publish events in the EventBridge envelope to an event bus | @@ -97,7 +98,27 @@ A matcher Floci does not evaluate, such as `cidr` or `anything-but` with `numeri `UpdateSubscriber` changes only the settings the request gives. Its `InvokeConfiguration` replaces the role and the target parameters but has no `TargetArn`: a subscriber keeps its target. An update is checked as a whole, so a request with one invalid setting changes nothing. `ResumePosition` is accepted and has no effect, since events are -not retained. `DescribeSubscriber` and `ListSubscribers` always report `Revoked` as `false`. +not retained. `DescribeSubscriber` and `ListSubscribers` return `Revoked` once the subscriber is revoked, and leave it out before. + +## Revoking a resource + +`RevokeResource` takes the ARN of a webhook 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 + and its name stays taken. `UpdateEventSource` and `RotateWebhookCredentials` answer `InvalidStateException` + (409) after their own `400` checks. A rotation also checks its `ClientToken` first, so a repeat of an earlier + rotation still answers `200`. +- A revoked subscriber receives no more events. `UpdateSubscriber` answers `InvalidStateException` (409) after its + own `400` checks. +- Both stay `ACTIVE` or `RUNNING`, report `Revoked`, and can still be described, listed and deleted. +- `DeleteEventBus` ignores revoked sources and subscribers. A revoked resource outlives its bus. Its description + then has no `Configuration` for a source. A subscriber has no `InvokeConfiguration`, `BatchConfiguration`, + `Transformer`, `RetryPolicy`, `FilterConfiguration`, `OnFailureConfiguration` or `LogConfiguration`, and its + `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`. ## Webhook event sources @@ -124,7 +145,7 @@ Floci serves event sources of the `WebhookEventsConfiguration` kind. A request w secret is scheduled for deletion or deleted. - `KmsKeyIdentifier` is stored and returned. It is not used for the secret. - `DeleteEventSource` schedules the secret for deletion at once. -- `DescribeEventSource` and `ListEventSources` do not return `Revoked`. +- `DescribeEventSource` and `ListEventSources` return `Revoked` once the source is revoked, and leave it out before. ### Receiving events @@ -166,7 +187,7 @@ A `400` also sends `Connection: close` and closes the connection. a 64 character hash, and otherwise a random UUID. The hash is SHA-256 over an encoding of Floci's own, so it does not equal the hash AWS gives. The hashes are kept in memory and are lost on restart. - The host of the request decides the source. The Region in the host is not checked. -- Not emulated: `429` throttling, `LogConfiguration` delivery and `Revoked`. +- Not emulated: `429` throttling and `LogConfiguration` delivery. ## IAM diff --git a/docs/services/index.md b/docs/services/index.md index fe65196124..7fa00bd81f 100644 --- a/docs/services/index.md +++ b/docs/services/index.md @@ -57,7 +57,7 @@ Operation counts are exact. For dispatch-table services (Query and JSON 1.1) eac | [CloudFormation](cloudformation.md) | `POST /` with `Action=` param | Query | 36 | | [Cloud Control API](cloudcontrol.md) | `POST /` + `X-Amz-Target: CloudApiService.*` | JSON 1.1 | 5 | | [EventBridge](eventbridge.md) | `POST /` + `X-Amz-Target: AmazonEventBridge.*` | JSON 1.1 | 41 | -| [EventBridge V2](eventbridgev2.md) | `POST /service/AWSEventsV2/operation/*` | Smithy RPC v2 CBOR | 16 | +| [EventBridge V2](eventbridgev2.md) | `POST /service/AWSEventsV2/operation/*` | Smithy RPC v2 CBOR | 17 | | [EventBridge Scheduler](scheduler.md) | `/schedules/*`, `/schedule-groups/*`, `/tags/*` | REST JSON | 12 | | [EventBridge Pipes](pipes.md) | `/v1/pipes/*` | REST JSON | 10 | | [CloudWatch OAM](oam.md) | REST paths such as `POST /CreateSink` and `POST /CreateLink` | REST JSON | 15 | 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 ef7aa1ab45..723f8480a5 100644 --- a/src/main/java/io/floci/aws/services/eventbridgev2/EventBridgeV2EventSources.java +++ b/src/main/java/io/floci/aws/services/eventbridgev2/EventBridgeV2EventSources.java @@ -167,6 +167,8 @@ public class EventBridgeV2EventSources implements Resettable { configuration, WebhookEventsConfigurations.authType( source.getConfiguration().get(WebhookEventsConfigurations.WEBHOOK))); + requireNotRevoked(source, "EventSource is revoked and cannot be updated"); + EventSourceV2 changed = copyOf(source); changed.setDescription(request.hasNonNull("Description") ? request.get("Description").textValue() : source.getDescription()); @@ -217,6 +219,7 @@ public class EventBridgeV2EventSources implements Resettable { } return source.getSecretArn(); } + requireNotRevoked(source, "EventSource is revoked and its credentials cannot be rotated"); requireSecretUsable(source, region); String current = secrets.getSecretValue(source.getSecretArn(), null, null, region).getSecretString(); @@ -288,6 +291,7 @@ public class EventBridgeV2EventSources implements Resettable { copy.setWebhookHostId(source.getWebhookHostId()); copy.setWebhookToken(source.getWebhookToken()); copy.setSecretArn(source.getSecretArn()); + copy.setRevoked(source.isRevoked()); copy.setRotationRequests(new LinkedHashMap<>(source.getRotationRequests())); return copy; } @@ -367,7 +371,8 @@ public class EventBridgeV2EventSources implements Resettable { } boolean hasSourcesOn(String eventBusArn, String region) { - return inRegion(region).stream().anyMatch(source -> eventBusArn.equals(source.getEventBusArn())); + return inRegion(region).stream() + .anyMatch(source -> eventBusArn.equals(source.getEventBusArn()) && !source.isRevoked()); } /** The URL a source receives its events at, in the scheme of Floci's own base URL. */ @@ -454,19 +459,53 @@ public class EventBridgeV2EventSources implements Resettable { return EventBridgeV2Service.invalidInput("Invalid nextToken"); } - private void checkArn(String eventSourceArn, String region) { - requireEndpointRegion(eventSourceArn, region, "EventSourceArn"); - requireOwnAccount(eventSourceArn); + /** Refuses an ARN of another Region, partition or account. {@code member} names the request member in the error. */ + void checkArn(String arn, String region, String member) { + requireEndpointRegion(arn, region, member); + requireOwnAccount(arn); } - private EventSourceV2 require(String eventSourceArn, String region) { + private void checkArn(String eventSourceArn, String region) { + checkArn(eventSourceArn, region, "EventSourceArn"); + } + + private Optional lookup(String eventSourceArn, String region) { String[] resource = AwsArnUtils.parse(eventSourceArn).resource().split("/"); - Optional found = resource.length == 4 && "event-sourcev2".equals(resource[0]) + return resource.length == 4 && "event-sourcev2".equals(resource[0]) ? sources.get(EventBridgeV2Service.storageKey(region, resource[2])) .filter(source -> eventSourceArn.equals(source.getArn())) : Optional.empty(); - return found.orElseThrow(() -> new AwsException("ResourceNotFoundException", - "EventSource not found: " + eventSourceArn, 404)); + } + + private EventSourceV2 require(String eventSourceArn, String region) { + return lookup(eventSourceArn, region).orElseThrow(() -> notFound(eventSourceArn)); + } + + private static AwsException notFound(String eventSourceArn) { + return new AwsException("ResourceNotFoundException", "EventSource not found: " + eventSourceArn, 404); + } + + private static void requireNotRevoked(EventSourceV2 source, String message) { + if (source.isRevoked()) { + throw new AwsException("InvalidStateException", message, 409); + } + } + + /** + * Revokes the source {@code eventSourceArn} names. A webhook source that does not exist is answered as access + * denied, and any other source type as not found. + */ + void revoke(String eventSourceArn, String region) { + boolean webhook = "webhook".equals(AwsArnUtils.parse(eventSourceArn).resource().split("/")[1]); + EventSourceV2 source = lookup(eventSourceArn, region) + .orElseThrow(() -> webhook ? accessDenied() : notFound(eventSourceArn)); + if (source.isRevoked()) { + return; + } + EventSourceV2 revoked = copyOf(source); + revoked.setRevoked(true); + revoked.setLastModifiedTime(clock.instant()); + sources.put(EventBridgeV2Service.storageKey(region, source.getName()), revoked); } private void requireEndpointRegion(String arn, String region, String member) { @@ -479,10 +518,14 @@ public class EventBridgeV2EventSources implements Resettable { private void requireOwnAccount(String arn) { if (AwsArnUtils.isForeignAccount(AwsArnUtils.parse(arn), regionResolver.getAccountId())) { - throw new AwsException("AccessDeniedException", "Access denied.", 403); + throw accessDenied(); } } + static AwsException accessDenied() { + return new AwsException("AccessDeniedException", "Access denied.", 403); + } + private List inRegion(String region) { String prefix = region + "::"; return sources.scan(key -> key.startsWith(prefix)); 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 03b48f6759..3557db5234 100644 --- a/src/main/java/io/floci/aws/services/eventbridgev2/EventBridgeV2Handler.java +++ b/src/main/java/io/floci/aws/services/eventbridgev2/EventBridgeV2Handler.java @@ -58,6 +58,7 @@ public class EventBridgeV2Handler { case "ListEventSources" -> handleListEventSources(request, region); case "UpdateEventSource" -> handleUpdateEventSource(request, region); case "RotateWebhookCredentials" -> handleRotateWebhookCredentials(request, region); + case "RevokeResource" -> handleRevokeResource(request, region); case "DeleteEventSource" -> handleDeleteEventSource(request, region); case "PutEvents" -> handlePutEvents(request, region); default -> throw new AwsException("UnsupportedOperation", @@ -139,17 +140,25 @@ public class EventBridgeV2Handler { private Response handleDescribeSubscriber(JsonNode request, String region) { SubscriberV2 subscriber = service.describeSubscriber(request, region); ObjectNode response = subscriberIdentity(subscriber); - response.set("InvokeConfiguration", subscriber.getInvokeConfiguration()); - if (subscriber.getDescription() != null) { - response.put("Description", subscriber.getDescription()); + boolean busExists = service.findEventBus(subscriber.getEventBusArn(), region).isPresent(); + if (busExists) { + response.set("InvokeConfiguration", subscriber.getInvokeConfiguration()); + } + if (subscriber.getDescription() != null) { + response.put("Description", + busExists ? subscriber.getDescription() : "*** Not accessible: event bus deleted ***"); + } + if (busExists) { + putIfSet(response, "FilterConfiguration", subscriber.getFilterConfiguration()); + putIfSet(response, "BatchConfiguration", subscriber.getBatchConfiguration()); + putIfSet(response, "Transformer", subscriber.getTransformer()); + putIfSet(response, "RetryPolicy", subscriber.getRetryPolicy()); + putIfSet(response, "OnFailureConfiguration", subscriber.getOnFailureConfiguration()); + putIfSet(response, "LogConfiguration", subscriber.getLogConfiguration()); + } + if (subscriber.isRevoked()) { + response.put("Revoked", true); } - putIfSet(response, "FilterConfiguration", subscriber.getFilterConfiguration()); - putIfSet(response, "BatchConfiguration", subscriber.getBatchConfiguration()); - putIfSet(response, "Transformer", subscriber.getTransformer()); - putIfSet(response, "RetryPolicy", subscriber.getRetryPolicy()); - putIfSet(response, "OnFailureConfiguration", subscriber.getOnFailureConfiguration()); - putIfSet(response, "LogConfiguration", subscriber.getLogConfiguration()); - response.put("Revoked", false); response.put("CreationTime", epochSeconds(subscriber.getCreationTime())); response.put("LastModifiedTime", epochSeconds(subscriber.getLastModifiedTime())); return Response.ok(response).build(); @@ -166,7 +175,9 @@ public class EventBridgeV2Handler { summary.put("EventBusArn", subscriber.getEventBusArn()); summary.put("TargetArn", subscriber.getInvokeConfiguration().path("TargetArn").asText()); summary.put("Type", subscriber.getType()); - summary.put("Revoked", false); + if (subscriber.isRevoked()) { + summary.put("Revoked", true); + } summary.put("State", subscriber.getState()); summary.put("CreationTime", epochSeconds(subscriber.getCreationTime())); summary.put("LastModifiedTime", epochSeconds(subscriber.getLastModifiedTime())); @@ -216,11 +227,16 @@ public class EventBridgeV2Handler { response.put("EventSourceArn", source.getArn()); response.put("Name", source.getName()); response.put("EventBusArn", source.getEventBusArn()); - response.set("Configuration", source.getConfiguration()); + if (service.findEventBus(source.getEventBusArn(), region).isPresent()) { + response.set("Configuration", source.getConfiguration()); + } if (source.getDescription() != null) { response.put("Description", source.getDescription()); } response.put("State", source.getState()); + if (source.isRevoked()) { + response.put("Revoked", true); + } response.set("EventSourceDetails", eventSourceDetails(source)); response.put("CreationTime", epochSeconds(source.getCreationTime())); response.put("LastModifiedTime", epochSeconds(source.getLastModifiedTime())); @@ -240,6 +256,12 @@ public class EventBridgeV2Handler { return Response.ok(response).build(); } + private Response handleRevokeResource(JsonNode request, String region) { + ObjectNode response = objectMapper.createObjectNode(); + response.put("Arn", service.revokeResource(request, region)); + return Response.ok(response).build(); + } + private Response handleDeleteEventSource(JsonNode request, String region) { service.deleteEventSource(request, region); return Response.ok(objectMapper.createObjectNode()).build(); @@ -256,6 +278,9 @@ public class EventBridgeV2Handler { summary.put("EventBusArn", source.getEventBusArn()); summary.put("Type", "WEBHOOK_EVENTS"); summary.put("State", source.getState()); + if (source.isRevoked()) { + summary.put("Revoked", true); + } summary.put("CreationTime", epochSeconds(source.getCreationTime())); summary.put("LastModifiedTime", epochSeconds(source.getLastModifiedTime())); summary.put("EventSourceAccountId", AwsArnUtils.parse(source.getArn()).accountId()); 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 e8d7cf0344..c26c610e50 100644 --- a/src/main/java/io/floci/aws/services/eventbridgev2/EventBridgeV2Service.java +++ b/src/main/java/io/floci/aws/services/eventbridgev2/EventBridgeV2Service.java @@ -207,10 +207,10 @@ public class EventBridgeV2Service implements Resettable { deleteEventBus(requireText(request, "EventBusArn"), region); } - /** Deletes a bus, which must have no subscribers or event sources left. */ + /** Deletes a bus, which must have no subscribers or event sources left that are not revoked. */ public synchronized void deleteEventBus(String eventBusArn, String region) { EventBusV2 bus = requireEventBus(eventBusArn, region); - boolean hasSubscribers = !subscribersOf(bus, region).isEmpty(); + boolean hasSubscribers = subscribersOf(bus, region).stream().anyMatch(subscriber -> !subscriber.isRevoked()); if (eventSources.hasSourcesOn(bus.getArn(), region)) { throw new AwsException("ResourceInUseException", "The event bus cannot be deleted because it has " + (hasSubscribers ? "subscribers and event sources" : "one or more event sources") @@ -220,6 +220,11 @@ public class EventBridgeV2Service implements Resettable { throw new AwsException("ResourceInUseException", "Event bus " + bus.getName() + " still has subscribers; delete them first.", 409); } + for (SubscriberV2 orphan : subscribersOf(bus, region)) { + // Written before the old entry goes, so a stop between the two writes loses nothing. + subscribers.put(orphanKey(region, orphan), orphan); + subscribers.delete(subscriberKey(region, bus.getName(), orphan.getName())); + } buses.delete(storageKey(region, bus.getName())); deliveriesByBus.remove(bus.getArn()); } @@ -336,19 +341,13 @@ public class EventBridgeV2Service implements Resettable { if (filterConfiguration != null) { SubscriberFilters.validate(filterConfiguration); } - SubscriberV2 changed = new SubscriberV2(); + SubscriberV2 changed = copyOf(subscriber); applySettings(changed, settings, filterConfiguration); - changed.setName(subscriber.getName()); - changed.setArn(subscriber.getArn()); - changed.setEventBusArn(subscriber.getEventBusArn()); - changed.setType(subscriber.getType()); - changed.setStartingPosition(subscriber.getStartingPosition()); - changed.setPointInTimeConfiguration(subscriber.getPointInTimeConfiguration()); - changed.setCreationTime(subscriber.getCreationTime()); + if (subscriber.isRevoked()) { + throw new AwsException("InvalidStateException", "Subscriber is revoked and cannot be updated", 409); + } changed.setLastModifiedTime(clock.instant()); - changed.setClientToken(subscriber.getClientToken()); - changed.setCreateRequest(subscriber.getCreateRequest()); - subscribers.put(subscriberKey(region, busName(subscriber.getEventBusArn()), subscriber.getName()), changed); + subscribers.put(keyOf(subscriber, region), changed); return changed; } @@ -369,8 +368,9 @@ public class EventBridgeV2Service implements Resettable { : subscribersOf(bus, region)).stream() .filter(subscriber -> namePrefix == null || subscriber.getName().startsWith(namePrefix)) .toList(); - return page(listed, subscriber -> busName(subscriber.getEventBusArn()) + "::" + subscriber.getName(), - request, "subscriber"); + // A revoked subscriber of a deleted bus can share both names with one on the new bus of that name. + return page(listed, subscriber -> busName(subscriber.getEventBusArn()) + "::" + subscriber.getName() + "::" + + subscriber.getArn(), request, "subscriber"); } /** @@ -397,7 +397,7 @@ public class EventBridgeV2Service implements Resettable { public synchronized void deleteSubscriber(String subscriberArn, String region) { SubscriberV2 subscriber = requireSubscriber(subscriberArn, region); - subscribers.delete(subscriberKey(region, busName(subscriber.getEventBusArn()), subscriber.getName())); + subscribers.delete(keyOf(subscriber, region)); } public Optional findSubscriber(String subscriberArn, String region) { @@ -442,6 +442,60 @@ public class EventBridgeV2Service implements Resettable { return eventSources.list(request, region, name -> buses.get(storageKey(region, name))); } + /** + * Revokes the event source or the subscriber {@code Arn} names, for good. The resource stays and can be + * described, listed and deleted, but it takes no more events and cannot be updated. + */ + public synchronized String revokeResource(JsonNode request, String region) { + EventBridgeV2RequestShapes.check("RevokeResource", request); + String arn = request.get("Arn").textValue(); + eventSources.checkArn(arn, region, "Arn"); + if (AwsArnUtils.parse(arn).resource().startsWith("subscriber/")) { + revokeSubscriber(arn, region); + } else { + eventSources.revoke(arn, region); + } + return arn; + } + + private void revokeSubscriber(String subscriberArn, String region) { + SubscriberV2 subscriber = findSubscriber(subscriberArn, region) + .orElseThrow(EventBridgeV2EventSources::accessDenied); + if (subscriber.isRevoked()) { + return; + } + SubscriberV2 revoked = copyOf(subscriber); + revoked.setRevoked(true); + revoked.setLastModifiedTime(clock.instant()); + subscribers.put(keyOf(subscriber, region), revoked); + } + + private static SubscriberV2 copyOf(SubscriberV2 subscriber) { + SubscriberV2 copy = new SubscriberV2(); + copy.setName(subscriber.getName()); + copy.setArn(subscriber.getArn()); + copy.setEventBusArn(subscriber.getEventBusArn()); + copy.setDescription(subscriber.getDescription()); + copy.setType(subscriber.getType()); + copy.setStartingPosition(subscriber.getStartingPosition()); + copy.setState(subscriber.getState()); + copy.setPointInTimeConfiguration(subscriber.getPointInTimeConfiguration()); + copy.setInvokeConfiguration(subscriber.getInvokeConfiguration()); + copy.setFilterConfiguration(subscriber.getFilterConfiguration()); + copy.setTransformer(subscriber.getTransformer()); + copy.setBatchConfiguration(subscriber.getBatchConfiguration()); + copy.setRetryPolicy(subscriber.getRetryPolicy()); + copy.setOnFailureConfiguration(subscriber.getOnFailureConfiguration()); + copy.setLogConfiguration(subscriber.getLogConfiguration()); + copy.setCreationTime(subscriber.getCreationTime()); + copy.setLastModifiedTime(subscriber.getLastModifiedTime()); + copy.setTags(subscriber.getTags()); + copy.setClientToken(subscriber.getClientToken()); + copy.setCreateRequest(subscriber.getCreateRequest()); + copy.setRevoked(subscriber.isRevoked()); + return copy; + } + public String webhookUrl(EventSourceV2 source) { return eventSources.webhookUrl(source); } @@ -478,7 +532,7 @@ public class EventBridgeV2Service implements Resettable { synchronized (this) { EventBusV2 bus = requireEventBus(eventBusArn, region); List running = subscribersOf(bus, region).stream() - .filter(subscriber -> RUNNING.equals(subscriber.getState())) + .filter(subscriber -> RUNNING.equals(subscriber.getState()) && !subscriber.isRevoked()) .toList(); for (int i = 0; i < entries.size(); i++) { JsonNode entry = entries.get(i); @@ -511,7 +565,7 @@ public class EventBridgeV2Service implements Resettable { synchronized (this) { EventBusV2 bus = requireEventBus(eventBusArn, region); List running = subscribersOf(bus, region).stream() - .filter(subscriber -> RUNNING.equals(subscriber.getState())) + .filter(subscriber -> RUNNING.equals(subscriber.getState()) && !subscriber.isRevoked()) .toList(); event = accept(bus, running, deliveries, build); ordered = enqueue(bus, region, deliveries); @@ -862,6 +916,20 @@ public class EventBridgeV2Service implements Resettable { return region + "::" + busName + "::" + name; } + /** Where a subscriber is stored: under its bus's name while the bus exists, and under its bus's id after. */ + private String keyOf(SubscriberV2 subscriber, String region) { + return findEventBus(subscriber.getEventBusArn(), region).isPresent() + ? subscriberKey(region, busName(subscriber.getEventBusArn()), subscriber.getName()) + : orphanKey(region, subscriber); + } + + /** A revoked subscriber outlives its bus under a key a new bus of the same name cannot reach. */ + private static String orphanKey(String region, SubscriberV2 subscriber) { + String arn = subscriber.getEventBusArn(); + return region + "::" + busName(arn) + "@" + arn.substring(arn.lastIndexOf('/') + 1) + "::" + + subscriber.getName(); + } + // ──────────────────────────── Validation ──────────────────────────── private static String requireName(JsonNode request) { diff --git a/src/main/java/io/floci/aws/services/eventbridgev2/EventBridgeV2Webhooks.java b/src/main/java/io/floci/aws/services/eventbridgev2/EventBridgeV2Webhooks.java index 3eba87bf47..db091d2f39 100644 --- a/src/main/java/io/floci/aws/services/eventbridgev2/EventBridgeV2Webhooks.java +++ b/src/main/java/io/floci/aws/services/eventbridgev2/EventBridgeV2Webhooks.java @@ -94,7 +94,7 @@ public class EventBridgeV2Webhooks { String accountId = located.get().accountId(); String region = AwsArnUtils.parse(source.getArn()).region(); JsonNode webhook = source.getConfiguration().path(WebhookEventsConfigurations.WEBHOOK); - if (!credentialAccepted(accountId, region, source, webhook, request)) { + if (source.isRevoked() || !credentialAccepted(accountId, region, source, webhook, request)) { return FORBIDDEN; } Optional data = WebhookEvents.parseBody(request.body()); diff --git a/src/main/java/io/floci/aws/services/eventbridgev2/model/EventSourceV2.java b/src/main/java/io/floci/aws/services/eventbridgev2/model/EventSourceV2.java index b370359778..4d719a1af4 100644 --- a/src/main/java/io/floci/aws/services/eventbridgev2/model/EventSourceV2.java +++ b/src/main/java/io/floci/aws/services/eventbridgev2/model/EventSourceV2.java @@ -29,6 +29,7 @@ public class EventSourceV2 { private String webhookHost; private String webhookToken; private String secretArn; + private boolean revoked; private Map rotationRequests = new LinkedHashMap<>(); public EventSourceV2() { @@ -146,6 +147,14 @@ public class EventSourceV2 { this.secretArn = secretArn; } + public boolean isRevoked() { + return revoked; + } + + public void setRevoked(boolean revoked) { + this.revoked = revoked; + } + /** The rotations of the last 8 hours, by ClientToken. */ public Map getRotationRequests() { return rotationRequests; diff --git a/src/main/java/io/floci/aws/services/eventbridgev2/model/SubscriberV2.java b/src/main/java/io/floci/aws/services/eventbridgev2/model/SubscriberV2.java index 67001e749a..64a7a69f81 100644 --- a/src/main/java/io/floci/aws/services/eventbridgev2/model/SubscriberV2.java +++ b/src/main/java/io/floci/aws/services/eventbridgev2/model/SubscriberV2.java @@ -35,6 +35,7 @@ public class SubscriberV2 { private Map tags = new LinkedHashMap<>(); private String clientToken; private String createRequest; + private boolean revoked; public SubscriberV2() { } @@ -198,4 +199,12 @@ public class SubscriberV2 { public void setCreateRequest(String createRequest) { this.createRequest = createRequest; } + + public boolean isRevoked() { + return revoked; + } + + public void setRevoked(boolean revoked) { + this.revoked = revoked; + } } diff --git a/src/main/resources/aws/eventbridgev2-request-shapes.json b/src/main/resources/aws/eventbridgev2-request-shapes.json index 0f0015217f..4ef79b9950 100644 --- a/src/main/resources/aws/eventbridgev2-request-shapes.json +++ b/src/main/resources/aws/eventbridgev2-request-shapes.json @@ -8,6 +8,7 @@ "DeleteEventSource": "DeleteEventSourceRequest", "DescribeEventSource": "DescribeEventSourceRequest", "ListEventSources": "ListEventSourcesRequest", + "RevokeResource": "RevokeResourceRequest", "RotateWebhookCredentials": "RotateWebhookCredentialsRequest", "UpdateEventSource": "UpdateEventSourceRequest" }, @@ -190,6 +191,21 @@ "max": 3753, "sensitive": true }, + "RevocableResourceArn": { + "type": "string", + "min": 1, + "max": 1011, + "pattern": "arn:aws(-[a-z0-9]+)*:events:[a-z][a-z0-9]*(-[a-z0-9]+)*:([0-9]{12}):(subscriber|event-sourcev2\\/(aws\\.service|aws\\.partner|webhook))\\/[A-Za-z0-9][\\.\\-_A-Za-z0-9]{0,255}\\/[a-z0-9]{25}" + }, + "RevokeResourceRequest": { + "type": "structure", + "required": [ + "Arn" + ], + "members": { + "Arn": "RevocableResourceArn" + } + }, "RoleArn": { "type": "string", "min": 1, diff --git a/src/test/java/io/floci/aws/services/eventbridgev2/EventBridgeV2RequestShapesTest.java b/src/test/java/io/floci/aws/services/eventbridgev2/EventBridgeV2RequestShapesTest.java index 9fdb7a918a..9a59ea4c65 100644 --- a/src/test/java/io/floci/aws/services/eventbridgev2/EventBridgeV2RequestShapesTest.java +++ b/src/test/java/io/floci/aws/services/eventbridgev2/EventBridgeV2RequestShapesTest.java @@ -645,6 +645,54 @@ class EventBridgeV2RequestShapesTest { + "\"Credential\":{\"StaticTokenSecretValue\":\"abcdef\",\"HmacSecretValue\":null}}"))); } + private static final String REVOKE_ARN_PATTERN = "arn:aws(-[a-z0-9]+)*:events:[a-z][a-z0-9]*(-[a-z0-9]+)*:" + + "([0-9]{12}):(subscriber|event-sourcev2\\/(aws\\.service|aws\\.partner|webhook))" + + "\\/[A-Za-z0-9][\\.\\-_A-Za-z0-9]{0,255}\\/[a-z0-9]{25}"; + + @Test + void revokeResourceAnEmptyArnFailsLengthBeforePattern() { + assertAnswers("RevokeResource", "{\"Arn\":\"\"}", + "Value '' at 'arn' failed to satisfy constraint: Member must have length greater than or equal to 1", + "Value '' at 'arn' failed to satisfy constraint: Member must satisfy regular expression pattern: " + + REVOKE_ARN_PATTERN); + } + + @Test + void revokeResourceATooLongArnFailsTheLengthOnly() { + String arn = "arn:aws:events:us-east-1:123456789012:subscriber/" + "a".repeat(1000) + "/abcdefghijklmnopqrstuvwxy"; + + assertAnswers("RevokeResource", "{\"Arn\":\"" + arn + "\"}", + "Value '" + arn + "' at 'arn' failed to satisfy constraint: " + + "Member must have length less than or equal to 1011", + "Value '" + arn + "' at 'arn' failed to satisfy constraint: " + + "Member must satisfy regular expression pattern: " + REVOKE_ARN_PATTERN); + } + + @Test + void revokeResourceABusArnFailsThePattern() { + assertAnswers("RevokeResource", "{\"Arn\":\"" + BUS_ARN + "\"}", + "Value '" + BUS_ARN + "' at 'arn' failed to satisfy constraint: " + + "Member must satisfy regular expression pattern: " + REVOKE_ARN_PATTERN); + } + + @Test + void revokeResourceAMissingArnIsRefusedAsNullAndANumberIsASerializationException() { + assertAnswers("RevokeResource", "{}", + "Value null at 'arn' failed to satisfy constraint: Member must not be null"); + assertSerializationException("RevokeResource", "{\"Arn\":1}"); + } + + @Test + void revokeResourceAcceptsSourceAndSubscriberArnsOfEveryPartitionAndType() { + for (String arn : List.of( + "arn:aws:events:us-east-1:123456789012:event-sourcev2/webhook/x/abcdefghijklmnopqrstuvwxy", + "arn:aws:events:us-east-1:123456789012:event-sourcev2/aws.service/x/abcdefghijklmnopqrstuvwxy", + "arn:aws:events:us-east-1:123456789012:event-sourcev2/aws.partner/x/abcdefghijklmnopqrstuvwxy", + "arn:aws-us-gov:events:us-gov-west-1:123456789012:subscriber/x/abcdefghijklmnopqrstuvwxy")) { + assertDoesNotThrow(() -> EventBridgeV2RequestShapes.check("RevokeResource", json("{\"Arn\":\"" + arn + "\"}"))); + } + } + private static void assertAnswers(String operation, String request, String... violations) { assertAnswers(operation, json(request), violations); } diff --git a/src/test/java/io/floci/aws/services/eventbridgev2/EventBridgeV2RevokeResourceTest.java b/src/test/java/io/floci/aws/services/eventbridgev2/EventBridgeV2RevokeResourceTest.java new file mode 100644 index 0000000000..21667cfb5d --- /dev/null +++ b/src/test/java/io/floci/aws/services/eventbridgev2/EventBridgeV2RevokeResourceTest.java @@ -0,0 +1,778 @@ +package io.floci.aws.services.eventbridgev2; + +import com.fasterxml.jackson.core.type.TypeReference; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.node.ObjectNode; +import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule; +import io.floci.aws.config.EmulatorConfig; +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.common.SmithyValidationErrors; +import io.floci.aws.core.storage.AccountAwareStorageBackend; +import io.floci.aws.core.storage.StorageFactory; +import io.floci.aws.services.eventbridgev2.EventBridgeV2Webhooks.Request; +import io.floci.aws.services.eventbridgev2.model.EventSourceV2; +import io.floci.aws.services.eventbridgev2.model.SubscriberV2; +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 java.net.URI; +import java.nio.charset.StandardCharsets; +import java.time.Duration; +import java.time.Instant; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.TreeSet; + +import static io.floci.aws.services.eventbridgev2.WebhookSourceFixture.HMAC_AUTH; +import static io.floci.aws.services.eventbridgev2.WebhookSourceFixture.MAPPER; +import static io.floci.aws.services.eventbridgev2.WebhookSourceFixture.NOW; +import static io.floci.aws.services.eventbridgev2.WebhookSourceFixture.REGION; +import static io.floci.aws.services.eventbridgev2.WebhookSourceFixture.ROLE; +import static io.floci.aws.services.eventbridgev2.WebhookSourceFixture.STATIC_AUTH; +import static io.floci.aws.services.eventbridgev2.WebhookSourceFixture.json; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +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.RETURNS_DEEP_STUBS; +import static org.mockito.Mockito.doAnswer; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +/** + * RevokeResource against a real Secrets Manager service, with the messages, statuses and the order of checks as + * measured on AWS. + */ +class EventBridgeV2RevokeResourceTest { + private static final String QUEUE = "arn:aws:sqs:us-east-1:000000000000:orders"; + private static final String ID = "abcdefghijklmnopqrstuvwxy"; + private static final String ARN_PATTERN = "arn:aws(-[a-z0-9]+)*:events:[a-z][a-z0-9]*(-[a-z0-9]+)*:([0-9]{12}):" + + "(subscriber|event-sourcev2\\/(aws\\.service|aws\\.partner|webhook))" + + "\\/[A-Za-z0-9][\\.\\-_A-Za-z0-9]{0,255}\\/[a-z0-9]{25}"; + private static final String SOURCE_MISSING_ID = + "arn:aws:events:us-east-1:000000000000:event-sourcev2/webhook/hook/" + ID; + private static final String UPDATE_MESSAGE = "EventSource is revoked and cannot be updated"; + private static final String ROTATE_MESSAGE = "EventSource is revoked and its credentials cannot be rotated"; + private static final String SUBSCRIBER_UPDATE_MESSAGE = "Subscriber is revoked and cannot be updated"; + private static final String IN_USE_SOURCES = "The event bus cannot be deleted because it has one or more event " + + "sources that are not revoked. Delete or revoke them and retry."; + private static final String IN_USE_BOTH = "The event bus cannot be deleted because it has subscribers and event " + + "sources that are not revoked. Delete or revoke them and retry."; + + private final List delivered = new ArrayList<>(); + private WebhookSourceFixture fixture; + private SecretsManagerService secrets; + private EventBridgeV2Service service; + private EventBridgeV2Handler handler; + private EventBridgeV2Webhooks webhooks; + private ManualClock clock; + private String bus; + private int tokens; + + @BeforeEach + void setUp() { + EventBridgeV2Delivery delivery = mock(EventBridgeV2Delivery.class); + doAnswer(call -> delivered.add(call.getArgument(0).getName())).when(delivery) + .deliver(any(), any()); + fixture = new WebhookSourceFixture(delivery); + secrets = fixture.secrets; + service = fixture.service; + webhooks = fixture.webhooks; + clock = fixture.clock; + bus = fixture.bus; + handler = new EventBridgeV2Handler(service, MAPPER); + } + + // ──────────────────────────── Order of checks ──────────────────────────── + + @Test + void theArnIsAnsweredBackForASourceAndForASubscriber() { + EventSourceV2 source = fixture.source("hook", STATIC_AUTH); + SubscriberV2 subscriber = subscriber("keep", bus); + + assertEquals(source.getArn(), revoke(source.getArn())); + assertEquals(subscriber.getArn(), revoke(subscriber.getArn())); + ObjectNode answer = (ObjectNode) handler.handle("RevokeResource", json("{\"Arn\":\"" + source.getArn() + "\"}"), + REGION).getEntity(); + assertEquals(Set.of("Arn"), fieldNames(answer)); + assertEquals(source.getArn(), answer.get("Arn").textValue()); + } + + @Test + void constraintsComeBeforeTheRegionCheck() { + assertRefused(400, "InvalidInputException", "1 validation error detected: Value 'arn:aws:events:" + + "eu-west-1:000000000000:event-busv2/orders/" + ID + "' at 'arn' failed to satisfy constraint: " + + "Member must satisfy regular expression pattern: " + ARN_PATTERN, + "{\"Arn\":\"arn:aws:events:eu-west-1:000000000000:event-busv2/orders/" + ID + "\"}"); + } + + @Test + void anEmptyArnFailsLengthBeforePattern() { + assertRefused(400, "InvalidInputException", SmithyValidationErrors.message(List.of( + "Value '' at 'arn' failed to satisfy constraint: Member must have length greater than or equal to 1", + "Value '' at 'arn' failed to satisfy constraint: Member must satisfy regular expression pattern: " + + ARN_PATTERN)), "{\"Arn\":\"\"}"); + } + + @Test + void aMissingArnIsRefusedAsNull() { + assertRefused(400, "InvalidInputException", + "1 validation error detected: Value null at 'arn' failed to satisfy constraint: Member must not be null", + "{}"); + } + + @Test + void theRegionCheckComesBeforeTheAccountCheck() { + String message = "The region or partition in Arn does not match this endpoint"; + assertRefused(400, "InvalidInputException", message, "{\"Arn\":\"arn:aws:events:eu-west-1:111111111111:" + + "event-sourcev2/webhook/hook/" + ID + "\"}"); + assertRefused(400, "InvalidInputException", message, "{\"Arn\":\"arn:aws:events:eu-west-1:111111111111:" + + "subscriber/keep/" + ID + "\"}"); + assertRefused(400, "InvalidInputException", message, "{\"Arn\":\"arn:aws-us-gov:events:us-east-1:" + + "111111111111:event-sourcev2/webhook/hook/" + ID + "\"}"); + } + + @Test + void theAccountCheckComesBeforeTheLookup() { + assertRefused(403, "AccessDeniedException", "Access denied.", "{\"Arn\":\"arn:aws:events:us-east-1:" + + "111111111111:event-sourcev2/webhook/hook/" + ID + "\"}"); + assertRefused(403, "AccessDeniedException", "Access denied.", "{\"Arn\":\"arn:aws:events:us-east-1:" + + "111111111111:subscriber/keep/" + ID + "\"}"); + assertRefused(403, "AccessDeniedException", "Access denied.", "{\"Arn\":\"arn:aws:events:us-east-1:" + + "111111111111:event-sourcev2/aws.service/hook/" + ID + "\"}"); + } + + @Test + void aWebhookSourceThatDoesNotExistIsAccessDeniedNotNotFound() { + EventSourceV2 source = fixture.source("hook", STATIC_AUTH); + String wrongId = source.getArn().substring(0, source.getArn().length() - 5) + "aaaaa"; + + assertRefused(403, "AccessDeniedException", "Access denied.", "{\"Arn\":\"arn:aws:events:us-east-1:" + + "000000000000:event-sourcev2/webhook/nope/" + ID + "\"}"); + assertRefused(403, "AccessDeniedException", "Access denied.", "{\"Arn\":\"" + wrongId + "\"}"); + assertFalse(describe(source).has("Revoked")); + } + + @Test + void aSubscriberThatDoesNotExistIsAccessDenied() { + SubscriberV2 subscriber = subscriber("keep", bus); + String wrongId = subscriber.getArn().substring(0, subscriber.getArn().length() - 5) + "aaaaa"; + + assertRefused(403, "AccessDeniedException", "Access denied.", "{\"Arn\":\"arn:aws:events:us-east-1:" + + "000000000000:subscriber/nope/" + ID + "\"}"); + assertRefused(403, "AccessDeniedException", "Access denied.", "{\"Arn\":\"" + wrongId + "\"}"); + assertFalse(subscriber(subscriber.getArn()).isRevoked()); + } + + @Test + void anAwsServiceOrPartnerSourceArnIsNotFound() { + for (String type : List.of("aws.service", "aws.partner")) { + String arn = "arn:aws:events:us-east-1:000000000000:event-sourcev2/" + type + "/rv-src/" + ID; + assertRefused(404, "ResourceNotFoundException", "EventSource not found: " + arn, + "{\"Arn\":\"" + arn + "\"}"); + } + } + + // ──────────────────────────── A revoked source ──────────────────────────── + + @Test + void aRevokedSourceStaysActiveAndMovesItsModifiedTimeToTheRevokeTime() { + EventSourceV2 source = fixture.source("hook", STATIC_AUTH); + clock.advance(Duration.ofMinutes(1)); + + revoke(source.getArn()); + + EventSourceV2 revoked = service.describeEventSource(json("{\"EventSourceArn\":\"" + source.getArn() + "\"}"), + REGION); + assertTrue(revoked.isRevoked()); + assertEquals("ACTIVE", revoked.getState()); + assertEquals(NOW, revoked.getCreationTime()); + assertEquals(NOW.plusSeconds(60), revoked.getLastModifiedTime()); + } + + @Test + void aSecondRevokeAnswersOkAndLeavesTheModifiedTimeAlone() { + EventSourceV2 source = fixture.source("hook", STATIC_AUTH); + clock.advance(Duration.ofMinutes(1)); + revoke(source.getArn()); + clock.advance(Duration.ofMinutes(1)); + + assertEquals(source.getArn(), revoke(source.getArn())); + + assertTrue(service.describeEventSource(json("{\"EventSourceArn\":\"" + source.getArn() + "\"}"), REGION) + .isRevoked()); + assertEquals(NOW.plusSeconds(60), service.describeEventSource(json("{\"EventSourceArn\":\"" + + source.getArn() + "\"}"), REGION).getLastModifiedTime()); + } + + @Test + void theSecretOfARevokedSourceStaysAndItsNameStaysTaken() { + EventSourceV2 source = fixture.source("hook", STATIC_AUTH); + revoke(source.getArn()); + + assertNull(secrets.describeSecret(source.getSecretArn(), REGION).getDeletedDate()); + assertEquals("original-token", secrets.getSecretValue(source.getSecretArn(), null, "AWSCURRENT", REGION) + .getSecretString()); + AwsException e = assertThrows(AwsException.class, () -> service.createEventSource(json("{\"ClientToken\":" + + "\"another\",\"Name\":\"hook\",\"EventBusArn\":\"" + bus + "\",\"Configuration\":" + + "{\"WebhookEventsConfiguration\":{\"AuthConfiguration\":" + STATIC_AUTH + ",\"RoleArn\":\"" + ROLE + + "\"}}}"), REGION)); + assertEquals("ResourceAlreadyExistsException", e.getErrorCode()); + assertEquals(409, e.getHttpStatus()); + assertEquals("Resource already exists", e.getMessage()); + } + + @Test + void describeAndListReportRevokedOnlyOnceTheSourceIsRevoked() { + EventSourceV2 revoked = fixture.source("rv-src", STATIC_AUTH); + EventSourceV2 live = fixture.source("rv-live", STATIC_AUTH); + revoke(revoked.getArn()); + + assertEquals(true, describe(revoked).get("Revoked").booleanValue()); + assertEquals("ACTIVE", describe(revoked).get("State").textValue()); + assertTrue(describe(revoked).has("Configuration")); + assertFalse(describe(live).has("Revoked")); + JsonNode listed = list("{}").get("EventSources"); + for (JsonNode summary : listed) { + boolean isRevoked = summary.get("Name").textValue().equals("rv-src"); + assertEquals(isRevoked, summary.has("Revoked"), summary.toString()); + if (isRevoked) { + assertEquals(true, summary.get("Revoked").booleanValue()); + assertEquals("ACTIVE", summary.get("State").textValue()); + } + } + assertEquals(2, listed.size()); + } + + @Test + void updateOfARevokedSourceIsInvalidStateAndChangesNothing() { + EventSourceV2 source = fixture.source("hook", STATIC_AUTH); + revoke(source.getArn()); + + assertAnswer(409, "InvalidStateException", UPDATE_MESSAGE, "UpdateEventSource", + "{\"EventSourceArn\":\"" + source.getArn() + "\",\"Description\":\"changed\"}"); + assertAnswer(409, "InvalidStateException", UPDATE_MESSAGE, "UpdateEventSource", + "{\"EventSourceArn\":\"" + source.getArn() + "\",\"Configuration\":{\"WebhookEventsConfiguration\":" + + "{\"AuthConfiguration\":{\"StaticTokenAuthConfiguration\":{\"TokenHttpHeader\":\"X-Tok\"}}," + + "\"RoleArn\":\"" + ROLE + "\"}}}"); + assertAnswer(409, "InvalidStateException", UPDATE_MESSAGE, "UpdateEventSource", + "{\"EventSourceArn\":\"" + source.getArn() + "\"}"); + assertNull(describe(source).get("Description")); + } + + @Test + void theRevokedCheckOfUpdateComesAfterItsBadRequestChecks() { + EventSourceV2 source = fixture.source("hook", STATIC_AUTH); + revoke(source.getArn()); + + assertAnswer(400, "InvalidInputException", "Exactly one Configuration sub-field must be provided", + "UpdateEventSource", "{\"EventSourceArn\":\"" + source.getArn() + "\",\"Configuration\":{}}"); + assertAnswer(400, "InvalidInputException", + "The webhook authentication type can't be changed after the EventSource is created", + "UpdateEventSource", "{\"EventSourceArn\":\"" + source.getArn() + "\",\"Configuration\":" + + "{\"WebhookEventsConfiguration\":{\"AuthConfiguration\":{\"BasicHttpAuthConfiguration\":{}}," + + "\"RoleArn\":\"" + ROLE + "\"}}}"); + assertAnswer(400, "InvalidInputException", "1 validation error detected: Value 'bad' at 'eventSourceArn' " + + "failed to satisfy constraint: Member must satisfy regular expression pattern: " + + "arn:aws(-[a-z0-9]+)*:events:[a-z][a-z0-9]*(-[a-z0-9]+)*:([0-9]{12}):event-sourcev2\\/" + + "(aws\\.service|aws\\.partner|webhook)\\/[A-Za-z0-9][\\.\\-_A-Za-z0-9]{0,255}\\/[a-z0-9]{25}", + "UpdateEventSource", "{\"EventSourceArn\":\"bad\"}"); + assertAnswer(403, "AccessDeniedException", "Access denied.", "UpdateEventSource", + "{\"EventSourceArn\":\"" + source.getArn() + "\",\"Configuration\":{\"WebhookEventsConfiguration\":" + + "{\"AuthConfiguration\":" + STATIC_AUTH + ",\"RoleArn\":\"arn:aws:iam::111111111111:role/x\"}}}"); + } + + @Test + void rotateOfARevokedSourceIsInvalidState() { + EventSourceV2 source = fixture.source("hook", STATIC_AUTH); + revoke(source.getArn()); + + assertAnswer(409, "InvalidStateException", ROTATE_MESSAGE, "RotateWebhookCredentials", + rotation(source, "{\"StaticTokenSecretValue\":\"second-token\"}")); + assertAnswer(409, "InvalidStateException", ROTATE_MESSAGE, "RotateWebhookCredentials", rotation(source, null)); + assertEquals("original-token", secrets.getSecretValue(source.getSecretArn(), null, "AWSCURRENT", REGION) + .getSecretString()); + } + + @Test + void theRevokedCheckOfRotateComesAfterItsBadRequestChecks() { + EventSourceV2 source = fixture.source("hook", STATIC_AUTH); + revoke(source.getArn()); + + assertAnswer(400, "InvalidInputException", + "Credential must set exactly one of StaticTokenSecretValue, BasicHttpPassword or HmacSecretValue", + "RotateWebhookCredentials", rotation(source, "{}")); + assertAnswer(400, "InvalidInputException", "Credential must set StaticTokenSecretValue, because the " + + "authentication type of this EventSource is StaticTokenAuthConfiguration", + "RotateWebhookCredentials", rotation(source, "{\"BasicHttpPassword\":\"password\"}")); + assertAnswer(400, "InvalidInputException", "ClientToken is required", "RotateWebhookCredentials", + "{\"EventSourceArn\":\"" + source.getArn() + "\"}"); + assertAnswer(404, "ResourceNotFoundException", "EventSource not found: " + SOURCE_MISSING_ID, + "RotateWebhookCredentials", "{\"EventSourceArn\":\"" + SOURCE_MISSING_ID + "\",\"ClientToken\":\"t\"," + + "\"Credential\":{\"StaticTokenSecretValue\":\"second-token\"}}"); + } + + @Test + void theRevokedCheckOfRotateComesAfterTheValueRulesOfTheAuthenticationType() { + EventSourceV2 source = fixture.source("hmac", HMAC_AUTH); + revoke(source.getArn()); + + assertAnswer(400, "InvalidInputException", + "Credential.HmacSecretValue cannot be used with the authentication settings of this EventSource", + "RotateWebhookCredentials", rotation(source, "{\"HmacSecretValue\":\"short-secret1\"}")); + assertAnswer(409, "InvalidStateException", ROTATE_MESSAGE, "RotateWebhookCredentials", + rotation(source, "{\"HmacSecretValue\":\"0123456789abcdefghij\"}")); + } + + @Test + void theRevokedCheckOfRotateComesAfterTheReplayOfAClientToken() { + EventSourceV2 source = fixture.source("hook", STATIC_AUTH); + String request = "{\"EventSourceArn\":\"" + source.getArn() + "\",\"ClientToken\":\"same\"," + + "\"Credential\":{\"StaticTokenSecretValue\":\"second-token\"}}"; + service.rotateWebhookCredentials(json(request), REGION); + revoke(source.getArn()); + + assertEquals(source.getSecretArn(), service.rotateWebhookCredentials(json(request), REGION)); + assertAnswer(409, "IdempotentParameterMismatchException", + "ClientToken was used by a previous request with different parameters", "RotateWebhookCredentials", + request.replace("second-token", "third-token")); + assertAnswer(409, "InvalidStateException", ROTATE_MESSAGE, "RotateWebhookCredentials", + request.replace("same", "new")); + } + + @Test + void aRevokedSourceCanStillBeDescribedAndDeletedAndItsSecretGoesWithIt() { + EventSourceV2 source = fixture.source("hook", STATIC_AUTH); + revoke(source.getArn()); + + service.deleteEventSource(json("{\"EventSourceArn\":\"" + source.getArn() + "\"}"), REGION); + + assertNotNull(secrets.describeSecret(source.getSecretArn(), REGION).getDeletedDate()); + assertTrue(list("{}").get("EventSources").isEmpty()); + assertEquals("hook", fixture.source("hook", STATIC_AUTH).getName()); + } + + @Test + void aRevokedSourceAnswersForbiddenOnItsUrl() { + EventSourceV2 source = fixture.source("hook", STATIC_AUTH); + URI url = URI.create(service.webhookUrl(source)); + revoke(source.getArn()); + + assertEquals(EventBridgeV2Webhooks.FORBIDDEN, webhooks.receive(new Request("POST", source.getWebhookHostId(), + url.getPath(), Map.of("x-tok", "original-token"), "{}".getBytes(StandardCharsets.UTF_8), false))); + } + + // ──────────────────────────── A revoked subscriber ──────────────────────────── + + @Test + void aRevokedSubscriberStaysRunningAndMovesItsModifiedTimeToTheRevokeTime() { + SubscriberV2 subscriber = subscriber("keep", bus); + clock.advance(Duration.ofMinutes(1)); + + revoke(subscriber.getArn()); + + SubscriberV2 revoked = subscriber(subscriber.getArn()); + assertTrue(revoked.isRevoked()); + assertEquals("RUNNING", revoked.getState()); + assertEquals(NOW, revoked.getCreationTime()); + assertEquals(NOW.plusSeconds(60), revoked.getLastModifiedTime()); + } + + @Test + void aSecondRevokeOfASubscriberAnswersOkAndLeavesTheModifiedTimeAlone() { + SubscriberV2 subscriber = subscriber("keep", bus); + clock.advance(Duration.ofMinutes(1)); + revoke(subscriber.getArn()); + clock.advance(Duration.ofMinutes(1)); + + assertEquals(subscriber.getArn(), revoke(subscriber.getArn())); + + assertEquals(NOW.plusSeconds(60), subscriber(subscriber.getArn()).getLastModifiedTime()); + } + + @Test + void describeAndListReportTheStoredRevokedFlagOfASubscriber() { + SubscriberV2 revoked = subscriber("rv-rev", bus); + SubscriberV2 keep = subscriber("rv-keep", bus); + revoke(revoked.getArn()); + + assertEquals(true, describeSubscriber(revoked).get("Revoked").booleanValue()); + assertEquals("RUNNING", describeSubscriber(revoked).get("State").textValue()); + assertFalse(describeSubscriber(keep).has("Revoked")); + for (JsonNode summary : handlerList("ListSubscribers", "{}").get("Subscribers")) { + assertEquals(summary.get("Name").textValue().equals("rv-rev"), summary.has("Revoked")); + assertEquals(QUEUE, summary.get("TargetArn").textValue()); + } + } + + @Test + void updateOfARevokedSubscriberIsInvalidStateAndChangesNothing() { + SubscriberV2 subscriber = subscriber("keep", bus); + revoke(subscriber.getArn()); + + assertAnswer(409, "InvalidStateException", SUBSCRIBER_UPDATE_MESSAGE, "UpdateSubscriber", + "{\"SubscriberArn\":\"" + subscriber.getArn() + "\",\"Description\":\"changed\"}"); + assertAnswer(409, "InvalidStateException", SUBSCRIBER_UPDATE_MESSAGE, "UpdateSubscriber", + "{\"SubscriberArn\":\"" + subscriber.getArn() + "\"}"); + assertNull(subscriber(subscriber.getArn()).getDescription()); + assertTrue(subscriber(subscriber.getArn()).isRevoked()); + } + + @Test + void theRevokedCheckOfUpdateSubscriberComesAfterItsBadRequestChecks() { + SubscriberV2 subscriber = subscriber("keep", bus); + revoke(subscriber.getArn()); + String arn = subscriber.getArn(); + + assertAnswer(400, "InvalidInputException", "InvokeConfiguration.TargetArn cannot be updated.", + "UpdateSubscriber", "{\"SubscriberArn\":\"" + arn + "\",\"InvokeConfiguration\":{\"TargetArn\":\"" + + QUEUE + "\",\"RoleArn\":\"" + ROLE + "\"}}"); + assertAnswer(400, "InvalidInputException", "ResumePosition must be one of LAST_PROCESSED, LATEST.", + "UpdateSubscriber", "{\"SubscriberArn\":\"" + arn + "\",\"ResumePosition\":\"NEVER\"}"); + assertAnswer(404, "ResourceNotFoundException", "Subscriber arn:aws:events:us-east-1:000000000000:subscriber/" + + "nope/" + ID + " does not exist.", "UpdateSubscriber", "{\"SubscriberArn\":\"arn:aws:events:" + + "us-east-1:000000000000:subscriber/nope/" + ID + "\"}"); + } + + @Test + void aRevokedSubscriberGetsNoMoreEventsAndTheOtherSubscribersOfTheBusStillDo() { + SubscriberV2 revoked = subscriber("rv-rev", bus); + subscriber("rv-keep", bus); + + putEvent(); + assertEquals(Set.of("rv-rev", "rv-keep"), Set.copyOf(delivered)); + delivered.clear(); + revoke(revoked.getArn()); + putEvent(); + + assertEquals(List.of("rv-keep"), delivered); + } + + @Test + void aRevokedSubscriberCanStillBeDeleted() { + SubscriberV2 subscriber = subscriber("keep", bus); + revoke(subscriber.getArn()); + + service.deleteSubscriber(json("{\"SubscriberArn\":\"" + subscriber.getArn() + "\"}"), REGION); + + assertTrue(service.listSubscribers(json("{}"), REGION).items().isEmpty()); + } + + // ──────────────────────────── DeleteEventBus ──────────────────────────── + + @Test + void aLiveSourceOrSubscriberStillKeepsTheBus() { + EventSourceV2 source = fixture.source("hook", STATIC_AUTH); + SubscriberV2 subscriber = subscriber("keep", bus); + + assertBusKept(IN_USE_BOTH); + revoke(subscriber.getArn()); + assertBusKept(IN_USE_SOURCES); + revoke(source.getArn()); + service.deleteEventBus(bus, REGION); + assertTrue(service.listEventBuses(json("{}"), REGION).items().isEmpty()); + } + + @Test + void aBusWhoseOnlySourceIsRevokedIsDeleted() { + EventSourceV2 source = fixture.source("hook", STATIC_AUTH); + revoke(source.getArn()); + + service.deleteEventBus(bus, REGION); + + assertTrue(service.listEventBuses(json("{}"), REGION).items().isEmpty()); + } + + @Test + void aBusWhoseOnlySubscriberIsRevokedIsDeleted() { + SubscriberV2 subscriber = subscriber("keep", bus); + revoke(subscriber.getArn()); + + service.deleteEventBus(bus, REGION); + + assertTrue(service.listEventBuses(json("{}"), REGION).items().isEmpty()); + } + + @Test + void aLiveSubscriberAlongsideARevokedSourceKeepsTheBus() { + EventSourceV2 source = fixture.source("hook", STATIC_AUTH); + subscriber("keep", bus); + revoke(source.getArn()); + + AwsException e = assertThrows(AwsException.class, () -> service.deleteEventBus(bus, REGION)); + assertEquals("ResourceInUseException", e.getErrorCode()); + assertEquals("Event bus orders still has subscribers; delete them first.", e.getMessage()); + } + + @Test + void aRevokedSourceOutlivesItsBusAndIsDescribedWithoutItsConfiguration() { + EventSourceV2 source = fixture.source("hook", STATIC_AUTH); + revoke(source.getArn()); + service.deleteEventBus(bus, REGION); + + JsonNode described = describe(source); + + assertEquals(Set.of("EventSourceArn", "Name", "EventBusArn", "State", "Revoked", "EventSourceDetails", + "CreationTime", "LastModifiedTime"), fieldNames(described)); + assertEquals(bus, described.get("EventBusArn").textValue()); + assertEquals(true, described.get("Revoked").booleanValue()); + assertEquals(source.getSecretArn(), described.at("/EventSourceDetails/WebhookDetails/SecretArn").textValue()); + assertEquals(1, list("{}").get("EventSources").size()); + } + + @Test + void aRevokedSubscriberOutlivesItsBusAndIsDescribedWithoutItsDeliverySettings() { + SubscriberV2 subscriber = subscriber("keep", bus); + revoke(subscriber.getArn()); + service.deleteEventBus(bus, REGION); + + JsonNode described = describeSubscriber(subscriber); + + assertEquals(Set.of("SubscriberArn", "Name", "EventBusArn", "Type", "StartingPosition", "State", "Revoked", + "CreationTime", "LastModifiedTime"), fieldNames(described)); + JsonNode listed = handlerList("ListSubscribers", "{}").get("Subscribers"); + assertEquals(1, listed.size()); + assertEquals(QUEUE, listed.get(0).get("TargetArn").textValue()); + assertEquals(true, listed.get(0).get("Revoked").booleanValue()); + } + + @Test + void listingTheSourcesOfADeletedBusIsNotFound() { + EventSourceV2 source = fixture.source("hook", STATIC_AUTH); + revoke(source.getArn()); + service.deleteEventBus(bus, REGION); + + assertAnswer(404, "ResourceNotFoundException", "Resource does not exist", "ListEventSources", + "{\"EventBusArn\":\"" + bus + "\"}"); + } + + @Test + void anOrphanCanBeRevokedAgainAndDeletedAndItsSecretGoesWithIt() { + EventSourceV2 source = fixture.source("hook", STATIC_AUTH); + SubscriberV2 subscriber = subscriber("keep", bus); + revoke(source.getArn()); + revoke(subscriber.getArn()); + service.deleteEventBus(bus, REGION); + + assertEquals(source.getArn(), revoke(source.getArn())); + assertEquals(subscriber.getArn(), revoke(subscriber.getArn())); + service.deleteEventSource(json("{\"EventSourceArn\":\"" + source.getArn() + "\"}"), REGION); + service.deleteSubscriber(json("{\"SubscriberArn\":\"" + subscriber.getArn() + "\"}"), REGION); + + assertNotNull(secrets.describeSecret(source.getSecretArn(), REGION).getDeletedDate()); + assertTrue(list("{}").get("EventSources").isEmpty()); + assertTrue(service.listSubscribers(json("{}"), REGION).items().isEmpty()); + } + + @Test + void aNewBusOfTheSameNameDoesNotAdoptTheOrphans() { + EventSourceV2 source = fixture.source("hook", STATIC_AUTH); + SubscriberV2 subscriber = subscriber("keep", bus); + revoke(source.getArn()); + revoke(subscriber.getArn()); + service.deleteEventBus(bus, REGION); + + String recreated = service.createEventBus(json("{\"Name\":\"orders\"}"), REGION).getArn(); + + assertTrue(!recreated.equals(bus)); + assertTrue(list("{\"EventBusArn\":\"" + recreated + "\"}").get("EventSources").isEmpty()); + assertTrue(service.listSubscribers(json("{\"EventBusArn\":\"" + recreated + "\"}"), REGION).items().isEmpty()); + service.deleteEventBus(recreated, REGION); + assertEquals(1, list("{}").get("EventSources").size()); + } + + @Test + void anOrphanSubscriberDescribesItsDescriptionAsNotAccessibleOrNotAtAll() { + SubscriberV2 described = service.createSubscriber(json("{\"Name\":\"with\",\"EventBusArn\":\"" + bus + + "\",\"Description\":\"d\",\"InvokeConfiguration\":{\"TargetArn\":\"" + QUEUE + + "\",\"RoleArn\":\"" + ROLE + "\"},\"FilterConfiguration\":{\"Filters\":[{\"Scope\":" + + "\"DATA\",\"Pattern\":\"{}\"}]}}"), REGION); + SubscriberV2 plain = subscriber("without", bus); + revoke(described.getArn()); + revoke(plain.getArn()); + service.deleteEventBus(bus, REGION); + + JsonNode with = describeSubscriber(described); + assertEquals("*** Not accessible: event bus deleted ***", with.get("Description").textValue()); + assertFalse(with.has("FilterConfiguration")); + assertFalse(describeSubscriber(plain).has("Description")); + } + + @Test + void aSubscriberOfTheOrphansNameCanBeCreatedOnTheNewBusAndTheOrphanIsKept() { + SubscriberV2 orphan = subscriber("keep", bus); + revoke(orphan.getArn()); + service.deleteEventBus(bus, REGION); + String recreated = service.createEventBus(json("{\"Name\":\"orders\"}"), REGION).getArn(); + + SubscriberV2 fresh = subscriber("keep", recreated); + + assertEquals(List.of(fresh.getArn()), service.listSubscribers(json("{\"EventBusArn\":\"" + recreated + + "\"}"), REGION).items().stream().map(SubscriberV2::getArn).toList()); + assertEquals(2, service.listSubscribers(json("{}"), REGION).items().size()); + assertTrue(subscriber(orphan.getArn()).isRevoked()); + assertFalse(subscriber(fresh.getArn()).isRevoked()); + service.deleteSubscriber(json("{\"SubscriberArn\":\"" + orphan.getArn() + "\"}"), REGION); + assertEquals(fresh.getArn(), subscriber(fresh.getArn()).getArn()); + assertEquals(1, service.listSubscribers(json("{}"), REGION).items().size()); + } + + @Test + void pagesOfSubscribersShowBothTheOrphanAndItsNamesakeOnTheNewBus() { + SubscriberV2 orphan = subscriber("keep", bus); + revoke(orphan.getArn()); + service.deleteEventBus(bus, REGION); + String recreated = service.createEventBus(json("{\"Name\":\"orders\"}"), REGION).getArn(); + SubscriberV2 fresh = subscriber("keep", recreated); + + PaginatedResult first = service.listSubscribers(json("{\"MaxResults\":1}"), REGION); + PaginatedResult second = service.listSubscribers( + json("{\"MaxResults\":1,\"NextToken\":\"" + first.nextToken() + "\"}"), REGION); + + assertEquals(Set.of(orphan.getArn(), fresh.getArn()), + Set.of(first.items().get(0).getArn(), second.items().get(0).getArn())); + assertNull(second.nextToken()); + } + + @Test + void aSourceOfTheOrphansNameIsRefusedOnTheNewBusAndTheNewBusListsNone() { + EventSourceV2 orphan = fixture.source("hook", STATIC_AUTH); + revoke(orphan.getArn()); + service.deleteEventBus(bus, REGION); + String recreated = service.createEventBus(json("{\"Name\":\"orders\"}"), REGION).getArn(); + + AwsException e = assertThrows(AwsException.class, () -> service.createEventSource(json("{\"ClientToken\":" + + "\"fresh\",\"Name\":\"hook\",\"EventBusArn\":\"" + recreated + "\",\"Configuration\":" + + "{\"WebhookEventsConfiguration\":{\"AuthConfiguration\":" + STATIC_AUTH + ",\"RoleArn\":\"" + + ROLE + "\"}}}"), REGION)); + assertEquals("ResourceAlreadyExistsException", e.getErrorCode()); + assertEquals(409, e.getHttpStatus()); + assertEquals("Resource already exists", e.getMessage()); + assertTrue(list("{\"EventBusArn\":\"" + recreated + "\"}").get("EventSources").isEmpty()); + } + + @Test + void aNewBusOfTheSameNameDoesNotReceiveTheOrphanSubscribersDeliveries() { + SubscriberV2 subscriber = subscriber("keep", bus); + revoke(subscriber.getArn()); + service.deleteEventBus(bus, REGION); + String recreated = service.createEventBus(json("{\"Name\":\"orders\"}"), REGION).getArn(); + + service.putEvents(json("{\"EventBusArn\":\"" + recreated + "\",\"Entries\":[{\"Source\":\"s\"," + + "\"DetailType\":\"t\",\"Detail\":\"{}\"}]}"), REGION); + + assertTrue(delivered.isEmpty()); + } + + // ──────────────────────────── Stored state ──────────────────────────── + + @Test + void storedSourcesAndSubscribersWithoutTheFlagLoadAsNotRevoked() throws Exception { + ObjectMapper stored = new ObjectMapper().registerModule(new JavaTimeModule()); + + assertFalse(stored.readValue("{\"name\":\"hook\"}", EventSourceV2.class).isRevoked()); + assertFalse(stored.readValue("{\"name\":\"keep\"}", SubscriberV2.class).isRevoked()); + assertTrue(stored.readValue("{\"name\":\"hook\",\"revoked\":true}", EventSourceV2.class).isRevoked()); + assertTrue(stored.readValue("{\"name\":\"keep\",\"revoked\":true}", SubscriberV2.class).isRevoked()); + } + + @Test + void theFlagSurvivesTheCopiesAnUpdateOrARotationMakes() { + EventSourceV2 source = fixture.source("hook", STATIC_AUTH); + SubscriberV2 subscriber = subscriber("keep", bus); + revoke(subscriber.getArn()); + + service.updateEventSource(json("{\"EventSourceArn\":\"" + source.getArn() + "\",\"Description\":\"d\"}"), + REGION); + service.rotateWebhookCredentials(json(rotation(source, null)), REGION); + revoke(source.getArn()); + + assertTrue(describeSource(source).isRevoked()); + assertTrue(subscriber(subscriber.getArn()).isRevoked()); + assertEquals("d", describeSource(source).getDescription()); + } + + // ──────────────────────────── Helpers ──────────────────────────── + + private String revoke(String arn) { + return service.revokeResource(json("{\"Arn\":\"" + arn + "\"}"), REGION); + } + + private SubscriberV2 subscriber(String name, String eventBusArn) { + return service.createSubscriber(json("{\"Name\":\"" + name + "\",\"EventBusArn\":\"" + eventBusArn + + "\",\"InvokeConfiguration\":{\"TargetArn\":\"" + QUEUE + "\",\"RoleArn\":\"" + ROLE + "\"}}"), + REGION); + } + + private SubscriberV2 subscriber(String arn) { + return service.describeSubscriber(json("{\"SubscriberArn\":\"" + arn + "\"}"), REGION); + } + + private EventSourceV2 describeSource(EventSourceV2 source) { + return service.describeEventSource(json("{\"EventSourceArn\":\"" + source.getArn() + "\"}"), REGION); + } + + private JsonNode describe(EventSourceV2 source) { + return (JsonNode) handler.handle("DescribeEventSource", json("{\"EventSourceArn\":\"" + source.getArn() + + "\"}"), REGION).getEntity(); + } + + private JsonNode describeSubscriber(SubscriberV2 subscriber) { + return (JsonNode) handler.handle("DescribeSubscriber", json("{\"SubscriberArn\":\"" + subscriber.getArn() + + "\"}"), REGION).getEntity(); + } + + private JsonNode list(String request) { + return handlerList("ListEventSources", request); + } + + private JsonNode handlerList(String operation, String request) { + return (JsonNode) handler.handle(operation, json(request), REGION).getEntity(); + } + + private String rotation(EventSourceV2 source, String credential) { + return "{\"EventSourceArn\":\"" + source.getArn() + "\",\"ClientToken\":\"token-" + tokens++ + "\"" + + (credential == null ? "" : ",\"Credential\":" + credential) + "}"; + } + + private void putEvent() { + service.putEvents(json("{\"EventBusArn\":\"" + bus + "\",\"Entries\":[{\"Source\":\"s\"," + + "\"DetailType\":\"t\",\"Detail\":\"{}\"}]}"), REGION); + } + + private void assertBusKept(String message) { + AwsException e = assertThrows(AwsException.class, () -> service.deleteEventBus(bus, REGION)); + assertEquals("ResourceInUseException", e.getErrorCode()); + assertEquals(409, e.getHttpStatus()); + assertEquals(message, e.getMessage()); + } + + private void assertRefused(int status, String code, String message, String request) { + assertAnswer(status, code, message, "RevokeResource", request); + } + + private void assertAnswer(int status, String code, String message, String operation, String request) { + AwsException e = assertThrows(AwsException.class, () -> handler.handle(operation, json(request), REGION)); + assertEquals(status, e.getHttpStatus()); + assertEquals(code, e.getErrorCode()); + assertEquals(message, e.getMessage()); + } + + private static Set fieldNames(JsonNode node) { + Set names = new TreeSet<>(); + node.fieldNames().forEachRemaining(names::add); + return names; + } +} diff --git a/src/test/java/io/floci/aws/services/eventbridgev2/EventBridgeV2RotateCredentialsTest.java b/src/test/java/io/floci/aws/services/eventbridgev2/EventBridgeV2RotateCredentialsTest.java index b6458e95e4..68ddd5e281 100644 --- a/src/test/java/io/floci/aws/services/eventbridgev2/EventBridgeV2RotateCredentialsTest.java +++ b/src/test/java/io/floci/aws/services/eventbridgev2/EventBridgeV2RotateCredentialsTest.java @@ -32,6 +32,12 @@ import java.util.Map; import java.util.Set; import java.util.TreeMap; +import static io.floci.aws.services.eventbridgev2.WebhookSourceFixture.HMAC_AUTH; +import static io.floci.aws.services.eventbridgev2.WebhookSourceFixture.MAPPER; +import static io.floci.aws.services.eventbridgev2.WebhookSourceFixture.NOW; +import static io.floci.aws.services.eventbridgev2.WebhookSourceFixture.REGION; +import static io.floci.aws.services.eventbridgev2.WebhookSourceFixture.STATIC_AUTH; +import static io.floci.aws.services.eventbridgev2.WebhookSourceFixture.json; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotEquals; import static org.junit.jupiter.api.Assertions.assertThrows; @@ -47,18 +53,8 @@ import static org.mockito.Mockito.when; * checks as measured on AWS. */ class EventBridgeV2RotateCredentialsTest { - private static final String REGION = "us-east-1"; - private static final String ACCOUNT = "000000000000"; - private static final Instant NOW = Instant.parse("2026-11-25T06:00:00Z"); - private static final ObjectMapper MAPPER = new ObjectMapper(); - private static final String ROLE = "arn:aws:iam::000000000000:role/Hook"; - private static final String STATIC_AUTH = "{\"StaticTokenAuthConfiguration\":{\"TokenHttpHeader\":\"X-Tok\"," - + "\"SecretValue\":\"original-token\"}}"; private static final String BASIC_AUTH = "{\"BasicHttpAuthConfiguration\":{\"Username\":\"alice\"," + "\"Password\":\"original-pw\"}}"; - private static final String HMAC_AUTH = "{\"HmacAuthConfiguration\":{\"Algorithm\":\"SHA256\"," - + "\"Encoding\":\"HEX\",\"SignatureHttpHeader\":\"X-Sig\",\"SignedMessageComposition\":\"BODY\"," - + "\"SecretValue\":\"0123456789abcdef\"}}"; private static final String HMAC_BASE64_AUTH = "{\"HmacAuthConfiguration\":{\"Algorithm\":\"SHA256\"," + "\"Encoding\":\"HEX\",\"SignatureHttpHeader\":\"X-Sig\",\"SignedMessageComposition\":\"BODY\"," + "\"SecretEncoding\":\"BASE64\",\"SecretValue\":\"MDEyMzQ1Njc4OWFiY2RlZg==\"}}"; @@ -71,6 +67,7 @@ class EventBridgeV2RotateCredentialsTest { private static final String HMAC_BASE64_MESSAGE = "Credential.HmacSecretValue must be standard Base64 when the " + "SecretEncoding of the EventSource is BASE64"; + private WebhookSourceFixture fixture; private SecretsManagerService secrets; private EventBridgeV2Service service; private EventBridgeV2Webhooks webhooks; @@ -80,28 +77,19 @@ class EventBridgeV2RotateCredentialsTest { @BeforeEach void setUp() { - StorageFactory factory = mock(StorageFactory.class); - when(factory.create(eq("secretsmanager"), any(), any(TypeReference.class))) - .thenAnswer(call -> AccountAwareStorageBackend.inMemory(ACCOUNT)); - EmulatorConfig config = mock(EmulatorConfig.class, RETURNS_DEEP_STUBS); - when(config.services().secretsmanager().defaultRecoveryWindowDays()).thenReturn(30); - RegionResolver regionResolver = new RegionResolver(REGION, ACCOUNT); - secrets = new SecretsManagerService(factory, config, regionResolver, null, MAPPER, null); - clock = new ManualClock(NOW); - EventBridgeV2EventSources sources = new EventBridgeV2EventSources( - AccountAwareStorageBackend.inMemory(ACCOUNT), secrets, regionResolver, clock, "http://floci.test:4566"); - service = new EventBridgeV2Service(AccountAwareStorageBackend.inMemory(ACCOUNT), - AccountAwareStorageBackend.inMemory(ACCOUNT), regionResolver, mock(EventBridgeV2Delivery.class), - sources, clock, true); - webhooks = new EventBridgeV2Webhooks(service, sources, secrets, clock); - bus = service.createEventBus(json("{\"Name\":\"orders\"}"), REGION).getArn(); + fixture = new WebhookSourceFixture(mock(EventBridgeV2Delivery.class)); + secrets = fixture.secrets; + service = fixture.service; + webhooks = fixture.webhooks; + clock = fixture.clock; + bus = fixture.bus; } // ──────────────────────────── The secret ──────────────────────────── @Test void aSuppliedStaticTokenReplacesTheSecretAndKeepsTheOldOneAsPrevious() { - EventSourceV2 source = source("hook", STATIC_AUTH); + EventSourceV2 source = fixture.source("hook", STATIC_AUTH); String first = versionOf(source, "AWSCURRENT"); String secretArn = rotate(source, "{\"StaticTokenSecretValue\":\"second-token\"}"); @@ -115,7 +103,7 @@ class EventBridgeV2RotateCredentialsTest { @Test void aSecondRotationLeavesOnlyTheNewestTwoVersionsStaged() { - EventSourceV2 source = source("hook", STATIC_AUTH); + EventSourceV2 source = fixture.source("hook", STATIC_AUTH); String first = versionOf(source, "AWSCURRENT"); rotate(source, "{\"StaticTokenSecretValue\":\"second-token\"}"); String second = versionOf(source, "AWSCURRENT"); @@ -131,7 +119,7 @@ class EventBridgeV2RotateCredentialsTest { @Test void noCredentialGeneratesA44CharacterValue() { - EventSourceV2 source = source("hook", STATIC_AUTH); + EventSourceV2 source = fixture.source("hook", STATIC_AUTH); rotate(source, null); @@ -143,7 +131,7 @@ class EventBridgeV2RotateCredentialsTest { @Test void aNullCredentialAndAKnownMemberWithANullOneAreAccepted() { - EventSourceV2 source = source("hook", STATIC_AUTH); + EventSourceV2 source = fixture.source("hook", STATIC_AUTH); service.rotateWebhookCredentials(json("{\"EventSourceArn\":\"" + source.getArn() + "\",\"ClientToken\":\"t-null\",\"Credential\":null}"), REGION); @@ -155,7 +143,7 @@ class EventBridgeV2RotateCredentialsTest { @Test void basicKeepsItsUsernameWhetherThePasswordIsSuppliedOrGenerated() throws Exception { - EventSourceV2 source = source("hook", BASIC_AUTH); + EventSourceV2 source = fixture.source("hook", BASIC_AUTH); rotate(source, "{\"BasicHttpPassword\":\"pass:with:colon é\"}"); JsonNode supplied = MAPPER.readTree(valueOf(source, "AWSCURRENT")); @@ -172,7 +160,7 @@ class EventBridgeV2RotateCredentialsTest { @Test void basicWithAGeneratedUsernameKeepsTheGeneratedOne() throws Exception { - EventSourceV2 source = source("hook", "{\"BasicHttpAuthConfiguration\":{}}"); + EventSourceV2 source = fixture.source("hook", "{\"BasicHttpAuthConfiguration\":{}}"); String username = MAPPER.readTree(valueOf(source, "AWSCURRENT")).get("username").textValue(); rotate(source, "{\"BasicHttpPassword\":\"new-password\"}"); @@ -182,7 +170,7 @@ class EventBridgeV2RotateCredentialsTest { @Test void aRawHmacSecretIsStoredAsGivenWithItsPrefix() { - EventSourceV2 source = source("hook", HMAC_AUTH); + EventSourceV2 source = fixture.source("hook", HMAC_AUTH); rotate(source, "{\"HmacSecretValue\":\"whsec_aaaaaaaaaa\"}"); assertEquals("whsec_aaaaaaaaaa", valueOf(source, "AWSCURRENT")); @@ -196,7 +184,7 @@ class EventBridgeV2RotateCredentialsTest { @Test void aRawHmacSecretOutsideSixteenToFiveHundredTwelveBytesIsRefused() { - EventSourceV2 source = source("hook", HMAC_AUTH); + EventSourceV2 source = fixture.source("hook", HMAC_AUTH); assertRefused(source, "{\"HmacSecretValue\":\"aaaaaaaaaaaaaaa\"}", HMAC_RANGE_MESSAGE); assertRefused(source, "{\"HmacSecretValue\":\"" + "é".repeat(257) + "\"}", HMAC_RANGE_MESSAGE); @@ -206,7 +194,7 @@ class EventBridgeV2RotateCredentialsTest { @Test void aBase64HmacSecretLosesItsPrefixAndKeepsItsPadding() { - EventSourceV2 source = source("hook", HMAC_BASE64_AUTH); + EventSourceV2 source = fixture.source("hook", HMAC_BASE64_AUTH); rotate(source, "{\"HmacSecretValue\":\"whsec_a2tra2tra2tra2tra2traw==\"}"); assertEquals("a2tra2tra2tra2tra2traw==", valueOf(source, "AWSCURRENT")); @@ -217,7 +205,7 @@ class EventBridgeV2RotateCredentialsTest { @Test void aBase64HmacSecretMustBeStandardBase64OfEnoughBytes() { - EventSourceV2 source = source("hook", HMAC_BASE64_AUTH); + EventSourceV2 source = fixture.source("hook", HMAC_BASE64_AUTH); assertRefused(source, "{\"HmacSecretValue\":\"a2tra2tra2tra2tra2tr_w==\"}", HMAC_BASE64_MESSAGE); assertRefused(source, "{\"HmacSecretValue\":\"a2tra2tra2tra2tra2tr\\naw==\"}", HMAC_BASE64_MESSAGE); @@ -230,7 +218,7 @@ class EventBridgeV2RotateCredentialsTest { @Test void aGeneratedHmacSecretIs44Characters() { - EventSourceV2 source = source("hook", HMAC_BASE64_AUTH); + EventSourceV2 source = fixture.source("hook", HMAC_BASE64_AUTH); rotate(source, null); @@ -239,7 +227,7 @@ class EventBridgeV2RotateCredentialsTest { @Test void rotatingToTheValueThatIsAlreadyCurrentWritesNoVersion() { - EventSourceV2 source = source("hook", STATIC_AUTH); + EventSourceV2 source = fixture.source("hook", STATIC_AUTH); Map> before = secrets.listSecretVersionIds(source.getSecretArn(), REGION); rotate(source, "{\"StaticTokenSecretValue\":\"original-token\"}"); @@ -249,7 +237,7 @@ class EventBridgeV2RotateCredentialsTest { @Test void rotatingBasicToTheCurrentPasswordWritesNoVersion() { - EventSourceV2 source = source("hook", BASIC_AUTH); + EventSourceV2 source = fixture.source("hook", BASIC_AUTH); Map> before = secrets.listSecretVersionIds(source.getSecretArn(), REGION); rotate(source, "{\"BasicHttpPassword\":\"original-pw\"}"); @@ -259,7 +247,7 @@ class EventBridgeV2RotateCredentialsTest { @Test void rotatingHmacToTheCurrentValueWithItsPrefixWritesNoVersion() { - EventSourceV2 source = source("hook", HMAC_BASE64_AUTH); + EventSourceV2 source = fixture.source("hook", HMAC_BASE64_AUTH); Map> before = secrets.listSecretVersionIds(source.getSecretArn(), REGION); rotate(source, "{\"HmacSecretValue\":\"whsec_MDEyMzQ1Njc4OWFiY2RlZg==\"}"); @@ -269,7 +257,7 @@ class EventBridgeV2RotateCredentialsTest { @Test void theSourceKeepsItsModifiedTimeUrlAndSecret() { - EventSourceV2 source = source("hook", STATIC_AUTH); + EventSourceV2 source = fixture.source("hook", STATIC_AUTH); String url = service.webhookUrl(source); clock.advance(Duration.ofMinutes(5)); @@ -284,7 +272,7 @@ class EventBridgeV2RotateCredentialsTest { @Test void anUpdateKeepsTheRememberedTokens() { - EventSourceV2 source = source("hook", STATIC_AUTH); + EventSourceV2 source = fixture.source("hook", STATIC_AUTH); rotate(source, "{\"StaticTokenSecretValue\":\"second-token\"}"); EventSourceV2 updated = service.updateEventSource(json("{\"EventSourceArn\":\"" + source.getArn() @@ -306,7 +294,7 @@ class EventBridgeV2RotateCredentialsTest { @Test void anyCountOfMembersButOneIsRefused() { - EventSourceV2 source = source("hook", STATIC_AUTH); + EventSourceV2 source = fixture.source("hook", STATIC_AUTH); assertRefused(source, "{}", UNION_MESSAGE); assertRefused(source, "{\"StaticTokenSecretValue\":null}", UNION_MESSAGE); @@ -318,9 +306,9 @@ class EventBridgeV2RotateCredentialsTest { @Test void theMemberMustBeTheOneOfTheAuthenticationType() { - EventSourceV2 staticSource = source("tok", STATIC_AUTH); - EventSourceV2 basicSource = source("bas", BASIC_AUTH); - EventSourceV2 hmacSource = source("hmc", HMAC_AUTH); + EventSourceV2 staticSource = fixture.source("tok", STATIC_AUTH); + EventSourceV2 basicSource = fixture.source("bas", BASIC_AUTH); + EventSourceV2 hmacSource = fixture.source("hmc", HMAC_AUTH); assertRefused(staticSource, "{\"BasicHttpPassword\":\"second-pw\"}", "Credential must set StaticTokenSecretValue, because the authentication type of this EventSource is " @@ -382,7 +370,7 @@ class EventBridgeV2RotateCredentialsTest { @Test void theMemberCheckComesBeforeTheValueRules() { - EventSourceV2 source = source("hook", HMAC_AUTH); + EventSourceV2 source = fixture.source("hook", HMAC_AUTH); assertRefused(source, "{\"StaticTokenSecretValue\":\"short1\"}", "Credential must set HmacSecretValue, " + "because the authentication type of this EventSource is HmacAuthConfiguration"); @@ -390,7 +378,7 @@ class EventBridgeV2RotateCredentialsTest { @Test void theValueRulesComeBeforeTheClientTokenReplay() { - EventSourceV2 source = source("hook", HMAC_AUTH); + EventSourceV2 source = fixture.source("hook", HMAC_AUTH); rotate(source, "t-replay", "{\"HmacSecretValue\":\"aaaaaaaaaaaaaaaa\"}"); AwsException e = assertThrows(AwsException.class, @@ -402,7 +390,7 @@ class EventBridgeV2RotateCredentialsTest { @Test void aRefusedRotationChangesNothing() { - EventSourceV2 source = source("hook", HMAC_AUTH); + EventSourceV2 source = fixture.source("hook", HMAC_AUTH); Map> before = secrets.listSecretVersionIds(source.getSecretArn(), REGION); assertRefused(source, "{\"HmacSecretValue\":\"short\"}", "1 validation error detected: Value at " @@ -419,7 +407,7 @@ class EventBridgeV2RotateCredentialsTest { @Test void aReplayWithTheSameRequestAnswersTheArnAndWritesNothing() { - EventSourceV2 source = source("hook", STATIC_AUTH); + EventSourceV2 source = fixture.source("hook", STATIC_AUTH); rotate(source, "t-one", "{\"StaticTokenSecretValue\":\"second-token\"}"); Map> before = secrets.listSecretVersionIds(source.getSecretArn(), REGION); @@ -431,7 +419,7 @@ class EventBridgeV2RotateCredentialsTest { @Test void aReplayStaysAReplayAfterLaterRotations() { - EventSourceV2 source = source("hook", STATIC_AUTH); + EventSourceV2 source = fixture.source("hook", STATIC_AUTH); rotate(source, "t-one", "{\"StaticTokenSecretValue\":\"second-token\"}"); rotate(source, "t-two", "{\"StaticTokenSecretValue\":\"third-token\"}"); @@ -443,7 +431,7 @@ class EventBridgeV2RotateCredentialsTest { @Test void aReplayOfAGeneratedRotationKeepsTheGeneratedValue() { - EventSourceV2 source = source("hook", STATIC_AUTH); + EventSourceV2 source = fixture.source("hook", STATIC_AUTH); rotate(source, "t-gen", null); String generated = valueOf(source, "AWSCURRENT"); Map> before = secrets.listSecretVersionIds(source.getSecretArn(), REGION); @@ -456,7 +444,7 @@ class EventBridgeV2RotateCredentialsTest { @Test void aReplayWithAnotherRequestIsAConflict() { - EventSourceV2 source = source("hook", STATIC_AUTH); + EventSourceV2 source = fixture.source("hook", STATIC_AUTH); rotate(source, "t-one", "{\"StaticTokenSecretValue\":\"second-token\"}"); rotate(source, "t-gen", null); @@ -473,8 +461,8 @@ class EventBridgeV2RotateCredentialsTest { @Test void aTokenOfAnotherSourceRotatesThisOne() { - EventSourceV2 one = source("one", STATIC_AUTH); - EventSourceV2 two = source("two", STATIC_AUTH); + EventSourceV2 one = fixture.source("one", STATIC_AUTH); + EventSourceV2 two = fixture.source("two", STATIC_AUTH); rotate(one, "t-shared", "{\"StaticTokenSecretValue\":\"second-token\"}"); rotate(two, "t-shared", "{\"StaticTokenSecretValue\":\"second-token\"}"); @@ -485,7 +473,7 @@ class EventBridgeV2RotateCredentialsTest { @Test void aRotationToTheCurrentValueStillRemembersItsToken() { - EventSourceV2 source = source("hook", STATIC_AUTH); + EventSourceV2 source = fixture.source("hook", STATIC_AUTH); rotate(source, "t-same", "{\"StaticTokenSecretValue\":\"original-token\"}"); AwsException e = assertThrows(AwsException.class, @@ -496,7 +484,7 @@ class EventBridgeV2RotateCredentialsTest { @Test void aTokenIsRememberedForJustUnderEightHours() { - EventSourceV2 source = source("hook", STATIC_AUTH); + EventSourceV2 source = fixture.source("hook", STATIC_AUTH); rotate(source, "t-1", "{\"StaticTokenSecretValue\":\"second-token\"}"); clock.advance(Duration.ofHours(8).minusSeconds(1)); @@ -510,7 +498,7 @@ class EventBridgeV2RotateCredentialsTest { @Test void aTokenIsForgottenAtExactlyEightHoursAndTheSameRequestRotatesAgain() { - EventSourceV2 source = source("hook", STATIC_AUTH); + EventSourceV2 source = fixture.source("hook", STATIC_AUTH); rotate(source, "t-1", null); String first = versionOf(source, "AWSCURRENT"); clock.advance(Duration.ofHours(8)); @@ -524,7 +512,7 @@ class EventBridgeV2RotateCredentialsTest { @Test void aForgottenTokenRotatesAgainWithADifferentRequest() { - EventSourceV2 source = source("hook", STATIC_AUTH); + EventSourceV2 source = fixture.source("hook", STATIC_AUTH); rotate(source, "t-1", "{\"StaticTokenSecretValue\":\"second-token\"}"); clock.advance(Duration.ofHours(8)); @@ -536,7 +524,7 @@ class EventBridgeV2RotateCredentialsTest { @Test void aRotationDropsTheTokensItForgot() { - EventSourceV2 source = source("hook", STATIC_AUTH); + EventSourceV2 source = fixture.source("hook", STATIC_AUTH); rotate(source, "t-old", "{\"StaticTokenSecretValue\":\"second-token\"}"); clock.advance(Duration.ofHours(4)); rotate(source, "t-mid", "{\"StaticTokenSecretValue\":\"third-token\"}"); @@ -554,7 +542,7 @@ class EventBridgeV2RotateCredentialsTest { @Test void aSecretScheduledForDeletionAnswersInvalidState() { - EventSourceV2 source = source("hook", STATIC_AUTH); + EventSourceV2 source = fixture.source("hook", STATIC_AUTH); secrets.deleteSecret(source.getSecretArn(), null, false, REGION); AwsException e = assertThrows(AwsException.class, @@ -568,7 +556,7 @@ class EventBridgeV2RotateCredentialsTest { @Test void aDeletedSecretAnswersInvalidState() { - EventSourceV2 source = source("hook", STATIC_AUTH); + EventSourceV2 source = fixture.source("hook", STATIC_AUTH); secrets.deleteSecret(source.getSecretArn(), null, true, REGION); AwsException e = assertThrows(AwsException.class, @@ -581,7 +569,7 @@ class EventBridgeV2RotateCredentialsTest { @Test void aRememberedTokenStillReplaysWhenTheSecretIsScheduledForDeletion() { - EventSourceV2 source = source("hook", STATIC_AUTH); + EventSourceV2 source = fixture.source("hook", STATIC_AUTH); rotate(source, "t-1", "{\"StaticTokenSecretValue\":\"second-token\"}"); secrets.deleteSecret(source.getSecretArn(), null, false, REGION); @@ -592,7 +580,7 @@ class EventBridgeV2RotateCredentialsTest { @Test void aReplacedStaticTokenIsAcceptedUntilFifteenMinutesAfterTheRotation() { - Target target = target(source("hook", STATIC_AUTH)); + Target target = target(fixture.source("hook", STATIC_AUTH)); assertEquals(EventBridgeV2Webhooks.OK, post(target, Map.of("x-tok", "original-token"), "{}")); rotate(target.source(), "{\"StaticTokenSecretValue\":\"second-token\"}"); @@ -609,7 +597,7 @@ class EventBridgeV2RotateCredentialsTest { @Test void aReplacedBasicCredentialIsAcceptedUntilFifteenMinutesAfterTheRotation() { - Target target = target(source("hook", BASIC_AUTH)); + Target target = target(fixture.source("hook", BASIC_AUTH)); rotate(target.source(), "{\"BasicHttpPassword\":\"second-pw\"}"); stampCurrentVersion(target.source()); @@ -627,7 +615,7 @@ class EventBridgeV2RotateCredentialsTest { @Test void aReplacedHmacSecretIsAcceptedUntilFifteenMinutesAfterTheRotation() throws Exception { - Target target = target(source("hook", HMAC_AUTH)); + Target target = target(fixture.source("hook", HMAC_AUTH)); rotate(target.source(), "{\"HmacSecretValue\":\"fedcba9876543210\"}"); stampCurrentVersion(target.source()); String body = "{\"a\":1}"; @@ -645,7 +633,7 @@ class EventBridgeV2RotateCredentialsTest { @Test void onlyTheCredentialTheLastRotationReplacedIsAccepted() { - Target target = target(source("hook", STATIC_AUTH)); + Target target = target(fixture.source("hook", STATIC_AUTH)); rotate(target.source(), "{\"StaticTokenSecretValue\":\"second-token\"}"); rotate(target.source(), "{\"StaticTokenSecretValue\":\"third-token\"}"); stampCurrentVersion(target.source()); @@ -657,7 +645,7 @@ class EventBridgeV2RotateCredentialsTest { @Test void aSourceThatWasNeverRotatedAcceptsNothingButItsCurrentCredential() { - Target target = target(source("hook", STATIC_AUTH)); + Target target = target(fixture.source("hook", STATIC_AUTH)); assertEquals(EventBridgeV2Webhooks.OK, post(target, Map.of("x-tok", "original-token"), "{}")); assertEquals(EventBridgeV2Webhooks.FORBIDDEN, post(target, Map.of("x-tok", "other-token"), "{}")); @@ -666,7 +654,7 @@ class EventBridgeV2RotateCredentialsTest { @Test void aRotationToTheCurrentValueDoesNotStartAGracePeriodForAnythingElse() { - Target target = target(source("hook", STATIC_AUTH)); + Target target = target(fixture.source("hook", STATIC_AUTH)); rotate(target.source(), "{\"StaticTokenSecretValue\":\"original-token\"}"); assertEquals(EventBridgeV2Webhooks.FORBIDDEN, post(target, Map.of("x-tok", "other-token"), "{}")); @@ -706,12 +694,6 @@ class EventBridgeV2RotateCredentialsTest { return HexFormat.of().formatHex(mac.doFinal(body.getBytes(StandardCharsets.UTF_8))); } - private EventSourceV2 source(String name, String auth) { - return service.createEventSource(json("{\"ClientToken\":\"" + name + "-token\",\"Name\":\"" + name - + "\",\"EventBusArn\":\"" + bus + "\",\"Configuration\":{\"WebhookEventsConfiguration\":" - + "{\"AuthConfiguration\":" + auth + ",\"RoleArn\":\"" + ROLE + "\"}}}"), REGION); - } - private String rotate(EventSourceV2 source, String credential) { return rotate(source, "token-" + tokens++, credential); } @@ -751,12 +733,4 @@ class EventBridgeV2RotateCredentialsTest { .forEach((versionId, stages) -> stages.forEach(stage -> found.put(stage, versionId))); return found; } - - 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/EventBridgeV2SubscriberIntegrationTest.java b/src/test/java/io/floci/aws/services/eventbridgev2/EventBridgeV2SubscriberIntegrationTest.java index b04eeaaedc..e5322c553c 100644 --- a/src/test/java/io/floci/aws/services/eventbridgev2/EventBridgeV2SubscriberIntegrationTest.java +++ b/src/test/java/io/floci/aws/services/eventbridgev2/EventBridgeV2SubscriberIntegrationTest.java @@ -29,6 +29,7 @@ import java.util.List; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; @@ -152,7 +153,7 @@ class EventBridgeV2SubscriberIntegrationTest { assertEquals("all orders", described.description()); assertEquals("{\"source\":[\"com.shop\"]}", described.filterConfiguration().filters().getFirst().pattern()); assertEquals(SubscriberState.RUNNING, described.state()); - assertEquals(Boolean.FALSE, described.revoked()); + assertNull(described.revoked()); // The SDK decodes these only from CBOR timestamps. assertNotNull(described.creationTime()); assertNotNull(described.lastModifiedTime()); diff --git a/src/test/java/io/floci/aws/services/eventbridgev2/EventBridgeV2WebhookIntegrationTest.java b/src/test/java/io/floci/aws/services/eventbridgev2/EventBridgeV2WebhookIntegrationTest.java index f9fa5d2675..fb31c99d2c 100644 --- a/src/test/java/io/floci/aws/services/eventbridgev2/EventBridgeV2WebhookIntegrationTest.java +++ b/src/test/java/io/floci/aws/services/eventbridgev2/EventBridgeV2WebhookIntegrationTest.java @@ -20,8 +20,14 @@ import org.junit.jupiter.api.Test; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.eventbridgev2.EventBridgeV2Client; import software.amazon.awssdk.services.eventbridgev2.model.CreateEventSourceResponse; +import software.amazon.awssdk.services.eventbridgev2.model.DescribeEventSourceResponse; +import software.amazon.awssdk.services.eventbridgev2.model.DescribeSubscriberResponse; import software.amazon.awssdk.services.eventbridgev2.model.EventSourceConfiguration; +import software.amazon.awssdk.services.eventbridgev2.model.EventSourceState; import software.amazon.awssdk.services.eventbridgev2.model.InvalidInputException; +import software.amazon.awssdk.services.eventbridgev2.model.InvalidStateException; +import software.amazon.awssdk.services.eventbridgev2.model.ResourceInUseException; +import software.amazon.awssdk.services.eventbridgev2.model.ResourceNotFoundException; import software.amazon.awssdk.services.eventbridgev2.model.RotateWebhookCredentialsResponse; import software.amazon.awssdk.services.eventbridgev2.model.TransformerType; import software.amazon.awssdk.services.eventbridgev2.model.WebhookAuthConfiguration; @@ -52,6 +58,7 @@ import static io.restassured.RestAssured.given; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.matchesPattern; 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; @@ -306,6 +313,110 @@ class EventBridgeV2WebhookIntegrationTest { } } + @Test + void aRevokedSourceRefusesItsUrlAndCannotBeUpdatedOrRotatedButCanBeDescribedListedAndDeleted() { + String suffix = suffix(); + try (EventBridgeV2Client events = events(); SqsClient sqs = sqs()) { + Fixture fixture = fixture(events, sqs, suffix); + Endpoint endpoint = source(events, fixture.bus(), "revoked-" + suffix, webhook -> webhook + .authConfiguration(staticToken("X-Token", "s3cret-token"))); + expect(post(endpoint, "{}", "X-Token", "s3cret-token"), 200, "OK"); + + assertEquals(endpoint.arn(), events.revokeResource(request -> request.arn(endpoint.arn())).arn()); + + DescribeEventSourceResponse described = events.describeEventSource(request -> request + .eventSourceArn(endpoint.arn())); + assertEquals(Boolean.TRUE, described.revoked()); + assertEquals(EventSourceState.ACTIVE, described.state()); + assertEquals(Boolean.TRUE, events.listEventSources(request -> request.eventBusArn(fixture.bus())) + .eventSources().getFirst().revoked()); + expect(post(endpoint, "{}", "X-Token", "s3cret-token"), 403, "Forbidden"); + expect(post(endpoint, "{}", "X-Token", "wrong"), 403, "Forbidden"); + expect(request(endpoint.host(), endpoint.path().substring(0, endpoint.path().length() - 1), "{}", + "X-Token", "s3cret-token"), 404, "Not Found"); + InvalidStateException update = assertThrows(InvalidStateException.class, + () -> events.updateEventSource(request -> request.eventSourceArn(endpoint.arn()) + .description("changed"))); + assertEquals("EventSource is revoked and cannot be updated", update.awsErrorDetails().errorMessage()); + InvalidStateException rotate = assertThrows(InvalidStateException.class, + () -> events.rotateWebhookCredentials(request -> request.eventSourceArn(endpoint.arn()))); + assertEquals("EventSource is revoked and its credentials cannot be rotated", + rotate.awsErrorDetails().errorMessage()); + assertEquals(endpoint.arn(), events.revokeResource(request -> request.arn(endpoint.arn())).arn()); + + fixture.cleanUp(events, sqs, endpoint); + } + } + + @Test + void aRevokedSubscriberGetsNoMoreEventsWhileTheOtherSubscriberOfTheBusStillDoes() throws Exception { + String suffix = suffix(); + try (EventBridgeV2Client events = events(); SqsClient sqs = sqs()) { + Fixture fixture = fixture(events, sqs, suffix); + Endpoint endpoint = source(events, fixture.bus(), "live-" + suffix, webhook -> webhook + .authConfiguration(staticToken("X-Token", "s3cret-token"))); + + events.revokeResource(request -> request.arn(fixture.rawSubscriber())); + expect(post(endpoint, "{\"n\":1}", "X-Token", "s3cret-token"), 200, "OK"); + + DescribeSubscriberResponse described = events.describeSubscriber(request -> request + .subscriberArn(fixture.rawSubscriber())); + assertEquals(Boolean.TRUE, described.revoked()); + assertEquals(Boolean.TRUE, events.listSubscribers(request -> request.eventBusArn(fixture.bus())) + .subscribers().stream().filter(summary -> summary.subscriberArn().equals(fixture.rawSubscriber())) + .findFirst().orElseThrow().revoked()); + assertEquals(1, received(sqs, fixture.metadataQueue(), 1).size()); + assertTrue(messages(sqs, fixture.rawQueue(), 1).isEmpty()); + InvalidStateException update = assertThrows(InvalidStateException.class, + () -> events.updateSubscriber(request -> request.subscriberArn(fixture.rawSubscriber()) + .description("changed"))); + assertEquals("Subscriber is revoked and cannot be updated", update.awsErrorDetails().errorMessage()); + + fixture.cleanUp(events, sqs, endpoint); + } + } + + @Test + void aBusWhoseOnlyResourcesAreRevokedIsDeletedAndTheyAreDescribedAfterItWithoutTheirConfiguration() { + String suffix = suffix(); + try (EventBridgeV2Client events = events(); SqsClient sqs = sqs()) { + String queueUrl = sqs.createQueue(request -> request.queueName("v2-orphan-" + suffix)).queueUrl(); + String bus = events.createEventBus(request -> request.name("v2-orphan-" + suffix)).eventBusArn(); + String subscriber = events.createSubscriber(request -> request.name("orphan").eventBusArn(bus) + .invokeConfiguration(invoke -> invoke.targetArn(queueArn(sqs, queueUrl)).roleArn(ROLE))) + .subscriberArn(); + Endpoint endpoint = source(events, bus, "orphan-" + suffix, webhook -> webhook + .authConfiguration(staticToken("X-Token", "s3cret-token"))); + assertThrows(ResourceInUseException.class, + () -> events.deleteEventBus(request -> request.eventBusArn(bus))); + + events.revokeResource(request -> request.arn(subscriber)); + events.revokeResource(request -> request.arn(endpoint.arn())); + events.deleteEventBus(request -> request.eventBusArn(bus)); + + DescribeEventSourceResponse source = events.describeEventSource(request -> request + .eventSourceArn(endpoint.arn())); + assertEquals(Boolean.TRUE, source.revoked()); + assertNull(source.configuration()); + DescribeSubscriberResponse described = events.describeSubscriber(request -> request + .subscriberArn(subscriber)); + assertEquals(Boolean.TRUE, described.revoked()); + assertNull(described.invokeConfiguration()); + assertNull(described.retryPolicy()); + assertNull(described.transformer()); + assertNull(described.batchConfiguration()); + assertEquals(queueArn(sqs, queueUrl), events.listSubscribers(request -> { }).subscribers().stream() + .filter(summary -> summary.subscriberArn().equals(subscriber)).findFirst().orElseThrow() + .targetArn()); + assertThrows(ResourceNotFoundException.class, + () -> events.listEventSources(request -> request.eventBusArn(bus))); + + events.deleteEventSource(request -> request.eventSourceArn(endpoint.arn())); + events.deleteSubscriber(request -> request.subscriberArn(subscriber)); + sqs.deleteQueue(request -> request.queueUrl(queueUrl)); + } + } + // ──────────────────────────── Fixtures ──────────────────────────── private record Fixture(String bus, String metadataQueue, String rawQueue, String metadataSubscriber, 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 f21960338a..20d2a28adb 100644 --- a/src/test/java/io/floci/aws/services/eventbridgev2/EventBridgeV2WebhooksTest.java +++ b/src/test/java/io/floci/aws/services/eventbridgev2/EventBridgeV2WebhooksTest.java @@ -289,6 +289,75 @@ class EventBridgeV2WebhooksTest { answer("POST", target, target.path(), Map.of("x-sig", signature), "{\"a\":1}")); } + // ──────────────────────────── Revoked sources and subscribers ──────────────────────────── + + @Test + void aRevokedStaticTokenSourceAnswersForbiddenForTheRightAndAWrongToken() { + Target target = source("hook", TOKEN_AUTH, ""); + revoke(target.source().getArn()); + + assertEquals(EventBridgeV2Webhooks.FORBIDDEN, answer("POST", target, target.path(), Map.of("x-tok", "s3cret"), "{}")); + assertEquals(EventBridgeV2Webhooks.FORBIDDEN, answer("POST", target, target.path(), Map.of("x-tok", "no"), "{}")); + assertEquals(EventBridgeV2Webhooks.FORBIDDEN, answer("POST", target, target.path(), Map.of(), "{bad")); + assertTrue(deliveredBodies.isEmpty()); + } + + @Test + void aRevokedBasicSourceAnswersForbiddenForTheRightAndAWrongCredential() { + Target target = source("basic", "{\"BasicHttpAuthConfiguration\":{\"Username\":\"alice\"," + + "\"Password\":\"pw1234\"}}", ""); + String good = "Basic " + Base64.getEncoder().encodeToString("alice:pw1234".getBytes(StandardCharsets.UTF_8)); + revoke(target.source().getArn()); + + assertEquals(EventBridgeV2Webhooks.FORBIDDEN, answer("POST", target, target.path(), Map.of("authorization", good), "{}")); + assertEquals(EventBridgeV2Webhooks.FORBIDDEN, + answer("POST", target, target.path(), Map.of("authorization", good + "x"), "{}")); + assertTrue(deliveredBodies.isEmpty()); + } + + @Test + void aRevokedHmacSourceAnswersForbiddenForTheRightAndAWrongSignature() throws Exception { + Target target = source("hmac", "{\"HmacAuthConfiguration\":{\"Algorithm\":\"SHA256\",\"Encoding\":\"HEX\"," + + "\"SignatureHttpHeader\":\"X-Sig\",\"SignedMessageComposition\":\"BODY\"," + + "\"SecretValue\":\"0123456789abcdef\"}}", ""); + String body = "{\"a\":1}"; + Mac mac = Mac.getInstance("HmacSHA256"); + mac.init(new SecretKeySpec("0123456789abcdef".getBytes(StandardCharsets.UTF_8), "HmacSHA256")); + String signature = HexFormat.of().formatHex(mac.doFinal(body.getBytes(StandardCharsets.UTF_8))); + revoke(target.source().getArn()); + + assertEquals(EventBridgeV2Webhooks.FORBIDDEN, answer("POST", target, target.path(), Map.of("x-sig", signature), body)); + assertEquals(EventBridgeV2Webhooks.FORBIDDEN, answer("POST", target, target.path(), Map.of("x-sig", "00"), body)); + assertTrue(deliveredBodies.isEmpty()); + } + + @Test + void aRevokedSourceKeepsTheEarlierChecksOfTheDataPlane() { + Target target = source("hook", TOKEN_AUTH, ""); + revoke(target.source().getArn()); + Map good = Map.of("x-tok", "s3cret"); + + assertEquals(EventBridgeV2Webhooks.BAD_REQUEST, answer("GET", target, target.path(), good, "{}")); + assertEquals(EventBridgeV2Webhooks.NOT_FOUND, + answer("POST", target, target.path().substring(0, target.path().length() - 1), good, "{}")); + assertEquals(EventBridgeV2Webhooks.NOT_FOUND, answer("POST", target, target.path() + "extra/", good, "{}")); + assertEquals(EventBridgeV2Webhooks.BAD_REQUEST, webhooks.receive(new Request("POST", target.hostId(), + target.path(), good, new byte[0], true))); + } + + @Test + void aRevokedSubscriberGetsNothingAndTheOthersOfTheBusStillDo() { + Target target = source("hook", TOKEN_AUTH, ""); + String metaArn = service.listSubscribers(json("{\"EventBusArn\":\"" + bus + "\"}"), REGION).items().stream() + .filter(subscriber -> subscriber.getName().equals("meta")).findFirst().orElseThrow().getArn(); + revoke(metaArn); + + assertEquals(EventBridgeV2Webhooks.OK, answer("POST", target, target.path(), Map.of("x-tok", "s3cret"), "{}")); + + assertEquals(1, deliveredBodies.size()); + assertTrue(deliveredBodies.getFirst().startsWith("raw=")); + } + // ──────────────────────────── Deduplication ──────────────────────────── private static final String DEDUP = ",\"DeduplicationConfiguration\":{\"DeduplicationType\":\"CONTENT_BASED\"}"; @@ -425,6 +494,10 @@ class EventBridgeV2WebhooksTest { + "\"},\"Transformer\":" + transformer + String.join("", extra) + "}"), REGION); } + private void revoke(String arn) { + service.revokeResource(json("{\"Arn\":\"" + arn + "\"}"), REGION); + } + private Answer answer(String method, Target target, String path, Map headers, String body) { return webhooks.receive(new Request(method, target.hostId(), path, headers, body.getBytes(StandardCharsets.UTF_8), false)); diff --git a/src/test/java/io/floci/aws/services/eventbridgev2/WebhookSourceFixture.java b/src/test/java/io/floci/aws/services/eventbridgev2/WebhookSourceFixture.java new file mode 100644 index 0000000000..42e4d8aa12 --- /dev/null +++ b/src/test/java/io/floci/aws/services/eventbridgev2/WebhookSourceFixture.java @@ -0,0 +1,72 @@ +package io.floci.aws.services.eventbridgev2; + +import com.fasterxml.jackson.core.type.TypeReference; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import io.floci.aws.config.EmulatorConfig; +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.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 java.time.Instant; + +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.RETURNS_DEEP_STUBS; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +/** A real Secrets Manager service under the EventBridge V2 service, with one bus, for webhook source tests. */ +final class WebhookSourceFixture { + static final String REGION = "us-east-1"; + static final String ACCOUNT = "000000000000"; + static final Instant NOW = Instant.parse("2026-11-25T06:00:00Z"); + static final ObjectMapper MAPPER = new ObjectMapper(); + static final String ROLE = "arn:aws:iam::000000000000:role/Hook"; + static final String STATIC_AUTH = "{\"StaticTokenAuthConfiguration\":{\"TokenHttpHeader\":\"X-Tok\"," + + "\"SecretValue\":\"original-token\"}}"; + static final String HMAC_AUTH = "{\"HmacAuthConfiguration\":{\"Algorithm\":\"SHA256\"," + + "\"Encoding\":\"HEX\",\"SignatureHttpHeader\":\"X-Sig\",\"SignedMessageComposition\":\"BODY\"," + + "\"SecretValue\":\"0123456789abcdef\"}}"; + + final SecretsManagerService secrets; + final EventBridgeV2Service service; + final EventBridgeV2Webhooks webhooks; + final ManualClock clock; + final String bus; + + WebhookSourceFixture(EventBridgeV2Delivery delivery) { + StorageFactory factory = mock(StorageFactory.class); + when(factory.create(eq("secretsmanager"), any(), any(TypeReference.class))) + .thenAnswer(call -> AccountAwareStorageBackend.inMemory(ACCOUNT)); + EmulatorConfig config = mock(EmulatorConfig.class, RETURNS_DEEP_STUBS); + when(config.services().secretsmanager().defaultRecoveryWindowDays()).thenReturn(30); + RegionResolver regionResolver = new RegionResolver(REGION, ACCOUNT); + secrets = new SecretsManagerService(factory, config, regionResolver, null, MAPPER, null); + clock = new ManualClock(NOW); + EventBridgeV2EventSources sources = new EventBridgeV2EventSources( + AccountAwareStorageBackend.inMemory(ACCOUNT), secrets, regionResolver, clock, "http://floci.test:4566"); + service = new EventBridgeV2Service(AccountAwareStorageBackend.inMemory(ACCOUNT), + AccountAwareStorageBackend.inMemory(ACCOUNT), regionResolver, delivery, sources, clock, true); + webhooks = new EventBridgeV2Webhooks(service, sources, secrets, clock); + bus = service.createEventBus(json("{\"Name\":\"orders\"}"), REGION).getArn(); + } + + EventSourceV2 source(String name, String auth) { + return service.createEventSource(json("{\"ClientToken\":\"" + name + "-token\",\"Name\":\"" + name + + "\",\"EventBusArn\":\"" + bus + "\",\"Configuration\":{\"WebhookEventsConfiguration\":" + + "{\"AuthConfiguration\":" + auth + ",\"RoleArn\":\"" + ROLE + "\"}}}"), REGION); + } + + static JsonNode json(String json) { + try { + return MAPPER.readTree(json); + } catch (Exception e) { + throw new IllegalArgumentException(json, e); + } + } +} diff --git a/tools/aws/regen_eventbridgev2_shapes.py b/tools/aws/regen_eventbridgev2_shapes.py index 36700fc837..9c864031e7 100644 --- a/tools/aws/regen_eventbridgev2_shapes.py +++ b/tools/aws/regen_eventbridgev2_shapes.py @@ -15,7 +15,7 @@ MODEL = Path("eventbridgev2/2025-05-15") OUTPUT = request_shapes.REPO_ROOT / "src/main/resources/aws/eventbridgev2-request-shapes.json" OPERATIONS = ("CreateEventSource", "DeleteEventSource", "DescribeEventSource", "ListEventSources", - "RotateWebhookCredentials", "UpdateEventSource") + "RevokeResource", "RotateWebhookCredentials", "UpdateEventSource") # The order AWS lists the values of a violated enum in. It follows no rule, so each is measured. ENUM_ORDER = { diff --git a/tools/aws/test_request_shapes.py b/tools/aws/test_request_shapes.py index a6db8cf27d..9bd3f90a72 100644 --- a/tools/aws/test_request_shapes.py +++ b/tools/aws/test_request_shapes.py @@ -596,8 +596,8 @@ def test_eventbridgev2_shapes_keep_the_measured_orders_and_the_sensitive_mark(): shapes = doc["shapes"] assert sorted(doc["operations"]) == ["CreateEventSource", "DeleteEventSource", "DescribeEventSource", - "ListEventSources", "RotateWebhookCredentials", - "UpdateEventSource"] + "ListEventSources", "RevokeResource", + "RotateWebhookCredentials", "UpdateEventSource"] assert shapes["WebhookSecretValue"] == {"type": "string", "min": 6, "max": 512, "sensitive": True} assert shapes["WebhookMetadataHttpHeaderList"]["max"] == 20 assert shapes["TagMap"]["max"] == 200 @@ -620,6 +620,8 @@ def test_eventbridgev2_shapes_list_members_in_the_order_aws_walks_them(): assert list(shapes["UpdateEventSourceRequest"]["members"]) == ["Configuration", "EventSourceArn", "Description"] assert list(shapes["ListEventSourcesRequest"]["members"]) == [ "MaxResults", "NextToken", "NamePrefix", "EventBusArn"] + assert list(shapes["RevokeResourceRequest"]["members"]) == ["Arn"] + assert shapes["RevocableResourceArn"]["max"] == 1011 assert list(shapes["RotateWebhookCredentialsRequest"]["members"]) == [ "Credential", "EventSourceArn", "ClientToken"] assert list(shapes["WebhookCredential"]["members"]) == [