diff --git a/docs/services/eventbridge.md b/docs/services/eventbridge.md index a7d1cf35d6..cdf3d7e39d 100644 --- a/docs/services/eventbridge.md +++ b/docs/services/eventbridge.md @@ -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 diff --git a/docs/services/index.md b/docs/services/index.md index a3db1feb78..6fb29c0747 100644 --- a/docs/services/index.md +++ b/docs/services/index.md @@ -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 | diff --git a/src/main/java/io/floci/aws/core/storage/AccountAwareStorageBackend.java b/src/main/java/io/floci/aws/core/storage/AccountAwareStorageBackend.java index ce273c5777..3595e390d4 100644 --- a/src/main/java/io/floci/aws/core/storage/AccountAwareStorageBackend.java +++ b/src/main/java/io/floci/aws/core/storage/AccountAwareStorageBackend.java @@ -624,6 +624,24 @@ public class AccountAwareStorageBackend implements StorageBackend .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 keysIncludingLegacyForAccount(String accountId, Predicate keyFilter) { + Set 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 keysForAccount(String accountId) { String prefix = accountId + "/"; return delegate.keys().stream() diff --git a/src/main/java/io/floci/aws/services/eventbridge/EventBridgeHandler.java b/src/main/java/io/floci/aws/services/eventbridge/EventBridgeHandler.java index 9cad161500..073b67a8aa 100644 --- a/src/main/java/io/floci/aws/services/eventbridge/EventBridgeHandler.java +++ b/src/main/java/io/floci/aws/services/eventbridge/EventBridgeHandler.java @@ -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 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); diff --git a/src/main/java/io/floci/aws/services/eventbridge/EventBridgeService.java b/src/main/java/io/floci/aws/services/eventbridge/EventBridgeService.java index 0d6cc34338..1a2425b95d 100644 --- a/src/main/java/io/floci/aws/services/eventbridge/EventBridgeService.java +++ b/src/main/java/io/floci/aws/services/eventbridge/EventBridgeService.java @@ -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 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 keys = ruleStore instanceof AccountAwareStorageBackend aware + ? aware.keysIncludingLegacyForAccount(account, key -> key.startsWith(prefix)) + : ruleStore.keys(); + List 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 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 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 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 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 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) { diff --git a/src/test/java/io/floci/aws/core/storage/AccountAwareStorageBackendTest.java b/src/test/java/io/floci/aws/core/storage/AccountAwareStorageBackendTest.java index 881acdfa2d..663ad41bc4 100644 --- a/src/test/java/io/floci/aws/core/storage/AccountAwareStorageBackendTest.java +++ b/src/test/java/io/floci/aws/core/storage/AccountAwareStorageBackendTest.java @@ -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 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 before = raw.keys(); + clearInvocations(raw); + AccountAwareStorageBackend 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 raw = new InMemoryStorage<>(); diff --git a/src/test/java/io/floci/aws/services/apigatewayv2/AuthorizerPolicyFixtures.java b/src/test/java/io/floci/aws/services/apigatewayv2/AuthorizerPolicyFixtures.java index 5110febf89..906bea80b9 100644 --- a/src/test/java/io/floci/aws/services/apigatewayv2/AuthorizerPolicyFixtures.java +++ b/src/test/java/io/floci/aws/services/apigatewayv2/AuthorizerPolicyFixtures.java @@ -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); } diff --git a/src/test/java/io/floci/aws/services/eventbridge/EventBridgeTargetLookupFixtures.java b/src/test/java/io/floci/aws/services/eventbridge/EventBridgeTargetLookupFixtures.java new file mode 100644 index 0000000000..803713daf6 --- /dev/null +++ b/src/test/java/io/floci/aws/services/eventbridge/EventBridgeTargetLookupFixtures.java @@ -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 buses, StorageBackend rules, + StorageBackend> targets, RegionResolver resolver) { + return new EventBridgeService(buses, rules, targets, new InMemoryStorage<>(), new InMemoryStorage<>(), + new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(), resolver, + new ObjectMapper(), null, null, null, null, null); + } +} diff --git a/src/test/java/io/floci/aws/services/eventbridge/EventBridgeTargetLookupHandlerTest.java b/src/test/java/io/floci/aws/services/eventbridge/EventBridgeTargetLookupHandlerTest.java new file mode 100644 index 0000000000..bfb9a278c7 --- /dev/null +++ b/src/test/java/io/floci/aws/services/eventbridge/EventBridgeTargetLookupHandlerTest.java @@ -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 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 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")); + } +} diff --git a/src/test/java/io/floci/aws/services/eventbridge/EventBridgeTargetLookupIamIntegrationTest.java b/src/test/java/io/floci/aws/services/eventbridge/EventBridgeTargetLookupIamIntegrationTest.java new file mode 100644 index 0000000000..6517f1bb4d --- /dev/null +++ b/src/test/java/io/floci/aws/services/eventbridge/EventBridgeTargetLookupIamIntegrationTest.java @@ -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 buses = raw(factory.create("eventbridge", "eventbridge-buses.json", + new TypeReference>() {})); + StorageBackend rules = raw(factory.create("eventbridge", "eventbridge-rules.json", + new TypeReference>() {})); + StorageBackend> targets = raw(factory.create("eventbridge", "eventbridge-targets.json", + new TypeReference>>() {})); + 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 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 void unchanged(StorageBackend 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 StorageBackend raw(AccountAwareStorageBackend store) throws ReflectiveOperationException { + Field delegate = AccountAwareStorageBackend.class.getDeclaredField("delegate"); + delegate.setAccessible(true); + return (StorageBackend) delegate.get(store); + } +} diff --git a/src/test/java/io/floci/aws/services/eventbridge/EventBridgeTargetLookupIntegrationTest.java b/src/test/java/io/floci/aws/services/eventbridge/EventBridgeTargetLookupIntegrationTest.java new file mode 100644 index 0000000000..425451833b --- /dev/null +++ b/src/test/java/io/floci/aws/services/eventbridge/EventBridgeTargetLookupIntegrationTest.java @@ -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 buses = factory.create("eventbridge", "eventbridge-buses.json", + new TypeReference>() {}); + Set 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 names(EventBridgeClient client, String bus, String target, int limit) { + List result = new ArrayList<>(); + Set 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 buses = new ArrayList<>(); + private final List 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(); + } + } + } +} diff --git a/src/test/java/io/floci/aws/services/eventbridge/EventBridgeTargetLookupPersistenceTest.java b/src/test/java/io/floci/aws/services/eventbridge/EventBridgeTargetLookupPersistenceTest.java new file mode 100644 index 0000000000..157154de44 --- /dev/null +++ b/src/test/java/io/floci/aws/services/eventbridge/EventBridgeTargetLookupPersistenceTest.java @@ -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 buses = factory.create("eventbridge", "eventbridge-buses.json", + new TypeReference>() {}); + AccountAwareStorageBackend rules = factory.create("eventbridge", "eventbridge-rules.json", + new TypeReference>() {}); + AccountAwareStorageBackend> targets = factory.create("eventbridge", "eventbridge-targets.json", + new TypeReference>>() {}); + String before = MAPPER.writeValueAsString(List.of(buses.scanAllAccountsWithRawKeys(), + rules.scanAllAccountsWithRawKeys(), targets.scanAllAccountsWithRawKeys())); + Map 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 fileDigests() throws IOException { + Map hashes = new TreeMap<>(); + try (Stream 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); + } +} diff --git a/src/test/java/io/floci/aws/services/eventbridge/EventBridgeTargetLookupTest.java b/src/test/java/io/floci/aws/services/eventbridge/EventBridgeTargetLookupTest.java new file mode 100644 index 0000000000..0d1cabba5b --- /dev/null +++ b/src/test/java/io/floci/aws/services/eventbridge/EventBridgeTargetLookupTest.java @@ -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 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 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 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 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 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 rawBuses = new InMemoryStorage<>(); + private final InMemoryStorage rawRules = spy(new InMemoryStorage<>()); + private final InMemoryStorage> rawTargets = new InMemoryStorage<>(); + private final AccountAwareStorageBackend buses = new AccountAwareStorageBackend<>(rawBuses, null, ACCOUNT); + private final AccountAwareStorageBackend rules = new AccountAwareStorageBackend<>(rawRules, null, ACCOUNT); + private final AccountAwareStorageBackend> 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 value = List.of(new Target("one", TARGET, null, null)); + if (legacy) { + rawTargets.put(key, value); + } else { + targets.putForAccount(account, key, value); + } + } + } +} diff --git a/src/test/java/io/floci/aws/services/iam/LogsArnTagAuthorizationIntegrationTest.java b/src/test/java/io/floci/aws/services/iam/LogsArnTagAuthorizationIntegrationTest.java index 248eee3219..0d85780a42 100644 --- a/src/test/java/io/floci/aws/services/iam/LogsArnTagAuthorizationIntegrationTest.java +++ b/src/test/java/io/floci/aws/services/iam/LogsArnTagAuthorizationIntegrationTest.java @@ -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; } diff --git a/src/test/java/io/floci/aws/testing/EnforcementFixtures.java b/src/test/java/io/floci/aws/testing/EnforcementFixtures.java index 07e35f2c88..365b4f13dd 100644 --- a/src/test/java/io/floci/aws/testing/EnforcementFixtures.java +++ b/src/test/java/io/floci/aws/testing/EnforcementFixtures.java @@ -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); }