diff --git a/docs/services/eventbridgev2.md b/docs/services/eventbridgev2.md index 76202e4823..d2e7cd6776 100644 --- a/docs/services/eventbridgev2.md +++ b/docs/services/eventbridgev2.md @@ -32,6 +32,9 @@ The AWS CLI calls it `aws eventsv2` and the SDKs `EventBridgeV2`. | `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 | +| `TagResource` | Add tags to an event bus, a subscriber or an event source | +| `UntagResource` | Remove tags from an event bus, a subscriber or an event source | +| `ListTagsForResource` | List the tags of an event bus, a subscriber or an event source | | `PutEvents` | Publish events in the EventBridge envelope to an event bus | @@ -225,6 +228,13 @@ An `AwsServiceEventsConfiguration` source forwards the events of one AWS service A `PartnerEventsConfiguration` always fails with `InvalidInputException`, as AWS does for a partner event source that does not exist, since Floci models no partner event sources. +## Tags + +`TagResource` refuses to take a bus, a subscriber or an event source past 50 tags with `LimitExceededException`. +A key that starts with `aws:` in any case is refused with `AccessDeniedException` (403). A revoked subscriber or +event source cannot be tagged or untagged, and still lists its tags. `TagResource` and `UntagResource` do not change +`LastModifiedTime`. `DescribeEventBus`, `DescribeSubscriber` and `DescribeEventSource` return no tags. + ## IAM Under IAM enforcement, EventBridge V2 operations are authorized as the `events` actions of the same diff --git a/docs/services/index.md b/docs/services/index.md index 7fa00bd81f..37a078dcad 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 | 17 | +| [EventBridge V2](eventbridgev2.md) | `POST /service/AWSEventsV2/operation/*` | Smithy RPC v2 CBOR | 20 | | [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/core/common/RequestConstraintCheck.java b/src/main/java/io/floci/aws/core/common/RequestConstraintCheck.java index bcae2529f4..fe6251ede2 100644 --- a/src/main/java/io/floci/aws/core/common/RequestConstraintCheck.java +++ b/src/main/java/io/floci/aws/core/common/RequestConstraintCheck.java @@ -546,7 +546,15 @@ public final class RequestConstraintCheck { } private String mapText(JsonNode map) { - Map quoted = order.mapsInHashOrder() ? new HashMap<>(map.size()) : new LinkedHashMap<>(); + return order.mapsInHashOrder() ? hashOrderedMapText(map) : mapText(map, new LinkedHashMap<>()); + } + + /** {@code map} quoted as a violation does with {@link ViolationOrder#mapsInHashOrder()}. */ + public static String hashOrderedMapText(JsonNode map) { + return mapText(map, new HashMap<>(map.size())); + } + + private static String mapText(JsonNode map, Map quoted) { for (Map.Entry entry : map.properties()) { quoted.put(entry.getKey(), elementText(entry.getValue())); } 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 4b72914181..ce8fa62544 100644 --- a/src/main/java/io/floci/aws/services/eventbridgev2/EventBridgeV2EventSources.java +++ b/src/main/java/io/floci/aws/services/eventbridgev2/EventBridgeV2EventSources.java @@ -441,6 +441,13 @@ public class EventBridgeV2EventSources implements Resettable { return now.isBefore(request.rotatedAt().plus(ROTATION_TOKEN_MEMORY)); } + /** Stores {@code tags} on the source and changes nothing else about it. */ + void storeTags(EventSourceV2 source, Map tags, String region, String accountId) { + EventSourceV2 changed = copyOf(source); + changed.setTags(tags); + sources.putForAccount(accountId, EventBridgeV2Service.storageKey(region, source.getName()), changed); + } + private void requireSecretUsable(EventSourceV2 source, String region) { boolean unusable; try { @@ -711,10 +718,14 @@ public class EventBridgeV2EventSources implements Resettable { String busName = EventBridgeV2Service.busName(eventBusArn); EventBusV2 bus = findBusByName.apply(busName).orElseThrow(EventBridgeV2EventSources::busMissing); if (!eventBusArn.equals(bus.getArn())) { - throw new AwsException("ResourceNotFoundException", "Event bus not found: " + busName, 404); + throw busNotFound(busName); } } + static AwsException busNotFound(String busName) { + return new AwsException("ResourceNotFoundException", "Event bus not found: " + busName, 404); + } + static AwsException busMissing() { return new AwsException("ResourceNotFoundException", "Resource does not exist", 404); } @@ -749,7 +760,7 @@ public class EventBridgeV2EventSources implements Resettable { return lookup(eventSourceArn, region).orElseThrow(() -> notFound(eventSourceArn)); } - private static AwsException notFound(String eventSourceArn) { + static AwsException notFound(String eventSourceArn) { return new AwsException("ResourceNotFoundException", "EventSource not found: " + eventSourceArn, 404); } @@ -776,7 +787,7 @@ public class EventBridgeV2EventSources implements Resettable { sources.put(EventBridgeV2Service.storageKey(region, source.getName()), revoked); } - private void requireEndpointRegion(String arn, String region, String member) { + void requireEndpointRegion(String arn, String region, String member) { AwsArnUtils.Arn parsed = AwsArnUtils.parse(arn); if (!parsed.region().equals(region) || !parsed.partition().equals(regionResolver.partitionForRegion(region))) { throw EventBridgeV2Service.invalidInput( @@ -784,7 +795,7 @@ public class EventBridgeV2EventSources implements Resettable { } } - private void requireOwnAccount(String arn) { + void requireOwnAccount(String arn) { if (AwsArnUtils.isForeignAccount(AwsArnUtils.parse(arn), regionResolver.getAccountId())) { throw accessDenied(); } 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 e9f8bf734b..3d29fded8b 100644 --- a/src/main/java/io/floci/aws/services/eventbridgev2/EventBridgeV2Handler.java +++ b/src/main/java/io/floci/aws/services/eventbridgev2/EventBridgeV2Handler.java @@ -17,6 +17,7 @@ import jakarta.ws.rs.core.Response; import java.math.BigDecimal; import java.time.Instant; import java.util.List; +import java.util.Map; import java.util.Set; /** @@ -60,6 +61,9 @@ public class EventBridgeV2Handler { case "RotateWebhookCredentials" -> handleRotateWebhookCredentials(request, region); case "RevokeResource" -> handleRevokeResource(request, region); case "DeleteEventSource" -> handleDeleteEventSource(request, region); + case "TagResource" -> handleTagResource(request, region); + case "UntagResource" -> handleUntagResource(request, region); + case "ListTagsForResource" -> handleListTagsForResource(request, region); case "PutEvents" -> handlePutEvents(request, region); default -> throw new AwsException("UnsupportedOperation", "Operation " + operation + " is not supported.", 400); @@ -315,6 +319,24 @@ public class EventBridgeV2Handler { return details; } + private Response handleTagResource(JsonNode request, String region) { + service.tagResource(request, region); + return Response.ok(objectMapper.createObjectNode()).build(); + } + + private Response handleUntagResource(JsonNode request, String region) { + service.untagResource(request, region); + return Response.ok(objectMapper.createObjectNode()).build(); + } + + private Response handleListTagsForResource(JsonNode request, String region) { + Map tags = service.listTagsForResource(request, region); + ObjectNode response = objectMapper.createObjectNode(); + ObjectNode listed = response.putObject("Tags"); + tags.forEach(listed::put); + return Response.ok(response).build(); + } + private Response handlePutEvents(JsonNode request, String region) { List results = service.putEvents(request, region); ObjectNode response = objectMapper.createObjectNode(); 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 686bd71912..a3ccde9988 100644 --- a/src/main/java/io/floci/aws/services/eventbridgev2/EventBridgeV2Service.java +++ b/src/main/java/io/floci/aws/services/eventbridgev2/EventBridgeV2Service.java @@ -14,8 +14,10 @@ import io.floci.aws.core.common.AwsJsonTimestamp; import io.floci.aws.core.common.PaginatedResult; import io.floci.aws.core.common.Pagination; import io.floci.aws.core.common.RegionResolver; +import io.floci.aws.core.common.RequestConstraintCheck; import io.floci.aws.core.common.RequestScopes; import io.floci.aws.core.common.Resettable; +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.model.EventBusV2; @@ -31,8 +33,10 @@ import java.time.Clock; import java.time.Instant; import java.time.temporal.ChronoUnit; import java.util.ArrayList; +import java.util.HashMap; import java.util.LinkedHashMap; import java.util.List; +import java.util.Locale; import java.util.Map; import java.util.Optional; import java.util.Queue; @@ -42,6 +46,7 @@ import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentLinkedQueue; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.locks.ReentrantLock; +import java.util.function.Consumer; import java.util.function.Function; import java.util.function.Supplier; import java.util.regex.Pattern; @@ -75,6 +80,7 @@ public class EventBridgeV2Service implements Resettable { private static final String ID_ALPHABET = "abcdefghijklmnopqrstuvwxyz0123456789"; static final int ID_LENGTH = 25; private static final int MAX_TAGS = 200; + private static final int MAX_STORED_TAGS = 50; private static final int MAX_ENTRIES = 100; static final int MAX_LIST_RESULTS = 100; private static final List UPDATABLE_SETTINGS = List.of("Description", "State", "FilterConfiguration", @@ -429,16 +435,109 @@ public class EventBridgeV2Service implements Resettable { if (!AwsArnUtils.isArnFor(resourceArn, "events")) { return Map.of(); } + return taggable(resourceArn).map(found -> new LinkedHashMap<>(found.tags())).orElseGet(LinkedHashMap::new); + } + + /** Adds the tags {@code Tags} gives to the bus, subscriber or event source {@code ResourceArn} names. */ + public synchronized void tagResource(JsonNode request, String region) { + EventBridgeV2RequestShapes.check("TagResource", request); + JsonNode tags = request.get("Tags"); + List keys = new ArrayList<>(tags.size()); + tags.fieldNames().forEachRemaining(keys::add); + Taggable resource = findTaggable(request, region, keys, "tagged"); + if (tags.size() > MAX_TAGS) { + throw SmithyValidationErrors.exception("InvalidInputException", "Value '" + + RequestConstraintCheck.hashOrderedMapText(tags) + + "' at 'addedTags' failed to satisfy constraint: Member must have length less than or equal to " + + MAX_TAGS); + } + Map merged = new LinkedHashMap<>(resource.tags()); + tags.properties().forEach(tag -> merged.put(tag.getKey(), tag.getValue().textValue())); + if (merged.size() > MAX_STORED_TAGS) { + throw new AwsException("LimitExceededException", + "The maximum number of tags for this resource was exceeded.", 400); + } + resource.store().accept(merged); + } + + /** Removes the tags {@code TagKeys} lists from the bus, subscriber or event source {@code ResourceArn} names. */ + public synchronized void untagResource(JsonNode request, String region) { + EventBridgeV2RequestShapes.check("UntagResource", request); + List keys = new ArrayList<>(request.get("TagKeys").size()); + request.get("TagKeys").forEach(key -> keys.add(key.textValue())); + Taggable resource = findTaggable(request, region, keys, "untagged"); + if (keys.size() > MAX_TAGS) { + throw SmithyValidationErrors.exception("InvalidInputException", "Value '" + keys + + "' at 'removedTagKeys' failed to satisfy constraint: Member must have length less than or equal to " + + MAX_TAGS); + } + Map remaining = new LinkedHashMap<>(resource.tags()); + remaining.keySet().removeAll(keys); + resource.store().accept(remaining); + } + + /** The tags of the resource {@code ResourceArn} names, in the order AWS answers in. */ + public Map listTagsForResource(JsonNode request, String region) { + EventBridgeV2RequestShapes.check("ListTagsForResource", request); + Map stored = findTaggable(request, region, List.of(), null).tags(); + // AWS answers a copy of a HashMap filled in key order. + Map filled = new HashMap<>(); + stored.keySet().stream().sorted().forEach(key -> filled.put(key, stored.get(key))); + return new HashMap<>(filled); + } + + private record Taggable(Map tags, boolean revoked, Consumer> store) { + } + + /** {@code revokedVerb} is null for a read, which a revoked resource allows. */ + private Taggable findTaggable(JsonNode request, String region, List keys, String revokedVerb) { + String arn = request.get("ResourceArn").textValue(); + eventSources.requireEndpointRegion(arn, region, "ResourceArn"); + if (keys.stream().anyMatch(key -> key.toLowerCase(Locale.ROOT).startsWith("aws:"))) { + throw new AwsException("AccessDeniedException", + "Not authorized to set or remove tag keys with the reserved 'aws:' prefix", 403); + } + eventSources.requireOwnAccount(arn); + Taggable resource = taggable(arn).orElseThrow(() -> taggableNotFound(arn, region)); + if (resource.revoked() && revokedVerb != null) { + throw new AwsException("InvalidStateException", "Resource is revoked and cannot be " + revokedVerb, 409); + } + return resource; + } + + /** The bus, subscriber or event source the exact ARN names, in the account and Region the ARN names. */ + private Optional taggable(String resourceArn) { 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); + String region = arn.region(); + String account = arn.accountId(); + return switch (arn.resource().split("/")[0]) { + case "event-busv2" -> findEventBus(resourceArn, region, account).map(bus -> new Taggable(bus.getTags(), + false, tags -> { + EventBusV2 changed = copyOf(bus); + changed.setTags(tags); + buses.putForAccount(account, storageKey(region, bus.getName()), changed); + })); + case "subscriber" -> findSubscriber(resourceArn, region, account).map(subscriber -> new Taggable( + subscriber.getTags(), subscriber.isRevoked(), tags -> { + SubscriberV2 changed = copyOf(subscriber); + changed.setTags(tags); + subscribers.putForAccount(account, keyOf(subscriber, region, account), changed); + })); + case "event-sourcev2" -> eventSources.lookup(resourceArn, region, account).map(source -> new Taggable( + source.getTags(), source.isRevoked(), tags -> eventSources.storeTags(source, tags, region, + account))); default -> Optional.empty(); }; - return tags.map(found -> new LinkedHashMap<>(found)).orElseGet(LinkedHashMap::new); + } + + /** What AWS answers for an ARN {@link #taggable} finds nothing under, which depends on the resource kind. */ + private AwsException taggableNotFound(String arn, String region) { + return switch (AwsArnUtils.parse(arn).resource().split("/")[0]) { + case "event-busv2" -> buses.get(storageKey(region, busName(arn))).isPresent() + ? EventBridgeV2EventSources.busNotFound(busName(arn)) : EventBridgeV2EventSources.busMissing(); + case "subscriber" -> new AwsException("ResourceNotFoundException", "Subscriber not found: " + arn, 404); + default -> EventBridgeV2EventSources.notFound(arn); + }; } // ──────────────────────────── Event sources ──────────────────────────── @@ -519,6 +618,23 @@ public class EventBridgeV2Service implements Resettable { subscribers.put(keyOf(subscriber, region), revoked); } + private static EventBusV2 copyOf(EventBusV2 bus) { + EventBusV2 copy = new EventBusV2(); + copy.setName(bus.getName()); + copy.setArn(bus.getArn()); + copy.setDescription(bus.getDescription()); + copy.setKmsKeyIdentifier(bus.getKmsKeyIdentifier()); + copy.setRetentionPeriodInDays(bus.getRetentionPeriodInDays()); + copy.setState(bus.getState()); + copy.setCreationTime(bus.getCreationTime()); + copy.setLastModifiedTime(bus.getLastModifiedTime()); + copy.setTags(bus.getTags()); + copy.setClientToken(bus.getClientToken()); + copy.setCreateRequest(bus.getCreateRequest()); + copy.setSequenceNumber(bus.getSequenceNumber()); + return copy; + } + private static SubscriberV2 copyOf(SubscriberV2 subscriber) { SubscriberV2 copy = new SubscriberV2(); copy.setName(subscriber.getName()); @@ -1017,7 +1133,11 @@ public class EventBridgeV2Service implements Resettable { /** 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() + return keyOf(subscriber, region, subscribers.accountId()); + } + + private String keyOf(SubscriberV2 subscriber, String region, String accountId) { + return findEventBus(subscriber.getEventBusArn(), region, accountId).isPresent() ? subscriberKey(region, busName(subscriber.getEventBusArn()), subscriber.getName()) : orphanKey(region, subscriber); } diff --git a/src/main/resources/aws/eventbridgev2-request-shapes.json b/src/main/resources/aws/eventbridgev2-request-shapes.json index 4ef79b9950..01eaa34859 100644 --- a/src/main/resources/aws/eventbridgev2-request-shapes.json +++ b/src/main/resources/aws/eventbridgev2-request-shapes.json @@ -8,8 +8,11 @@ "DeleteEventSource": "DeleteEventSourceRequest", "DescribeEventSource": "DescribeEventSourceRequest", "ListEventSources": "ListEventSourcesRequest", + "ListTagsForResource": "ListTagsForResourceRequest", "RevokeResource": "RevokeResourceRequest", "RotateWebhookCredentials": "RotateWebhookCredentialsRequest", + "TagResource": "TagResourceRequest", + "UntagResource": "UntagResourceRequest", "UpdateEventSource": "UpdateEventSourceRequest" }, "shapes": { @@ -136,6 +139,15 @@ "EventBusArn": "EventBusArn" } }, + "ListTagsForResourceRequest": { + "type": "structure", + "required": [ + "ResourceArn" + ], + "members": { + "ResourceArn": "TaggableResourceArn" + } + }, "LogConfiguration": { "type": "structure", "members": { @@ -236,12 +248,51 @@ "key": "TagKey", "value": "TagValue" }, + "TagResourceRequest": { + "type": "structure", + "required": [ + "ResourceArn", + "Tags" + ], + "members": { + "ResourceArn": "TaggableResourceArn", + "Tags": "TagResourceRequestTagsMap" + } + }, + "TagResourceRequestTagsMap": { + "type": "map", + "min": 1, + "key": "TagKey", + "value": "TagValue" + }, "TagValue": { "type": "string", "min": 0, "max": 256, "pattern": "(\\S([\\s\\S]*\\S)?)?(?![\\s\\S]).*" }, + "TaggableResourceArn": { + "type": "string", + "min": 1, + "max": 1011, + "pattern": "arn:aws(-[a-z0-9]+)*:events:[a-z][a-z0-9]*(-[a-z0-9]+)*:([0-9]{12}):(event-busv2|subscriber|event-sourcev2\\/(aws\\.service|aws\\.partner|webhook))\\/[A-Za-z0-9][\\.\\-_A-Za-z0-9]{0,255}\\/[a-z0-9]{25}" + }, + "UntagResourceRequest": { + "type": "structure", + "required": [ + "ResourceArn", + "TagKeys" + ], + "members": { + "TagKeys": "UntagResourceRequestTagKeysList", + "ResourceArn": "TaggableResourceArn" + } + }, + "UntagResourceRequestTagKeysList": { + "type": "list", + "min": 1, + "member": "TagKey" + }, "UpdateEventSourceRequest": { "type": "structure", "required": [ diff --git a/src/test/java/io/floci/aws/services/eventbridgev2/EventBridgeV2IntegrationTest.java b/src/test/java/io/floci/aws/services/eventbridgev2/EventBridgeV2IntegrationTest.java index 0fbab3a34e..e54a0aea29 100644 --- a/src/test/java/io/floci/aws/services/eventbridgev2/EventBridgeV2IntegrationTest.java +++ b/src/test/java/io/floci/aws/services/eventbridgev2/EventBridgeV2IntegrationTest.java @@ -160,7 +160,7 @@ class EventBridgeV2IntegrationTest { @Test void sdkUnsupportedOperationFailsAsSuch() { try (EventBridgeV2Client client = client()) { - EventBridgeV2Exception e = assertThrows(EventBridgeV2Exception.class, () -> client.listTagsForResource( + EventBridgeV2Exception e = assertThrows(EventBridgeV2Exception.class, () -> client.getResourcePolicy( request -> request.resourceArn("arn:aws:events:us-east-1:000000000000:subscriber/x/" + "abcdefghijklmnopqrstuvwxy"))); assertEquals("UnsupportedOperation", e.awsErrorDetails().errorCode()); diff --git a/src/test/java/io/floci/aws/services/eventbridgev2/EventBridgeV2ResourceTagIamIntegrationTest.java b/src/test/java/io/floci/aws/services/eventbridgev2/EventBridgeV2ResourceTagIamIntegrationTest.java index 0c213d049d..7456f37eb8 100644 --- a/src/test/java/io/floci/aws/services/eventbridgev2/EventBridgeV2ResourceTagIamIntegrationTest.java +++ b/src/test/java/io/floci/aws/services/eventbridgev2/EventBridgeV2ResourceTagIamIntegrationTest.java @@ -65,6 +65,25 @@ class EventBridgeV2ResourceTagIamIntegrationTest { } } + @Test + void aTagAddedByTagResourceMakesTheDenyOnTagPolicyApply() { + String suffix = UUID.randomUUID().toString().substring(0, 8); + try (EventBridgeV2Client root = AwsTestClients.create(EventBridgeV2Client.builder(), ACCOUNT, + Region.US_EAST_1)) { + String bus = root.createEventBus(r -> r.name("late-" + suffix)).eventBusArn(); + + EnforcementFixtures.UserCredentials credentials = limitedUser(); + try (EventBridgeV2Client limited = AwsTestClients.create(EventBridgeV2Client.builder(), + credentials.accessKeyId(), credentials.secretAccessKey(), Region.US_EAST_1)) { + assertEquals(bus, limited.describeEventBus(r -> r.eventBusArn(bus)).eventBusArn()); + + root.tagResource(r -> r.resourceArn(bus).tags(DENY)); + + assertDenied(() -> limited.describeEventBus(r -> r.eventBusArn(bus))); + } + } + } + private EnforcementFixtures.UserCredentials limitedUser() { String user = "v2-tag-user-" + UUID.randomUUID(); EnforcementFixtures.UserCredentials credentials = EnforcementFixtures.createUser( diff --git a/src/test/java/io/floci/aws/services/eventbridgev2/EventBridgeV2TaggingIntegrationTest.java b/src/test/java/io/floci/aws/services/eventbridgev2/EventBridgeV2TaggingIntegrationTest.java new file mode 100644 index 0000000000..9520d18a1c --- /dev/null +++ b/src/test/java/io/floci/aws/services/eventbridgev2/EventBridgeV2TaggingIntegrationTest.java @@ -0,0 +1,137 @@ +package io.floci.aws.services.eventbridgev2; + +import io.floci.aws.testing.AwsTestClients; +import io.quarkus.test.junit.QuarkusTest; +import org.junit.jupiter.api.Test; +import software.amazon.awssdk.regions.Region; +import software.amazon.awssdk.services.eventbridgev2.EventBridgeV2Client; +import software.amazon.awssdk.services.eventbridgev2.model.AccessDeniedException; +import software.amazon.awssdk.services.eventbridgev2.model.InvalidStateException; +import software.amazon.awssdk.services.eventbridgev2.model.LimitExceededException; +import software.amazon.awssdk.services.eventbridgev2.model.ListTagsForResourceResponse; +import software.amazon.awssdk.services.eventbridgev2.model.ResourceNotFoundException; + +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +/** TagResource, UntagResource and ListTagsForResource of EventBridge V2, through the SDK. */ +@QuarkusTest +class EventBridgeV2TaggingIntegrationTest { + + private static final String ROLE = "arn:aws:iam::000000000000:role/EventBusDelivery"; + private static final String QUEUE = "arn:aws:sqs:us-east-1:000000000000:tagged"; + + @Test + void aBusIsTaggedListedInAwsOrderAndUntagged() { + try (EventBridgeV2Client events = events()) { + String bus = events.createEventBus(request -> request.name("v2-tag-" + suffix())).eventBusArn(); + + events.tagResource(request -> request.resourceArn(bus) + .tags(Map.of("c", "1", "k", "2", "s", "3", "t", "4"))); + + assertEquals(List.of("c", "s", "k", "t"), List.copyOf(events.listTagsForResource( + request -> request.resourceArn(bus)).tags().keySet())); + + events.untagResource(request -> request.resourceArn(bus).tagKeys("c", "t", "missing")); + + assertEquals(Map.of("k", "2", "s", "3"), + events.listTagsForResource(request -> request.resourceArn(bus)).tags()); + } + } + + @Test + void aBusWithoutTagsListsAnEmptyMap() { + try (EventBridgeV2Client events = events()) { + String bus = events.createEventBus(request -> request.name("v2-tag-none-" + suffix())).eventBusArn(); + + ListTagsForResourceResponse listed = events.listTagsForResource(request -> request.resourceArn(bus)); + + assertTrue(listed.hasTags()); + assertTrue(listed.tags().isEmpty()); + } + } + + @Test + void aSubscriberIsTagged() { + try (EventBridgeV2Client events = events()) { + String bus = events.createEventBus(request -> request.name("v2-tag-sub-" + suffix())).eventBusArn(); + String subscriber = events.createSubscriber(request -> request.name("sub").eventBusArn(bus) + .invokeConfiguration(invoke -> invoke.targetArn(QUEUE).roleArn(ROLE))).subscriberArn(); + + events.tagResource(request -> request.resourceArn(subscriber).tags(Map.of("team", "orders"))); + + assertEquals(Map.of("team", "orders"), + events.listTagsForResource(request -> request.resourceArn(subscriber)).tags()); + } + } + + @Test + void aResourceThatDoesNotExistIsNotFound() { + try (EventBridgeV2Client events = events()) { + String bus = events.createEventBus(request -> request.name("v2-tag-gone-" + suffix())).eventBusArn(); + String other = bus.substring(0, bus.lastIndexOf('/') + 1) + "zzzzzzzzzzzzzzzzzzzzzzzzz"; + + ResourceNotFoundException wrongId = assertThrows(ResourceNotFoundException.class, + () -> events.tagResource(request -> request.resourceArn(other).tags(Map.of("a", "b")))); + assertEquals("Event bus not found: " + bus.split("/")[1], wrongId.awsErrorDetails().errorMessage()); + } + } + + @Test + void aReservedKeyIsRefused() { + try (EventBridgeV2Client events = events()) { + String bus = events.createEventBus(request -> request.name("v2-tag-aws-" + suffix())).eventBusArn(); + + AccessDeniedException reserved = assertThrows(AccessDeniedException.class, + () -> events.tagResource(request -> request.resourceArn(bus).tags(Map.of("AWS:x", "v")))); + assertEquals("Not authorized to set or remove tag keys with the reserved 'aws:' prefix", + reserved.awsErrorDetails().errorMessage()); + } + } + + @Test + void fiftyOneTagsExceedTheLimit() { + try (EventBridgeV2Client events = events()) { + String bus = events.createEventBus(request -> request.name("v2-tag-max-" + suffix())).eventBusArn(); + Map tags = new LinkedHashMap<>(); + for (int i = 0; i < 51; i++) { + tags.put("k" + i, "v"); + } + + LimitExceededException exceeded = assertThrows(LimitExceededException.class, + () -> events.tagResource(request -> request.resourceArn(bus).tags(tags))); + assertEquals("The maximum number of tags for this resource was exceeded.", + exceeded.awsErrorDetails().errorMessage()); + } + } + + @Test + void aRevokedSubscriberCannotBeTagged() { + try (EventBridgeV2Client events = events()) { + String bus = events.createEventBus(request -> request.name("v2-tag-rev-" + suffix())).eventBusArn(); + String subscriber = events.createSubscriber(request -> request.name("sub").eventBusArn(bus) + .invokeConfiguration(invoke -> invoke.targetArn(QUEUE).roleArn(ROLE)) + .tags(Map.of("team", "orders"))).subscriberArn(); + events.revokeResource(request -> request.arn(subscriber)); + + InvalidStateException revoked = assertThrows(InvalidStateException.class, + () -> events.tagResource(request -> request.resourceArn(subscriber).tags(Map.of("a", "b")))); + assertEquals("Resource is revoked and cannot be tagged", revoked.awsErrorDetails().errorMessage()); + assertEquals(Map.of("team", "orders"), + events.listTagsForResource(request -> request.resourceArn(subscriber)).tags()); + } + } + + private static EventBridgeV2Client events() { + return AwsTestClients.create(EventBridgeV2Client.builder(), "000000000000", Region.US_EAST_1); + } + + private static String suffix() { + return Long.toString(System.nanoTime(), 36); + } +} diff --git a/src/test/java/io/floci/aws/services/eventbridgev2/EventBridgeV2TaggingTest.java b/src/test/java/io/floci/aws/services/eventbridgev2/EventBridgeV2TaggingTest.java new file mode 100644 index 0000000000..ee256c72b2 --- /dev/null +++ b/src/test/java/io/floci/aws/services/eventbridgev2/EventBridgeV2TaggingTest.java @@ -0,0 +1,459 @@ +package io.floci.aws.services.eventbridgev2; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.node.ObjectNode; +import io.floci.aws.config.TlsCertificateManager; +import io.floci.aws.core.common.AwsException; +import io.floci.aws.core.common.RegionResolver; +import io.floci.aws.core.storage.AccountAwareStorageBackend; +import io.floci.aws.services.eventbridge.EventBridgeService; +import io.floci.aws.services.eventbridgev2.model.EventBusV2; +import io.floci.aws.services.eventbridgev2.model.EventSourceV2; +import io.floci.aws.services.eventbridgev2.model.SubscriberV2; +import io.floci.aws.services.kms.KmsService; +import io.floci.aws.services.secretsmanager.SecretsManagerService; +import io.floci.aws.testing.ManualClock; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import java.time.Duration; +import java.time.Instant; +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertSame; +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.Mockito.RETURNS_DEEP_STUBS; +import static org.mockito.Mockito.doThrow; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.spy; + +class EventBridgeV2TaggingTest { + private static final String REGION = "us-east-1"; + private static final String ACCOUNT = "000000000000"; + 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 static final String NO_KEY_RULES = "Member must have length less than or equal to 128, " + + "Member must have length greater than or equal to 1, " + + "Member must satisfy regular expression pattern: \\S([\\s\\S]*\\S)?(?![\\s\\S]).*"; + private static final String MORE_THAN_200_TAGS = "1 validation error detected: Value '" + + "{k31=v, k30=v, k33=v, k32=v, k35=v, k34=v, k37=v, k36=v, k39=v, k38=v, k141=v, k140=v, " + + "k143=v, k142=v, k145=v, k144=v, k147=v, k146=v, k149=v, k148=v, k40=v, k42=v, k41=v, k44=v, " + + "k43=v, k46=v, k45=v, k48=v, k47=v, k49=v, k130=v, k132=v, k131=v, k134=v, k133=v, k136=v, " + + "k135=v, k138=v, k137=v, k139=v, k51=v, k50=v, k53=v, k52=v, k55=v, k54=v, k57=v, k56=v, " + + "k59=v, k170=v, k58=v, k161=v, k160=v, k163=v, k162=v, k165=v, k164=v, k167=v, k166=v, k169=v, " + + "k168=v, k60=v, k62=v, k61=v, k64=v, k63=v, k66=v, k65=v, k68=v, k67=v, k69=v, k150=v, " + + "k152=v, k151=v, k154=v, k153=v, k156=v, k155=v, k158=v, k157=v, k159=v, k71=v, k70=v, k73=v, " + + "k72=v, k75=v, k74=v, k77=v, k76=v, k79=v, k190=v, k78=v, k192=v, k191=v, k183=v, k182=v, " + + "k185=v, k184=v, k187=v, k186=v, k189=v, k188=v, k80=v, k82=v, k81=v, k84=v, k83=v, k86=v, " + + "k85=v, k88=v, k87=v, k89=v, k181=v, k180=v, k172=v, k171=v, k174=v, k173=v, k176=v, k175=v, " + + "k178=v, k177=v, k179=v, k91=v, k90=v, k93=v, k92=v, k95=v, k94=v, k97=v, k96=v, k99=v, " + + "k98=v, k194=v, k193=v, k196=v, k195=v, k198=v, k197=v, k199=v, k0=v, k1=v, k2=v, k3=v, " + + "k4=v, k5=v, k6=v, k7=v, k8=v, k9=v, k200=v, k101=v, k100=v, k103=v, k102=v, k105=v, " + + "k104=v, k107=v, k106=v, k109=v, k108=v, k11=v, k10=v, k13=v, k12=v, k15=v, k14=v, k17=v, " + + "k16=v, k19=v, k18=v, k121=v, k120=v, k123=v, k122=v, k125=v, k124=v, k127=v, k126=v, k129=v, " + + "k128=v, k20=v, k22=v, k21=v, k24=v, k23=v, k26=v, k25=v, k28=v, k27=v, k29=v, k110=v, " + + "k112=v, k111=v, k114=v, k113=v, k116=v, k115=v, k118=v, k117=v, k119=v}" + + "' at 'addedTags' failed to satisfy constraint: Member must have length less than or equal to 200"; + + 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); + ManualClock clock = new ManualClock(Instant.parse("2026-11-27T00:00:00Z")); + sources = spy(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), + mock(KmsService.class)); + buses = spy(AccountAwareStorageBackend.inMemory(ACCOUNT)); + subscribers = spy(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(); + sourceArn = 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).getArn(); + clock.advance(Duration.ofDays(1)); + } + + @Test + void tagReplacesValuesAndKeepsOtherKeysOfEachKind() { + tag(busArn, Map.of("a", "9", "c", "3")); + tag(subscriberArn, Map.of("team", "y", "env", "dev")); + tag(sourceArn, Map.of("src", "z", "env", "dev")); + + assertEquals(Map.of("b", "2", "a", "9", "c", "3"), service.storedTags(busArn)); + assertEquals(Map.of("team", "y", "env", "dev"), service.storedTags(subscriberArn)); + assertEquals(Map.of("src", "z", "env", "dev"), service.storedTags(sourceArn)); + } + + @Test + void aFailedWriteLeavesTheTagsOfEachKindAsTheyWere() { + IllegalStateException failure = new IllegalStateException("disk full"); + doThrow(failure).when(buses).putForAccount(any(), any(), any()); + doThrow(failure).when(subscribers).putForAccount(any(), any(), any()); + doThrow(failure).when(sources).putForAccount(any(), any(), any()); + + for (String arn : List.of(busArn, subscriberArn, sourceArn)) { + Map before = service.storedTags(arn); + assertSame(failure, assertThrows(IllegalStateException.class, () -> tag(arn, Map.of("c", "3")))); + assertSame(failure, assertThrows(IllegalStateException.class, + () -> untag(arn, before.keySet().toArray(new String[0])))); + assertEquals(before, service.storedTags(arn)); + } + } + + @Test + void tagKeepsInsertionOrderOfStoredTags() { + tag(busArn, linked("c", "3", "b", "9")); + + assertEquals(List.of("b", "a", "c"), List.copyOf(service.storedTags(busArn).keySet())); + } + + @Test + void untagRemovesTheListedKeysAndIgnoresMissingAndRepeatedOnes() { + untag(busArn, "a", "a", "missing"); + untag(subscriberArn, "team"); + untag(sourceArn, "nothing"); + + assertEquals(Map.of("b", "2"), service.storedTags(busArn)); + assertTrue(service.storedTags(subscriberArn).isEmpty()); + assertEquals(Map.of("src", "y"), service.storedTags(sourceArn)); + } + + @Test + void tagAndUntagChangeNeitherLastModifiedTimeNorAnythingElse() { + Instant busModified = service.describeEventBus(json("{\"EventBusArn\":\"" + busArn + "\"}"), REGION) + .getLastModifiedTime(); + Instant subscriberModified = service.describeSubscriber( + json("{\"SubscriberArn\":\"" + subscriberArn + "\"}"), REGION).getLastModifiedTime(); + Instant sourceModified = service.describeEventSource( + json("{\"EventSourceArn\":\"" + sourceArn + "\"}"), REGION).getLastModifiedTime(); + + tag(busArn, Map.of("c", "3")); + tag(subscriberArn, Map.of("c", "3")); + tag(sourceArn, Map.of("c", "3")); + untag(busArn, "a"); + untag(subscriberArn, "team"); + untag(sourceArn, "src"); + + EventBusV2 bus = service.describeEventBus(json("{\"EventBusArn\":\"" + busArn + "\"}"), REGION); + SubscriberV2 subscriber = service.describeSubscriber( + json("{\"SubscriberArn\":\"" + subscriberArn + "\"}"), REGION); + EventSourceV2 source = service.describeEventSource( + json("{\"EventSourceArn\":\"" + sourceArn + "\"}"), REGION); + assertEquals(busModified, bus.getLastModifiedTime()); + assertEquals(subscriberModified, subscriber.getLastModifiedTime()); + assertEquals(sourceModified, source.getLastModifiedTime()); + assertEquals("orders", bus.getName()); + assertEquals(QUEUE, subscriber.getInvokeConfiguration().get("TargetArn").textValue()); + assertEquals("hook", source.getName()); + } + + @Test + void listAnswersTheTagsOfEachKindAndNothingForNone() { + assertEquals(Map.of("b", "2", "a", "1"), service.listTagsForResource(listRequest(busArn), REGION)); + assertEquals(Map.of("team", "x"), service.listTagsForResource(listRequest(subscriberArn), REGION)); + assertEquals(Map.of("src", "y"), service.listTagsForResource(listRequest(sourceArn), REGION)); + untag(busArn, "a", "b"); + assertTrue(service.listTagsForResource(listRequest(busArn), REGION).isEmpty()); + } + + @Test + void listOrdersKeysAsACopyOfAHashMapFilledInKeyOrder() { + tag(busArn, linked("c", "1", "k", "1", "s", "1", "t", "1")); + untag(busArn, "a", "b"); + assertEquals(List.of("c", "s", "k", "t"), listedKeys(busArn)); + + untag(busArn, "c", "k", "s", "t"); + tag(busArn, linked("s", "1", "t", "1")); + assertEquals(List.of("t", "s"), listedKeys(busArn)); + + untag(busArn, "s", "t"); + tag(busArn, linked("s", "1", "t", "1", "env", "1", "Env", "1")); + assertEquals(List.of("s", "t", "Env", "env"), listedKeys(busArn)); + } + + @Test + void replacingAValueAtFiftyTagsWorksAndANewKeyFails() { + tag(busArn, numbered(48)); + assertEquals(50, service.storedTags(busArn).size()); + + tag(busArn, Map.of("k0", "changed")); + assertEquals("changed", service.storedTags(busArn).get("k0")); + + assertError("LimitExceededException", 400, "The maximum number of tags for this resource was exceeded.", + () -> tag(busArn, Map.of("one-more", "v"))); + assertEquals(50, service.storedTags(busArn).size()); + } + + @Test + void fiftyOneTagsAtOnceFail() { + untag(busArn, "a", "b"); + + assertError("LimitExceededException", 400, "The maximum number of tags for this resource was exceeded.", + () -> tag(busArn, numbered(51))); + assertTrue(service.storedTags(busArn).isEmpty()); + } + + @Test + void theLimitAppliesToSubscribersAndEventSourcesToo() { + for (String arn : List.of(subscriberArn, sourceArn)) { + assertError("LimitExceededException", 400, "The maximum number of tags for this resource was exceeded.", + () -> tag(arn, numbered(51))); + } + } + + @Test + void moreThan200TagsInTheRequestAnswerTheAddedTagsMessageInHashOrder() { + assertError("InvalidInputException", 400, MORE_THAN_200_TAGS, () -> tag(busArn, numbered(201))); + } + + @Test + void moreThan200TagKeysInTheRequestAnswerTheRemovedTagKeysMessageInRequestOrder() { + List keys = new ArrayList<>(); + for (int i = 0; i < 201; i++) { + keys.add("k" + i); + } + + assertError("InvalidInputException", 400, "1 validation error detected: Value '" + keys + + "' at 'removedTagKeys' failed to satisfy constraint: Member must have length less than or equal to 200", + () -> untag(busArn, keys.toArray(new String[0]))); + } + + @Test + void aReservedPrefixIsRefusedInAnyCaseOnTagAndUntag() { + for (String key : List.of("aws:x", "AWS:x", "Aws:y")) { + assertError("AccessDeniedException", 403, + "Not authorized to set or remove tag keys with the reserved 'aws:' prefix", + () -> tag(busArn, Map.of(key, "v"))); + assertError("AccessDeniedException", 403, + "Not authorized to set or remove tag keys with the reserved 'aws:' prefix", + () -> untag(busArn, "ok", key)); + } + assertEquals(Map.of("b", "2", "a", "1"), service.storedTags(busArn)); + } + + @Test + void theRegionIsCheckedBeforeTheReservedKeyAndTheAccountAfterIt() { + String otherRegion = busArn.replace("us-east-1", "us-west-2"); + String otherAccount = busArn.replace(":" + ACCOUNT + ":", ":111122223333:"); + + assertError("InvalidInputException", 400, "The region or partition in ResourceArn does not match this endpoint", + () -> tag(otherRegion, Map.of("aws:x", "v"))); + assertError("AccessDeniedException", 403, + "Not authorized to set or remove tag keys with the reserved 'aws:' prefix", + () -> tag(otherAccount, Map.of("aws:x", "v"))); + assertError("AccessDeniedException", 403, "Access denied.", () -> tag(otherAccount, Map.of("x", "v"))); + assertError("AccessDeniedException", 403, "Access denied.", () -> untag(otherAccount, "x")); + assertError("AccessDeniedException", 403, "Access denied.", + () -> service.listTagsForResource(listRequest(otherAccount), REGION)); + assertError("InvalidInputException", 400, "The region or partition in ResourceArn does not match this endpoint", + () -> untag(otherRegion, "x")); + assertError("InvalidInputException", 400, "The region or partition in ResourceArn does not match this endpoint", + () -> service.listTagsForResource(listRequest(otherRegion), REGION)); + } + + @Test + void aBusThatDoesNotExistIsNotFound() { + String missing = busArn.replace("orders", "nothing"); + + assertError("ResourceNotFoundException", 404, "Resource does not exist", () -> tag(missing, Map.of("x", "v"))); + assertError("ResourceNotFoundException", 404, "Resource does not exist", () -> untag(missing, "x")); + assertError("ResourceNotFoundException", 404, "Resource does not exist", + () -> service.listTagsForResource(listRequest(missing), REGION)); + } + + @Test + void aBusWithAnotherIdNamesTheBus() { + String otherId = withOtherId(busArn); + + assertError("ResourceNotFoundException", 404, "Event bus not found: orders", () -> tag(otherId, Map.of("x", "v"))); + assertError("ResourceNotFoundException", 404, "Event bus not found: orders", () -> untag(otherId, "x")); + assertError("ResourceNotFoundException", 404, "Event bus not found: orders", + () -> service.listTagsForResource(listRequest(otherId), REGION)); + } + + @Test + void aSubscriberThatDoesNotExistOrHasAnotherIdIsNotFound() { + String missing = subscriberArn.replace("/sub/", "/nothing/"); + String otherId = withOtherId(subscriberArn); + + for (String arn : List.of(missing, otherId)) { + assertError("ResourceNotFoundException", 404, "Subscriber not found: " + arn, () -> tag(arn, Map.of("x", "v"))); + assertError("ResourceNotFoundException", 404, "Subscriber not found: " + arn, () -> untag(arn, "x")); + assertError("ResourceNotFoundException", 404, "Subscriber not found: " + arn, + () -> service.listTagsForResource(listRequest(arn), REGION)); + } + } + + @Test + void anEventSourceThatDoesNotExistHasAnotherIdOrKindIsNotFound() { + String missing = sourceArn.replace("/hook/", "/nothing/"); + String otherId = withOtherId(sourceArn); + String serviceKind = sourceArn.replace("/webhook/", "/aws.service/"); + String partner = sourceArn.replace("/webhook/", "/aws.partner/"); + + for (String arn : List.of(missing, otherId, serviceKind, partner)) { + assertError("ResourceNotFoundException", 404, "EventSource not found: " + arn, () -> tag(arn, Map.of("x", "v"))); + assertError("ResourceNotFoundException", 404, "EventSource not found: " + arn, () -> untag(arn, "x")); + assertError("ResourceNotFoundException", 404, "EventSource not found: " + arn, + () -> service.listTagsForResource(listRequest(arn), REGION)); + } + } + + @Test + void theLookupComesBeforeTheTwoHundredAndTheFiftyChecks() { + String missing = busArn.replace("orders", "nothing"); + + assertError("ResourceNotFoundException", 404, "Resource does not exist", () -> tag(missing, numbered(201))); + assertError("ResourceNotFoundException", 404, "Resource does not exist", () -> tag(missing, numbered(51))); + } + + @Test + void aRevokedSubscriberOrEventSourceCannotBeTaggedOrUntaggedButStillLists() { + service.revokeResource(json("{\"Arn\":\"" + subscriberArn + "\"}"), REGION); + service.revokeResource(json("{\"Arn\":\"" + sourceArn + "\"}"), REGION); + + for (String arn : List.of(subscriberArn, sourceArn)) { + assertError("InvalidStateException", 409, "Resource is revoked and cannot be tagged", + () -> tag(arn, Map.of("x", "v"))); + assertError("InvalidStateException", 409, "Resource is revoked and cannot be untagged", + () -> untag(arn, "x")); + assertError("InvalidStateException", 409, "Resource is revoked and cannot be tagged", + () -> tag(arn, numbered(201))); + assertError("InvalidStateException", 409, "Resource is revoked and cannot be untagged", + () -> untag(arn, "a", "b")); + } + assertEquals(Map.of("team", "x"), service.listTagsForResource(listRequest(subscriberArn), REGION)); + assertEquals(Map.of("src", "y"), service.listTagsForResource(listRequest(sourceArn), REGION)); + } + + @Test + void aRevokedSubscriberWhoseBusIsGoneStillListsItsTags() { + service.revokeResource(json("{\"Arn\":\"" + subscriberArn + "\"}"), REGION); + service.revokeResource(json("{\"Arn\":\"" + sourceArn + "\"}"), REGION); + service.deleteEventBus(busArn, REGION); + + assertEquals(Map.of("team", "x"), service.listTagsForResource(listRequest(subscriberArn), REGION)); + assertError("InvalidStateException", 409, "Resource is revoked and cannot be tagged", + () -> tag(subscriberArn, Map.of("x", "v"))); + } + + @Test + void aBusThatIsStillCreatingCanBeTagged() { + EventBusV2 bus = buses.get(EventBridgeV2Service.storageKey(REGION, "orders")).orElseThrow(); + bus.setState("CREATING"); + buses.put(EventBridgeV2Service.storageKey(REGION, "orders"), bus); + + tag(busArn, Map.of("c", "3")); + + assertEquals(Map.of("b", "2", "a", "1", "c", "3"), service.storedTags(busArn)); + } + + @Test + void anEmptyTagKeyAnswersTheModelConstraintMessage() { + ObjectNode request = tagRequest(busArn, Map.of()); + request.putObject("Tags").put("", "v"); + + assertError("InvalidInputException", 400, "1 validation error detected: Value '{=v}' at 'tags' failed to " + + "satisfy constraint: Map keys must satisfy constraint: [" + NO_KEY_RULES + "]", + () -> service.tagResource(request, REGION)); + } + + @Test + void anEmptyTagKeyListAnswersTheModelConstraintMessage() { + ObjectNode request = MAPPER.createObjectNode(); + request.put("ResourceArn", busArn); + request.putArray("TagKeys").add(""); + + assertError("InvalidInputException", 400, "1 validation error detected: Value '[]' at 'tagKeys' failed to " + + "satisfy constraint: Member must satisfy constraint: [" + NO_KEY_RULES + ", Member must not be null]", + () -> service.untagResource(request, REGION)); + } + + private void tag(String arn, Map tags) { + service.tagResource(tagRequest(arn, tags), REGION); + } + + private void untag(String arn, String... keys) { + ObjectNode request = MAPPER.createObjectNode(); + request.put("ResourceArn", arn); + for (String key : keys) { + request.withArray("TagKeys").add(key); + } + service.untagResource(request, REGION); + } + + private static ObjectNode tagRequest(String arn, Map tags) { + ObjectNode request = MAPPER.createObjectNode(); + request.put("ResourceArn", arn); + ObjectNode tagNode = request.putObject("Tags"); + tags.forEach(tagNode::put); + return request; + } + + private static JsonNode listRequest(String arn) { + return MAPPER.createObjectNode().put("ResourceArn", arn); + } + + private List listedKeys(String arn) { + return List.copyOf(service.listTagsForResource(listRequest(arn), REGION).keySet()); + } + + private static Map numbered(int count) { + Map tags = new LinkedHashMap<>(); + for (int i = 0; i < count; i++) { + tags.put("k" + i, "v"); + } + return tags; + } + + private static Map linked(String... keysAndValues) { + Map tags = new LinkedHashMap<>(); + for (int i = 0; i < keysAndValues.length; i += 2) { + tags.put(keysAndValues[i], keysAndValues[i + 1]); + } + return tags; + } + + private static void assertError(String code, int status, String message, Runnable call) { + AwsException exception = assertThrows(AwsException.class, call::run); + assertEquals(code, exception.getErrorCode()); + assertEquals(status, exception.getHttpStatus()); + assertEquals(message, exception.getMessage()); + } + + 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); + } + } +} diff --git a/tools/aws/regen_eventbridgev2_shapes.py b/tools/aws/regen_eventbridgev2_shapes.py index 9c864031e7..9c17768a25 100644 --- a/tools/aws/regen_eventbridgev2_shapes.py +++ b/tools/aws/regen_eventbridgev2_shapes.py @@ -15,7 +15,8 @@ MODEL = Path("eventbridgev2/2025-05-15") OUTPUT = request_shapes.REPO_ROOT / "src/main/resources/aws/eventbridgev2-request-shapes.json" OPERATIONS = ("CreateEventSource", "DeleteEventSource", "DescribeEventSource", "ListEventSources", - "RevokeResource", "RotateWebhookCredentials", "UpdateEventSource") + "ListTagsForResource", "RevokeResource", "RotateWebhookCredentials", "TagResource", + "UntagResource", "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 9bd3f90a72..c47aaedc44 100644 --- a/tools/aws/test_request_shapes.py +++ b/tools/aws/test_request_shapes.py @@ -596,8 +596,9 @@ def test_eventbridgev2_shapes_keep_the_measured_orders_and_the_sensitive_mark(): shapes = doc["shapes"] assert sorted(doc["operations"]) == ["CreateEventSource", "DeleteEventSource", "DescribeEventSource", - "ListEventSources", "RevokeResource", - "RotateWebhookCredentials", "UpdateEventSource"] + "ListEventSources", "ListTagsForResource", "RevokeResource", + "RotateWebhookCredentials", "TagResource", "UntagResource", + "UpdateEventSource"] assert shapes["WebhookSecretValue"] == {"type": "string", "min": 6, "max": 512, "sensitive": True} assert shapes["WebhookMetadataHttpHeaderList"]["max"] == 20 assert shapes["TagMap"]["max"] == 200