mirror of
https://github.com/floci-io/floci.git
synced 2026-12-01 01:12:48 -05:00
feat(eventbridgev2): refuse reserved tag keys and more than 50 tags on create (#9709)
#9686 refused tag keys with the reserved aws: prefix, and more than 50 tags, on TagResource only. CreateEventBus, CreateSubscriber and CreateEventSource, and a CloudFormation update of a bus or a subscriber, now refuse them too, in the order measured on AWS: a reserved key answers AccessDeniedException (403) right after the request constraints, ahead of the name clash, the ClientToken replay and the bus lookup, and more than 50 tags answers LimitExceededException (400) after those checks, and before a ClientToken mismatch when the token named another resource. A refused create stores nothing and makes no secret or managed rule.
This commit is contained in:
1 parent
10855b0023
commit
e92bbf66dc
6 files changed
+401
-18
No files matched your search
@@ -234,6 +234,8 @@ that does not exist, since Floci models no partner event sources.
|
||||
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.
|
||||
`CreateEventBus`, `CreateSubscriber` and `CreateEventSource` refuse a key that starts with `aws:` and more than
|
||||
50 tags in the same way.
|
||||
|
||||
## IAM
|
||||
|
||||
|
||||
@@ -118,10 +118,12 @@ public class EventBridgeV2EventSources implements Resettable {
|
||||
String roleArn = configuration.path(WebhookEventsConfigurations.WEBHOOK).path("RoleArn").asText(null);
|
||||
|
||||
requireEndpointRegion(eventBusArn, region, "EventBusArn");
|
||||
requireOwnAccount(eventBusArn);
|
||||
if (roleArn != null) {
|
||||
requireOwnAccount(roleArn);
|
||||
}
|
||||
Map<String, String> tags = tags(request.get("Tags"));
|
||||
EventBridgeV2Service.refuseReservedTagKeys(tags.keySet());
|
||||
requireOwnAccount(eventBusArn);
|
||||
String keyIdentifier = WebhookEventsConfigurations.keyIdentifier(
|
||||
configuration.path(WebhookEventsConfigurations.WEBHOOK));
|
||||
WebhookEventsConfigurations.requireKeyArnOfCaller(keyIdentifier, region, regionResolver.getAccountId());
|
||||
@@ -136,7 +138,7 @@ public class EventBridgeV2EventSources implements Resettable {
|
||||
throw ServiceEventsConfigurations.partnerSourceMissing(variant.getValue());
|
||||
}
|
||||
if (ServiceEventsConfigurations.AWS_SERVICE.equals(variant.getKey())) {
|
||||
return createServiceSource(request, region, clientToken, variant.getValue(), findBusByName);
|
||||
return createServiceSource(request, region, clientToken, variant.getValue(), tags, findBusByName);
|
||||
}
|
||||
JsonNode webhook = WebhookEventsConfigurations.validateForCreate(configuration);
|
||||
|
||||
@@ -155,6 +157,7 @@ public class EventBridgeV2EventSources implements Resettable {
|
||||
if (kmsKey != null) {
|
||||
refuseAwsManagedKey(keyIdentifier, kmsKey, region);
|
||||
}
|
||||
EventBridgeV2Service.requireStoredTagLimit(tags.size());
|
||||
|
||||
String hostId = WebhookTokens.newHostId(random);
|
||||
Instant now = clock.instant();
|
||||
@@ -173,7 +176,7 @@ public class EventBridgeV2EventSources implements Resettable {
|
||||
source.setState(EventBridgeV2Service.ACTIVE);
|
||||
source.setCreationTime(now);
|
||||
source.setLastModifiedTime(now);
|
||||
source.setTags(tags(request.get("Tags")));
|
||||
source.setTags(tags);
|
||||
source.setClientToken(clientToken);
|
||||
source.setCreateRequestHash(requestHash);
|
||||
source.setWebhookHostId(hostId);
|
||||
@@ -216,6 +219,7 @@ public class EventBridgeV2EventSources implements Resettable {
|
||||
* behind, as {@code CREATE_FAILED}, with no rule.
|
||||
*/
|
||||
private EventSourceV2 createServiceSource(JsonNode request, String region, String clientToken, JsonNode service,
|
||||
Map<String, String> tags,
|
||||
Function<String, Optional<EventBusV2>> findBusByName) {
|
||||
String eventBusArn = request.get("EventBusArn").textValue();
|
||||
checkServiceSource(service, region);
|
||||
@@ -233,6 +237,7 @@ public class EventBridgeV2EventSources implements Resettable {
|
||||
if (sources.get(key).isPresent()) {
|
||||
throw new AwsException("ResourceAlreadyExistsException", "Resource already exists", 409);
|
||||
}
|
||||
EventBridgeV2Service.requireStoredTagLimit(tags.size());
|
||||
|
||||
Instant now = clock.instant();
|
||||
EventSourceV2 source = new EventSourceV2();
|
||||
@@ -243,7 +248,7 @@ public class EventBridgeV2EventSources implements Resettable {
|
||||
source.setConfiguration(ServiceEventsConfigurations.echo(service));
|
||||
source.setCreationTime(now);
|
||||
source.setLastModifiedTime(now);
|
||||
source.setTags(tags(request.get("Tags")));
|
||||
source.setTags(tags);
|
||||
source.setClientToken(clientToken);
|
||||
source.setCreateRequestHash(requestHash);
|
||||
boolean provisioned = provisionRule(source, service, region);
|
||||
|
||||
@@ -33,6 +33,7 @@ import java.time.Clock;
|
||||
import java.time.Instant;
|
||||
import java.time.temporal.ChronoUnit;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collection;
|
||||
import java.util.HashMap;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
@@ -142,8 +143,12 @@ public class EventBridgeV2Service implements Resettable {
|
||||
Map<String, String> tags = readTags(request.get("Tags"));
|
||||
String clientToken = optionalClientToken(request);
|
||||
String createRequest = withoutClientToken(request);
|
||||
refuseReservedTagKeys(tags.keySet());
|
||||
|
||||
Optional<EventBusV2> retried = retried(() -> buses.scan(key -> key.startsWith(region + "::")), clientToken,
|
||||
List<EventBusV2> inRegion = clientToken == null ? List.of() : buses.scan(key -> key.startsWith(region + "::"));
|
||||
requireTagLimitBeforeMismatch(inRegion, clientToken, EventBusV2::getClientToken, EventBusV2::getName, name,
|
||||
tags.size());
|
||||
Optional<EventBusV2> retried = retried(() -> inRegion, clientToken,
|
||||
createRequest, EventBusV2::getClientToken, EventBusV2::getCreateRequest,
|
||||
() -> idempotentMismatch(clientToken));
|
||||
if (retried.isPresent()) {
|
||||
@@ -153,6 +158,7 @@ public class EventBridgeV2Service implements Resettable {
|
||||
if (buses.get(key).isPresent()) {
|
||||
throw new AwsException("ResourceAlreadyExistsException", "Event bus " + name + " already exists.", 409);
|
||||
}
|
||||
requireStoredTagLimit(tags.size());
|
||||
|
||||
Instant now = clock.instant();
|
||||
EventBusV2 bus = new EventBusV2();
|
||||
@@ -181,6 +187,8 @@ public class EventBridgeV2Service implements Resettable {
|
||||
String kmsKeyIdentifier = optionalKmsKeyIdentifier(request);
|
||||
Integer retentionPeriodInDays = optionalRetentionPeriodInDays(request);
|
||||
Map<String, String> tags = readTags(request.get("Tags"));
|
||||
refuseReservedTagKeys(tags.keySet());
|
||||
requireStoredTagLimit(tags.size());
|
||||
bus.setDescription(description);
|
||||
bus.setKmsKeyIdentifier(kmsKeyIdentifier);
|
||||
bus.setRetentionPeriodInDays(retentionPeriodInDays);
|
||||
@@ -267,13 +275,19 @@ public class EventBridgeV2Service implements Resettable {
|
||||
public synchronized SubscriberV2 createSubscriber(JsonNode request, String region) {
|
||||
String name = requireName(request);
|
||||
String eventBusArn = requireText(request, "EventBusArn");
|
||||
Map<String, String> tags = readTags(request.get("Tags"));
|
||||
String clientToken = optionalClientToken(request);
|
||||
refuseReservedTagKeys(tags.keySet());
|
||||
JsonNode filterConfiguration = optionalStructure(request, "FilterConfiguration");
|
||||
if (filterConfiguration != null) {
|
||||
SubscriberFilters.validate(filterConfiguration);
|
||||
}
|
||||
String clientToken = optionalClientToken(request);
|
||||
String createRequest = withoutClientToken(request);
|
||||
Optional<SubscriberV2> retried = retried(() -> subscribers.scan(key -> key.startsWith(region + "::")),
|
||||
List<SubscriberV2> inRegion = clientToken == null ? List.of()
|
||||
: subscribers.scan(key -> key.startsWith(region + "::"));
|
||||
requireTagLimitBeforeMismatch(inRegion, clientToken, SubscriberV2::getClientToken, SubscriberV2::getName,
|
||||
name, tags.size());
|
||||
Optional<SubscriberV2> retried = retried(() -> inRegion,
|
||||
clientToken, createRequest, SubscriberV2::getClientToken, SubscriberV2::getCreateRequest,
|
||||
() -> idempotentMismatch(clientToken));
|
||||
if (retried.isPresent()) {
|
||||
@@ -296,6 +310,7 @@ public class EventBridgeV2Service implements Resettable {
|
||||
"LATEST"));
|
||||
subscriber.setPointInTimeConfiguration(pointInTimeConfiguration(request, subscriber.getStartingPosition()));
|
||||
applySettings(subscriber, request, filterConfiguration);
|
||||
requireStoredTagLimit(tags.size());
|
||||
subscriber.setCreationTime(now);
|
||||
subscriber.setLastModifiedTime(now);
|
||||
subscriber.setClientToken(clientToken);
|
||||
@@ -311,6 +326,9 @@ public class EventBridgeV2Service implements Resettable {
|
||||
*/
|
||||
public synchronized SubscriberV2 replaceSubscriberSettings(String subscriberArn, JsonNode request, String region) {
|
||||
SubscriberV2 subscriber = requireSubscriber(subscriberArn, region);
|
||||
Map<String, String> tags = readTags(request.get("Tags"));
|
||||
refuseReservedTagKeys(tags.keySet());
|
||||
requireStoredTagLimit(tags.size());
|
||||
return changeSettings(subscriber, request, region);
|
||||
}
|
||||
|
||||
@@ -453,10 +471,7 @@ public class EventBridgeV2Service implements Resettable {
|
||||
}
|
||||
Map<String, String> 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);
|
||||
}
|
||||
requireStoredTagLimit(merged.size());
|
||||
resource.store().accept(merged);
|
||||
}
|
||||
|
||||
@@ -493,10 +508,7 @@ public class EventBridgeV2Service implements Resettable {
|
||||
private Taggable findTaggable(JsonNode request, String region, List<String> 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);
|
||||
}
|
||||
refuseReservedTagKeys(keys);
|
||||
eventSources.requireOwnAccount(arn);
|
||||
Taggable resource = taggable(arn).orElseThrow(() -> taggableNotFound(arn, region));
|
||||
if (resource.revoked() && revokedVerb != null) {
|
||||
@@ -505,6 +517,30 @@ public class EventBridgeV2Service implements Resettable {
|
||||
return resource;
|
||||
}
|
||||
|
||||
static void refuseReservedTagKeys(Collection<String> keys) {
|
||||
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);
|
||||
}
|
||||
}
|
||||
|
||||
static void requireStoredTagLimit(int count) {
|
||||
if (count > MAX_STORED_TAGS) {
|
||||
throw new AwsException("LimitExceededException",
|
||||
"The maximum number of tags for this resource was exceeded.", 400);
|
||||
}
|
||||
}
|
||||
|
||||
/** AWS answers the tag limit, not the mismatch, for a ClientToken an earlier create used for another name. */
|
||||
private static <T> void requireTagLimitBeforeMismatch(List<T> candidates, String clientToken,
|
||||
Function<T, String> tokenOf, Function<T, String> nameOf,
|
||||
String name, int tagCount) {
|
||||
if (clientToken != null && candidates.stream().anyMatch(
|
||||
candidate -> clientToken.equals(tokenOf.apply(candidate)) && !name.equals(nameOf.apply(candidate)))) {
|
||||
requireStoredTagLimit(tagCount);
|
||||
}
|
||||
}
|
||||
|
||||
/** The bus, subscriber or event source the exact ARN names, in the account and Region the ARN names. */
|
||||
private Optional<Taggable> taggable(String resourceArn) {
|
||||
AwsArnUtils.Arn arn = AwsArnUtils.parse(resourceArn);
|
||||
|
||||
@@ -2,6 +2,7 @@ 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.PaginatedResult;
|
||||
@@ -24,6 +25,7 @@ import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.stream.Collectors;
|
||||
import java.util.stream.IntStream;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertNull;
|
||||
@@ -49,6 +51,9 @@ class AwsServiceEventSourcesTest {
|
||||
private static final String PARTNER = "arn:aws:events:us-east-1:111111111111:event-source/aws.partner/"
|
||||
+ "example.com/123/orders";
|
||||
private static final String RULE_ARN_PREFIX = "arn:aws:events:us-east-1:000000000000:rule/";
|
||||
private static final String RESERVED =
|
||||
"Not authorized to set or remove tag keys with the reserved 'aws:' prefix";
|
||||
private static final String TAG_LIMIT = "The maximum number of tags for this resource was exceeded.";
|
||||
private static final String PROVISIONING_FAILED =
|
||||
"EventSource forwarding could not be provisioned: InvalidEventPatternException";
|
||||
|
||||
@@ -734,6 +739,77 @@ class AwsServiceEventSourcesTest {
|
||||
REGION)).getMessage();
|
||||
}
|
||||
|
||||
@Test
|
||||
void createRefusesAReservedTagKeyBeforeAnythingElseOfTheSource() {
|
||||
String reserved = "{\"aws:x\":\"v\"}";
|
||||
assertError("AccessDeniedException", 403, RESERVED, () -> service.createEventSource(
|
||||
withTags(create("svc", "{\"AwsService\":\"aws.ssm\"}"), reserved), REGION));
|
||||
assertError("AccessDeniedException", 403, RESERVED, () -> service.createEventSource(
|
||||
withTags(create("svc", "{\"AwsService\":\"aws.ssm\",\"Pattern\":\"{oops\"}"), "{\"AWS:y\":\"v\"}"),
|
||||
REGION));
|
||||
assertError("AccessDeniedException", 403, RESERVED, () -> service.createEventSource(
|
||||
withTags(partner("{\"PartnerEventSourceArn\":\"" + PARTNER + "\"}"), reserved), REGION));
|
||||
assertTrue(service.listEventSources(json("{}"), REGION).items().isEmpty());
|
||||
verify(eventBridge, never()).putManagedRule(any(), any(), any(), any(), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void createAcceptsFiftyTagsAndRefusesFiftyOne() {
|
||||
assertEquals(50, service.createEventSource(withTags(create("fifty", "{\"AwsService\":\"aws.ssm\"}"),
|
||||
tags(50)), REGION).getTags().size());
|
||||
|
||||
assertError("LimitExceededException", 400, TAG_LIMIT, () -> service.createEventSource(
|
||||
withTags(create("fifty-one", "{\"AwsService\":\"aws.ssm\"}"), tags(51)), REGION));
|
||||
assertEquals(1, service.listEventSources(json("{}"), REGION).items().size());
|
||||
verify(eventBridge, times(1)).putManagedRule(any(), any(), any(), any(), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void createAnswersTheNameClashTheBusAndTheBadPatternBeforeTheLimit() {
|
||||
service.createEventSource(create("svc", "{\"AwsService\":\"aws.ssm\"}"), REGION);
|
||||
|
||||
assertError("ResourceAlreadyExistsException", 409, "Resource already exists", () -> service.createEventSource(
|
||||
withTags(create("svc", "{\"AwsService\":\"aws.s3\"}"), tags(51)), REGION));
|
||||
assertError("InvalidInputException", 400, "Pattern is not valid JSON", () -> service.createEventSource(
|
||||
withTags(create("other", "{\"AwsService\":\"aws.ssm\",\"Pattern\":\"{oops\"}"), tags(51)),
|
||||
REGION));
|
||||
assertEquals("Resource does not exist", assertThrows(AwsException.class, () -> service.createEventSource(
|
||||
withTags(request("other", missingBus(), "{\"AwsService\":\"aws.ssm\"}"), tags(51)), REGION))
|
||||
.getMessage());
|
||||
}
|
||||
|
||||
@Test
|
||||
void createAnswersTheLimitInsteadOfAProvisioningFailureAndStoresNothing() {
|
||||
doThrow(new AwsException("InvalidEventPatternException", "refused", 400))
|
||||
.when(eventBridge).validateEventPattern(any());
|
||||
String failing = "{\"AwsService\":\"aws.s3\",\"Pattern\":\"" + escaped("{\"detail-type\":[\"x\"]}") + "\"}";
|
||||
|
||||
assertError("LimitExceededException", 400, TAG_LIMIT,
|
||||
() -> service.createEventSource(withTags(create("svc", failing), tags(51)), REGION));
|
||||
assertTrue(service.listEventSources(json("{}"), REGION).items().isEmpty());
|
||||
|
||||
assertError("InvalidInputException", 400, PROVISIONING_FAILED,
|
||||
() -> service.createEventSource(withTags(create("svc", failing), tags(50)), REGION));
|
||||
assertEquals("CREATE_FAILED", service.listEventSources(json("{}"), REGION).items().getFirst().getState());
|
||||
verify(eventBridge, never()).putManagedRule(any(), any(), any(), any(), any());
|
||||
}
|
||||
|
||||
private static JsonNode withTags(JsonNode request, String tagsJson) {
|
||||
return ((ObjectNode) request).set("Tags", json(tagsJson));
|
||||
}
|
||||
|
||||
private static String tags(int count) {
|
||||
return MAPPER.valueToTree(IntStream.range(0, count).boxed().collect(
|
||||
Collectors.toMap(i -> "k" + i, i -> "v"))).toString();
|
||||
}
|
||||
|
||||
private static void assertError(String code, int status, String message, Runnable call) {
|
||||
AwsException e = assertThrows(AwsException.class, call::run);
|
||||
assertEquals(code, e.getErrorCode());
|
||||
assertEquals(status, e.getHttpStatus());
|
||||
assertEquals(message, e.getMessage());
|
||||
}
|
||||
|
||||
private String missingBus() {
|
||||
return bus.substring(0, bus.lastIndexOf('/') + 1).replace("orders", "gone") + "abcdefghijklmnopqrstuvwxy";
|
||||
}
|
||||
|
||||
+32
@@ -6,6 +6,7 @@ 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.EventSourceConfiguration;
|
||||
import software.amazon.awssdk.services.eventbridgev2.model.InvalidStateException;
|
||||
import software.amazon.awssdk.services.eventbridgev2.model.LimitExceededException;
|
||||
import software.amazon.awssdk.services.eventbridgev2.model.ListTagsForResourceResponse;
|
||||
@@ -110,6 +111,37 @@ class EventBridgeV2TaggingIntegrationTest {
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void createCallsRefuseAReservedKeyAndMoreThanFiftyTags() {
|
||||
try (EventBridgeV2Client events = events()) {
|
||||
Map<String, String> tags = new LinkedHashMap<>();
|
||||
for (int i = 0; i < 51; i++) {
|
||||
tags.put("k" + i, "v");
|
||||
}
|
||||
AccessDeniedException reserved = assertThrows(AccessDeniedException.class, () -> events.createEventBus(
|
||||
request -> request.name("v2-create-aws-" + suffix()).tags(Map.of("aws:x", "v"))));
|
||||
assertEquals("Not authorized to set or remove tag keys with the reserved 'aws:' prefix",
|
||||
reserved.awsErrorDetails().errorMessage());
|
||||
LimitExceededException busLimit = assertThrows(LimitExceededException.class, () -> events.createEventBus(
|
||||
request -> request.name("v2-create-max-" + suffix()).tags(tags)));
|
||||
assertEquals("The maximum number of tags for this resource was exceeded.",
|
||||
busLimit.awsErrorDetails().errorMessage());
|
||||
|
||||
String bus = events.createEventBus(request -> request.name("v2-create-bus-" + suffix())).eventBusArn();
|
||||
LimitExceededException subscriberLimit = assertThrows(LimitExceededException.class,
|
||||
() -> events.createSubscriber(request -> request.name("sub").eventBusArn(bus)
|
||||
.invokeConfiguration(invoke -> invoke.targetArn(QUEUE).roleArn(ROLE)).tags(tags)));
|
||||
assertEquals("The maximum number of tags for this resource was exceeded.",
|
||||
subscriberLimit.awsErrorDetails().errorMessage());
|
||||
LimitExceededException sourceLimit = assertThrows(LimitExceededException.class,
|
||||
() -> events.createEventSource(request -> request.name("src").eventBusArn(bus).tags(tags)
|
||||
.configuration(EventSourceConfiguration.fromAwsServiceEventsConfiguration(
|
||||
service -> service.awsService("aws.ssm")))));
|
||||
assertEquals("The maximum number of tags for this resource was exceeded.",
|
||||
sourceLimit.awsErrorDetails().errorMessage());
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void aRevokedSubscriberCannotBeTagged() {
|
||||
try (EventBridgeV2Client events = events()) {
|
||||
|
||||
@@ -12,6 +12,7 @@ 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.kms.model.KmsKey;
|
||||
import io.floci.aws.services.secretsmanager.SecretsManagerService;
|
||||
import io.floci.aws.testing.ManualClock;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
@@ -25,6 +26,7 @@ import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertSame;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
@@ -33,6 +35,9 @@ 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;
|
||||
import static org.mockito.Mockito.times;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
class EventBridgeV2TaggingTest {
|
||||
private static final String REGION = "us-east-1";
|
||||
@@ -67,6 +72,8 @@ class EventBridgeV2TaggingTest {
|
||||
private AccountAwareStorageBackend<SubscriberV2> subscribers;
|
||||
private AccountAwareStorageBackend<EventSourceV2> sources;
|
||||
private EventBridgeV2Service service;
|
||||
private SecretsManagerService secrets;
|
||||
private KmsService kms;
|
||||
private String busArn;
|
||||
private String subscriberArn;
|
||||
private String sourceArn;
|
||||
@@ -76,10 +83,11 @@ class EventBridgeV2TaggingTest {
|
||||
RegionResolver regionResolver = new RegionResolver(REGION, ACCOUNT);
|
||||
ManualClock clock = new ManualClock(Instant.parse("2026-11-27T00:00:00Z"));
|
||||
sources = spy(AccountAwareStorageBackend.<EventSourceV2>inMemory(ACCOUNT));
|
||||
secrets = mock(SecretsManagerService.class, RETURNS_DEEP_STUBS);
|
||||
kms = mock(KmsService.class);
|
||||
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));
|
||||
secrets, regionResolver, clock,
|
||||
"http://floci.test:4566", mock(TlsCertificateManager.class), mock(EventBridgeService.class), kms);
|
||||
buses = spy(AccountAwareStorageBackend.<EventBusV2>inMemory(ACCOUNT));
|
||||
subscribers = spy(AccountAwareStorageBackend.<SubscriberV2>inMemory(ACCOUNT));
|
||||
service = new EventBridgeV2Service(buses, subscribers, regionResolver, mock(EventBridgeV2Delivery.class),
|
||||
@@ -393,6 +401,230 @@ class EventBridgeV2TaggingTest {
|
||||
() -> service.untagResource(request, REGION));
|
||||
}
|
||||
|
||||
// ──────────────────────────── Create-time tag checks ────────────────────────────
|
||||
|
||||
private static final String RESERVED = "Not authorized to set or remove tag keys with the reserved 'aws:' prefix";
|
||||
private static final String TAG_LIMIT = "The maximum number of tags for this resource was exceeded.";
|
||||
private static final String OTHER_ACCOUNT_BUS =
|
||||
"arn:aws:events:us-east-1:111111111111:event-busv2/orders/abcdefghijklmnopqrstuvwxy";
|
||||
|
||||
@Test
|
||||
void createEventBusRefusesAReservedKeyInAnyCaseAndStoresNothing() {
|
||||
assertError("AccessDeniedException", 403, RESERVED,
|
||||
() -> service.createEventBus(bus("new", "{\"aws:x\":\"v\"}", null), REGION));
|
||||
assertError("AccessDeniedException", 403, RESERVED,
|
||||
() -> service.createEventBus(bus("new", "{\"AWS:y\":\"v\"}", null), REGION));
|
||||
|
||||
assertEquals(1, service.listEventBuses(json("{}"), REGION).items().size());
|
||||
}
|
||||
|
||||
@Test
|
||||
void createEventBusAcceptsFiftyTagsAndRefusesFiftyOne() {
|
||||
assertEquals(50, service.createEventBus(bus("fifty", tagsOf(50), null), REGION).getTags().size());
|
||||
|
||||
assertError("LimitExceededException", 400, TAG_LIMIT,
|
||||
() -> service.createEventBus(bus("fifty-one", tagsOf(51), null), REGION));
|
||||
assertEquals(2, service.listEventBuses(json("{}"), REGION).items().size());
|
||||
}
|
||||
|
||||
@Test
|
||||
void createEventBusAnswersAReservedKeyBeforeTheNameClashAndTheReplay() {
|
||||
assertError("AccessDeniedException", 403, RESERVED,
|
||||
() -> service.createEventBus(bus("orders", "{\"aws:x\":\"v\"}", null), REGION));
|
||||
service.createEventBus(bus("first", "{}", "t1"), REGION);
|
||||
assertError("AccessDeniedException", 403, RESERVED,
|
||||
() -> service.createEventBus(bus("second", "{\"aws:x\":\"v\"}", "t1"), REGION));
|
||||
}
|
||||
|
||||
@Test
|
||||
void createEventBusAnswersTheNameClashBeforeTheLimit() {
|
||||
assertError("ResourceAlreadyExistsException", 409, "Event bus orders already exists.",
|
||||
() -> service.createEventBus(bus("orders", tagsOf(51), "other"), REGION));
|
||||
}
|
||||
|
||||
@Test
|
||||
void createEventBusAnswersTheLimitBeforeTheMismatchOfAnotherNameOnly() {
|
||||
service.createEventBus(bus("first", "{}", "t1"), REGION);
|
||||
|
||||
assertError("LimitExceededException", 400, TAG_LIMIT,
|
||||
() -> service.createEventBus(bus("second", tagsOf(51), "t1"), REGION));
|
||||
assertError("IdempotentParameterMismatchException", 409, "ClientToken t1 was used with a different request.",
|
||||
() -> service.createEventBus(bus("first", tagsOf(51), "t1"), REGION));
|
||||
}
|
||||
|
||||
@Test
|
||||
void createSubscriberRefusesAReservedKeyInAnyCaseAndStoresNothing() {
|
||||
assertError("AccessDeniedException", 403, RESERVED,
|
||||
() -> service.createSubscriber(subscriber("new", busArn, "{\"aws:x\":\"v\"}", null), REGION));
|
||||
assertError("AccessDeniedException", 403, RESERVED,
|
||||
() -> service.createSubscriber(subscriber("new", busArn, "{\"AWS:y\":\"v\"}", null), REGION));
|
||||
|
||||
assertEquals(1, subscribers.scan(key -> true).size());
|
||||
}
|
||||
|
||||
@Test
|
||||
void createSubscriberAnswersABadClientTokenBeforeAReservedKey() {
|
||||
assertError("InvalidInputException", 400, "ClientToken must be 1-64 printable ASCII characters.",
|
||||
() -> service.createSubscriber(subscriber("new", busArn, "{\"aws:x\":\"v\"}", ""), REGION));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aCloudFormationUpdateRefusesAReservedKeyAndMoreThanFiftyTagsAndChangesNothing() {
|
||||
Map<String, String> busTags = service.storedTags(busArn);
|
||||
Map<String, String> subscriberTags = service.storedTags(subscriberArn);
|
||||
|
||||
assertError("AccessDeniedException", 403, RESERVED, () -> service.replaceEventBusSettings(busArn,
|
||||
json("{\"Description\":\"changed\",\"Tags\":{\"aws:x\":\"v\"}}"), REGION));
|
||||
assertError("LimitExceededException", 400, TAG_LIMIT, () -> service.replaceEventBusSettings(busArn,
|
||||
json("{\"Description\":\"changed\",\"Tags\":" + tagsOf(51) + "}"), REGION));
|
||||
assertError("AccessDeniedException", 403, RESERVED, () -> service.replaceSubscriberSettings(subscriberArn,
|
||||
json("{\"Description\":\"changed\",\"Tags\":{\"AWS:y\":\"v\"}}"), REGION));
|
||||
assertError("LimitExceededException", 400, TAG_LIMIT, () -> service.replaceSubscriberSettings(subscriberArn,
|
||||
json("{\"Description\":\"changed\",\"Tags\":" + tagsOf(51) + "}"), REGION));
|
||||
|
||||
assertEquals(busTags, service.storedTags(busArn));
|
||||
assertEquals(subscriberTags, service.storedTags(subscriberArn));
|
||||
assertNull(service.describeEventBus(json("{\"EventBusArn\":\"" + busArn + "\"}"), REGION).getDescription());
|
||||
assertNull(service.describeSubscriber(json("{\"SubscriberArn\":\"" + subscriberArn + "\"}"), REGION)
|
||||
.getDescription());
|
||||
}
|
||||
|
||||
@Test
|
||||
void createSubscriberAcceptsFiftyTagsAndRefusesFiftyOne() {
|
||||
assertEquals(50, service.createSubscriber(subscriber("fifty", busArn, tagsOf(50), null), REGION)
|
||||
.getTags().size());
|
||||
|
||||
assertError("LimitExceededException", 400, TAG_LIMIT,
|
||||
() -> service.createSubscriber(subscriber("fifty-one", busArn, tagsOf(51), null), REGION));
|
||||
assertEquals(2, subscribers.scan(key -> true).size());
|
||||
}
|
||||
|
||||
@Test
|
||||
void createSubscriberAnswersAReservedKeyBeforeTheFilterTheReplayTheBusAndTheNameClash() {
|
||||
ObjectNode badFilter = (ObjectNode) subscriber("new", busArn, "{\"aws:x\":\"v\"}", null);
|
||||
badFilter.putObject("FilterConfiguration").put("Scope", "BAD");
|
||||
assertError("AccessDeniedException", 403, RESERVED, () -> service.createSubscriber(badFilter, REGION));
|
||||
service.createSubscriber(subscriber("first", busArn, "{}", "t1"), REGION);
|
||||
assertError("AccessDeniedException", 403, RESERVED,
|
||||
() -> service.createSubscriber(subscriber("second", busArn, "{\"aws:x\":\"v\"}", "t1"), REGION));
|
||||
assertError("AccessDeniedException", 403, RESERVED, () -> service.createSubscriber(
|
||||
subscriber("new", withOtherId(busArn), "{\"aws:x\":\"v\"}", null), REGION));
|
||||
assertError("AccessDeniedException", 403, RESERVED,
|
||||
() -> service.createSubscriber(subscriber("sub", busArn, "{\"aws:x\":\"v\"}", null), REGION));
|
||||
}
|
||||
|
||||
@Test
|
||||
void createSubscriberAnswersTheBusLookupAndTheNameClashBeforeTheLimit() {
|
||||
String missing = withOtherId(busArn);
|
||||
assertError("ResourceNotFoundException", 404, "Event bus " + missing + " does not exist.",
|
||||
() -> service.createSubscriber(subscriber("new", missing, tagsOf(51), null), REGION));
|
||||
assertError("ResourceAlreadyExistsException", 409, "Subscriber sub already exists on event bus orders.",
|
||||
() -> service.createSubscriber(subscriber("sub", busArn, tagsOf(51), "other"), REGION));
|
||||
}
|
||||
|
||||
@Test
|
||||
void createSubscriberAnswersTheLimitBeforeTheMismatchOfAnotherNameOnly() {
|
||||
service.createSubscriber(subscriber("first", busArn, "{}", "t1"), REGION);
|
||||
|
||||
assertError("LimitExceededException", 400, TAG_LIMIT,
|
||||
() -> service.createSubscriber(subscriber("second", busArn, tagsOf(51), "t1"), REGION));
|
||||
assertError("IdempotentParameterMismatchException", 409, "ClientToken t1 was used with a different request.",
|
||||
() -> service.createSubscriber(subscriber("first", busArn, tagsOf(51), "t1"), REGION));
|
||||
}
|
||||
|
||||
@Test
|
||||
void createEventSourceRefusesAReservedKeyInAnyCaseAndStoresNothing() {
|
||||
assertError("AccessDeniedException", 403, RESERVED, () -> service.createEventSource(
|
||||
webhook("new", "n1", busArn, "{\"aws:x\":\"v\"}"), REGION));
|
||||
assertError("AccessDeniedException", 403, RESERVED, () -> service.createEventSource(
|
||||
webhook("new", "n2", busArn, "{\"AWS:y\":\"v\"}"), REGION));
|
||||
|
||||
assertEquals(1, sources.scan(key -> true).size());
|
||||
verify(secrets, times(1)).createSecret(any(), any(), any(), any(), any(), any(), any(), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void createEventSourceAcceptsFiftyTagsAndRefusesFiftyOneWithoutASecret() {
|
||||
assertEquals(50, service.createEventSource(webhook("fifty", "n1", busArn, tagsOf(50)), REGION)
|
||||
.getTags().size());
|
||||
|
||||
assertError("LimitExceededException", 400, TAG_LIMIT, () -> service.createEventSource(
|
||||
webhook("fifty-one", "n2", busArn, tagsOf(51)), REGION));
|
||||
assertEquals(2, sources.scan(key -> true).size());
|
||||
verify(secrets, times(2)).createSecret(any(), any(), any(), any(), any(), any(), any(), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void createEventSourceAnswersAReservedKeyBeforeEverythingButAnotherAccountsRole() {
|
||||
String reserved = "{\"aws:x\":\"v\"}";
|
||||
assertError("AccessDeniedException", 403, RESERVED, () -> service.createEventSource(
|
||||
webhook("new", "n1", OTHER_ACCOUNT_BUS, reserved), REGION));
|
||||
assertError("AccessDeniedException", 403, RESERVED, () -> service.createEventSource(
|
||||
webhook("new", "n2", withOtherId(busArn), reserved), REGION));
|
||||
assertError("AccessDeniedException", 403, RESERVED, () -> service.createEventSource(
|
||||
webhook("hook", "n3", busArn, reserved), REGION));
|
||||
assertError("AccessDeniedException", 403, RESERVED, () -> service.createEventSource(
|
||||
webhook("new", "t", busArn, reserved), REGION));
|
||||
assertError("AccessDeniedException", 403, "Access denied.", () -> service.createEventSource(
|
||||
json(webhook("new", "n4", busArn, reserved).toString().replace(ROLE,
|
||||
"arn:aws:iam::111111111111:role/Hook")), REGION));
|
||||
assertError("AccessDeniedException", 403, "Access denied.", () -> service.createEventSource(
|
||||
webhook("new", "n5", OTHER_ACCOUNT_BUS, "{}"), REGION));
|
||||
}
|
||||
|
||||
@Test
|
||||
void createEventSourceAnswersTheBusTheNameClashTheMismatchAndTheManagedKeyBeforeTheLimit() {
|
||||
String missing = withOtherId(busArn);
|
||||
assertError("ResourceNotFoundException", 404, "Event bus not found: orders", () -> service.createEventSource(
|
||||
webhook("new", "n1", missing, tagsOf(51)), REGION));
|
||||
assertError("ResourceAlreadyExistsException", 409, "Resource already exists", () -> service.createEventSource(
|
||||
webhook("hook", "n2", busArn, tagsOf(51)), REGION));
|
||||
assertError("IdempotentParameterMismatchException", 409,
|
||||
"ClientToken was used by a previous request with different parameters",
|
||||
() -> service.createEventSource(webhook("other", "t", busArn, tagsOf(51)), REGION));
|
||||
|
||||
KmsKey key = new KmsKey();
|
||||
key.setArn("arn:aws:kms:us-east-1:000000000000:key/aws-key");
|
||||
when(kms.describeKey("alias/aws/secretsmanager", REGION)).thenReturn(key);
|
||||
when(kms.isAwsManagedKey(key.getArn())).thenReturn(true);
|
||||
ObjectNode managed = (ObjectNode) webhook("managed", "n3", busArn, tagsOf(51));
|
||||
((ObjectNode) managed.get("Configuration").get("WebhookEventsConfiguration"))
|
||||
.put("KmsKeyIdentifier", "alias/aws/secretsmanager");
|
||||
AwsException refused = assertThrows(AwsException.class, () -> service.createEventSource(managed, REGION));
|
||||
assertEquals("InvalidInputException", refused.getErrorCode());
|
||||
assertTrue(refused.getMessage().endsWith("because it is an AWS managed key. Supply a customer managed key, "
|
||||
+ "or omit KmsKeyIdentifier to use the AWS managed key aws/secretsmanager"), refused.getMessage());
|
||||
}
|
||||
|
||||
private static ObjectNode bus(String name, String tagsJson, String clientToken) {
|
||||
ObjectNode request = (ObjectNode) json("{\"Name\":\"" + name + "\",\"Tags\":" + tagsJson + "}");
|
||||
if (clientToken != null) {
|
||||
request.put("ClientToken", clientToken);
|
||||
}
|
||||
return request;
|
||||
}
|
||||
|
||||
private static JsonNode subscriber(String name, String eventBusArn, String tagsJson, String clientToken) {
|
||||
ObjectNode request = (ObjectNode) json("{\"Name\":\"" + name + "\",\"EventBusArn\":\"" + eventBusArn
|
||||
+ "\",\"InvokeConfiguration\":{\"TargetArn\":\"" + QUEUE + "\",\"RoleArn\":\"" + ROLE
|
||||
+ "\"},\"Tags\":" + tagsJson + "}");
|
||||
if (clientToken != null) {
|
||||
request.put("ClientToken", clientToken);
|
||||
}
|
||||
return request;
|
||||
}
|
||||
|
||||
private static JsonNode webhook(String name, String clientToken, String eventBusArn, String tagsJson) {
|
||||
return json("{\"ClientToken\":\"" + clientToken + "\",\"Name\":\"" + name + "\",\"EventBusArn\":\""
|
||||
+ eventBusArn + "\",\"Configuration\":{\"WebhookEventsConfiguration\":"
|
||||
+ "{\"AuthConfiguration\":{\"StaticTokenAuthConfiguration\":{\"TokenHttpHeader\":\"X-Tok\","
|
||||
+ "\"SecretValue\":\"original-token\"}},\"RoleArn\":\"" + ROLE + "\"}},\"Tags\":" + tagsJson + "}");
|
||||
}
|
||||
|
||||
private static String tagsOf(int count) {
|
||||
return MAPPER.valueToTree(numbered(count)).toString();
|
||||
}
|
||||
|
||||
private void tag(String arn, Map<String, String> tags) {
|
||||
service.tagResource(tagRequest(arn, tags), REGION);
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user