From c5dddb8c2f139cfe59f157f20de607f6be7db79c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?TATSUNO=20=E2=80=9CTaz=E2=80=9D=20Yasuhiro?= Date: Sat, 28 Nov 2026 21:15:09 +0900 Subject: [PATCH] fix(iam): read the tags of EventBridge V2 buses, subscribers and event sources (#9627) EventBridge's storedTags answered only event-bus and rule ARNs, so aws:ResourceTag conditions on EventBridge V2 buses, subscribers and event sources saw no tags, and a Deny keyed on a tag never matched. EventBridgeService now hands an event-busv2, subscriber or event-sourcev2 ARN to EventBridgeV2Service, which reads the tags through findEventBus, findSubscriber and EventBridgeV2EventSources.lookup in the account and Region the ARN names. With V2 disabled or absent the answer stays empty. --- docs/services/eventbridgev2.md | 2 + .../eventbridge/EventBridgeService.java | 19 ++- .../EventBridgeV2EventSources.java | 6 +- .../eventbridgev2/EventBridgeV2Service.java | 29 +++- .../ecs/EcsEventBridgeIntegrationTest.java | 3 +- .../EventBridgeManagedRuleTest.java | 2 +- .../EventBridgeSchedulerIntegrationTest.java | 2 +- .../eventbridge/EventBridgeServiceTest.java | 33 +++- .../EventBridgeTargetLookupFixtures.java | 2 +- ...BridgeV2ResourceTagIamIntegrationTest.java | 91 +++++++++++ .../EventBridgeV2StoredTagsTest.java | 151 ++++++++++++++++++ 11 files changed, 328 insertions(+), 12 deletions(-) create mode 100644 src/test/java/io/floci/aws/services/eventbridgev2/EventBridgeV2ResourceTagIamIntegrationTest.java create mode 100644 src/test/java/io/floci/aws/services/eventbridgev2/EventBridgeV2StoredTagsTest.java diff --git a/docs/services/eventbridgev2.md b/docs/services/eventbridgev2.md index 740fe8bf0c..2446b2b670 100644 --- a/docs/services/eventbridgev2.md +++ b/docs/services/eventbridgev2.md @@ -231,6 +231,8 @@ and `DeleteEventBus` on the `event-busv2` ARN in `EventBusArn`, the subscriber o `subscriber//*`, and `CreateEventBus` on `event-busv2//*`. A V2 request is never checked on the default [EventBridge](eventbridge.md) bus. +The tags of a bus, a subscriber and an event source are read for `aws:ResourceTag` conditions. + Where the two APIs share an operation name, the API serving the request decides which resource is checked, not the members the request gives. An EventBridge request that adds a V2 bus's `EventBusArn` is still checked on the EventBridge bus it acts on. diff --git a/src/main/java/io/floci/aws/services/eventbridge/EventBridgeService.java b/src/main/java/io/floci/aws/services/eventbridge/EventBridgeService.java index 4bf1c40eb0..98f24857ea 100644 --- a/src/main/java/io/floci/aws/services/eventbridge/EventBridgeService.java +++ b/src/main/java/io/floci/aws/services/eventbridge/EventBridgeService.java @@ -42,10 +42,12 @@ import io.floci.aws.services.eventbridge.model.ReplayState; import io.floci.aws.services.eventbridge.model.Rule; import io.floci.aws.services.eventbridge.model.RuleState; import io.floci.aws.services.eventbridge.model.Target; +import io.floci.aws.services.eventbridgev2.EventBridgeV2Service; import io.floci.aws.services.pipes.PipesFilterMatcher; import io.floci.aws.services.resourcegroupstagging.ResourceGroupsTaggingService; import jakarta.annotation.PostConstruct; import jakarta.enterprise.context.ApplicationScoped; +import jakarta.enterprise.inject.Instance; import jakarta.inject.Inject; import org.jboss.logging.Logger; @@ -96,6 +98,7 @@ public class EventBridgeService implements ResourceProvider, StoredResourceArns private final ResourceGroupsTaggingService resourceGroupsTaggingService; private final ReplayDispatcher replayDispatcher; private final AppSyncTargetValidator appSyncTargetValidator; + private final Instance v2Service; @Inject public EventBridgeService(StorageFactory storageFactory, @@ -106,7 +109,8 @@ public class EventBridgeService implements ResourceProvider, StoredResourceArns TargetDispatcher dispatcher, ReplayDispatcher replayDispatcher, ResourceGroupsTaggingService resourceGroupsTaggingService, - AppSyncTargetValidator appSyncTargetValidator) { + AppSyncTargetValidator appSyncTargetValidator, + Instance v2Service) { this( storageFactory.create("eventbridge", "eventbridge-buses.json", new TypeReference>() {}), @@ -125,7 +129,7 @@ public class EventBridgeService implements ResourceProvider, StoredResourceArns storageFactory.create("eventbridge", "eventbridge-api-destinations.json", new TypeReference>() {}), regionResolver, objectMapper, ruleScheduler, dispatcher, replayDispatcher, - resourceGroupsTaggingService, appSyncTargetValidator + resourceGroupsTaggingService, appSyncTargetValidator, v2Service ); } @@ -143,7 +147,8 @@ public class EventBridgeService implements ResourceProvider, StoredResourceArns TargetDispatcher dispatcher, ReplayDispatcher replayDispatcher, ResourceGroupsTaggingService resourceGroupsTaggingService, - AppSyncTargetValidator appSyncTargetValidator) { + AppSyncTargetValidator appSyncTargetValidator, + Instance v2Service) { this.busStore = busStore; this.ruleStore = ruleStore; this.targetStore = targetStore; @@ -159,6 +164,7 @@ public class EventBridgeService implements ResourceProvider, StoredResourceArns this.replayDispatcher = replayDispatcher; this.resourceGroupsTaggingService = resourceGroupsTaggingService; this.appSyncTargetValidator = appSyncTargetValidator; + this.v2Service = v2Service; } @PostConstruct @@ -2088,7 +2094,7 @@ public class EventBridgeService implements ResourceProvider, StoredResourceArns return "events"; } - /** The tags of the exact bus or rule ARN, read without changing the stored resource. */ + /** The tags of the exact bus, rule or EventBridge V2 resource ARN, read without changing the stored resource. */ @Override public Map storedTags(String resourceArn) { if (!AwsArnUtils.isArnFor(resourceArn, "events")) { @@ -2098,6 +2104,11 @@ public class EventBridgeService implements ResourceProvider, StoredResourceArns if (!regionResolver.partitionForRegion(arn.region()).equals(arn.partition())) { return Map.of(); } + if (arn.resource().startsWith("event-busv2/") || arn.resource().startsWith("subscriber/") + || arn.resource().startsWith("event-sourcev2/")) { + return v2Service.isResolvable() && !v2Service.get().isDisabled() + ? v2Service.get().storedTags(resourceArn) : Map.of(); + } if (!arn.resource().startsWith("event-bus/") && !arn.resource().startsWith("rule/")) { return Map.of(); } 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 2bb4c8ca44..288509e726 100644 --- a/src/main/java/io/floci/aws/services/eventbridgev2/EventBridgeV2EventSources.java +++ b/src/main/java/io/floci/aws/services/eventbridgev2/EventBridgeV2EventSources.java @@ -678,9 +678,13 @@ public class EventBridgeV2EventSources implements Resettable { } private Optional lookup(String eventSourceArn, String region) { + return lookup(eventSourceArn, region, sources.accountId()); + } + + Optional lookup(String eventSourceArn, String region, String accountId) { String[] resource = AwsArnUtils.parse(eventSourceArn).resource().split("/"); return resource.length == 4 && "event-sourcev2".equals(resource[0]) - ? sources.get(EventBridgeV2Service.storageKey(region, resource[2])) + ? sources.getForAccount(accountId, EventBridgeV2Service.storageKey(region, resource[2])) .filter(source -> eventSourceArn.equals(source.getArn())) : Optional.empty(); } 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 4299026293..686bd71912 100644 --- a/src/main/java/io/floci/aws/services/eventbridgev2/EventBridgeV2Service.java +++ b/src/main/java/io/floci/aws/services/eventbridgev2/EventBridgeV2Service.java @@ -405,17 +405,42 @@ public class EventBridgeV2Service implements Resettable { } public Optional findSubscriber(String subscriberArn, String region) { - return subscribers.scan(key -> key.startsWith(region + "::")).stream() + return findSubscriber(subscriberArn, region, subscribers.accountId()); + } + + private Optional findSubscriber(String subscriberArn, String region, String accountId) { + return subscribers.scanForAccount(accountId, key -> key.startsWith(region + "::")).stream() .filter(subscriber -> subscriber.getArn().equals(subscriberArn)) .findFirst(); } public Optional findEventBus(String eventBusArn, String region) { + return findEventBus(eventBusArn, region, buses.accountId()); + } + + private Optional findEventBus(String eventBusArn, String region, String accountId) { return Optional.ofNullable(busName(eventBusArn)) - .flatMap(name -> buses.get(storageKey(region, name))) + .flatMap(name -> buses.getForAccount(accountId, storageKey(region, name))) .filter(bus -> bus.getArn().equals(eventBusArn)); } + /** The tags of the bus, subscriber or event source the exact ARN names, in the account and Region it names. */ + public Map storedTags(String resourceArn) { + if (!AwsArnUtils.isArnFor(resourceArn, "events")) { + return Map.of(); + } + AwsArnUtils.Arn arn = AwsArnUtils.parse(resourceArn); + Optional> tags = switch (arn.resource().split("/")[0]) { + case "event-busv2" -> findEventBus(resourceArn, arn.region(), arn.accountId()).map(EventBusV2::getTags); + case "subscriber" -> findSubscriber(resourceArn, arn.region(), arn.accountId()) + .map(SubscriberV2::getTags); + case "event-sourcev2" -> eventSources.lookup(resourceArn, arn.region(), arn.accountId()) + .map(EventSourceV2::getTags); + default -> Optional.empty(); + }; + return tags.map(found -> new LinkedHashMap<>(found)).orElseGet(LinkedHashMap::new); + } + // ──────────────────────────── Event sources ──────────────────────────── public EventSourceV2 createEventSource(JsonNode request, String region) { diff --git a/src/test/java/io/floci/aws/services/ecs/EcsEventBridgeIntegrationTest.java b/src/test/java/io/floci/aws/services/ecs/EcsEventBridgeIntegrationTest.java index d0d1f93b81..1564e20649 100644 --- a/src/test/java/io/floci/aws/services/ecs/EcsEventBridgeIntegrationTest.java +++ b/src/test/java/io/floci/aws/services/ecs/EcsEventBridgeIntegrationTest.java @@ -68,7 +68,8 @@ class EcsEventBridgeIntegrationTest { dispatcher, null, null, - mock(AppSyncTargetValidator.class) + mock(AppSyncTargetValidator.class), + null ); EcsEventPublisher eventPublisher = new EcsEventPublisher(eventBridgeService, regionResolver, objectMapper); diff --git a/src/test/java/io/floci/aws/services/eventbridge/EventBridgeManagedRuleTest.java b/src/test/java/io/floci/aws/services/eventbridge/EventBridgeManagedRuleTest.java index 8ba8e5acc4..440a24cfdb 100644 --- a/src/test/java/io/floci/aws/services/eventbridge/EventBridgeManagedRuleTest.java +++ b/src/test/java/io/floci/aws/services/eventbridge/EventBridgeManagedRuleTest.java @@ -41,7 +41,7 @@ class EventBridgeManagedRuleTest { new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(), new RegionResolver(REGION, "000000000000"), MAPPER, null, mock(TargetDispatcher.class), mock(ReplayDispatcher.class), new ResourceGroupsTaggingService(null), - mock(AppSyncTargetValidator.class)); + mock(AppSyncTargetValidator.class), null); handler = new EventBridgeHandler(service, MAPPER); service.putManagedRule(RULE, PRINCIPAL, "{\"source\":[\"aws.ssm\"]}", new Target(RULE, BUS_ARN, null, null), REGION); diff --git a/src/test/java/io/floci/aws/services/eventbridge/EventBridgeSchedulerIntegrationTest.java b/src/test/java/io/floci/aws/services/eventbridge/EventBridgeSchedulerIntegrationTest.java index 86339c5de5..78b3558ca5 100644 --- a/src/test/java/io/floci/aws/services/eventbridge/EventBridgeSchedulerIntegrationTest.java +++ b/src/test/java/io/floci/aws/services/eventbridge/EventBridgeSchedulerIntegrationTest.java @@ -60,7 +60,7 @@ class EventBridgeSchedulerIntegrationTest { new InMemoryStorage<>(), new InMemoryStorage<>(), new RegionResolver(REGION, ACCOUNT), new ObjectMapper(), scheduler, dispatcher, replayDispatcher, - new ResourceGroupsTaggingService(null), mock(AppSyncTargetValidator.class)); + new ResourceGroupsTaggingService(null), mock(AppSyncTargetValidator.class), null); } @AfterEach diff --git a/src/test/java/io/floci/aws/services/eventbridge/EventBridgeServiceTest.java b/src/test/java/io/floci/aws/services/eventbridge/EventBridgeServiceTest.java index 95c1e837c4..965198678e 100644 --- a/src/test/java/io/floci/aws/services/eventbridge/EventBridgeServiceTest.java +++ b/src/test/java/io/floci/aws/services/eventbridge/EventBridgeServiceTest.java @@ -18,8 +18,10 @@ import io.floci.aws.services.eventbridge.model.ReplayState; import io.floci.aws.services.eventbridge.model.Rule; import io.floci.aws.services.eventbridge.model.RuleState; import io.floci.aws.services.eventbridge.model.Target; +import io.floci.aws.services.eventbridgev2.EventBridgeV2Service; import io.floci.aws.services.resourcegroupstagging.ResourceGroupsTaggingService; import io.floci.aws.testing.PartitionMatrix; +import jakarta.enterprise.inject.Instance; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.function.Executable; @@ -64,9 +66,12 @@ class EventBridgeServiceTest { private StorageBackend archiveStore; private StorageBackend replayStore; private ReplayDispatcher replayDispatcherMock; + private Instance v2Service; @BeforeEach + @SuppressWarnings("unchecked") void setUp() { + v2Service = mock(Instance.class); dispatcherMock = mock(TargetDispatcher.class); busStore = spy(new InMemoryStorage<>()); ruleStore = spy(new InMemoryStorage<>()); @@ -88,7 +93,8 @@ class EventBridgeServiceTest { dispatcherMock, replayDispatcherMock, new ResourceGroupsTaggingService(null), - mock(AppSyncTargetValidator.class) + mock(AppSyncTargetValidator.class), + v2Service ); } @@ -2548,4 +2554,29 @@ class EventBridgeServiceTest { AwsException e = assertThrows(AwsException.class, () -> service.findConnectionByArn(arn, "us-east-1")); assertEquals("Connection " + arn + " does not exist.", e.getMessage()); } + + @Test + void storedTagsAnswersAV2ArnFromTheV2Service() { + String arn = "arn:aws:events:us-east-1:000000000000:event-busv2/orders/abcdefghijklmnopqrstuvwxy"; + EventBridgeV2Service v2 = mock(EventBridgeV2Service.class); + when(v2Service.isResolvable()).thenReturn(true); + when(v2Service.get()).thenReturn(v2); + when(v2.storedTags(arn)).thenReturn(Map.of("floci", "deny")); + + assertEquals(Map.of("floci", "deny"), service.storedTags(arn)); + } + + @Test + void storedTagsAnswersEmptyForAV2ArnWhenV2IsDisabledOrAbsent() { + String arn = "arn:aws:events:us-east-1:000000000000:subscriber/sub/abcdefghijklmnopqrstuvwxy"; + EventBridgeV2Service v2 = mock(EventBridgeV2Service.class); + when(v2.isDisabled()).thenReturn(true); + when(v2.storedTags(arn)).thenReturn(Map.of("floci", "deny")); + when(v2Service.isResolvable()).thenReturn(true); + when(v2Service.get()).thenReturn(v2); + assertTrue(service.storedTags(arn).isEmpty()); + + when(v2Service.isResolvable()).thenReturn(false); + assertTrue(service.storedTags(arn).isEmpty()); + } } diff --git a/src/test/java/io/floci/aws/services/eventbridge/EventBridgeTargetLookupFixtures.java b/src/test/java/io/floci/aws/services/eventbridge/EventBridgeTargetLookupFixtures.java index 803713daf6..ed59786c2f 100644 --- a/src/test/java/io/floci/aws/services/eventbridge/EventBridgeTargetLookupFixtures.java +++ b/src/test/java/io/floci/aws/services/eventbridge/EventBridgeTargetLookupFixtures.java @@ -17,6 +17,6 @@ final class EventBridgeTargetLookupFixtures { StorageBackend> targets, RegionResolver resolver) { return new EventBridgeService(buses, rules, targets, new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(), resolver, - new ObjectMapper(), null, null, null, null, null); + new ObjectMapper(), null, null, null, null, null, null); } } diff --git a/src/test/java/io/floci/aws/services/eventbridgev2/EventBridgeV2ResourceTagIamIntegrationTest.java b/src/test/java/io/floci/aws/services/eventbridgev2/EventBridgeV2ResourceTagIamIntegrationTest.java new file mode 100644 index 0000000000..0c213d049d --- /dev/null +++ b/src/test/java/io/floci/aws/services/eventbridgev2/EventBridgeV2ResourceTagIamIntegrationTest.java @@ -0,0 +1,91 @@ +package io.floci.aws.services.eventbridgev2; + +import io.floci.aws.testing.AwsTestClients; +import io.floci.aws.testing.EnforcementFixtures; +import io.floci.aws.testing.IamEnforcementProfile; +import io.floci.aws.testing.PartitionCleanup; +import io.quarkus.test.junit.QuarkusTest; +import io.quarkus.test.junit.TestProfile; +import io.restassured.RestAssured; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.RegisterExtension; +import software.amazon.awssdk.regions.Region; +import software.amazon.awssdk.services.eventbridgev2.EventBridgeV2Client; +import software.amazon.awssdk.services.eventbridgev2.model.EventBridgeV2Exception; +import software.amazon.awssdk.services.eventbridgev2.model.EventSourceConfiguration; +import software.amazon.awssdk.services.eventbridgev2.model.WebhookAuthConfiguration; + +import java.util.Map; +import java.util.UUID; +import java.util.function.Supplier; + +import static io.floci.aws.testing.EnforcementFixtures.auth; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertThrows; + +@QuarkusTest +@TestProfile(IamEnforcementProfile.class) +class EventBridgeV2ResourceTagIamIntegrationTest { + private static final String ACCOUNT = "000000000000"; + private static final String ROLE = "arn:aws:iam::000000000000:role/EventBusDelivery"; + private static final Map DENY = Map.of("floci", "deny"); + + @RegisterExtension + final PartitionCleanup cleanup = new PartitionCleanup(); + + @Test + void theTagsOfABusASubscriberAndAnEventSourceDecideTheirOwnRequests() { + String suffix = UUID.randomUUID().toString().substring(0, 8); + try (EventBridgeV2Client root = AwsTestClients.create(EventBridgeV2Client.builder(), ACCOUNT, + Region.US_EAST_1)) { + String taggedBus = root.createEventBus(r -> r.name("tagged-" + suffix).tags(DENY)).eventBusArn(); + String plainBus = root.createEventBus(r -> r.name("plain-" + suffix)).eventBusArn(); + String taggedSource = root.createEventSource(r -> r.name("hook-" + suffix).eventBusArn(plainBus) + .tags(DENY).configuration(webhook())).eventSourceArn(); + String plainSource = root.createEventSource(r -> r.name("plain-hook-" + suffix).eventBusArn(plainBus) + .configuration(webhook())).eventSourceArn(); + String taggedSubscriber = root.createSubscriber(r -> r.name("sub-" + suffix).eventBusArn(plainBus) + .tags(DENY).invokeConfiguration(invoke -> invoke.targetArn( + "arn:aws:sqs:us-east-1:000000000000:q-" + suffix).roleArn(ROLE))).subscriberArn(); + + EnforcementFixtures.UserCredentials credentials = limitedUser(); + try (EventBridgeV2Client limited = AwsTestClients.create(EventBridgeV2Client.builder(), + credentials.accessKeyId(), credentials.secretAccessKey(), Region.US_EAST_1)) { + assertDenied(() -> limited.describeEventBus(r -> r.eventBusArn(taggedBus))); + assertDenied(() -> limited.describeEventSource(r -> r.eventSourceArn(taggedSource))); + assertDenied(() -> limited.describeSubscriber(r -> r.subscriberArn(taggedSubscriber))); + assertDenied(() -> limited.createEventSource(r -> r.name("new-" + suffix).eventBusArn(taggedBus) + .configuration(webhook()))); + + assertEquals(plainBus, limited.describeEventBus(r -> r.eventBusArn(plainBus)).eventBusArn()); + assertNotNull(limited.describeEventSource(r -> r.eventSourceArn(plainSource)).eventSourceArn()); + assertEquals(taggedSource, limited.revokeResource(r -> r.arn(taggedSource)).arn()); + } + } + } + + private EnforcementFixtures.UserCredentials limitedUser() { + String user = "v2-tag-user-" + UUID.randomUUID(); + EnforcementFixtures.UserCredentials credentials = EnforcementFixtures.createUser( + cleanup, RestAssured.port, auth(ACCOUNT, "iam"), user); + EnforcementFixtures.putUserPolicy(RestAssured.port, auth(ACCOUNT, "iam"), user, "scope", """ + {"Version":"2012-10-17","Statement":[ + {"Effect":"Allow","Action":["events:*","iam:PassRole"],"Resource":"*"}, + {"Effect":"Deny","Action":"events:*","Resource":"*", + "Condition":{"StringEquals":{"aws:ResourceTag/floci":"deny"}}}]} + """); + return credentials; + } + + private static EventSourceConfiguration webhook() { + return EventSourceConfiguration.fromWebhookEventsConfiguration(webhook -> webhook.roleArn(ROLE) + .authConfiguration(WebhookAuthConfiguration.builder().staticTokenAuthConfiguration( + token -> token.tokenHttpHeader("X-Token").secretValue("s3cret-token")).build())); + } + + private static void assertDenied(Supplier call) { + EventBridgeV2Exception exception = assertThrows(EventBridgeV2Exception.class, call::get); + assertEquals("AccessDeniedException", exception.awsErrorDetails().errorCode()); + } +} diff --git a/src/test/java/io/floci/aws/services/eventbridgev2/EventBridgeV2StoredTagsTest.java b/src/test/java/io/floci/aws/services/eventbridgev2/EventBridgeV2StoredTagsTest.java new file mode 100644 index 0000000000..a0d7b5d910 --- /dev/null +++ b/src/test/java/io/floci/aws/services/eventbridgev2/EventBridgeV2StoredTagsTest.java @@ -0,0 +1,151 @@ +package io.floci.aws.services.eventbridgev2; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import io.floci.aws.config.TlsCertificateManager; +import io.floci.aws.core.common.RegionResolver; +import io.floci.aws.core.storage.AccountAwareStorageBackend; +import io.floci.aws.services.eventbridge.EventBridgeService; +import io.floci.aws.services.eventbridgev2.model.EventBusV2; +import io.floci.aws.services.eventbridgev2.model.EventSourceV2; +import io.floci.aws.services.eventbridgev2.model.SubscriberV2; +import io.floci.aws.services.secretsmanager.SecretsManagerService; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import java.time.Clock; +import java.time.Instant; +import java.time.ZoneOffset; +import java.util.List; +import java.util.Map; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.Mockito.RETURNS_DEEP_STUBS; +import static org.mockito.Mockito.mock; + +class EventBridgeV2StoredTagsTest { + private static final String REGION = "us-east-1"; + private static final String ACCOUNT = "000000000000"; + private static final String OTHER_ACCOUNT = "111122223333"; + private static final ObjectMapper MAPPER = new ObjectMapper(); + private static final String ROLE = "arn:aws:iam::000000000000:role/Hook"; + private static final String QUEUE = "arn:aws:sqs:us-east-1:000000000000:orders"; + + private AccountAwareStorageBackend buses; + private AccountAwareStorageBackend subscribers; + private AccountAwareStorageBackend sources; + private EventBridgeV2Service service; + private String busArn; + private String subscriberArn; + private String sourceArn; + + @BeforeEach + void setUp() { + RegionResolver regionResolver = new RegionResolver(REGION, ACCOUNT); + Clock clock = Clock.fixed(Instant.parse("2026-11-27T00:00:00Z"), ZoneOffset.UTC); + sources = AccountAwareStorageBackend.inMemory(ACCOUNT); + EventBridgeV2EventSources eventSources = new EventBridgeV2EventSources(sources, + mock(SecretsManagerService.class, RETURNS_DEEP_STUBS), regionResolver, clock, + "http://floci.test:4566", mock(TlsCertificateManager.class), mock(EventBridgeService.class)); + buses = AccountAwareStorageBackend.inMemory(ACCOUNT); + subscribers = AccountAwareStorageBackend.inMemory(ACCOUNT); + service = new EventBridgeV2Service(buses, subscribers, regionResolver, mock(EventBridgeV2Delivery.class), + eventSources, clock, true); + busArn = service.createEventBus(json("{\"Name\":\"orders\",\"Tags\":{\"b\":\"2\",\"a\":\"1\"}}"), REGION) + .getArn(); + subscriberArn = service.createSubscriber(json("{\"Name\":\"sub\",\"EventBusArn\":\"" + busArn + + "\",\"InvokeConfiguration\":{\"TargetArn\":\"" + QUEUE + "\",\"RoleArn\":\"" + ROLE + + "\"},\"Tags\":{\"team\":\"x\"}}"), REGION).getArn(); + EventSourceV2 source = service.createEventSource(json("{\"ClientToken\":\"t\",\"Name\":\"hook\"," + + "\"EventBusArn\":\"" + busArn + "\",\"Configuration\":{\"WebhookEventsConfiguration\":" + + "{\"AuthConfiguration\":{\"StaticTokenAuthConfiguration\":{\"TokenHttpHeader\":\"X-Tok\"," + + "\"SecretValue\":\"original-token\"}},\"RoleArn\":\"" + ROLE + "\"}},\"Tags\":{\"src\":\"y\"}}"), + REGION); + sourceArn = source.getArn(); + } + + @Test + void eachTypeAnswersTheTagsOfTheResourceItsArnNames() { + assertEquals(List.of("b", "a"), List.copyOf(service.storedTags(busArn).keySet())); + assertEquals(Map.of("b", "2", "a", "1"), service.storedTags(busArn)); + assertEquals(Map.of("team", "x"), service.storedTags(subscriberArn)); + assertEquals(Map.of("src", "y"), service.storedTags(sourceArn)); + } + + @Test + void anArnWithAnotherIdDoesNotBorrowTheTagsOfTheSameName() { + assertTrue(service.storedTags(withOtherId(busArn)).isEmpty()); + assertTrue(service.storedTags(withOtherId(subscriberArn)).isEmpty()); + assertTrue(service.storedTags(withOtherId(sourceArn)).isEmpty()); + } + + @Test + void anArnOfAnotherAccountOrRegionAnswersEmpty() { + for (String arn : List.of(busArn, subscriberArn, sourceArn)) { + assertTrue(service.storedTags(arn.replace(":" + ACCOUNT + ":", ":" + OTHER_ACCOUNT + ":")).isEmpty()); + assertTrue(service.storedTags(arn.replace("us-east-1", "us-west-2")).isEmpty()); + } + } + + @Test + void theTagsAreReadInTheAccountTheArnNames() { + EventBusV2 bus = new EventBusV2(); + String otherArn = "arn:aws:events:us-east-1:" + OTHER_ACCOUNT + ":event-busv2/orders/abcdefghijklmnopqrstuvwxy"; + bus.setName("orders"); + bus.setArn(otherArn); + bus.setTags(Map.of("owner", "other")); + buses.putForAccount(OTHER_ACCOUNT, REGION + "::orders", bus); + SubscriberV2 subscriber = new SubscriberV2(); + String otherSubscriberArn = subscriberArn.replace(":" + ACCOUNT + ":", ":" + OTHER_ACCOUNT + ":"); + subscriber.setName("sub"); + subscriber.setArn(otherSubscriberArn); + subscriber.setEventBusArn(otherArn); + subscriber.setTags(Map.of("owner", "other")); + subscribers.putForAccount(OTHER_ACCOUNT, REGION + "::orders::sub", subscriber); + EventSourceV2 source = new EventSourceV2(); + String otherSourceArn = sourceArn.replace(":" + ACCOUNT + ":", ":" + OTHER_ACCOUNT + ":"); + source.setName("hook"); + source.setArn(otherSourceArn); + source.setTags(Map.of("owner", "other")); + sources.putForAccount(OTHER_ACCOUNT, REGION + "::hook", source); + + assertEquals(Map.of("owner", "other"), service.storedTags(otherArn)); + assertEquals(Map.of("b", "2", "a", "1"), service.storedTags(busArn)); + assertEquals(Map.of("owner", "other"), service.storedTags(otherSubscriberArn)); + assertEquals(Map.of("team", "x"), service.storedTags(subscriberArn)); + assertEquals(Map.of("owner", "other"), service.storedTags(otherSourceArn)); + assertEquals(Map.of("src", "y"), service.storedTags(sourceArn)); + } + + @Test + void aRevokedSubscriberKeepsItsTagsAfterItsBusIsDeleted() { + service.revokeResource(json("{\"Arn\":\"" + subscriberArn + "\"}"), REGION); + service.revokeResource(json("{\"Arn\":\"" + sourceArn + "\"}"), REGION); + service.deleteEventBus(busArn, REGION); + + assertEquals(Map.of("team", "x"), service.storedTags(subscriberArn)); + } + + @Test + void nothingStoredOrAnotherResourceTypeAnswersEmpty() { + assertTrue(service.storedTags("arn:aws:events:us-east-1:000000000000:event-busv2/none/abcdefghijklmnopqrstuvwxy") + .isEmpty()); + assertTrue(service.storedTags("arn:aws:events:us-east-1:000000000000:subscriber/none/abc").isEmpty()); + assertTrue(service.storedTags("arn:aws:events:us-east-1:000000000000:event-bus/default").isEmpty()); + assertTrue(service.storedTags("arn:aws:sqs:us-east-1:000000000000:orders").isEmpty()); + assertTrue(service.storedTags("orders").isEmpty()); + } + + private static String withOtherId(String arn) { + return arn.substring(0, arn.lastIndexOf('/') + 1) + "zzzzzzzzzzzzzzzzzzzzzzzzz"; + } + + private static JsonNode json(String value) { + try { + return MAPPER.readTree(value); + } catch (Exception e) { + throw new AssertionError(e); + } + } +}