diff --git a/docs/services/eventbridge.md b/docs/services/eventbridge.md index 8d38b8d863..a7d1cf35d6 100644 --- a/docs/services/eventbridge.md +++ b/docs/services/eventbridge.md @@ -440,3 +440,11 @@ refuses it. Across accounts the bus policy and the caller's identity policies bo - A bus ARN naming another account is forwarded under that account, so the target bus and its rules resolve there. - Onward delivery from that bus follows each target type: SQS and Step Functions resolve cross-account, while Lambda, SNS, Batch and Firehose resolve in the caller's account. - An event is forwarded between buses only once, matching AWS: a bus that received an event from another bus does not forward it on to a third. The second hop is dropped with only a `WARN` rather than reported to the caller. + +### IAM resource tags + +With IAM enforcement enabled, event bus and rule operations that support +`aws:ResourceTag` conditions read the exact target's stored tags. Tag changes take +immediate effect. Request tags and another bus or rule's tags do not satisfy an +existing-resource tag condition. The lookup validates the ARN's account, Region +and partition before reading tags. 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 5fee808799..e8be512679 100644 --- a/src/main/java/io/floci/aws/services/eventbridge/EventBridgeService.java +++ b/src/main/java/io/floci/aws/services/eventbridge/EventBridgeService.java @@ -56,6 +56,7 @@ import java.util.ArrayList; import java.util.Comparator; import java.util.HashMap; import java.util.Iterator; +import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Optional; @@ -748,30 +749,41 @@ public class EventBridgeService implements ResourceProvider, StoredResourceArns public Map listTagsForResource(String resourceArn, String region) { validateTagResourceArn(resourceArn, region); String resource = AwsArnUtils.parse(resourceArn).resource(); + if ("event-bus/default".equals(resource)) { + getOrCreateDefaultBus(region); + } + return requireTagResource(resourceArn, region, resource).tags(); + } + + private record TagResource(String arn, Map tags, Runnable save) {} + + private Optional findTagResource(String accountId, String region, String resource) { if (resource.startsWith("event-bus/")) { - String busName = resource.substring("event-bus/".length()); - if (busName.isBlank()) { - throw new AwsException("ResourceNotFoundException", "Resource not found: " + resourceArn, 400); - } - return describeEventBus(busName, region).getTags(); + String key = busKey(region, resource.substring("event-bus/".length())); + return getInAccount(busStore, accountId, key) + .map(bus -> new TagResource(bus.getArn(), bus.getTags(), + () -> putInAccount(busStore, accountId, key, bus))); } if (resource.startsWith("rule/")) { RuleRef ref = parseRuleResource(resource); String key = ruleKey(region, ref.busName(), ref.ruleName()); - return ruleStore.get(key) - .map(Rule::getTags) - .orElseThrow(() -> new AwsException("ResourceNotFoundException", - "Resource not found: " + resourceArn, 400)); + return getInAccount(ruleStore, accountId, key) + .map(rule -> new TagResource(rule.getArn(), rule.getTags(), + () -> putInAccount(ruleStore, accountId, key, rule))); } if (resource.startsWith("archive/")) { - String archiveName = resource.substring("archive/".length()); - String key = archiveKey(region, archiveName); - return archiveStore.get(key) - .map(Archive::getTags) - .orElseThrow(() -> new AwsException("ResourceNotFoundException", - "Archive not found: " + archiveName, 400)); + String key = archiveKey(region, resource.substring("archive/".length())); + return getInAccount(archiveStore, accountId, key) + .map(archive -> new TagResource(archive.getArchiveArn(), archive.getTags(), + () -> putInAccount(archiveStore, accountId, key, archive))); } - throw new AwsException("ResourceNotFoundException", "Resource not found: " + resourceArn, 400); + return Optional.empty(); + } + + private TagResource requireTagResource(String resourceArn, String region, String resource) { + return findTagResource(regionResolver.getAccountId(), region, resource) + .orElseThrow(() -> new AwsException("ResourceNotFoundException", + "Resource not found: " + resourceArn, 400)); } /** EventBridge tag operations only address resources in the caller's account and Region. */ @@ -811,79 +823,19 @@ public class EventBridgeService implements ResourceProvider, StoredResourceArns public void tagResource(String resourceArn, Map tags, String region) { validateTagResourceArn(resourceArn, region); String resource = AwsArnUtils.parse(resourceArn).resource(); - if (resource.startsWith("archive/")) { - String archiveName = resource.substring("archive/".length()); - String key = archiveKey(region, archiveName); - Archive archive = archiveStore.get(key) - .orElseThrow(() -> new AwsException("ResourceNotFoundException", - "Archive not found: " + archiveName, 400)); - archive.getTags().putAll(tags); - archiveStore.put(key, archive); - resourceGroupsTaggingService.tagResources(List.of(resourceArn), tags, region); - return; - } - if (resource.startsWith("event-bus/")) { - String busName = resource.substring("event-bus/".length()); - String key = busKey(region, busName); - EventBus bus = busStore.get(key) - .orElseThrow(() -> new AwsException("ResourceNotFoundException", - "Resource not found: " + resourceArn, 400)); - bus.getTags().putAll(tags); - busStore.put(key, bus); - resourceGroupsTaggingService.tagResources(List.of(resourceArn), tags, region); - return; - } - if (resource.startsWith("rule/")) { - RuleRef ref = parseRuleResource(resource); - String key = ruleKey(region, ref.busName(), ref.ruleName()); - Rule rule = ruleStore.get(key) - .orElseThrow(() -> new AwsException("ResourceNotFoundException", - "Resource not found: " + resourceArn, 400)); - rule.getTags().putAll(tags); - ruleStore.put(key, rule); - resourceGroupsTaggingService.tagResources(List.of(resourceArn), tags, region); - return; - } - throw new AwsException("ResourceNotFoundException", "Resource not found: " + resourceArn, 400); + TagResource target = requireTagResource(resourceArn, region, resource); + target.tags().putAll(tags); + target.save().run(); + resourceGroupsTaggingService.tagResources(List.of(resourceArn), tags, region); } public void untagResource(String resourceArn, List tagKeys, String region) { validateTagResourceArn(resourceArn, region); String resource = AwsArnUtils.parse(resourceArn).resource(); - if (resource.startsWith("archive/")) { - String archiveName = resource.substring("archive/".length()); - String key = archiveKey(region, archiveName); - Archive archive = archiveStore.get(key) - .orElseThrow(() -> new AwsException("ResourceNotFoundException", - "Archive not found: " + archiveName, 400)); - tagKeys.forEach(archive.getTags()::remove); - archiveStore.put(key, archive); - resourceGroupsTaggingService.untagResources(List.of(resourceArn), tagKeys, region); - return; - } - if (resource.startsWith("event-bus/")) { - String busName = resource.substring("event-bus/".length()); - String key = busKey(region, busName); - EventBus bus = busStore.get(key) - .orElseThrow(() -> new AwsException("ResourceNotFoundException", - "Resource not found: " + resourceArn, 400)); - tagKeys.forEach(bus.getTags()::remove); - busStore.put(key, bus); - resourceGroupsTaggingService.untagResources(List.of(resourceArn), tagKeys, region); - return; - } - if (resource.startsWith("rule/")) { - RuleRef ref = parseRuleResource(resource); - String key = ruleKey(region, ref.busName(), ref.ruleName()); - Rule rule = ruleStore.get(key) - .orElseThrow(() -> new AwsException("ResourceNotFoundException", - "Resource not found: " + resourceArn, 400)); - tagKeys.forEach(rule.getTags()::remove); - ruleStore.put(key, rule); - resourceGroupsTaggingService.untagResources(List.of(resourceArn), tagKeys, region); - return; - } - throw new AwsException("ResourceNotFoundException", "Resource not found: " + resourceArn, 400); + TagResource target = requireTagResource(resourceArn, region, resource); + tagKeys.forEach(target.tags()::remove); + target.save().run(); + resourceGroupsTaggingService.untagResources(List.of(resourceArn), tagKeys, region); } // ──────────────────────────── Permissions ──────────────────────────── @@ -1920,6 +1872,24 @@ public class EventBridgeService implements ResourceProvider, StoredResourceArns return "events"; } + /** The tags of the exact bus or rule ARN, read without changing the stored resource. */ + @Override + public Map storedTags(String resourceArn) { + if (!AwsArnUtils.isArnFor(resourceArn, "events")) { + return Map.of(); + } + AwsArnUtils.Arn arn = AwsArnUtils.parse(resourceArn); + if (!regionResolver.partitionForRegion(arn.region()).equals(arn.partition())) { + return Map.of(); + } + if (!arn.resource().startsWith("event-bus/") && !arn.resource().startsWith("rule/")) { + return Map.of(); + } + return findTagResource(arn.accountId(), arn.region(), arn.resource()) + .filter(target -> resourceArn.equals(target.arn())) + .map(TagResource::tags).map(LinkedHashMap::new).orElseGet(LinkedHashMap::new); + } + /** The Region's default event bus, which a request naming no bus acts on. */ @Override public Optional findDefault(String type, String region) { diff --git a/src/test/java/io/floci/aws/services/eventbridge/EventBridgeListTagsIntegrationTest.java b/src/test/java/io/floci/aws/services/eventbridge/EventBridgeListTagsIntegrationTest.java index 131674e561..1e64be451c 100644 --- a/src/test/java/io/floci/aws/services/eventbridge/EventBridgeListTagsIntegrationTest.java +++ b/src/test/java/io/floci/aws/services/eventbridge/EventBridgeListTagsIntegrationTest.java @@ -1,9 +1,7 @@ package io.floci.aws.services.eventbridge; +import io.floci.aws.testing.RestAssuredJsonUtils; import io.quarkus.test.junit.QuarkusTest; -import io.restassured.RestAssured; -import io.restassured.config.EncoderConfig; -import io.restassured.http.ContentType; import org.junit.jupiter.api.*; import static io.restassured.RestAssured.given; @@ -17,10 +15,7 @@ class EventBridgeListTagsIntegrationTest { @BeforeAll static void configureRestAssured() { - RestAssured.config = RestAssured.config().encoderConfig( - EncoderConfig.encoderConfig() - .encodeContentTypeAs(EVENT_BRIDGE_CONTENT_TYPE, ContentType.TEXT) - ); + RestAssuredJsonUtils.configureAwsContentTypes(); } @Test diff --git a/src/test/java/io/floci/aws/services/eventbridge/EventBridgeResourceTagIamIntegrationTest.java b/src/test/java/io/floci/aws/services/eventbridge/EventBridgeResourceTagIamIntegrationTest.java new file mode 100644 index 0000000000..4cb311c45b --- /dev/null +++ b/src/test/java/io/floci/aws/services/eventbridge/EventBridgeResourceTagIamIntegrationTest.java @@ -0,0 +1,179 @@ +package io.floci.aws.services.eventbridge; + +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.floci.aws.testing.RestAssuredJsonUtils; +import io.quarkus.test.junit.QuarkusTest; +import io.quarkus.test.junit.TestProfile; +import io.restassured.RestAssured; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.RegisterExtension; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; +import software.amazon.awssdk.regions.Region; +import software.amazon.awssdk.services.eventbridge.EventBridgeClient; +import software.amazon.awssdk.services.eventbridge.model.EventBridgeException; +import software.amazon.awssdk.services.eventbridge.model.Tag; + +import java.util.UUID; + +import static io.floci.aws.testing.EnforcementFixtures.auth; +import static io.restassured.RestAssured.given; +import static org.hamcrest.Matchers.containsString; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; + +@QuarkusTest +@TestProfile(IamEnforcementProfile.class) +class EventBridgeResourceTagIamIntegrationTest { + private static final String ACCOUNT = "000000000000"; + + @RegisterExtension + final PartitionCleanup cleanup = new PartitionCleanup(); + + @BeforeAll + static void configureRestAssured() { + RestAssuredJsonUtils.configureAwsContentTypes(); + } + + @ParameterizedTest + @ValueSource(strings = {"us-east-1", "cn-north-1", "us-gov-west-1"}) + void describeUsesCurrentStoredTagsInEveryPartition(String regionName) { + Region region = Region.of(regionName); + String name = "bus-tags-" + UUID.randomUUID(); + try (EventBridgeClient root = AwsTestClients.create(EventBridgeClient.builder(), ACCOUNT, region)) { + String arn = root.createEventBus(r -> r.name(name).tags(tag("Owner", "team-a"))).eventBusArn(); + try { + EnforcementFixtures.UserCredentials credentials = reader(arn); + try (EventBridgeClient reader = AwsTestClients.create(EventBridgeClient.builder(), + credentials.accessKeyId(), credentials.secretAccessKey(), region)) { + assertEquals(arn, reader.describeEventBus(r -> r.name(name)).arn()); + assertEquals(arn, reader.describeEventBus(r -> r.name(arn)).arn()); + root.tagResource(r -> r.resourceARN(arn).tags(tag("Owner", "team-b"))); + denied(reader, name); + root.tagResource(r -> r.resourceARN(arn).tags(tag("Owner", "team-a"))); + assertEquals(arn, reader.describeEventBus(r -> r.name(name)).arn()); + root.untagResource(r -> r.resourceARN(arn).tagKeys("Owner")); + denied(reader, name); + root.deleteEventBus(r -> r.name(name)); + denied(reader, name); + } + } finally { + root.deleteEventBus(r -> r.name(name)); + } + } + } + + @Test + void anotherTargetOrForgedRequestTagCannotBorrowTheAllowedBusTags() { + String name = "bus-boundary-" + UUID.randomUUID(); + String other = name + "-other"; + try (EventBridgeClient root = AwsTestClients.create(EventBridgeClient.builder(), ACCOUNT, Region.US_EAST_1)) { + String arn = root.createEventBus(r -> r.name(name).tags(tag("Owner", "team-a"))).eventBusArn(); + try { + root.createEventBus(r -> r.name(other)); + try { + EnforcementFixtures.UserCredentials credentials = reader("*"); + try (EventBridgeClient reader = AwsTestClients.create(EventBridgeClient.builder(), + credentials.accessKeyId(), credentials.secretAccessKey(), Region.US_EAST_1)) { + assertEquals(arn, reader.describeEventBus(r -> r.name(name)).arn()); + denied(reader, other); + denied(reader, arn.replace(ACCOUNT, "111111111111")); + denied(reader, arn.replace("us-east-1", "us-west-2")); + denied(reader, arn.replace("arn:aws:", "arn:aws-cn:")); + } + given().header("Authorization", auth(credentials.accessKeyId(), "events")) + .header("X-Amz-Target", "AWSEvents.DescribeEventBus") + .contentType("application/x-amz-json-1.1") + .body("{\"Name\":\"" + other + "\",\"Tags\":[{\"Key\":\"Owner\",\"Value\":\"team-a\"}]}") + .post("/").then().statusCode(400).body(containsString("AccessDenied")); + } finally { + root.deleteEventBus(r -> r.name(other)); + } + } finally { + root.deleteEventBus(r -> r.name(name)); + } + } + } + + @Test + void ruleLifecycleUsesRuleTagsSeparatelyFromItsBus() { + String bus = "rule-tags-" + UUID.randomUUID(); + try (EventBridgeClient root = AwsTestClients.create(EventBridgeClient.builder(), ACCOUNT, Region.US_EAST_1)) { + String busArn = root.createEventBus(r -> r.name(bus).tags(tag("Owner", "team-a"))).eventBusArn(); + try { + String ruleArn = root.putRule(r -> r.name("rule").eventBusName(bus) + .eventPattern("{\"source\":[\"iam-regression\"]}").tags(tag("Owner", "team-b"))).ruleArn(); + try { + String user = "rule-reader-" + 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:DescribeRule","events:ListTargetsByRule","events:ListTagsForResource", + "events:RemoveTargets","events:DeleteRule","events:DeleteEventBus"], + "Resource":["%s","%s"], + "Condition":{"StringEquals":{"aws:ResourceTag/Owner":"team-a"}}}]} + """.formatted(busArn, ruleArn)); + try (EventBridgeClient limited = AwsTestClients.create(EventBridgeClient.builder(), + credentials.accessKeyId(), credentials.secretAccessKey(), Region.US_EAST_1)) { + EventBridgeException denied = assertThrows(EventBridgeException.class, + () -> limited.describeRule(r -> r.name("rule").eventBusName(bus))); + assertEquals("AccessDeniedException", denied.awsErrorDetails().errorCode()); + root.tagResource(r -> r.resourceARN(ruleArn).tags(tag("Owner", "team-a"))); + assertEquals(ruleArn, limited.describeRule(r -> r.name("rule").eventBusName(bus)).arn()); + assertEquals(1, limited.listTagsForResource(r -> r.resourceARN(ruleArn)).tags().size()); + root.putTargets(r -> r.rule("rule").eventBusName(bus).targets(target -> target.id("queue") + .arn("arn:aws:sqs:us-east-1:000000000000:iam-regression"))); + assertEquals(1, limited.listTargetsByRule(r -> r.rule("rule").eventBusName(bus)).targets().size()); + assertEquals(0, limited.removeTargets(r -> r.rule("rule").eventBusName(bus).ids("queue")) + .failedEntryCount()); + limited.deleteRule(r -> r.name("rule").eventBusName(bus)); + root.tagResource(r -> r.resourceARN(busArn).tags(tag("Owner", "team-b"))); + EventBridgeException busDenied = assertThrows(EventBridgeException.class, + () -> limited.deleteEventBus(r -> r.name(bus))); + assertEquals("AccessDeniedException", busDenied.awsErrorDetails().errorCode()); + root.tagResource(r -> r.resourceARN(busArn).tags(tag("Owner", "team-a"))); + limited.deleteEventBus(r -> r.name(bus)); + } + } finally { + try { + root.removeTargets(r -> r.rule("rule").eventBusName(bus).ids("queue")); + root.deleteRule(r -> r.name("rule").eventBusName(bus)); + } catch (EventBridgeException expected) { + // The authorized lifecycle may already have deleted both the rule and its bus. + if (!"ResourceNotFoundException".equals(expected.awsErrorDetails().errorCode())) { + throw expected; + } + } + } + } finally { + root.deleteEventBus(r -> r.name(bus)); + } + } + } + + private EnforcementFixtures.UserCredentials reader(String resource) { + String user = "event-tag-reader-" + UUID.randomUUID(); + EnforcementFixtures.UserCredentials credentials = EnforcementFixtures.createUser( + cleanup, RestAssured.port, auth(ACCOUNT, "iam"), user); + EnforcementFixtures.putUserPolicy(RestAssured.port, auth(ACCOUNT, "iam"), user, "read", """ + {"Version":"2012-10-17","Statement":[{"Effect":"Allow","Action":"events:DescribeEventBus", + "Resource":"%s","Condition":{"StringEquals":{"aws:ResourceTag/Owner":"team-a"}}}]} + """.formatted(resource)); + return credentials; + } + + private static Tag tag(String key, String value) { + return Tag.builder().key(key).value(value).build(); + } + + private static void denied(EventBridgeClient client, String name) { + EventBridgeException exception = assertThrows(EventBridgeException.class, + () -> client.describeEventBus(r -> r.name(name))); + assertEquals("AccessDeniedException", exception.awsErrorDetails().errorCode()); + } +} 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 6d9d79165a..21e5b08730 100644 --- a/src/test/java/io/floci/aws/services/eventbridge/EventBridgeServiceTest.java +++ b/src/test/java/io/floci/aws/services/eventbridge/EventBridgeServiceTest.java @@ -56,21 +56,25 @@ class EventBridgeServiceTest { private EventBridgeService service; private TargetDispatcher dispatcherMock; + private StorageBackend busStore; private StorageBackend ruleStore; + private StorageBackend archiveStore; private StorageBackend replayStore; private ReplayDispatcher replayDispatcherMock; @BeforeEach void setUp() { dispatcherMock = mock(TargetDispatcher.class); - ruleStore = new InMemoryStorage<>(); + busStore = spy(new InMemoryStorage<>()); + ruleStore = spy(new InMemoryStorage<>()); + archiveStore = spy(new InMemoryStorage<>()); replayStore = new InMemoryStorage<>(); replayDispatcherMock = mock(ReplayDispatcher.class); service = new EventBridgeService( - new InMemoryStorage<>(), + busStore, ruleStore, new InMemoryStorage<>(), - new InMemoryStorage<>(), + archiveStore, new InMemoryStorage<>(), replayStore, new InMemoryStorage<>(), @@ -184,6 +188,50 @@ class EventBridgeServiceTest { assertEquals("ResourceNotFoundException", error.getErrorCode()); } + @Test + void tagOperationsPersistBusRuleAndArchiveTagsThroughTheSharedLookup() { + EventBus bus = service.createEventBus("tagged-bus", null, null, REGION); + Rule defaultRule = service.putRule("tagged-rule", null, null, "rate(1 minute)", + RuleState.ENABLED, null, null, null, REGION); + Rule customRule = service.putRule("tagged-rule", bus.getName(), null, "rate(1 minute)", + RuleState.ENABLED, null, null, null, REGION); + Archive archive = service.createArchive("tagged-archive", bus.getArn(), null, null, 0, REGION); + Mockito.clearInvocations(busStore, ruleStore, archiveStore); + + for (String arn : List.of(bus.getArn(), defaultRule.getArn(), customRule.getArn(), archive.getArchiveArn())) { + service.tagResource(arn, Map.of("owner", arn, "remove", "value"), REGION); + assertEquals(Map.of("owner", arn, "remove", "value"), service.listTagsForResource(arn, REGION)); + service.untagResource(arn, List.of("remove"), REGION); + assertEquals(Map.of("owner", arn), service.listTagsForResource(arn, REGION)); + } + + verify(busStore, Mockito.times(2)).put(anyString(), any()); + verify(ruleStore, Mockito.times(4)).put(anyString(), any()); + verify(archiveStore, Mockito.times(2)).put(anyString(), any()); + Mockito.clearInvocations(busStore, ruleStore, archiveStore); + for (String arn : List.of(bus.getArn(), defaultRule.getArn(), customRule.getArn())) { + Map snapshot = service.storedTags(arn); + assertEquals(Map.of("owner", arn), snapshot); + snapshot.clear(); + assertEquals(Map.of("owner", arn), service.listTagsForResource(arn, REGION)); + assertTrue(service.storedTags(arn.replace(":000000000000:", ":111111111111:")).isEmpty()); + } + assertTrue(service.storedTags(archive.getArchiveArn()).isEmpty()); + verify(busStore, never()).put(anyString(), any()); + verify(ruleStore, never()).put(anyString(), any()); + verify(archiveStore, never()).put(anyString(), any()); + } + + @Test + void iamTagLookupDoesNotCreateTheDefaultBusButListingStillDoes() { + assertTrue(service.storedTags(DEFAULT_BUS).isEmpty()); + assertTrue(busStore.isEmpty()); + verify(busStore, never()).put(anyString(), any()); + + assertTrue(service.listTagsForResource(DEFAULT_BUS, REGION).isEmpty()); + assertFalse(busStore.isEmpty()); + } + @Test void createEventBusBlankNameThrows() { assertThrows(AwsException.class, () ->