feat(eventbridge): list rule names by target (#8632)

* feat(eventbridge): list rule names by target
* fix(eventbridge): reuse scoped rule lookup and policy fixtures
* fix(eventbridge): avoid redundant target lookup reads

Co-authored-by: Andre Kurait <AndreKurait@gmail.com>
This commit is contained in:
Jackson PriceandAndre Kurait authored and GitHub committed 2026-11-16 16:39:03 -04:00
1 parent 7872ef9c51
commit e281defa12
15 files changed
+1064 -35

No files matched your search

+29
View File
@@ -22,6 +22,7 @@
| `PutTargets` | Add targets to a rule |
| `RemoveTargets` | Remove targets from a rule |
| `ListTargetsByRule` | List targets for a rule |
| `ListRuleNamesByTarget` | Find rule names whose targets contain an exact ARN, with bus selection and pagination |
| `PutEvents` | Publish custom events to an event bus |
| `TestEventPattern` | Test whether a sample event matches a given pattern (no targets fired) |
| `ListTagsForResource` | - |
@@ -54,6 +55,34 @@
characters. Empty or overlong tokens return `ValidationException`; unrecognized
cursors within those bounds return `InvalidToken`.
## Find rules by target
`ListRuleNamesByTarget` returns each matching rule name once when a target has the
exact supplied `TargetArn`. Select an event bus by name or ARN; omitting
`EventBusName` selects the default bus. The bus and rules belong to the caller's
account, Region and partition. As with `ListRules`, Floci resolves a supplied bus
ARN to its name in the caller's account and Region. A target ARN is a filter and can name a resource
in another account or Region.
`Limit` accepts 1 to 100 names and defaults to 100. Keep every other request
argument unchanged when sending a returned `NextToken`. Floci sorts matching
names lexically before pagination and binds its cursor to the caller scope and
request arguments; AWS does not specify that ordering. Tokens have no timed
expiry in Floci. Empty or overlong tokens fail validation, and invalid cursors
return `InvalidToken`. An empty or final page has no `NextToken`.
With IAM enforcement enabled, grant `events:ListRuleNamesByTarget` on `*`.
This action has no resource type or resource-tag condition entitlement; a grant
on an event bus ARN alone does not allow it. Existing global IAM conditions,
permission boundaries and explicit denies still apply.
The lookup reads existing bus, rule and target stores without writing rows or
creating the logical default bus. Unprefixed legacy records are read in place
only for the configured default account. Rules are checked against their stored
key, bus, account and ARN. Explicit account records take precedence. Persisted legacy rule names
remain discoverable even if they no longer pass creation-time validation. The lookup does not provide
an atomic snapshot across concurrent rule and target updates.
## Numeric event patterns
`TestEventPattern` and `PutEvents` rule routing support `numeric` comparisons on
+1 -1
View File
@@ -41,7 +41,7 @@ Operation counts are exact. For dispatch-table services (Query and JSON 1.1) eac
| [SWF](swf.md) | `POST /` + `X-Amz-Target: SimpleWorkflowService.*` | JSON 1.0 | 39 |
| [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 | 40 |
| [EventBridge](eventbridge.md) | `POST /` + `X-Amz-Target: AmazonEventBridge.*` | JSON 1.1 | 41 |
| [EventBridge V2](eventbridgev2.md) | `POST /service/AWSEventsV2/operation/*` | Smithy RPC v2 CBOR | 10 |
| [EventBridge Scheduler](scheduler.md) | `/schedules/*`, `/schedule-groups/*`, `/tags/*` | REST JSON | 12 |
| [EventBridge Pipes](pipes.md) | `/v1/pipes/*` | REST JSON | 7 |
@@ -624,6 +624,24 @@ public class AccountAwareStorageBackend<V> implements StorageBackend<String, V>
.toList();
}
/**
* Account-relative keys, including unmigrated keys only for the configured default account.
* Filters ownership before collecting keys and never fetches or migrates a stored value.
*/
public Set<String> keysIncludingLegacyForAccount(String accountId, Predicate<String> keyFilter) {
Set<String> keys = new LinkedHashSet<>();
for (String rawKey : delegate.keys()) {
if (!accountId.equals(ownerOf(rawKey))) {
continue;
}
String key = hasAccountPrefix(rawKey) ? rawKey.substring(13) : rawKey;
if (keyFilter.test(key)) {
keys.add(key);
}
}
return keys;
}
public Set<String> keysForAccount(String accountId) {
String prefix = accountId + "/";
return delegate.keys().stream()
@@ -74,6 +74,7 @@ public class EventBridgeHandler {
case "PutTargets" -> handlePutTargets(request, region);
case "RemoveTargets" -> handleRemoveTargets(request, region);
case "ListTargetsByRule" -> handleListTargetsByRule(request, region);
case "ListRuleNamesByTarget" -> handleListRuleNamesByTarget(request, region);
case "PutEvents" -> handlePutEvents(request, region);
case "TestEventPattern" -> handleTestEventPattern(request);
case "ListTagsForResource" -> handleListTagsForResource(request, region);
@@ -343,6 +344,32 @@ public class EventBridgeHandler {
return Response.ok(response).build();
}
private Response handleListRuleNamesByTarget(JsonNode request, String region) {
String targetArn = targetLookupString(request, "TargetArn");
String busName = targetLookupString(request, "EventBusName");
String nextToken = targetLookupString(request, "NextToken");
PaginatedResult<String> page = eventBridgeService.listRuleNamesByTarget(
targetArn, busName, readLimit(request.path("Limit")), nextToken, region);
ObjectNode response = objectMapper.createObjectNode();
ArrayNode names = response.putArray("RuleNames");
page.items().forEach(names::add);
if (page.nextToken() != null) {
response.put("NextToken", page.nextToken());
}
return Response.ok(response).build();
}
private static String targetLookupString(JsonNode request, String field) {
JsonNode value = request.path(field);
if (value.isMissingNode() || value.isNull()) {
return null;
}
if (!value.isTextual()) {
throw new AwsException("SerializationException", field + " must be a string.", 400);
}
return value.textValue();
}
private Response handleListTargetsByRule(JsonNode request, String region) {
String ruleName = request.path("Rule").asText(null);
String busName = request.path("EventBusName").asText(null);
@@ -15,6 +15,7 @@ import io.floci.aws.core.common.AwsArnShapes;
import io.floci.aws.core.common.AwsArnUtils;
import io.floci.aws.core.common.AwsException;
import io.floci.aws.core.common.AwsPartitions;
import io.floci.aws.core.common.Digests;
import io.floci.aws.core.common.PaginatedResult;
import io.floci.aws.core.common.Pagination;
import io.floci.aws.core.common.RegionResolver;
@@ -68,6 +69,7 @@ import java.util.regex.Pattern;
import static io.floci.aws.core.storage.AccountAwareStorageBackend.getInAccount;
import static io.floci.aws.core.storage.AccountAwareStorageBackend.putInAccount;
import static io.floci.aws.core.storage.AccountAwareStorageBackend.readInAccount;
@ApplicationScoped
public class EventBridgeService implements ResourceProvider, StoredResourceArns {
@@ -272,8 +274,7 @@ public class EventBridgeService implements ResourceProvider, StoredResourceArns
return getOrCreateDefaultBus(region);
}
return busStore.get(busKey(region, effectiveName))
.orElseThrow(() -> new AwsException("ResourceNotFoundException",
"EventBus not found: " + name, 400));
.orElseThrow(() -> eventBusNotFound(name));
}
public EventBus updateEventBus(String name,
@@ -522,12 +523,24 @@ public class EventBridgeService implements ResourceProvider, StoredResourceArns
public List<Rule> listRules(String busName, String namePrefix, String region) {
String effectiveBus = resolvedBusName(busName);
String prefix = ruleKeyPrefix(region, effectiveBus);
return ruleStore.scan(k -> {
if (!isRuleKeyOfBus(k, prefix)) return false;
if (namePrefix == null || namePrefix.isBlank()) return true;
String ruleName = k.substring(prefix.length());
return ruleName.startsWith(namePrefix);
}).stream().filter(rule -> effectiveBus.equals(rule.getEventBusName())).toList();
String account = regionResolver.getAccountId();
Set<String> keys = ruleStore instanceof AccountAwareStorageBackend<Rule> aware
? aware.keysIncludingLegacyForAccount(account, key -> key.startsWith(prefix))
: ruleStore.keys();
List<Rule> rules = new ArrayList<>();
for (String key : keys) {
if (!key.startsWith(prefix)) {
continue;
}
String name = key.substring(prefix.length());
if (namePrefix != null && !namePrefix.isBlank() && !name.startsWith(namePrefix)) {
continue;
}
readInAccount(ruleStore, account, key)
.filter(rule -> name.equals(rule.getName()) && effectiveBus.equals(rule.getEventBusName()))
.ifPresent(rules::add);
}
return rules;
}
/**
@@ -744,6 +757,58 @@ public class EventBridgeService implements ResourceProvider, StoredResourceArns
return new RemoveTargetsResult(removed, ids.size() - removed);
}
public PaginatedResult<String> listRuleNamesByTarget(String targetArn, String busName, Integer limit,
String nextToken, String region) {
if (targetArn == null || targetArn.isEmpty() || targetArn.length() > 1600) {
throw new AwsException("ValidationException", "TargetArn must contain 1 to 1600 characters.", 400);
}
if (busName != null && (busName.isBlank() || busName.length() > 1600)) {
throw new AwsException("ValidationException", "EventBusName must contain 1 to 1600 characters.", 400);
}
String effectiveBus = resolvedBusName(busName);
if (!effectiveBus.matches("[/\\.\\-_A-Za-z0-9]+")) {
throw new AwsException("ValidationException", "Invalid EventBridge event bus name.", 400);
}
requireBusForRead(effectiveBus, region);
List<String> names = listRules(effectiveBus, null, region).stream()
.filter(rule -> ruleTargetsArn(rule, effectiveBus, targetArn, region))
.map(Rule::getName).toList();
String scope = targetRuleCursorScope(targetArn, busName, effectiveBus, limit, region);
return paginate(names, Function.identity(), limit, nextToken, scope);
}
private void requireBusForRead(String busName, String region) {
Optional<EventBus> bus = readInAccount(busStore, regionResolver.getAccountId(), busKey(region, busName));
if (bus.isEmpty() && !"default".equals(busName)) {
throw eventBusNotFound(busName);
}
}
private boolean ruleTargetsArn(Rule rule, String busName, String targetArn, String region) {
String account = regionResolver.getAccountId();
if (rule.getAccountId() != null && !account.equals(rule.getAccountId())) {
return false;
}
String expectedArn = buildRuleArn(region, busName, rule.getName());
if (!expectedArn.equals(rule.getArn())) {
return false;
}
String key = ruleKey(region, busName, rule.getName());
List<Target> targets = new ArrayList<>(readInAccount(targetStore, account, key).orElse(List.of()));
return targets.stream().anyMatch(target -> target != null && targetArn.equals(target.getArn()));
}
private String targetRuleCursorScope(String targetArn, String suppliedBus, String effectiveBus,
Integer limit, String region) {
StringBuilder scope = new StringBuilder();
for (String value : List.of(regionResolver.getAccountId(), regionResolver.partitionForRegion(region),
region, effectiveBus, targetArn, limit == null ? "omitted" : limit.toString(),
suppliedBus == null ? "" : suppliedBus)) {
scope.append(value.length()).append(':').append(value);
}
return "target-rules:" + Digests.sha256Hex(scope.toString());
}
public List<Target> listTargetsByRule(String ruleName, String busName, String region) {
String effectiveBus = resolvedBusName(busName);
validateRuleReference("rule", ruleName, effectiveBus, region);
@@ -1577,8 +1642,11 @@ public class EventBridgeService implements ResourceProvider, StoredResourceArns
return;
}
busStore.get(busKey(region, busName))
.orElseThrow(() -> new AwsException("ResourceNotFoundException",
"EventBus not found: " + busName, 400));
.orElseThrow(() -> eventBusNotFound(busName));
}
private static AwsException eventBusNotFound(String busName) {
return new AwsException("ResourceNotFoundException", "EventBus not found: " + busName, 400);
}
private static boolean isBlank(Object value) {
@@ -29,10 +29,33 @@ import static org.mockito.Mockito.never;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoMoreInteractions;
import static org.mockito.Mockito.when;
class AccountAwareStorageBackendTest {
@Test
void keysIncludingLegacyFiltersOwnershipWithoutReadingOrMigratingValues() {
InMemoryStorage<String, String> raw = spy(new InMemoryStorage<>());
String account = "000000000000";
String other = "111111111111";
String shared = "rule:us-east-1:default/old/name";
raw.put(shared, "legacy");
raw.put(account + "/" + shared, "explicit");
raw.put(other + "/rule:us-east-1:default/foreign", "foreign");
raw.put("unrelated", "unrelated");
Set<String> before = raw.keys();
clearInvocations(raw);
AccountAwareStorageBackend<String> storage = new AccountAwareStorageBackend<>(raw, null, account);
assertEquals(Set.of(shared), storage.keysIncludingLegacyForAccount(account, key -> key.startsWith("rule:")));
assertEquals(Set.of("rule:us-east-1:default/foreign"),
storage.keysIncludingLegacyForAccount(other, key -> key.startsWith("rule:")));
verify(raw, times(2)).keys();
verifyNoMoreInteractions(raw);
assertEquals(before, raw.keys());
}
@Test
void getInAccountReadsTheNamedAccountOutsideAnyRequest() {
InMemoryStorage<String, String> raw = new InMemoryStorage<>();
@@ -5,6 +5,8 @@ import org.junit.jupiter.params.provider.Arguments;
import java.util.Locale;
import java.util.stream.Stream;
import static io.floci.aws.testing.EnforcementFixtures.statement;
public final class AuthorizerPolicyFixtures {
private AuthorizerPolicyFixtures() {}
@@ -82,10 +84,6 @@ public final class AuthorizerPolicyFixtures {
+ conditionStatement("Deny", "Bool", "aws:SecureTransport", "false") + "]", 403));
}
private static String statement(String effect, String action, String resource) {
return "{\"Effect\":\"" + effect + "\",\"Action\":\"" + action + "\",\"Resource\":\"" + resource + "\"}";
}
private static String ipStatement(String effect, String operator, String addresses) {
return conditionStatement(effect, operator, "aws:SourceIp", addresses);
}
@@ -0,0 +1,22 @@
package io.floci.aws.services.eventbridge;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.floci.aws.core.common.RegionResolver;
import io.floci.aws.core.storage.InMemoryStorage;
import io.floci.aws.core.storage.StorageBackend;
import io.floci.aws.services.eventbridge.model.EventBus;
import io.floci.aws.services.eventbridge.model.Rule;
import io.floci.aws.services.eventbridge.model.Target;
import java.util.List;
final class EventBridgeTargetLookupFixtures {
private EventBridgeTargetLookupFixtures() {}
static EventBridgeService service(StorageBackend<String, EventBus> buses, StorageBackend<String, Rule> rules,
StorageBackend<String, List<Target>> targets, RegionResolver resolver) {
return new EventBridgeService(buses, rules, targets, new InMemoryStorage<>(), new InMemoryStorage<>(),
new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(), resolver,
new ObjectMapper(), null, null, null, null, null);
}
}
@@ -0,0 +1,105 @@
package io.floci.aws.services.eventbridge;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.floci.aws.core.common.AwsErrorResponse;
import io.floci.aws.core.common.PaginatedResult;
import io.floci.aws.core.common.RegionResolver;
import io.floci.aws.core.storage.InMemoryStorage;
import jakarta.ws.rs.core.Response;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.MethodSource;
import java.util.List;
import java.util.stream.Stream;
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.Mockito.*;
class EventBridgeTargetLookupHandlerTest {
private static final ObjectMapper MAPPER = new ObjectMapper();
private static final String REGION = "us-east-1";
@ParameterizedTest
@MethodSource("wrongTypes")
void wrongJsonTypesAreNotCoerced(String json) throws Exception {
EventBridgeService service = mock(EventBridgeService.class);
try (Response response = new EventBridgeHandler(service, MAPPER)
.handle("ListRuleNamesByTarget", MAPPER.readTree(json), REGION)) {
assertEquals(400, response.getStatus());
assertEquals("SerializationException", ((AwsErrorResponse) response.getEntity()).type());
verifyNoInteractions(service);
}
}
static Stream<String> wrongTypes() {
return Stream.of(
"{\"TargetArn\":1}", "{\"TargetArn\":true}", "{\"TargetArn\":[]}", "{\"TargetArn\":{}}",
"{\"TargetArn\":\"filter\",\"EventBusName\":12}",
"{\"TargetArn\":\"filter\",\"EventBusName\":{}}",
"{\"TargetArn\":\"filter\",\"NextToken\":false}",
"{\"TargetArn\":\"filter\",\"NextToken\":[]}",
"{\"TargetArn\":\"filter\",\"Limit\":\"1\"}",
"{\"TargetArn\":\"filter\",\"Limit\":1.5}",
"{\"TargetArn\":\"filter\",\"Limit\":true}",
"{\"TargetArn\":\"filter\",\"Limit\":{}}");
}
@ParameterizedTest
@MethodSource("outOfBounds")
void modeledBoundsReachValidationInsteadOfTruncation(String json) throws Exception {
EventBridgeService service = service();
try (Response response = new EventBridgeHandler(service, MAPPER)
.handle("ListRuleNamesByTarget", MAPPER.readTree(json), REGION)) {
assertEquals(400, response.getStatus());
assertEquals("ValidationException", ((AwsErrorResponse) response.getEntity()).type());
}
}
static Stream<String> outOfBounds() {
return Stream.of("{}", "{\"TargetArn\":null}", "{\"TargetArn\":\"\"}",
"{\"TargetArn\":\"" + "x".repeat(1601) + "\"}",
"{\"TargetArn\":\"filter\",\"EventBusName\":\"\"}",
"{\"TargetArn\":\"filter\",\"EventBusName\":\"bad name\"}",
"{\"TargetArn\":\"filter\",\"EventBusName\":\" \"}",
"{\"TargetArn\":\"filter\",\"EventBusName\":\"" + "x".repeat(1601) + "\"}",
"{\"TargetArn\":\"filter\",\"NextToken\":\"\"}",
"{\"TargetArn\":\"filter\",\"NextToken\":\"" + "x".repeat(2049) + "\"}",
"{\"TargetArn\":\"filter\",\"Limit\":0}",
"{\"TargetArn\":\"filter\",\"Limit\":101}",
"{\"TargetArn\":\"filter\",\"Limit\":2147483648}",
"{\"TargetArn\":\"filter\",\"Limit\":-2147483649}");
}
@Test
void dispatchPreservesStringsAndWritesOnlyModeledResponseMembers() throws Exception {
EventBridgeService service = mock(EventBridgeService.class);
when(service.listRuleNamesByTarget("filter", "default", 1, "token", REGION))
.thenReturn(new PaginatedResult<>(List.of("owned"), "next"));
try (Response response = new EventBridgeHandler(service, MAPPER).handle("ListRuleNamesByTarget",
MAPPER.readTree("{\"TargetArn\":\"filter\",\"EventBusName\":\"default\",\"Limit\":1,\"NextToken\":\"token\"}"),
REGION)) {
assertEquals(200, response.getStatus());
assertEquals(MAPPER.readTree("{\"RuleNames\":[\"owned\"],\"NextToken\":\"next\"}"), response.getEntity());
verify(service).listRuleNamesByTarget("filter", "default", 1, "token", REGION);
}
}
@Test
void omittedAndNullOptionalArgumentsYieldAnEmptyTerminalPage() throws Exception {
EventBridgeHandler handler = new EventBridgeHandler(service(), MAPPER);
for (String body : List.of("{\"TargetArn\":\"filter\"}",
"{\"TargetArn\":\"filter\",\"EventBusName\":null,\"Limit\":null,\"NextToken\":null}")) {
try (Response response = handler.handle("ListRuleNamesByTarget", MAPPER.readTree(body), REGION)) {
assertEquals(200, response.getStatus());
assertEquals(MAPPER.readTree("{\"RuleNames\":[]}"), (JsonNode) response.getEntity());
}
}
}
private static EventBridgeService service() {
return EventBridgeTargetLookupFixtures.service(new InMemoryStorage<>(), new InMemoryStorage<>(),
new InMemoryStorage<>(), new RegionResolver(REGION, "000000000000"));
}
}
@@ -0,0 +1,141 @@
package io.floci.aws.services.eventbridge;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.floci.aws.core.common.RegionResolver;
import io.floci.aws.core.storage.AccountAwareStorageBackend;
import io.floci.aws.core.storage.StorageBackend;
import io.floci.aws.core.storage.StorageFactory;
import io.floci.aws.services.eventbridge.model.EventBus;
import io.floci.aws.services.eventbridge.model.Rule;
import io.floci.aws.services.eventbridge.model.Target;
import io.floci.aws.testing.AwsTestClients;
import io.floci.aws.testing.EnforcementFixtures;
import io.floci.aws.testing.EnforcementFixtures.UserCredentials;
import io.floci.aws.testing.IamEnforcementProfile;
import io.floci.aws.testing.PartitionCleanup;
import io.quarkus.test.common.http.TestHTTPResource;
import io.quarkus.test.junit.QuarkusTest;
import io.quarkus.test.junit.TestProfile;
import jakarta.inject.Inject;
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 java.lang.reflect.Field;
import java.net.URI;
import java.time.Instant;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import static io.floci.aws.testing.EnforcementFixtures.auth;
import static io.floci.aws.testing.EnforcementFixtures.statement;
import static org.junit.jupiter.api.Assertions.assertAll;
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;
@QuarkusTest
@TestProfile(IamEnforcementProfile.class)
class EventBridgeTargetLookupIamIntegrationTest {
private static final ObjectMapper MAPPER = new ObjectMapper().findAndRegisterModules();
@Inject
StorageFactory factory;
@Inject
RegionResolver resolver;
@TestHTTPResource("/")
URI endpoint;
@RegisterExtension
final PartitionCleanup cleanup = new PartitionCleanup();
@ParameterizedTest
@ValueSource(strings = {"bus-resource", "wrong-action", "explicit-deny"})
void authorizationUsesWildcardAndBothDeniedAndAllowedReadsPreserveLegacyRows(String kind) throws Exception {
StorageBackend<String, EventBus> buses = raw(factory.create("eventbridge", "eventbridge-buses.json",
new TypeReference<Map<String, EventBus>>() {}));
StorageBackend<String, Rule> rules = raw(factory.create("eventbridge", "eventbridge-rules.json",
new TypeReference<Map<String, Rule>>() {}));
StorageBackend<String, List<Target>> targets = raw(factory.create("eventbridge", "eventbridge-targets.json",
new TypeReference<Map<String, List<Target>>>() {}));
String account = resolver.getDefaultAccountId();
String name = "reverse-legacy-" + UUID.randomUUID();
String busKey = "bus:us-east-1:" + name;
String ruleKey = "rule:us-east-1:" + name + "/owned";
String arn = "arn:aws:events:us-east-1:" + account + ":event-bus/" + name;
String targetArn = "arn:aws:sqs:us-east-1:" + account + ":reverse-owned";
EventBus bus = new EventBus(name, arn, "owned legacy", Instant.EPOCH);
Rule rule = new Rule();
rule.setName("owned");
rule.setArn("arn:aws:events:us-east-1:" + account + ":rule/" + name + "/owned");
rule.setEventBusName(name);
List<Target> values = List.of(new Target("one", targetArn, null, null));
JsonNode before = MAPPER.valueToTree(List.of(bus, rule, values));
buses.put(busKey, bus);
rules.put(ruleKey, rule);
targets.put(ruleKey, values);
String policy = switch (kind) {
case "bus-resource" -> statement("Allow", "events:ListRuleNamesByTarget", arn);
case "wrong-action" -> statement("Allow", "events:ListRules", "*");
case "explicit-deny" -> statement("Allow", "events:*", "*") + ","
+ statement("Deny", "events:ListRuleNamesByTarget", "*");
default -> throw new IllegalArgumentException(kind);
};
try (EventBridgeClient denied = caller(policy)) {
assertAll(
() -> {
EventBridgeException error = assertThrows(EventBridgeException.class,
() -> denied.listRuleNamesByTarget(request -> request.eventBusName(name).targetArn(targetArn)));
assertEquals("AccessDeniedException", error.awsErrorDetails().errorCode());
},
() -> unchanged(buses, busKey, bus, account),
() -> unchanged(rules, ruleKey, rule, account),
() -> unchanged(targets, ruleKey, values, account),
() -> assertEquals(before, MAPPER.valueToTree(List.of(bus, rule, values))));
try (EventBridgeClient allowed = caller(statement("Allow", "events:ListRuleNamesByTarget", "*"))) {
assertAll(
() -> assertEquals(List.of("owned"), allowed.listRuleNamesByTarget(
request -> request.eventBusName(name).targetArn(targetArn)).ruleNames()),
() -> unchanged(buses, busKey, bus, account),
() -> unchanged(rules, ruleKey, rule, account),
() -> unchanged(targets, ruleKey, values, account),
() -> assertEquals(before, MAPPER.valueToTree(List.of(bus, rule, values))));
}
} finally {
buses.delete(busKey);
buses.delete(account + "/" + busKey);
rules.delete(ruleKey);
rules.delete(account + "/" + ruleKey);
targets.delete(ruleKey);
targets.delete(account + "/" + ruleKey);
}
}
private EventBridgeClient caller(String statements) {
String user = "reverse-caller-" + UUID.randomUUID();
String iamAuth = auth("test", "iam");
UserCredentials credentials = EnforcementFixtures.createUser(cleanup, endpoint.getPort(), iamAuth, user);
EnforcementFixtures.putUserPolicy(endpoint.getPort(), iamAuth, user, "reverse",
"{\"Version\":\"2012-10-17\",\"Statement\":[" + statements + "]}");
return AwsTestClients.create(EventBridgeClient.builder(), credentials.accessKeyId(),
credentials.secretAccessKey(), Region.US_EAST_1);
}
private static <T> void unchanged(StorageBackend<String, T> store, String key, T value, String account) {
assertSame(value, store.get(key).orElse(null));
assertTrue(store.get(account + "/" + key).isEmpty());
}
/** Public APIs cannot create pre-account rows; only the three owned fixture keys use this seam. */
@SuppressWarnings("unchecked")
private static <T> StorageBackend<String, T> raw(AccountAwareStorageBackend<T> store) throws ReflectiveOperationException {
Field delegate = AccountAwareStorageBackend.class.getDeclaredField("delegate");
delegate.setAccessible(true);
return (StorageBackend<String, T>) delegate.get(store);
}
}
@@ -0,0 +1,264 @@
package io.floci.aws.services.eventbridge;
import com.fasterxml.jackson.core.type.TypeReference;
import io.floci.aws.core.storage.AccountAwareStorageBackend;
import io.floci.aws.core.storage.StorageFactory;
import io.floci.aws.services.eventbridge.model.EventBus;
import io.floci.aws.testing.AwsTestClients;
import io.quarkus.test.junit.QuarkusTest;
import jakarta.inject.Inject;
import org.junit.jupiter.api.Test;
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.ListRuleNamesByTargetResponse;
import software.amazon.awssdk.services.eventbridge.model.Rule;
import software.amazon.awssdk.services.eventbridge.model.Target;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.atomic.AtomicLong;
import java.util.stream.Collectors;
import static org.junit.jupiter.api.Assertions.assertAll;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
@QuarkusTest
class EventBridgeTargetLookupIntegrationTest {
private static final AtomicLong ACCOUNTS = new AtomicLong(742490000000L);
@Inject
StorageFactory factory;
@Test
void nativeReverseLookupTracksTargetReplacementAndRemovalAcrossBuses() {
try (Scenario fixture = scenario(Region.US_EAST_1)) {
String a = fixture.bus("a");
String b = fixture.bus("b");
String one = fixture.target("one");
String two = fixture.target("two");
fixture.rule(a, "alpha", one);
fixture.rule(a, "beta", one);
fixture.rule(a, "gamma", two);
fixture.rule(b, "delta", one);
assertEquals(Set.of("alpha", "beta"), names(fixture.client, a, one, 100));
assertEquals(Set.of("gamma"), names(fixture.client, a, two, 100));
assertEquals(Set.of("delta"), names(fixture.client, b, one, 100));
assertEquals(Set.of(), names(fixture.client, null, one, 100));
fixture.targets(a, "beta", two);
assertEquals(Set.of("alpha"), names(fixture.client, a, one, 100));
assertEquals(Set.of("beta", "gamma"), names(fixture.client, a, two, 100));
fixture.client.removeTargets(request -> request.eventBusName(a).rule("alpha").ids("one"));
assertEquals(Set.of(), names(fixture.client, a, one, 100));
assertEquals(Set.of("delta"), names(fixture.client, b, one, 100));
}
}
@Test
void filterPrecedesPaginationAndARepeatedTargetListsItsRuleOnce() {
try (Scenario fixture = scenario(Region.US_EAST_1)) {
String bus = fixture.bus("pages");
String one = fixture.target("one");
String two = fixture.target("two");
fixture.rule(bus, "alpha", two);
fixture.rule(bus, "beta", one);
fixture.rule(bus, "gamma", two);
fixture.rule(bus, "omega", one);
fixture.client.putTargets(request -> request.eventBusName(bus).rule("beta").targets(
Target.builder().id("two").arn(one).build()));
assertEquals(Set.of("beta", "omega"), names(fixture.client, bus, one, 1));
String arn = fixture.client.describeEventBus(request -> request.name(bus)).arn();
assertEquals(Set.of("beta", "omega"), names(fixture.client, arn, one, 100));
}
}
@ParameterizedTest
@ValueSource(strings = {"us-west-2", "cn-north-1", "us-gov-west-1"})
void sameBusAndRuleNamesRemainScopedByRegionAndPartition(String otherRegion) {
String account = Long.toString(ACCOUNTS.incrementAndGet());
try (Scenario owner = new Scenario(account, Region.US_EAST_1);
Scenario other = new Scenario(account, Region.of(otherRegion))) {
assertScopedIsolation(owner, other);
}
}
@Test
void sameBusNamesAndArnAliasesRemainScopedByAccount() {
try (Scenario owner = scenario(Region.US_EAST_1);
Scenario other = scenario(Region.US_EAST_1)) {
assertScopedIsolation(owner, other);
}
}
@ParameterizedTest
@ValueSource(ints = {1, 100})
void modeledBoundaryLimitsAreAccepted(int limit) {
try (Scenario fixture = scenario(Region.US_EAST_1)) {
String bus = fixture.bus("limit");
fixture.rule(bus, "owned", fixture.target("one"));
assertEquals(Set.of("owned"), names(fixture.client, bus, fixture.target("one"), limit));
}
}
@ParameterizedTest
@ValueSource(ints = {0, 101})
void modeledOutOfRangeLimitsAreRefused(int limit) {
try (Scenario fixture = scenario(Region.US_EAST_1)) {
String bus = fixture.bus("limit");
fixture.rule(bus, "owned", fixture.target("one"));
EventBridgeException error = assertThrows(EventBridgeException.class,
() -> names(fixture.client, bus, fixture.target("one"), limit));
assertEquals("ValidationException", error.awsErrorDetails().errorCode());
assertEquals(Set.of("owned"), names(fixture.client, bus, fixture.target("one"), 100));
}
}
@Test
void unknownBusIsNotFoundAndAnUnusedTargetIsEmpty() {
try (Scenario fixture = scenario(Region.US_EAST_1)) {
String bus = fixture.bus("empty");
assertEquals(Set.of(), names(fixture.client, bus, fixture.target("unused"), 100));
EventBridgeException error = assertThrows(EventBridgeException.class,
() -> names(fixture.client, "absent-" + UUID.randomUUID(), fixture.target("unused"), 100));
assertEquals("ResourceNotFoundException", error.awsErrorDetails().errorCode());
}
}
@Test
void listingTheLogicalDefaultBusDoesNotCreateAPersistentBusRow() {
String account = Long.toString(ACCOUNTS.incrementAndGet());
AccountAwareStorageBackend<EventBus> buses = factory.create("eventbridge", "eventbridge-buses.json",
new TypeReference<Map<String, EventBus>>() {});
Set<String> before = Set.copyOf(buses.keysForAccount(account));
try (EventBridgeClient client = AwsTestClients.create(EventBridgeClient.builder(), account, Region.US_EAST_1)) {
assertAll(
() -> assertEquals(Set.of(), names(client, null, "arn:aws:sqs:us-east-1:" + account + ":unused", 100)),
() -> assertEquals(before, buses.keysForAccount(account)));
}
}
@Test
void continuationCannotBeReusedWithAnotherTargetFilter() {
try (Scenario fixture = scenario(Region.US_EAST_1)) {
String bus = fixture.bus("token");
String target = fixture.target("one");
fixture.rule(bus, "alpha", target);
fixture.rule(bus, "omega", target);
ListRuleNamesByTargetResponse first = fixture.client.listRuleNamesByTarget(request ->
request.eventBusName(bus).targetArn(target).limit(1));
assertNotNull(first.nextToken());
EventBridgeException error = assertThrows(EventBridgeException.class,
() -> fixture.client.listRuleNamesByTarget(request -> request.eventBusName(bus)
.targetArn(fixture.target("two")).limit(1).nextToken(first.nextToken())));
assertEquals("InvalidToken", error.awsErrorDetails().errorCode());
assertEquals(Set.of("alpha", "omega"), names(fixture.client, bus, target, 1));
}
}
private static void assertScopedIsolation(Scenario owner, Scenario other) {
String bus = owner.bus("scope");
other.createBus(bus);
String target = owner.target("one");
owner.rule(bus, "owned", target);
other.rule(bus, "other", target);
assertEquals(Set.of("owned"), names(owner.client, bus, target, 100));
assertEquals(Set.of("other"), names(other.client, bus, target, 100));
String arn = owner.client.describeEventBus(request -> request.name(bus)).arn();
assertEquals(Set.of("other"), names(other.client, arn, target, 100));
assertEquals(Set.of("other"), other.client.listRules(request -> request.eventBusName(arn)).rules().stream()
.map(Rule::name).collect(Collectors.toSet()));
assertEquals(Set.of("owned"), names(owner.client, bus, target, 100));
}
private static Set<String> names(EventBridgeClient client, String bus, String target, int limit) {
List<String> result = new ArrayList<>();
Set<String> tokens = new HashSet<>();
String token = null;
do {
String current = token;
ListRuleNamesByTargetResponse page = client.listRuleNamesByTarget(request -> request
.eventBusName(bus).targetArn(target).limit(limit).nextToken(current));
assertTrue(page.ruleNames().size() <= limit);
result.addAll(page.ruleNames());
token = page.nextToken();
if (token != null) {
assertFalse(token.isEmpty());
assertTrue(tokens.add(token), "the token must advance");
assertTrue(tokens.size() < 10, "the owned fixture has at most four rules");
}
} while (token != null);
assertEquals(result.size(), new HashSet<>(result).size());
return Set.copyOf(result);
}
private static Scenario scenario(Region region) {
return new Scenario(Long.toString(ACCOUNTS.incrementAndGet()), region);
}
private record StoredRule(String bus, String name) {}
private static final class Scenario implements AutoCloseable {
private final EventBridgeClient client;
private final String account;
private final Region region;
private final List<String> buses = new ArrayList<>();
private final List<StoredRule> rules = new ArrayList<>();
private Scenario(String account, Region region) {
this.account = account;
this.region = region;
client = AwsTestClients.create(EventBridgeClient.builder(), account, region);
}
private String bus(String suffix) {
String name = "reverse-" + suffix + "-" + UUID.randomUUID();
createBus(name);
return name;
}
private void createBus(String name) {
client.createEventBus(request -> request.name(name));
buses.add(name);
}
private String target(String name) {
return "arn:aws:sqs:" + region.id() + ":" + account + ":" + name;
}
private void rule(String bus, String name, String target) {
client.putRule(request -> request.eventBusName(bus).name(name).eventPattern("{\"source\":[\"reverse\"]}"));
rules.add(new StoredRule(bus, name));
targets(bus, name, target);
}
private void targets(String bus, String name, String target) {
assertEquals(0, client.putTargets(request -> request.eventBusName(bus).rule(name)
.targets(Target.builder().id("one").arn(target).build())).failedEntryCount());
}
@Override
public void close() {
try {
for (StoredRule rule : rules.reversed()) {
client.removeTargets(request -> request.eventBusName(rule.bus()).rule(rule.name()).ids("one", "two"));
client.deleteRule(request -> request.eventBusName(rule.bus()).name(rule.name()));
}
for (String bus : buses.reversed()) {
client.deleteEventBus(request -> request.name(bus));
}
} finally {
client.close();
}
}
}
}
@@ -0,0 +1,108 @@
package io.floci.aws.services.eventbridge;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.floci.aws.config.EmulatorConfig;
import io.floci.aws.core.common.Digests;
import io.floci.aws.core.common.RegionResolver;
import io.floci.aws.core.common.ServiceConfigAccess;
import io.floci.aws.core.storage.AccountAwareStorageBackend;
import io.floci.aws.core.storage.StorageFactory;
import io.floci.aws.services.eventbridge.model.EventBus;
import io.floci.aws.services.eventbridge.model.Rule;
import io.floci.aws.services.eventbridge.model.Target;
import org.junit.jupiter.api.io.TempDir;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.CsvSource;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import java.util.stream.Stream;
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.RETURNS_DEEP_STUBS;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
class EventBridgeTargetLookupPersistenceTest {
private static final String ACCOUNT = "000000000000";
private static final String REGION = "us-east-1";
private static final String TARGET = "arn:aws:sqs:us-east-1:" + ACCOUNT + ":owned";
private static final ObjectMapper MAPPER = new ObjectMapper().findAndRegisterModules();
@TempDir
Path directory;
@ParameterizedTest
@CsvSource({"persistent,false", "persistent,true", "hybrid,false", "hybrid,true", "wal,false", "wal,true"})
void loadedScopedAndLegacyRecordsRemainUnchangedAcrossReadsAndReload(String mode, boolean legacy) throws Exception {
String prefix = legacy ? "" : ACCOUNT + "/";
String busKey = prefix + "bus:" + REGION + ":custom";
String ruleKey = prefix + "rule:" + REGION + ":custom/owned";
EventBus bus = new EventBus("custom", "arn:aws:events:" + REGION + ":" + ACCOUNT + ":event-bus/custom", null, null);
Rule rule = new Rule();
rule.setName("owned");
rule.setEventBusName("custom");
rule.setArn("arn:aws:events:" + REGION + ":" + ACCOUNT + ":rule/custom/owned");
rule.setAccountId(legacy ? null : ACCOUNT);
String suffix = "wal".equals(mode) ? "-snapshot.json" : ".json";
Files.writeString(directory.resolve("eventbridge-buses" + suffix), MAPPER.writeValueAsString(Map.of(busKey, bus)));
Files.writeString(directory.resolve("eventbridge-rules" + suffix), MAPPER.writeValueAsString(Map.of(ruleKey, rule)));
Files.writeString(directory.resolve("eventbridge-targets" + suffix), MAPPER.writeValueAsString(
Map.of(ruleKey, List.of(new Target("one", TARGET, null, null)))));
for (int round = 0; round < 2; round++) {
StorageFactory factory = factory(mode);
try {
AccountAwareStorageBackend<EventBus> buses = factory.create("eventbridge", "eventbridge-buses.json",
new TypeReference<Map<String, EventBus>>() {});
AccountAwareStorageBackend<Rule> rules = factory.create("eventbridge", "eventbridge-rules.json",
new TypeReference<Map<String, Rule>>() {});
AccountAwareStorageBackend<List<Target>> targets = factory.create("eventbridge", "eventbridge-targets.json",
new TypeReference<Map<String, List<Target>>>() {});
String before = MAPPER.writeValueAsString(List.of(buses.scanAllAccountsWithRawKeys(),
rules.scanAllAccountsWithRawKeys(), targets.scanAllAccountsWithRawKeys()));
Map<String, String> files = fileDigests();
EventBridgeService lookup = EventBridgeTargetLookupFixtures.service(buses, rules, targets,
new RegionResolver(REGION, ACCOUNT));
assertEquals(List.of("owned"), lookup.listRuleNamesByTarget(TARGET, "custom", 100, null, REGION).items());
assertEquals(List.of("owned"), lookup.listRuleNamesByTarget(TARGET, bus.getArn(), 100, null, REGION).items());
assertEquals(List.of(), lookup.listRuleNamesByTarget(TARGET, null, 100, null, REGION).items());
assertEquals(before, MAPPER.writeValueAsString(List.of(buses.scanAllAccountsWithRawKeys(),
rules.scanAllAccountsWithRawKeys(), targets.scanAllAccountsWithRawKeys())));
assertEquals(Set.of(busKey), buses.scanAllAccountsWithRawKeys().keySet());
assertEquals(Set.of(ruleKey), rules.scanAllAccountsWithRawKeys().keySet());
assertEquals(Set.of(ruleKey), targets.scanAllAccountsWithRawKeys().keySet());
assertEquals(files, fileDigests(), "the read must neither write storage bytes nor add files");
} finally {
factory.shutdownAll();
}
}
}
private Map<String, String> fileDigests() throws IOException {
Map<String, String> hashes = new TreeMap<>();
try (Stream<Path> paths = Files.walk(directory)) {
for (Path file : paths.filter(Files::isRegularFile).toList()) {
hashes.put(directory.relativize(file).toString(), Digests.sha256Hex(Files.readAllBytes(file)));
}
}
return hashes;
}
private StorageFactory factory(String mode) {
EmulatorConfig config = mock(EmulatorConfig.class, RETURNS_DEEP_STUBS);
when(config.defaultAccountId()).thenReturn(ACCOUNT);
when(config.storage().persistentPath()).thenReturn(directory.toString());
when(config.storage().wal().compactionIntervalMs()).thenReturn(60_000L);
ServiceConfigAccess access = mock(ServiceConfigAccess.class);
when(access.storageMode(anyString())).thenReturn(mode);
when(access.storageFlushInterval(anyString())).thenReturn(60_000L);
return new StorageFactory(config, access);
}
}
@@ -0,0 +1,222 @@
package io.floci.aws.services.eventbridge;
import io.floci.aws.core.common.AwsArnUtils;
import io.floci.aws.core.common.AwsException;
import io.floci.aws.core.common.PaginatedResult;
import io.floci.aws.core.common.RegionResolver;
import io.floci.aws.core.storage.AccountAwareStorageBackend;
import io.floci.aws.core.storage.InMemoryStorage;
import io.floci.aws.services.eventbridge.model.EventBus;
import io.floci.aws.services.eventbridge.model.Rule;
import io.floci.aws.services.eventbridge.model.Target;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.CsvSource;
import org.junit.jupiter.params.provider.ValueSource;
import java.util.List;
import java.util.Map;
import java.util.Set;
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.Mockito.clearInvocations;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.verify;
class EventBridgeTargetLookupTest {
private static final String ACCOUNT = "000000000000";
private static final String OTHER = "111111111111";
private static final String REGION = "us-east-1";
private static final String TARGET = "arn:aws:sqs:us-west-2:222222222222:foreign-target";
@Test
void defaultAccountLegacyRulesAreReadInPlaceAndExplicitRecordsTakePrecedence() {
Fixture fixture = new Fixture();
Rule legacy = fixture.rule(ACCOUNT, REGION, "default", "owned", true);
fixture.target(ACCOUNT, REGION, "default", "owned", true);
String key = "rule:" + REGION + ":default/owned";
assertEquals(List.of("owned"), fixture.lookup(ACCOUNT).listRuleNamesByTarget(TARGET, null, null, null, REGION).items());
assertSame(legacy, fixture.rawRules.get(key).orElseThrow());
assertEquals(Set.of(key), fixture.rawRules.keys());
assertEquals(Set.of(key), fixture.rawTargets.keys());
assertEquals(List.of(), fixture.lookup(OTHER).listRuleNamesByTarget(TARGET, null, null, null, REGION).items());
Rule explicit = fixture.rule(ACCOUNT, REGION, "default", "owned", false);
fixture.targets.putForAccount(ACCOUNT, key, List.of(new Target("other", "other-target", null, null)));
assertEquals(List.of(), fixture.lookup(ACCOUNT).listRuleNamesByTarget(TARGET, null, null, null, REGION).items());
assertSame(explicit, fixture.rules.getForAccount(ACCOUNT, key).orElseThrow());
assertSame(legacy, fixture.rawRules.get(key).orElseThrow());
assertEquals(Set.of(key, ACCOUNT + "/" + key), fixture.rawRules.keys());
}
@ParameterizedTest
@CsvSource({"old/name,true", "overlong,true", "old/name,false", "overlong,false"})
void persistedNamesRemainDiscoverableWithoutApplyingCreationConstraints(String storedName, boolean legacy) {
Fixture fixture = new Fixture();
String name = "overlong".equals(storedName) ? "x".repeat(65) : storedName;
Rule rule = fixture.rule(ACCOUNT, REGION, "default", name, legacy);
fixture.target(ACCOUNT, REGION, "default", name, legacy);
Map<String, Rule> before = fixture.rules.scanAllAccountsWithRawKeys();
EventBridgeService service = fixture.lookup(ACCOUNT);
assertEquals(List.of(name), service.listRuleNamesByTarget(TARGET, null, 100, null, REGION).items());
assertEquals(List.of(rule), service.listRules(null, null, REGION));
assertEquals(before, fixture.rules.scanAllAccountsWithRawKeys());
}
@Test
void lookupDoesNotFetchForeignAccountRuleValues() {
Fixture fixture = new Fixture();
fixture.rule(ACCOUNT, REGION, "default", "owned", false);
fixture.target(ACCOUNT, REGION, "default", "owned", false);
fixture.rule(OTHER, REGION, "default", "foreign", false);
fixture.target(OTHER, REGION, "default", "foreign", false);
clearInvocations(fixture.rawRules);
assertEquals(List.of("owned"), fixture.lookup(ACCOUNT)
.listRuleNamesByTarget(TARGET, null, 100, null, REGION).items());
verify(fixture.rawRules).get(ACCOUNT + "/rule:" + REGION + ":default/owned");
verify(fixture.rawRules, never()).get(OTHER + "/rule:" + REGION + ":default/foreign");
}
@ParameterizedTest
@ValueSource(strings = {"account", "region", "partition", "name", "bus", "accountField"})
void malformedOrForeignPersistedRuleIdentityIsExcludedWithoutMutation(String mismatch) {
Fixture fixture = new Fixture();
Rule rule = fixture.rule(ACCOUNT, REGION, "default", "owned", true);
fixture.target(ACCOUNT, REGION, "default", "owned", true);
switch (mismatch) {
case "account" -> rule.setArn(arn(OTHER, REGION, "rule/owned"));
case "region" -> rule.setArn(arn(ACCOUNT, "us-west-2", "rule/owned"));
case "partition" -> rule.setArn("arn:aws-cn:events:us-east-1:" + ACCOUNT + ":rule/owned");
case "name" -> rule.setName("different");
case "bus" -> rule.setEventBusName("different");
case "accountField" -> rule.setAccountId(OTHER);
default -> throw new IllegalArgumentException(mismatch);
}
Map<String, Rule> before = fixture.rules.scanAllAccountsWithRawKeys();
assertEquals(List.of(), fixture.lookup(ACCOUNT).listRuleNamesByTarget(TARGET, null, null, null, REGION).items());
assertEquals(before, fixture.rules.scanAllAccountsWithRawKeys());
assertSame(rule, fixture.rawRules.get("rule:" + REGION + ":default/owned").orElseThrow());
}
@Test
void accountPrefixedAliasesCannotReadForeignRulesOrMoveTheirKeys() {
Fixture fixture = new Fixture();
fixture.rule(OTHER, REGION, "default", "foreign", false);
fixture.target(OTHER, REGION, "default", "foreign", false);
Map<String, Rule> before = fixture.rules.scanAllAccountsWithRawKeys();
assertEquals(List.of(), fixture.lookup(ACCOUNT).listRuleNamesByTarget(TARGET, null, null, null, REGION).items());
assertEquals(List.of("foreign"), fixture.lookup(OTHER).listRuleNamesByTarget(TARGET, null, null, null, REGION).items());
assertEquals("ResourceNotFoundException", assertThrows(AwsException.class,
() -> fixture.lookup(ACCOUNT).listRuleNamesByTarget(TARGET, OTHER + "/default", null, null, REGION)).getErrorCode());
assertEquals(before, fixture.rules.scanAllAccountsWithRawKeys());
}
@Test
void legacyCustomBusIsReadByItsStoredKeyWithoutMutation() {
Fixture fixture = new Fixture();
EventBus bus = new EventBus("custom", null, null, null);
fixture.rawBuses.put("bus:" + REGION + ":custom", bus);
fixture.rule(ACCOUNT, REGION, "custom", "owned", true);
fixture.target(ACCOUNT, REGION, "custom", "owned", true);
assertEquals(List.of("owned"), fixture.lookup(ACCOUNT)
.listRuleNamesByTarget(TARGET, "custom", null, null, REGION).items());
assertEquals("ResourceNotFoundException", assertThrows(AwsException.class,
() -> fixture.lookup(OTHER).listRuleNamesByTarget(TARGET, "custom", null, null, REGION)).getErrorCode());
assertEquals(Set.of("bus:" + REGION + ":custom"), fixture.rawBuses.keys());
assertSame(bus, fixture.rawBuses.get("bus:" + REGION + ":custom").orElseThrow());
assertNull(bus.getArn());
}
@Test
void localCursorScopeBindsEveryRequestArgumentAndCallerScope() {
Fixture fixture = new Fixture();
for (String account : List.of(ACCOUNT, OTHER)) {
for (String region : List.of(REGION, "us-west-2")) {
for (String name : List.of("alpha", "omega")) {
fixture.rule(account, region, "default", name, false);
fixture.target(account, region, "default", name, false);
}
}
}
EventBridgeService lookup = fixture.lookup(ACCOUNT);
PaginatedResult<String> first = lookup.listRuleNamesByTarget(TARGET, null, 1, null, REGION);
String token = first.nextToken();
assertNotNull(token);
assertEquals(List.of("alpha"), first.items(), "lexical order is Floci's pagination policy");
assertEquals(List.of("omega"), lookup.listRuleNamesByTarget(TARGET, null, 1, token, REGION).items());
assertNull(lookup.listRuleNamesByTarget(TARGET, null, 1, token, REGION).nextToken());
assertInvalid(() -> lookup.listRuleNamesByTarget("different-target", null, 1, token, REGION));
assertInvalid(() -> lookup.listRuleNamesByTarget(TARGET, "default", 1, token, REGION));
assertInvalid(() -> lookup.listRuleNamesByTarget(TARGET, arn(ACCOUNT, REGION, "event-bus/default"), 1, token, REGION));
assertInvalid(() -> lookup.listRuleNamesByTarget(TARGET, null, 2, token, REGION));
assertInvalid(() -> lookup.listRuleNamesByTarget(TARGET, null, null, token, REGION));
assertInvalid(() -> lookup.listRuleNamesByTarget(TARGET, null, 1, token, "us-west-2"));
assertInvalid(() -> fixture.lookup(OTHER).listRuleNamesByTarget(TARGET, null, 1, token, REGION));
assertInvalid(() -> lookup.listRuleNamesByTarget(TARGET, null, 1, "not-a-cursor", REGION));
}
@Test
void maximumLengthFilterStillProducesAModeledSizeCursor() {
Fixture fixture = new Fixture();
String filter = "x".repeat(1600);
for (String name : List.of("alpha", "omega")) {
fixture.rule(ACCOUNT, REGION, "default", name, false);
fixture.targets.putForAccount(ACCOUNT, "rule:" + REGION + ":default/" + name,
List.of(new Target("one", filter, null, null)));
}
PaginatedResult<String> first = fixture.lookup(ACCOUNT).listRuleNamesByTarget(filter, null, 1, null, REGION);
assertNotNull(first.nextToken());
assertTrue(first.nextToken().length() <= 2048);
assertEquals(List.of("omega"), fixture.lookup(ACCOUNT).listRuleNamesByTarget(filter, null, 1, first.nextToken(), REGION).items());
}
private static void assertInvalid(Runnable call) {
assertEquals("InvalidToken", assertThrows(AwsException.class, call::run).getErrorCode());
}
private static String arn(String account, String region, String resource) {
return AwsArnUtils.Arn.of("events", region, account, resource).toString();
}
private static final class Fixture {
private final InMemoryStorage<String, EventBus> rawBuses = new InMemoryStorage<>();
private final InMemoryStorage<String, Rule> rawRules = spy(new InMemoryStorage<>());
private final InMemoryStorage<String, List<Target>> rawTargets = new InMemoryStorage<>();
private final AccountAwareStorageBackend<EventBus> buses = new AccountAwareStorageBackend<>(rawBuses, null, ACCOUNT);
private final AccountAwareStorageBackend<Rule> rules = new AccountAwareStorageBackend<>(rawRules, null, ACCOUNT);
private final AccountAwareStorageBackend<List<Target>> targets = new AccountAwareStorageBackend<>(rawTargets, null, ACCOUNT);
private EventBridgeService lookup(String account) {
return EventBridgeTargetLookupFixtures.service(buses, rules, targets, new RegionResolver(REGION, account));
}
private Rule rule(String account, String region, String bus, String name, boolean legacy) {
Rule rule = new Rule();
rule.setName(name);
rule.setEventBusName(bus);
rule.setAccountId(legacy ? null : account);
rule.setArn(arn(account, region, "default".equals(bus) ? "rule/" + name : "rule/" + bus + "/" + name));
String key = "rule:" + region + ":" + bus + "/" + name;
if (legacy) {
rawRules.put(key, rule);
} else {
rules.putForAccount(account, key, rule);
}
return rule;
}
private void target(String account, String region, String bus, String name, boolean legacy) {
String key = "rule:" + region + ":" + bus + "/" + name;
List<Target> value = List.of(new Target("one", TARGET, null, null));
if (legacy) {
rawTargets.put(key, value);
} else {
targets.putForAccount(account, key, value);
}
}
}
}
@@ -27,6 +27,7 @@ import java.util.List;
import java.util.Map;
import java.util.UUID;
import static io.floci.aws.testing.EnforcementFixtures.statement;
import static io.floci.aws.testing.LogsAuthorizationFixtures.expectedTags;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.equalTo;
@@ -63,7 +64,7 @@ class LogsArnTagAuthorizationIntegrationTest {
void exactBareGroupArnGrant(String action) {
String selected = group();
String other = group(Map.of("team", "green"));
String caller = user(statement("Allow", action, arn(selected)));
String caller = user(statement("Allow", "logs:" + action, arn(selected)));
invoke(caller, action, arn(other)).statusCode(400).body(containsString("AccessDeniedException"));
assertTags(other, Map.of("team", "green"));
assertSuccess(invoke(caller, action, arn(selected)), action);
@@ -75,7 +76,8 @@ class LogsArnTagAuthorizationIntegrationTest {
void exactBareGroupArnDenyOverridesWildcard(String action) {
String selected = group();
String other = group();
String caller = user(statement("Allow", action, "*") + "," + statement("Deny", action, arn(selected)));
String caller = user(statement("Allow", "logs:" + action, "*") + ","
+ statement("Deny", "logs:" + action, arn(selected)));
ValidatableResponse response = invoke(caller, action, arn(selected));
assertAll("the exact deny prevents access and preserves tags",
() -> response.statusCode(400).body(containsString("AccessDeniedException")),
@@ -102,7 +104,7 @@ class LogsArnTagAuthorizationIntegrationTest {
private void verifyForeignArn(String action, String dimension, boolean root) {
String local = group();
String caller = root ? ACCOUNT : user(statement("Allow", action, "*"));
String caller = root ? ACCOUNT : user(statement("Allow", "logs:" + action, "*"));
String foreign = switch (dimension) {
case "account" -> "arn:aws:logs:" + REGION + ":222222222222:log-group:" + local;
case "region" -> "arn:aws:logs:us-west-2:" + ACCOUNT + ":log-group:" + local;
@@ -125,7 +127,7 @@ class LogsArnTagAuthorizationIntegrationTest {
@ValueSource(strings = {"TagResource", "UntagResource", "ListTagsForResource"})
void incompleteArnPrefixRemainsALiteralLegacyName(String action) {
String name = historicalGroupNamed("arn:archive-" + UUID.randomUUID(), Map.of("team", "blue"));
String caller = user(statement("Allow", action, arn(name)));
String caller = user(statement("Allow", "logs:" + action, arn(name)));
assertSuccess(invoke(caller, action, name), action);
assertTags(name, expectedTags(action));
}
@@ -148,7 +150,7 @@ class LogsArnTagAuthorizationIntegrationTest {
case "marker" -> "x:log-group:" + local;
default -> throw new IllegalArgumentException(shape);
};
String caller = root ? ACCOUNT : user(statement("Allow", action, "*"));
String caller = root ? ACCOUNT : user(statement("Allow", "logs:" + action, "*"));
ValidatableResponse response = invoke(caller, action, input);
assertAll("noncanonical input cannot access the shortened local name",
() -> response.statusCode(400).body(containsString("ResourceNotFoundException")),
@@ -166,7 +168,7 @@ class LogsArnTagAuthorizationIntegrationTest {
void storedTagDenyUsesTheOwningGroup(String action) {
String selected = group();
String other = group(Map.of("team", "green"));
String caller = user(statement("Allow", action, "*") + ","
String caller = user(statement("Allow", "logs:" + action, "*") + ","
+ "{\"Effect\":\"Deny\",\"Action\":\"logs:" + action + "\",\"Resource\":\"*\","
+ "\"Condition\":{\"StringEquals\":{\"aws:ResourceTag/team\":\"blue\"}}}");
invoke(caller, action, arn(selected)).statusCode(400).body(containsString("AccessDeniedException"));
@@ -213,7 +215,7 @@ class LogsArnTagAuthorizationIntegrationTest {
void destinationTagReadUsesItsExactArn() {
String selected = destination("blue");
String other = destination("green");
String caller = user(statement("Allow", "ListTagsForResource", selected));
String caller = user(statement("Allow", "logs:ListTagsForResource", selected));
invoke(caller, "ListTagsForResource", other).statusCode(400)
.body(containsString("AccessDeniedException"));
@@ -225,7 +227,7 @@ class LogsArnTagAuthorizationIntegrationTest {
void destinationResourceTagsControlConditionalAccess() {
String selected = destination("blue");
String other = destination("green");
String caller = user(statement("Allow", "ListTagsForResource", "*") + ","
String caller = user(statement("Allow", "logs:ListTagsForResource", "*") + ","
+ "{\"Effect\":\"Deny\",\"Action\":\"logs:ListTagsForResource\",\"Resource\":\"*\","
+ "\"Condition\":{\"StringEquals\":{\"aws:ResourceTag/team\":\"blue\"}}}");
@@ -241,8 +243,8 @@ class LogsArnTagAuthorizationIntegrationTest {
String other = "logs-destination-tag-" + UUID.randomUUID();
registerDestinationCleanup(selected);
registerDestinationCleanup(other);
String caller = user(statement("Allow", "PutDestination", destinationArn(selected)) + ","
+ statement("Allow", "TagResource", "*") + ","
String caller = user(statement("Allow", "logs:PutDestination", destinationArn(selected)) + ","
+ statement("Allow", "logs:TagResource", "*") + ","
+ "{\"Effect\":\"Allow\",\"Action\":\"iam:PassRole\",\"Resource\":\"*\"}");
putTaggedDestination(caller, other).statusCode(400).body(containsString("AccessDeniedException"));
@@ -259,8 +261,8 @@ class LogsArnTagAuthorizationIntegrationTest {
String other = "logs-destination-tag-" + UUID.randomUUID();
registerDestinationCleanup(selected);
registerDestinationCleanup(other);
String caller = user(statement("Allow", "PutDestination", "*") + ","
+ statement("Allow", "TagResource", destinationArn(selected)) + ","
String caller = user(statement("Allow", "logs:PutDestination", "*") + ","
+ statement("Allow", "logs:TagResource", destinationArn(selected)) + ","
+ "{\"Effect\":\"Allow\",\"Action\":\"iam:PassRole\",\"Resource\":\"*\"}");
putTaggedDestination(caller, other).statusCode(400).body(containsString("AccessDeniedException"));
@@ -275,9 +277,9 @@ class LogsArnTagAuthorizationIntegrationTest {
String other = "logs-destination-tag-" + UUID.randomUUID();
registerDestinationCleanup(selected);
registerDestinationCleanup(other);
String caller = user(statement("Allow", "PutDestination", "*") + ","
+ statement("Allow", "TagResource", "*") + ","
+ statement("Deny", "TagResource", destinationArn(selected)) + ","
String caller = user(statement("Allow", "logs:PutDestination", "*") + ","
+ statement("Allow", "logs:TagResource", "*") + ","
+ statement("Deny", "logs:TagResource", destinationArn(selected)) + ","
+ "{\"Effect\":\"Allow\",\"Action\":\"iam:PassRole\",\"Resource\":\"*\"}");
putTaggedDestination(caller, selected).statusCode(400).body(containsString("AccessDeniedException"));
@@ -352,11 +354,6 @@ class LogsArnTagAuthorizationIntegrationTest {
"arn-tags", statements);
}
private static String statement(String effect, String action, String resource) {
return "{\"Effect\":\"" + effect + "\",\"Action\":\"logs:" + action
+ "\",\"Resource\":\"" + resource + "\"}";
}
private static String arn(String group) {
return "arn:aws:logs:" + REGION + ":" + ACCOUNT + ":log-group:" + group;
}
@@ -1,5 +1,6 @@
package io.floci.aws.testing;
import com.fasterxml.jackson.databind.node.JsonNodeFactory;
import io.restassured.filter.Filter;
import io.restassured.path.xml.XmlPath;
import io.restassured.response.ValidatableResponse;
@@ -423,6 +424,12 @@ public final class EnforcementFixtures {
return request.when().post("/").then();
}
/** A single-action, single-resource IAM statement, ready to place in a policy's Statement array. */
public static String statement(String effect, String action, String resource) {
return JsonNodeFactory.instance.objectNode().put("Effect", effect).put("Action", action)
.put("Resource", resource).toPrettyString();
}
private static RequestSpecification s3(int port, String authorization) {
return given().port(port).header("Authorization", authorization);
}