feat(resourceexplorer2): add AWS Resource Explorer 2 with cross-service resource discovery (#2485)

* feat(resourceexplorer2): Add AWS Resource Explorer 2 with cross-service resource discovery

Resource Explorer 2 lets AWS SDK clients discover resources across
S3, RDS, DynamoDB, ElastiCache, and OpenSearch through a single
query interface — the same way real AWS Resource Explorer aggregates
resources from multiple services.

Architecture: a ResourceProvider CDI interface in core/resource/
decouples Resource Explorer from individual services. Each service
implements the interface to expose its resources. Resource Explorer
discovers all providers via CDI Instance<ResourceProvider> and
queries them live on every request — no intermediate store, no
eventual consistency. New services become discoverable by
implementing the interface; Resource Explorer never imports service
packages directly.

Query parsing: hand-written character-by-character tokenizer that
implements the full Resource Explorer filter syntax — all 10 filter
attributes (accountid, application, id, region, resourcetype,
resourcetype.supports, service, tag, tag.key, tag.value), comma-OR
within filters, negation (-), wildcard suffix (*), quoted strings,
backslash escaping, and free-form text keywords. ListResources
rejects free-form text (filter-only mode); Search accepts both.
Tokens are classified by splitting on the first unescaped colon and
looking the prefix up against the known attributes, matching the
documented grammar.

API surface: 20 REST JSON endpoints covering ListResources, Search,
ListSupportedResourceTypes, full Index CRUD (CreateIndex always
creates LOCAL — promote via UpdateIndexType, matching real AWS),
full View CRUD with Scope and FilterString, BatchGetView with
Errors for missing ARNs, default view association, and pagination
with NextToken on all list operations. Tag operations use the
existing SharedTagsController + TagHandler infrastructure. A
default AGGREGATOR index and default view with tags included are
auto-provisioned on startup so ListResources works without setup.

AWS behavioral fidelity (matched against the API reference, not
guessed): ListResources/Search with no view and no regional default
return UnauthorizedException (401), not 404; the default view is
scoped per region; CreateView requires a unique, regex-valid
ViewName (ConflictException 409 / ValidationException 400) and only
accepts "tags" as an included property; promoting a second aggregator
index returns ConflictException; ListResources suppresses NextToken
at MaxResults=1000; Search/ListResources cap results at the first
1000 matches; QueryString is required (empty string allowed) and
MaxResults is range-validated. Pagination offsets are clamped so a
stale NextToken against a shrunk live result set returns an empty
page instead of a 500.

All response JSON uses PascalCase field names built via Jackson
ObjectNode (never valueToTree on domain models) to match the AWS
SDK wire format exactly. Verified by decompiling every SDK model
class with javap and comparing field-by-field, then running 16
read-only SDK tests against production resource-explorer-2 in
us-east-1.

ElastiCache ReplicationGroup gains arn and region fields so
Resource Explorer can discover it. RDS resources get tags via
ResourceGroupsTaggingService (the cross-service tagging API)
since floci's RDS service doesn't implement AddTagsToResource.

Indexes and views are persisted (hybrid storage) in production;
tests pin the service to in-memory storage so runs stay isolated
and idempotent.

Testing:
- 50 query parser unit tests covering the full grammar
- 20 filter evaluation unit tests against synthetic resources
- 9 pagination unit tests for the offset clamp and 1000-result cap
- 73 integration tests (@QuarkusTest + RestAssured), grouped with
  @Nested by behavior class: conditional/stateful response fields,
  data provenance across services, edge/boundary pagination,
  cross-service data consistency, filter semantics, and AWS API
  fidelity (401 no-default-view, conflict on duplicate view name and
  second aggregator, view-name and included-property validation)
- 28 SDK compatibility tests using real AWS SDK v2
  ResourceExplorer2Client, asserting every field the SDK model
  exposes. Dual-mode: run against floci or real AWS via
  FLOCI_TARGET=aws (mutating tests skipped against real AWS).

* feat(lambda): expose functions to Resource Explorer 2

Implement ResourceProvider so Lambda functions surface via the
Resource Explorer 2 ListResources/Search APIs and lambda appears in
ListSupportedResourceTypes. Iterates $LATEST versions only so published
versions don't produce duplicate function entries.

* feat(sns): expose topics to Resource Explorer 2

* feat(kms): expose keys to Resource Explorer 2

* feat(sqs): expose queues to Resource Explorer 2

Queue ARNs aren't persisted on the model; reconstruct them from the
region (recovered from the storage key) plus the queue name via
regionResolver.buildArn.

* feat(ecr): expose repositories to Resource Explorer 2

* feat(stepfunctions): expose state machines to Resource Explorer 2

* feat(msk): expose clusters to Resource Explorer 2

* feat(pipes): expose pipes to Resource Explorer 2

* feat(acm): expose certificates to Resource Explorer 2

* feat(cognito): expose user pools to Resource Explorer 2

* feat(iam): expose users and roles to Resource Explorer 2

IAM is a global service: its ARNs carry no region, and Resource Explorer
reports global resources with the region "global" (not an empty string),
matching real AWS. Emit two resource types, iam:user and iam:role.

* test(resourceexplorer2): parameterize per-service ListResources coverage

The ten single-service resource tests were byte-for-byte identical
except for the service name and resource type — the same
service-filter/assert-no-foreign-service/assert-type-present shape
copied ten times. Fold them into one @ParameterizedTest whose CsvSource
carries the (service, resourceType) pairs, so adding a service is one
row instead of a new @Nested class. IAM stays separate: it reports the
global region and two resource types, which the shared shape can't express.

* feat(amazonmq): expose brokers to Resource Explorer 2

Amazon MQ arrived on main after this branch was cut. Implement
ResourceProvider so brokers surface via Search/ListResources and mq
appears in ListSupportedResourceTypes, matching the other services
already wired into Resource Explorer. Brokers carry an ARN and tags, so
the mapping is the same shape as the rest: one mq:broker resource per
stored broker.

* feat(lightsail): expose resources to Resource Explorer 2

Lightsail landed upstream (#1583) after this branch began and models
taggable, ARN-bearing resources (instances, disks, static IPs, key
pairs) that AWS Resource Explorer indexes. Without a ResourceProvider
its resources were invisible to Search/ListResources, unlike every
other resource-owning service on this branch.

LightsailService now implements ResourceProvider: getResources() maps
each stored resource node to an ExplorerResource, deriving region and
account from the ARN and resourceType as lightsail:<Type>;
getSupportedResourceTypes() advertises the four stored types (static
IPs flagged non-taggable, matching AWS).

Coverage: a focused unit test asserts the node->ExplorerResource
mapping (arn, type, region, account, tags) without Quarkus, plus the
parameterized RE2 integration test seeds a Lightsail instance and disk
and asserts both surface via ListResources.

* feat(rum): expose app monitors to Resource Explorer 2

CloudWatch RUM (added upstream in #1797) owns taggable, ARN-addressable
app monitors, so it fits the ResourceProvider extension point the rest of
this branch uses to surface resources to Resource Explorer 2 Search,
ListResources, and ListSupportedResourceTypes.

RUM is the first RE2 provider whose API model carries neither an ARN nor a
region (GetAppMonitor returns neither), so getResources() reconstructs the
ARN: the region comes from the storage key, and the owning account is
captured at creation time on the AppMonitor. That owner account is
@JsonIgnore'd so it never leaks into the RUM API body and is not persisted;
getResources() falls back to the default account for monitors reloaded from
disk. Resolving the account at creation rather than at query time is what
keeps a monitor's identity stable — an earlier draft read the account from
the request context inside getResources(), which stamped every resource
with the account of whoever called ListResources instead of its true owner.

Injecting RegionResolver into RumService (threaded through the existing unit
tests) and adding RegionResolver.getDefaultAccountId() support this.

Adds RumResourceProviderTest, including a regression test proving the owner
account is the creator's, not the querying caller's, plus a RumServiceTest
assertion that the owner account never appears in the serialized API body.
Extends ResourceExplorer2IntegrationTest to seed an app monitor and assert
rum:appmonitor surfaces via ListResources and ListSupportedResourceTypes.

* feat(resourceexplorer2): complete the API surface and close the AWS gaps

Follow-up to the Resource Explorer 2 branch, addressing the gaps found reviewing
it against the AWS API reference and search-syntax documentation.

Wire-level corrections:

- MaxResults ceilings are now per-operation, as AWS models them: 1000 for
  Search/ListResources/ListSupportedResourceTypes, 100 for indexes, 50 for views,
  10 for member indexes. ListSupportedResourceTypes previously rejected page sizes
  AWS accepts, and ListViews accepted ones it rejects.
- ListViews is scoped to the calling Region. AWS returns "the views available in
  the AWS Region in which you call this operation"; every Region's views were
  being listed.
- Free-form keywords are OR'd rather than AND'd, which is how AWS reads them. The
  remaining deviation — AWS ranks a non-matching resource lower instead of
  excluding it — is documented rather than emulated, since a keyword-only search
  returning the whole account is not a useful local answer.
- A tag filter against a view whose IncludedProperties omit `tags` is rejected
  with a ValidationException, as AWS documents for tag: / tag.key: / tag.value: /
  application:, instead of being evaluated on data the view may not expose.
- Backslash escaping is honoured throughout the query grammar: escapes now survive
  tokenization and are resolved only where the character's meaning is decided, so
  `\-`, `\:`, `\,` and `\*` are literal text and a quoted phrase neutralises every
  operator inside it.
- application: matches the application name as well as the resource-group ARN;
  resourcetype.supports:tags consults the provider's declared tag support instead
  of passing everything through; free-form keywords match tag keys and values.

The remaining 12 operations are implemented, taking the service to all 32:
the multi-Region setup lifecycle (CreateResourceExplorerSetup,
DeleteResourceExplorerSetup, GetResourceExplorerSetup) provisions real indexes and
views and records each Region's outcome independently, so one Region's failure is
reported through its ErrorDetails rather than abandoning the task. The
organization and trusted-service surfaces answer with the wire-accurate empty
result, since floci models neither.

Eleven more services expose their resources: EC2 (instances, VPCs, subnets,
security groups, volumes, internet and NAT gateways, route tables),
CloudFormation, CloudWatch Logs, EventBridge, Secrets Manager, SSM, ECS, EKS,
Kinesis, Firehose, and ELB v2 — thirty providers in total. API Gateway and
Route 53 stay out: RestApi carries no Region and Route53Service resolves no
account id, so each needs a field added to an unrelated service first.

Also documents the service, which a new service requires: docs/services/
resource-explorer.md with the generated action table, the deviations above, and
the routing note, plus the mkdocs nav, README, and environment-variable entries.

Seven existing tests asserted on the emulator's total resource count, which thirty
providers push past Search's 1000-result cap; they are scoped to a bounded slice
so their arithmetic stays meaningful. 24 tests added for the new behaviour.

* fix(rum): keep a monitor's owning account across updates

UpdateAppMonitor rebuilds the AppMonitor from its current state and never carried
ownerAccountId over, so an update silently reassigned the monitor to whichever
account next called ListResources. Resource Explorer then reported a wrong ARN and
OwningAccountId for any monitor not owned by that caller.

getResources' fallback for monitors reloaded from disk — where the transient owner
account did not survive — was the configured default account. monitorStore.keys()
is already scoped to the calling account by the account-aware backend, so a monitor
reachable there is owned by that caller by construction; the caller's account is
the correct fallback.

Also addresses review findings on the Resource Explorer branch: braces in the
compatibility test's cleanup, a synchronized override in the Lightsail provider
test's storage stub, and four unread locals in the integration test.

* chore: drop the stray local-dev Dockerfile

docker/Dockerfile.localdev was carried in with the Resource Explorer work
but is unrelated to it: nothing in the repo references it, and its header
points at a CI pipeline and dev cluster that do not exist in this org.

* fix(resourceexplorer2): order paginated results before slicing

NextToken is a bare offset, but the list it indexes into is rebuilt on
every call by iterating Instance<ResourceProvider> and StorageBackend.scan,
neither of which promises an order. Offset pagination is only well defined
over a stable order: page through Search or ListResources with MaxResults
smaller than the result set and the second page indexes into a differently
arranged list, silently dropping or repeating resources.

Sort on a unique key before every paginate call: ARN for resources and
indexes, the view ARN for ListViews, the resource type for
ListSupportedResourceTypes. The regression test drives a provider that
reshuffles its resources on each call, which is what an unordered
map-backed store is free to do; without the sort a 25-resource set pages
down to 16 distinct ARNs.

This also makes ResourceProvider#getResources()'s "ordering is not
significant" contract true rather than merely permitted.

* docs: add the Resource Explorer row to the service matrix

The downmerge picks up #2465's service-matrix gate, which fails
`make docs-check` for any service registered in ResolvedServiceCatalog
without a row in docs/services/index.md — resource-explorer-2 was one.

The descriptor's external key carries the API version suffix while the
page is resource-explorer.md, so it also needs an alias entry, the same
way apigatewayv2 and cognito-idp do.

* test(resourceexplorer2): scope the tag-provenance lookup to the caller's Region

dynamoDbTagResourceUpdatesResourceExplorer took Resources[0] from an
unfiltered ListResources and tagged it. ListResources spans every Region
the view covers while DynamoDB TagResource resolves the table in the
request's Region, so the ARN it picked only worked as long as the first
result happened to be local.

Deterministic ARN ordering makes that assumption fail reliably instead of
by luck: the first table is now eu-west-2's and TagResource reports it as
not found. Filter on region:us-east-1, the same way the region-scoping
tests in this class already do.

---------

Co-authored-by: Marius Volkhart <marius@volkhart.com>
Co-authored-by: Hector Ventura <hectorvent@gmail.com>
This commit is contained in:
authored and GitHub committed 2026-08-25 21:05:52 -05:00
1 parent 943b4c1b45
commit d3871e1f25
86 files changed
+8562 -69

No files matched your search

@@ -30,7 +30,7 @@ class ElastiCacheQueryHandlerTest {
@Test
void describeCacheSubnetGroups_returnsEmptyWrapperWithoutMarker() {
Response response = handler.handle("DescribeCacheSubnetGroups", params());
Response response = handler.handle("DescribeCacheSubnetGroups", params(), "us-east-1");
assertEquals(200, response.getStatus());
String body = (String) response.getEntity();
@@ -41,7 +41,7 @@ class ElastiCacheQueryHandlerTest {
@Test
void describeCacheParameterGroups_returnsEmptyWrapperWithoutMarker() {
Response response = handler.handle("DescribeCacheParameterGroups", params());
Response response = handler.handle("DescribeCacheParameterGroups", params(), "us-east-1");
assertEquals(200, response.getStatus());
String body = (String) response.getEntity();
@@ -52,7 +52,7 @@ class ElastiCacheQueryHandlerTest {
@Test
void unsupportedOperationStillReturnsQueryError() {
Response response = handler.handle("NoSuchAction", params());
Response response = handler.handle("NoSuchAction", params(), "us-east-1");
assertEquals(400, response.getStatus());
assertTrue(((String) response.getEntity()).contains("UnsupportedOperation"));
@@ -59,7 +59,6 @@ class ElastiCacheServiceTest {
when(containerManager.start(anyString(), anyString()))
.thenReturn(new ElastiCacheContainerHandle("cid", "grp", "localhost", 6379));
doNothing().when(proxyManager).startProxy(anyString(), any(), anyInt(), anyString(), anyInt(), any());
Ec2Service ec2Service = org.mockito.Mockito.mock(Ec2Service.class);
service = new ElastiCacheService(containerManager, proxyManager, storageFactory, config,
ec2Service, new RegionResolver("us-east-1", "000000000000"));
@@ -91,17 +90,17 @@ class ElastiCacheServiceTest {
org.mockito.Mockito.mock(Ec2Service.class),
new RegionResolver("us-east-1", "000000000000"));
svc.createReplicationGroup("g1", "d", AuthMode.PASSWORD, null);
svc.createReplicationGroup("g1", "d", AuthMode.PASSWORD, null, "us-east-1");
AwsException ex = assertThrows(AwsException.class,
() -> svc.createReplicationGroup("g2", "d", AuthMode.PASSWORD, null));
() -> svc.createReplicationGroup("g2", "d", AuthMode.PASSWORD, null, "us-east-1"));
assertEquals("InsufficientCacheClusterCapacity", ex.getErrorCode());
assertEquals(400, ex.getHttpStatus());
}
@Test
void singleArgAuthMatchesDefaultUserOnly() {
service.createReplicationGroup("grp", "test", AuthMode.PASSWORD, null);
service.createReplicationGroup("grp", "test", AuthMode.PASSWORD, null, "us-east-1");
service.createUser("default-user-id", "default", AuthMode.PASSWORD,
List.of("default-pass"), "on ~* +@all", null);
@@ -121,7 +120,7 @@ class ElastiCacheServiceTest {
@Test
void twoArgAuthMatchesNamedUser() {
service.createReplicationGroup("grp", "test", AuthMode.PASSWORD, null);
service.createReplicationGroup("grp", "test", AuthMode.PASSWORD, null, "us-east-1");
service.createUser("other-user-id", "other", AuthMode.PASSWORD,
List.of("other-pass"), "on ~* +@all", null);
@@ -137,7 +136,7 @@ class ElastiCacheServiceTest {
@Test
void singleArgAuthFallsBackToGroupAuthToken() {
service.createReplicationGroup("grp", "test", AuthMode.PASSWORD, "group-token");
service.createReplicationGroup("grp", "test", AuthMode.PASSWORD, "group-token", "us-east-1");
// Single-arg AUTH with group auth token should succeed
assertTrue(service.validatePassword("grp", null, "group-token"));
@@ -158,7 +157,7 @@ class ElastiCacheServiceTest {
// The original failure must propagate to the caller (we clean up, then rethrow).
assertThrows(RuntimeException.class,
() -> service.createReplicationGroup("grp", "test", AuthMode.PASSWORD, null));
() -> service.createReplicationGroup("grp", "test", AuthMode.PASSWORD, null, "us-east-1"));
// Rollback stops by the exact handle, not a fresh by-id lookup.
verify(proxyManager).stopProxy("grp");
@@ -170,7 +169,7 @@ class ElastiCacheServiceTest {
doNothing().when(proxyManager)
.startProxy(anyString(), any(), anyInt(), anyString(), anyInt(), any());
ReplicationGroup recovered =
service.createReplicationGroup("grp2", "test", AuthMode.PASSWORD, null);
service.createReplicationGroup("grp2", "test", AuthMode.PASSWORD, null, "us-east-1");
assertEquals(16379, recovered.getProxyPort(),
"Port from the failed create must be released so the next group reuses it");
}
@@ -182,7 +181,7 @@ class ElastiCacheServiceTest {
.when(containerManager).start(eq("grp"), anyString());
assertThrows(RuntimeException.class,
() -> service.createReplicationGroup("grp", "test", AuthMode.PASSWORD, null));
() -> service.createReplicationGroup("grp", "test", AuthMode.PASSWORD, null, "us-east-1"));
verify(proxyManager, never()).stopProxy(anyString());
verify(containerManager).stopByGroupId("grp");
@@ -191,7 +190,7 @@ class ElastiCacheServiceTest {
when(containerManager.start(anyString(), anyString()))
.thenReturn(new ElastiCacheContainerHandle("cid", "grp2", "localhost", 6379));
ReplicationGroup recovered =
service.createReplicationGroup("grp2", "test", AuthMode.PASSWORD, null);
service.createReplicationGroup("grp2", "test", AuthMode.PASSWORD, null, "us-east-1");
assertEquals(16379, recovered.getProxyPort(),
"Port from the failed create must be released so the next group reuses it");
}
@@ -207,12 +206,12 @@ class ElastiCacheServiceTest {
});
Thread firstRequest = new Thread(() ->
service.createReplicationGroup("grp", "test", AuthMode.PASSWORD, null));
service.createReplicationGroup("grp", "test", AuthMode.PASSWORD, null, "us-east-1"));
firstRequest.start();
assertTrue(startedLatch.await(5, TimeUnit.SECONDS), "first request never reached container start");
AwsException ex = assertThrows(AwsException.class,
() -> service.createReplicationGroup("grp", "test", AuthMode.PASSWORD, null));
() -> service.createReplicationGroup("grp", "test", AuthMode.PASSWORD, null, "us-east-1"));
assertEquals("ReplicationGroupAlreadyExistsFault", ex.jsonType());
verify(containerManager, never()).stop(any());
verify(containerManager, never()).stopByGroupId(anyString());
@@ -0,0 +1,118 @@
package io.github.hectorvent.floci.services.lightsail;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import io.github.hectorvent.floci.core.common.RegionResolver;
import io.github.hectorvent.floci.core.resource.ExplorerResource;
import io.github.hectorvent.floci.core.resource.SupportedResourceType;
import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend;
import io.github.hectorvent.floci.core.storage.StorageFactory;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Nested;
import org.junit.jupiter.api.Test;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
class LightsailResourceProviderTest {
private static final String REGION = "us-east-1";
private static final String ACCOUNT = "000000000000";
private final ObjectMapper mapper = new ObjectMapper();
private LightsailService service;
@BeforeEach
void setUp() {
StorageFactory storageFactory = new StorageFactory(null, null) {
@Override
public synchronized <V> AccountAwareStorageBackend<V> create(String serviceName, String fileName,
TypeReference<Map<String, V>> typeReference) {
return AccountAwareStorageBackend.inMemory(ACCOUNT);
}
};
service = new LightsailService(storageFactory, mapper, new RegionResolver(REGION, ACCOUNT));
}
@Nested
class GetResources {
@Test
void emptyWhenNothingStored() {
assertTrue(service.getResources().isEmpty());
}
@Test
void surfacesInstanceWithArnTypeRegionAccountAndTags() {
ObjectNode request = mapper.createObjectNode()
.put("availabilityZone", REGION + "a")
.put("blueprintId", "ubuntu_22_04")
.put("bundleId", "nano_3_0");
request.set("instanceNames", mapper.createArrayNode().add("web"));
request.set("tags", mapper.createArrayNode()
.add(mapper.createObjectNode().put("key", "env").put("value", "prod")));
service.createInstances(REGION, request);
ExplorerResource instance = only(service.getResources(), "lightsail:Instance");
assertEquals("arn:aws:lightsail:" + REGION + ":" + ACCOUNT + ":Instance/web", instance.arn());
assertEquals("lightsail", instance.service());
assertEquals(REGION, instance.region());
assertEquals(ACCOUNT, instance.owningAccountId());
assertEquals(Map.of("env", "prod"), instance.tags());
}
@Test
void surfacesDiskInstanceStaticIpAndKeyPairTypes() {
service.createInstances(REGION, mapper.createObjectNode()
.put("availabilityZone", REGION + "a")
.put("blueprintId", "ubuntu_22_04")
.put("bundleId", "nano_3_0")
.set("instanceNames", mapper.createArrayNode().add("web")));
service.createDisk(REGION, mapper.createObjectNode()
.put("diskName", "data")
.put("availabilityZone", REGION + "a")
.put("sizeInGb", 32));
service.allocateStaticIp(REGION, "ip1");
service.createKeyPair(REGION, mapper.createObjectNode().put("keyPairName", "kp1"));
Set<String> types = service.getResources().stream()
.map(ExplorerResource::resourceType)
.collect(Collectors.toSet());
assertEquals(Set.of("lightsail:Instance", "lightsail:Disk",
"lightsail:StaticIp", "lightsail:KeyPair"), types);
}
@Test
void resourceWithoutTagsYieldsEmptyMapNotNull() {
service.allocateStaticIp(REGION, "ip1");
ExplorerResource ip = only(service.getResources(), "lightsail:StaticIp");
assertEquals(Map.of(), ip.tags());
}
}
@Nested
class GetSupportedResourceTypes {
@Test
void advertisesFourLightsailTypesAllUnderLightsailService() {
Set<SupportedResourceType> types = service.getSupportedResourceTypes();
assertEquals(Set.of("lightsail:Instance", "lightsail:Disk",
"lightsail:StaticIp", "lightsail:KeyPair"),
types.stream().map(SupportedResourceType::resourceType).collect(Collectors.toSet()));
assertTrue(types.stream().allMatch(t -> t.service().equals("lightsail")));
}
}
private static ExplorerResource only(List<ExplorerResource> resources, String resourceType) {
return resources.stream()
.filter(r -> r.resourceType().equals(resourceType))
.reduce((a, b) -> { throw new AssertionError("expected exactly one " + resourceType); })
.orElseThrow(() -> new AssertionError("no " + resourceType + " resource"));
}
}
@@ -4558,7 +4558,7 @@ class RdsServiceTest {
return new RdsService(containerManager, proxyManager, ec2Service, resolver, config,
new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(),
new InMemoryStorage<>(), new InMemoryStorage<>(), null, null, null,
new InMemoryStorage<>(), new InMemoryStorage<>(), optionGroups);
new InMemoryStorage<>(), new InMemoryStorage<>(), optionGroups, null);
}
private DbInstance createInstanceWithOptionGroup(
@@ -0,0 +1,118 @@
package io.github.hectorvent.floci.services.resourceexplorer2;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.github.hectorvent.floci.core.common.RegionResolver;
import io.github.hectorvent.floci.core.resource.ResourceProvider;
import io.github.hectorvent.floci.core.storage.InMemoryStorage;
import io.github.hectorvent.floci.core.storage.StorageBackend;
import io.github.hectorvent.floci.services.resourceexplorer2.model.Index;
import io.github.hectorvent.floci.services.resourceexplorer2.model.IndexState;
import io.github.hectorvent.floci.services.resourceexplorer2.model.IndexType;
import io.github.hectorvent.floci.services.resourceexplorer2.model.View;
import io.quarkus.runtime.StartupEvent;
import jakarta.enterprise.inject.Instance;
import org.junit.jupiter.api.Test;
import java.time.Instant;
import java.util.HashMap;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.mockito.Mockito.mock;
/**
* The default-view association is per-region state that must survive a process restart, the same
* way indexes and views do. These tests share the storage backends across two service instances —
* the second instance models a restart with persisted storage but fresh in-memory state.
*/
class ResourceExplorer2DefaultViewPersistenceTest {
private static final String REGION = "us-east-1";
private static final String ACCOUNT = "000000000000";
private final StorageBackend<String, Index> indexStore = new InMemoryStorage<>();
private final StorageBackend<String, View> viewStore = new InMemoryStorage<>();
private final StorageBackend<String, String> defaultViewStore = new InMemoryStorage<>();
@SuppressWarnings("unchecked")
private final Instance<ResourceProvider> providers = mock(Instance.class);
private final RegionResolver regionResolver = new RegionResolver(REGION, ACCOUNT);
private final ObjectMapper objectMapper = new ObjectMapper();
private ResourceExplorer2Service newInstance() {
return new ResourceExplorer2Service(
providers, regionResolver, objectMapper, indexStore, viewStore, defaultViewStore);
}
@Test
void userChosenDefaultViewSurvivesRestart() {
ResourceExplorer2Service before = newInstance();
before.onStartup(new StartupEvent());
String autoProvisioned = before.getDefaultView(REGION);
// Point the regional default at a custom view, distinct from the auto-provisioned one.
View custom = before.createView(REGION, "custom-view", null, null, null, null);
before.associateDefaultView(REGION, custom.viewArn());
assertNotEquals(autoProvisioned, custom.viewArn());
assertEquals(custom.viewArn(), before.getDefaultView(REGION));
// Restart: fresh instance, same persisted storage.
ResourceExplorer2Service after = newInstance();
after.onStartup(new StartupEvent());
// The association must not silently reset to the auto-provisioned default view.
assertEquals(custom.viewArn(), after.getDefaultView(REGION));
}
@Test
void disassociatedDefaultViewStaysDisassociatedAfterRestart() {
ResourceExplorer2Service before = newInstance();
before.onStartup(new StartupEvent());
before.disassociateDefaultView(REGION);
assertNull(before.getDefaultView(REGION));
ResourceExplorer2Service after = newInstance();
after.onStartup(new StartupEvent());
// No view should be re-associated by a startup guess once the user removed the default.
assertNull(after.getDefaultView(REGION));
}
@Test
void reprovisionsWhenStorageHasNoActiveDefaultRegionIndex() {
// Boot against storage that carries only a leftover DELETED index — no ACTIVE index in the
// default region, which is what a persistent/hybrid store looks like after a prior run
// created and deleted indexes. The old "provision only when the store is empty" guard
// skipped provisioning here, leaving GetIndex 404 and no default view and failing the whole
// integration suite. Startup must recover by provisioning a fresh index and default view.
String staleArn = "arn:aws:resource-explorer-2:" + REGION + ":" + ACCOUNT + ":index/stale";
indexStore.put(staleArn, new Index(staleArn, REGION, IndexType.AGGREGATOR,
IndexState.DELETED, new HashMap<>(), Instant.now()));
ResourceExplorer2Service service = newInstance();
service.onStartup(new StartupEvent());
// getIndex throws when the region has no ACTIVE index, so a non-null return proves recovery.
assertNotNull(service.getIndex(REGION));
assertNotNull(service.getDefaultView(REGION));
}
@Test
void recoversAfterInProcessStorageResetWipesIndexAndView() {
// Models a LocalStack state/reset: StorageFactory.clearAll() wipes every backend in-process
// with NO Quarkus restart, so onStartup never re-runs. RE2 must lazily re-provision on the
// next operation — otherwise GetIndex/GetDefaultView/Search fail for the whole service until
// the process restarts (this is what broke the full CI suite when a reset test ran first).
ResourceExplorer2Service service = newInstance();
service.onStartup(new StartupEvent());
indexStore.clear();
viewStore.clear();
defaultViewStore.clear();
assertNotNull(service.getIndex(REGION));
assertNotNull(service.getDefaultView(REGION));
}
}
@@ -0,0 +1,180 @@
package io.github.hectorvent.floci.services.resourceexplorer2;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import io.github.hectorvent.floci.core.common.RegionResolver;
import io.github.hectorvent.floci.core.resource.ExplorerResource;
import io.github.hectorvent.floci.core.resource.ResourceProvider;
import io.github.hectorvent.floci.core.resource.SupportedResourceType;
import io.github.hectorvent.floci.core.storage.InMemoryStorage;
import io.github.hectorvent.floci.core.storage.StorageBackend;
import io.github.hectorvent.floci.services.resourceexplorer2.model.Index;
import io.github.hectorvent.floci.services.resourceexplorer2.model.View;
import io.quarkus.runtime.StartupEvent;
import jakarta.enterprise.inject.Instance;
import org.junit.jupiter.api.Test;
import java.time.Instant;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
/**
* ListResources and Search share floci's resource pagination but differ in AWS: Search caps the total
* result set at 1000, ListResources does not. These service-level tests pin that difference with a
* provider that exposes 1500 resources.
*/
class ResourceExplorer2ListVsSearchCapTest {
private static final String REGION = "us-east-1";
private static final String ACCOUNT = "000000000000";
private static final int RESOURCE_COUNT = 1500;
private final StorageBackend<String, Index> indexStore = new InMemoryStorage<>();
private final StorageBackend<String, View> viewStore = new InMemoryStorage<>();
private final StorageBackend<String, String> defaultViewStore = new InMemoryStorage<>();
private final RegionResolver regionResolver = new RegionResolver(REGION, ACCOUNT);
private final ObjectMapper objectMapper = new ObjectMapper();
private ResourceExplorer2Service newServiceWith(int resourceCount) {
ResourceProvider provider = new ResourceProvider() {
@Override
public List<ExplorerResource> getResources() {
List<ExplorerResource> out = new ArrayList<>(resourceCount);
for (int i = 0; i < resourceCount; i++) {
out.add(new ExplorerResource(
"arn:aws:test:" + REGION + ":" + ACCOUNT + ":thing/" + i,
"test:thing", "test", REGION, ACCOUNT, Instant.now(), Map.of()));
}
return out;
}
@Override
public Set<SupportedResourceType> getSupportedResourceTypes() {
return Set.of(new SupportedResourceType("test:thing", "test", true));
}
};
@SuppressWarnings("unchecked")
Instance<ResourceProvider> providers = mock(Instance.class);
// Enhanced-for calls iterator() once per pagination call; hand back a fresh iterator each time.
when(providers.iterator()).thenAnswer(inv -> List.of(provider).iterator());
ResourceExplorer2Service service = new ResourceExplorer2Service(
providers, regionResolver, objectMapper, indexStore, viewStore, defaultViewStore);
service.onStartup(new StartupEvent());
return service;
}
@Test
void listResourcesPagesThroughAllResourcesWithNoTotalCap() {
// ListResources has no 1000-result cap (unlike Search); page until NextToken is null.
// https://docs.aws.amazon.com/resource-explorer/latest/apireference/API_ListResources.html
ResourceExplorer2Service service = newServiceWith(RESOURCE_COUNT);
Set<String> seen = new HashSet<>();
String token = null;
int pages = 0;
do {
ObjectNode r = service.listResources(null, 500, token, null, REGION);
for (JsonNode n : r.get("Resources")) {
seen.add(n.get("Arn").asText());
}
token = r.has("NextToken") ? r.get("NextToken").asText() : null;
pages++;
} while (token != null);
assertEquals(RESOURCE_COUNT, seen.size());
assertEquals(3, pages);
}
@Test
void listResourcesAtMaxPageSizeTruncatesSilentlyWithNoNextToken() {
// Documented AWS quirk: "The ListResources operation does not generate a NextToken if you set
// MaxResults to 1000." So the caller silently gets at most 1000 with no way to page further.
// https://docs.aws.amazon.com/resource-explorer/latest/apireference/API_ListResources.html
ResourceExplorer2Service service = newServiceWith(RESOURCE_COUNT);
ObjectNode r = service.listResources(null, 1000, null, null, REGION);
assertEquals(1000, r.get("Resources").size());
assertFalse(r.has("NextToken"));
}
@Test
void searchCapsTotalAtOneThousandAndReportsIncomplete() {
// Search "can return only the first 1,000 results."
// https://docs.aws.amazon.com/resource-explorer/latest/apireference/API_Search.html
ResourceExplorer2Service service = newServiceWith(RESOURCE_COUNT);
Set<String> seen = new HashSet<>();
String token = null;
boolean lastComplete = true;
int lastTotal = -1;
do {
// Empty query string matches all resources (see search()'s blank-query branch).
ObjectNode r = service.search("", null, token, null, REGION);
for (JsonNode n : r.get("Resources")) {
seen.add(n.get("Arn").asText());
}
lastComplete = r.get("Count").get("Complete").asBoolean();
lastTotal = r.get("Count").get("TotalResources").asInt();
token = r.has("NextToken") ? r.get("NextToken").asText() : null;
} while (token != null);
assertEquals(1000, seen.size());
assertFalse(lastComplete);
assertEquals(1000, lastTotal);
}
@Test
void oneThrowingProviderIsSkippedAndHealthyProvidersStillSurface() {
// Discovery aggregates every provider. A single provider blowing up (bad stored data, a bug)
// must not turn Search/ListResources into a 500 for every other service — the failing
// provider is skipped and the healthy ones still surface.
ResourceProvider healthy = new ResourceProvider() {
@Override
public List<ExplorerResource> getResources() {
return List.of(new ExplorerResource(
"arn:aws:test:" + REGION + ":" + ACCOUNT + ":thing/ok",
"test:thing", "test", REGION, ACCOUNT, Instant.now(), Map.of()));
}
@Override
public Set<SupportedResourceType> getSupportedResourceTypes() {
return Set.of(new SupportedResourceType("test:thing", "test", true));
}
};
ResourceProvider broken = new ResourceProvider() {
@Override
public List<ExplorerResource> getResources() {
throw new IllegalStateException("provider is broken");
}
@Override
public Set<SupportedResourceType> getSupportedResourceTypes() {
return Set.of();
}
};
@SuppressWarnings("unchecked")
Instance<ResourceProvider> providers = mock(Instance.class);
when(providers.iterator()).thenAnswer(inv -> List.of(broken, healthy).iterator());
ResourceExplorer2Service service = new ResourceExplorer2Service(
providers, regionResolver, objectMapper, indexStore, viewStore, defaultViewStore);
service.onStartup(new StartupEvent());
ObjectNode r = service.listResources(null, 1000, null, null, REGION);
assertEquals(1, r.get("Resources").size());
assertEquals("arn:aws:test:" + REGION + ":" + ACCOUNT + ":thing/ok",
r.get("Resources").get(0).get("Arn").asText());
}
}
@@ -0,0 +1,227 @@
package io.github.hectorvent.floci.services.resourceexplorer2;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import io.github.hectorvent.floci.core.common.RegionResolver;
import io.github.hectorvent.floci.core.resource.ExplorerResource;
import io.github.hectorvent.floci.core.resource.ResourceProvider;
import io.github.hectorvent.floci.core.resource.SupportedResourceType;
import io.github.hectorvent.floci.core.storage.InMemoryStorage;
import io.github.hectorvent.floci.core.storage.StorageBackend;
import io.github.hectorvent.floci.services.resourceexplorer2.model.Index;
import io.github.hectorvent.floci.services.resourceexplorer2.model.View;
import io.quarkus.runtime.StartupEvent;
import jakarta.enterprise.inject.Instance;
import org.junit.jupiter.api.Test;
import java.time.Instant;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.Set;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
/**
* {@code NextToken} on ListResources/Search is a bare offset, and the list it indexes into is
* rebuilt on every call by iterating {@code Instance<ResourceProvider>} and each provider's
* {@code StorageBackend.scan} — neither of which promises an order. Offset pagination is only
* well-defined over a stable order, so the service imposes one (by ARN) before slicing.
*
* <p>The provider here returns its resources in a different order on every call, which is what an
* unordered map-backed store is free to do. Without the sort the second page indexes into a
* differently arranged list and resources are silently dropped or returned twice.
*/
class ResourceExplorer2PaginationOrderingTest {
private static final String REGION = "us-east-1";
private static final String ACCOUNT = "000000000000";
private final StorageBackend<String, Index> indexStore = new InMemoryStorage<>();
private final StorageBackend<String, View> viewStore = new InMemoryStorage<>();
private final StorageBackend<String, String> defaultViewStore = new InMemoryStorage<>();
private final RegionResolver regionResolver = new RegionResolver(REGION, ACCOUNT);
private final ObjectMapper objectMapper = new ObjectMapper();
/** Zero-padded so lexical ARN order matches creation order, keeping the assertions readable. */
private static String arn(int i) {
return String.format("arn:aws:test:%s:%s:thing/%03d", REGION, ACCOUNT, i);
}
/**
* A provider whose resource set can grow between calls and whose iteration order is reshuffled
* on every call, modelling an unordered store scan.
*/
private static final class ShufflingProvider implements ResourceProvider {
private final List<String> arns = new ArrayList<>();
private final Random random = new Random(42);
void add(String resourceArn) {
arns.add(resourceArn);
}
@Override
public List<ExplorerResource> getResources() {
List<String> order = new ArrayList<>(arns);
Collections.shuffle(order, random);
List<ExplorerResource> out = new ArrayList<>(order.size());
for (String a : order) {
out.add(new ExplorerResource(a, "test:thing", "test", REGION, ACCOUNT,
Instant.now(), Map.of()));
}
return out;
}
@Override
public Set<SupportedResourceType> getSupportedResourceTypes() {
return Set.of(new SupportedResourceType("test:thing", "test", true));
}
}
private ResourceExplorer2Service newServiceWith(ResourceProvider provider) {
@SuppressWarnings("unchecked")
Instance<ResourceProvider> providers = mock(Instance.class);
when(providers.iterator()).thenAnswer(inv -> List.of(provider).iterator());
ResourceExplorer2Service service = new ResourceExplorer2Service(
providers, regionResolver, objectMapper, indexStore, viewStore, defaultViewStore);
service.onStartup(new StartupEvent());
return service;
}
private static List<String> arnsOf(ObjectNode response) {
List<String> out = new ArrayList<>();
for (JsonNode n : response.get("Resources")) {
out.add(n.get("Arn").asText());
}
return out;
}
@Test
void pagingAReshuffledResultSetReturnsEveryResourceExactlyOnce() {
ShufflingProvider provider = new ShufflingProvider();
for (int i = 0; i < 25; i++) {
provider.add(arn(i));
}
ResourceExplorer2Service service = newServiceWith(provider);
List<String> seen = new ArrayList<>();
String token = null;
do {
ObjectNode r = service.listResources(null, 5, token, null, REGION);
seen.addAll(arnsOf(r));
token = r.has("NextToken") ? r.get("NextToken").asText() : null;
} while (token != null);
// Nothing dropped, nothing repeated — and in the order the offsets assume.
List<String> expected = new ArrayList<>();
for (int i = 0; i < 25; i++) {
expected.add(arn(i));
}
assertEquals(expected, seen);
}
@Test
void searchPagesAReshuffledResultSetWithoutDropsOrDuplicates() {
ShufflingProvider provider = new ShufflingProvider();
for (int i = 0; i < 25; i++) {
provider.add(arn(i));
}
ResourceExplorer2Service service = newServiceWith(provider);
List<String> seen = new ArrayList<>();
String token = null;
do {
ObjectNode r = service.search("", 5, token, null, REGION);
seen.addAll(arnsOf(r));
token = r.has("NextToken") ? r.get("NextToken").asText() : null;
} while (token != null);
assertEquals(25, seen.size());
assertEquals(25, Set.copyOf(seen).size());
}
@Test
void resourceCreatedMidPaginationDoesNotDisturbThePagesAlreadyRead() {
ShufflingProvider provider = new ShufflingProvider();
for (int i = 0; i < 10; i++) {
provider.add(arn(i));
}
ResourceExplorer2Service service = newServiceWith(provider);
ObjectNode first = service.listResources(null, 5, null, null, REGION);
List<String> seen = new ArrayList<>(arnsOf(first));
String token = first.get("NextToken").asText();
// A resource appears between the two calls, as it would in a live emulator.
provider.add(arn(99));
do {
ObjectNode r = service.listResources(null, 5, token, null, REGION);
seen.addAll(arnsOf(r));
token = r.has("NextToken") ? r.get("NextToken").asText() : null;
} while (token != null);
// The insert sorts past the pages already read, so it is appended rather than shifting the
// offsets: every original ARN is returned once, plus the new one.
assertEquals(11, seen.size());
assertEquals(11, Set.copyOf(seen).size());
assertTrue(seen.contains(arn(99)));
for (int i = 0; i < 10; i++) {
assertTrue(seen.contains(arn(i)), "dropped " + arn(i));
}
}
@Test
void listSupportedResourceTypesPagesInAStableOrder() {
// Same offset-token mechanics, over a list built by iterating providers rather than a store.
List<ResourceProvider> providers = new ArrayList<>();
for (int i = 0; i < 12; i++) {
String type = String.format("test:type%02d", i);
providers.add(new ResourceProvider() {
@Override
public List<ExplorerResource> getResources() {
return List.of();
}
@Override
public Set<SupportedResourceType> getSupportedResourceTypes() {
return Set.of(new SupportedResourceType(type, "test", true));
}
});
}
List<ResourceProvider> shuffleSource = new ArrayList<>(providers);
Random random = new Random(7);
@SuppressWarnings("unchecked")
Instance<ResourceProvider> instance = mock(Instance.class);
when(instance.iterator()).thenAnswer(inv -> {
Collections.shuffle(shuffleSource, random);
return new ArrayList<>(shuffleSource).iterator();
});
ResourceExplorer2Service service = new ResourceExplorer2Service(
instance, regionResolver, objectMapper, indexStore, viewStore, defaultViewStore);
service.onStartup(new StartupEvent());
List<String> seen = new ArrayList<>();
String token = null;
do {
ObjectNode r = service.listSupportedResourceTypes(5, token);
for (JsonNode n : r.get("ResourceTypes")) {
seen.add(n.get("ResourceType").asText());
}
token = r.has("NextToken") ? r.get("NextToken").asText() : null;
} while (token != null);
List<String> expected = new ArrayList<>();
for (int i = 0; i < 12; i++) {
expected.add(String.format("test:type%02d", i));
}
assertEquals(expected, seen);
}
}
@@ -0,0 +1,121 @@
package io.github.hectorvent.floci.services.resourceexplorer2;
import org.junit.jupiter.api.Test;
import java.util.Base64;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* Unit tests for the pure pagination math behind ListResources/Search:
* {@link ResourceExplorer2Service#pageBounds} and
* {@link ResourceExplorer2Service#listResourcesEmitsToken}. Covers the offset clamp (live result sets
* can shrink between paginated calls), the 1000-result hard cap that real AWS enforces on Search, and
* the ListResources MaxResults=1000 no-NextToken quirk.
*/
class ResourceExplorer2PaginationTest {
private static final int CAP = ResourceExplorer2Service.MAX_RESOURCE_RESULTS;
private static String token(int offset) {
return Base64.getEncoder().encodeToString(String.valueOf(offset).getBytes());
}
@Test
void firstPageStartsAtZero() {
var b = ResourceExplorer2Service.pageBounds(50, 10, null, CAP);
assertEquals(0, b.start());
assertEquals(10, b.end());
assertEquals(50, b.total());
}
@Test
void secondPageOffsetsByToken() {
var b = ResourceExplorer2Service.pageBounds(50, 10, token(10), CAP);
assertEquals(10, b.start());
assertEquals(20, b.end());
assertEquals(50, b.total());
}
@Test
void lastPageIsPartial() {
var b = ResourceExplorer2Service.pageBounds(25, 10, token(20), CAP);
assertEquals(20, b.start());
assertEquals(25, b.end());
}
@Test
void nullMaxResultsDefaultsTo100() {
var b = ResourceExplorer2Service.pageBounds(200, null, null, CAP);
assertEquals(100, b.end());
}
@Test
void offsetBeyondSizeClampsToEmptyPageInsteadOfThrowing() {
// The live result set can shrink between calls; a stale offset must not produce
// subList(fromIndex > toIndex) which would throw and 500.
var b = ResourceExplorer2Service.pageBounds(10, 100, token(999), CAP);
assertEquals(10, b.start());
assertEquals(10, b.end());
assertEquals(0, b.end() - b.start());
}
@Test
void garbageTokenDecodesToZeroOffset() {
var b = ResourceExplorer2Service.pageBounds(50, 10, "!!!not-base64!!!", CAP);
assertEquals(0, b.start());
}
@Test
void totalIsCappedAt1000() {
var b = ResourceExplorer2Service.pageBounds(1500, 1000, null, CAP);
assertEquals(1000, b.total());
assertEquals(0, b.start());
assertEquals(1000, b.end());
}
@Test
void paginationStaysWithinTheCap() {
var b = ResourceExplorer2Service.pageBounds(1500, 100, token(950), CAP);
assertEquals(1000, b.total());
assertEquals(950, b.start());
assertEquals(1000, b.end());
}
@Test
void offsetBeyondCapClampsToEmpty() {
var b = ResourceExplorer2Service.pageBounds(1500, 100, token(1200), CAP);
assertEquals(1000, b.total());
assertEquals(1000, b.start());
assertEquals(1000, b.end());
}
@Test
void listResourcesSuppressesTokenAtMaxPageSize() {
// Documented AWS quirk: "The ListResources operation does not generate a NextToken if you set
// MaxResults to 1000."
// https://docs.aws.amazon.com/resource-explorer/latest/apireference/API_ListResources.html
assertFalse(ResourceExplorer2Service.listResourcesEmitsToken(1000, 1500, 1000));
}
@Test
void listResourcesSuppressesTokenAtMaxPageSizeRegardlessOfOffset() {
// The quirk is page-size-driven, not offset-driven: a caller who switches to MaxResults=1000
// mid-chain has the token suppressed even at a non-zero offset. The AWS docs describe the quirk
// purely in terms of MaxResults, so suppression must not depend on how far in the page starts.
// https://docs.aws.amazon.com/resource-explorer/latest/apireference/API_ListResources.html
assertFalse(ResourceExplorer2Service.listResourcesEmitsToken(1200, 1500, 1000));
}
@Test
void listResourcesEmitsTokenBelowMaxPageSizeWhenMoreRemain() {
assertTrue(ResourceExplorer2Service.listResourcesEmitsToken(500, 1500, 500));
}
@Test
void listResourcesOmitsTokenWhenResultsExhausted() {
assertFalse(ResourceExplorer2Service.listResourcesEmitsToken(1500, 1500, 500));
}
}
@@ -0,0 +1,422 @@
package io.github.hectorvent.floci.services.resourceexplorer2.query;
import org.junit.jupiter.api.Nested;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.NullAndEmptySource;
import org.junit.jupiter.params.provider.ValueSource;
import static org.junit.jupiter.api.Assertions.*;
class QueryParserTest {
@Nested
class EmptyInput {
@ParameterizedTest
@NullAndEmptySource
@ValueSource(strings = {" ", "\t"})
void emptyOrBlankReturnsEmptyQuery(String input) {
ParsedQuery query = QueryParser.parse(input);
assertTrue(query.keywords().isEmpty());
assertTrue(query.filters().isEmpty());
}
}
@Nested
class FreeFormKeywords {
@Test
void singleKeyword() {
ParsedQuery query = QueryParser.parse("ec2");
assertEquals(1, query.keywords().size());
assertEquals("ec2", query.keywords().getFirst().value());
assertFalse(query.keywords().getFirst().negated());
assertTrue(query.filters().isEmpty());
}
@Test
void multipleKeywordsAreSplitByWhitespace() {
ParsedQuery query = QueryParser.parse("ec2 billing test");
assertEquals(3, query.keywords().size());
assertEquals("ec2", query.keywords().get(0).value());
assertEquals("billing", query.keywords().get(1).value());
assertEquals("test", query.keywords().get(2).value());
}
@Test
void negatedKeyword() {
ParsedQuery query = QueryParser.parse("-forbidden");
assertEquals(1, query.keywords().size());
assertTrue(query.keywords().getFirst().negated());
assertEquals("forbidden", query.keywords().getFirst().value());
}
@Test
void quotedMultiWordKeyword() {
ParsedQuery query = QueryParser.parse("\"multi word phrase\"");
assertEquals(1, query.keywords().size());
assertEquals("multi word phrase", query.keywords().getFirst().value());
}
@Test
void negatedQuotedKeyword() {
ParsedQuery query = QueryParser.parse("-\"multi word\"");
assertEquals(1, query.keywords().size());
assertTrue(query.keywords().getFirst().negated());
assertEquals("multi word", query.keywords().getFirst().value());
}
@Test
void unknownPrefixTreatedAsKeyword() {
ParsedQuery query = QueryParser.parse("cat:blue");
assertEquals(1, query.keywords().size());
assertEquals("cat:blue", query.keywords().getFirst().value());
assertTrue(query.filters().isEmpty());
}
}
@Nested
class Filters {
@Test
void serviceFilter() {
ParsedQuery query = QueryParser.parse("service:ec2");
assertTrue(query.keywords().isEmpty());
assertEquals(1, query.filters().size());
var filter = query.filters().getFirst();
assertEquals(FilterAttribute.SERVICE, filter.attribute());
assertEquals(1, filter.values().size());
assertEquals("ec2", filter.values().getFirst().value());
assertFalse(filter.values().getFirst().prefixMatch());
assertFalse(filter.negated());
}
@Test
void regionFilter() {
ParsedQuery query = QueryParser.parse("region:us-east-1");
assertEquals(FilterAttribute.REGION, query.filters().getFirst().attribute());
assertEquals("us-east-1", query.filters().getFirst().values().getFirst().value());
}
@Test
void resourceTypeFilter() {
ParsedQuery query = QueryParser.parse("resourcetype:s3:bucket");
var filter = query.filters().getFirst();
assertEquals(FilterAttribute.RESOURCE_TYPE, filter.attribute());
assertEquals("s3:bucket", filter.values().getFirst().value());
}
@Test
void resourceTypeSupportsFilter() {
ParsedQuery query = QueryParser.parse("resourcetype.supports:tags");
assertEquals(FilterAttribute.RESOURCE_TYPE_SUPPORTS, query.filters().getFirst().attribute());
assertEquals("tags", query.filters().getFirst().values().getFirst().value());
}
@Test
void accountIdFilter() {
ParsedQuery query = QueryParser.parse("accountid:123456789012");
assertEquals(FilterAttribute.ACCOUNT_ID, query.filters().getFirst().attribute());
assertEquals("123456789012", query.filters().getFirst().values().getFirst().value());
}
@Test
void idFilterPreservesColonsInArn() {
ParsedQuery query = QueryParser.parse("id:arn:aws:s3:::my-bucket");
assertEquals(FilterAttribute.ID, query.filters().getFirst().attribute());
assertEquals("arn:aws:s3:::my-bucket", query.filters().getFirst().values().getFirst().value());
}
@Test
void tagKeyValueFilter() {
ParsedQuery query = QueryParser.parse("tag:environment=production");
assertEquals(FilterAttribute.TAG, query.filters().getFirst().attribute());
assertEquals("environment=production", query.filters().getFirst().values().getFirst().value());
}
@Test
void tagAllSpecialValue() {
ParsedQuery query = QueryParser.parse("tag:all");
assertEquals(FilterAttribute.TAG, query.filters().getFirst().attribute());
assertEquals("all", query.filters().getFirst().values().getFirst().value());
}
@Test
void tagNoneSpecialValue() {
ParsedQuery query = QueryParser.parse("tag:none");
assertEquals(FilterAttribute.TAG, query.filters().getFirst().attribute());
assertEquals("none", query.filters().getFirst().values().getFirst().value());
}
@Test
void tagKeyFilter() {
ParsedQuery query = QueryParser.parse("tag.key:environment");
assertEquals(FilterAttribute.TAG_KEY, query.filters().getFirst().attribute());
assertEquals("environment", query.filters().getFirst().values().getFirst().value());
}
@Test
void tagValueFilter() {
ParsedQuery query = QueryParser.parse("tag.value:production");
assertEquals(FilterAttribute.TAG_VALUE, query.filters().getFirst().attribute());
assertEquals("production", query.filters().getFirst().values().getFirst().value());
}
@Test
void applicationFilter() {
ParsedQuery query = QueryParser.parse("application:MyApp");
assertEquals(FilterAttribute.APPLICATION, query.filters().getFirst().attribute());
assertEquals("MyApp", query.filters().getFirst().values().getFirst().value());
}
@Test
void caseInsensitiveFilterPrefix() {
ParsedQuery query = QueryParser.parse("Service:EC2");
assertEquals(1, query.filters().size());
assertEquals(FilterAttribute.SERVICE, query.filters().getFirst().attribute());
assertEquals("EC2", query.filters().getFirst().values().getFirst().value());
}
}
@Nested
class CommaOrValues {
@Test
void twoValuesCommaOr() {
ParsedQuery query = QueryParser.parse("region:us-east-1,us-west-2");
var filter = query.filters().getFirst();
assertEquals(2, filter.values().size());
assertEquals("us-east-1", filter.values().get(0).value());
assertEquals("us-west-2", filter.values().get(1).value());
}
@Test
void threeValuesCommaOr() {
ParsedQuery query = QueryParser.parse("resourcetype:rds:db,s3:bucket,dynamodb:table");
var filter = query.filters().getFirst();
assertEquals(3, filter.values().size());
assertEquals("rds:db", filter.values().get(0).value());
assertEquals("s3:bucket", filter.values().get(1).value());
assertEquals("dynamodb:table", filter.values().get(2).value());
}
@Test
void doubleCommaProducesEmptySegment() {
ParsedQuery query = QueryParser.parse("region:us-east-1,,us-west-2");
var filter = query.filters().getFirst();
assertEquals(3, filter.values().size());
assertEquals("us-east-1", filter.values().get(0).value());
assertEquals("", filter.values().get(1).value());
assertEquals("us-west-2", filter.values().get(2).value());
}
}
@Nested
class Negation {
@Test
void negatedFilter() {
ParsedQuery query = QueryParser.parse("-service:ec2");
var filter = query.filters().getFirst();
assertTrue(filter.negated());
assertEquals(FilterAttribute.SERVICE, filter.attribute());
assertEquals("ec2", filter.values().getFirst().value());
}
@Test
void negatedFilterWithCommaOr() {
ParsedQuery query = QueryParser.parse("-region:us-east-1,us-west-2");
var filter = query.filters().getFirst();
assertTrue(filter.negated());
assertEquals(2, filter.values().size());
}
}
@Nested
class Wildcards {
@Test
void wildcardSuffix() {
ParsedQuery query = QueryParser.parse("region:us*");
var value = query.filters().getFirst().values().getFirst();
assertEquals("us", value.value());
assertTrue(value.prefixMatch());
}
@Test
void wildcardWithCommaOr() {
ParsedQuery query = QueryParser.parse("resourcetype:ec2:*,s3:bucket");
var values = query.filters().getFirst().values();
assertEquals("ec2:", values.get(0).value());
assertTrue(values.get(0).prefixMatch());
assertEquals("s3:bucket", values.get(1).value());
assertFalse(values.get(1).prefixMatch());
}
}
@Nested
class Escaping {
@Test
void escapedCommaInFilterValue() {
ParsedQuery query = QueryParser.parse("tag.key:comma\\,literal");
var filter = query.filters().getFirst();
assertEquals(1, filter.values().size());
assertEquals("comma,literal", filter.values().getFirst().value());
}
@Test
void escapedBackslash() {
ParsedQuery query = QueryParser.parse("tag.value:back\\\\slash");
assertEquals("back\\slash", query.filters().getFirst().values().getFirst().value());
}
@Test
void danglingEscapeAtEndOfInput() {
ParsedQuery query = QueryParser.parse("service:ec2\\");
assertEquals("ec2\\", query.filters().getFirst().values().getFirst().value());
}
@Test
void escapedHyphenIsAKeywordNotANegation() {
ParsedQuery query = QueryParser.parse("\"my\\-key\\-word\"");
assertEquals(1, query.keywords().size());
assertEquals("my-key-word", query.keywords().getFirst().value());
assertFalse(query.keywords().getFirst().negated());
}
@Test
void escapedWildcardIsLiteralNotAPrefixMatch() {
ParsedQuery query = QueryParser.parse("tag.value:literal\\*");
var value = query.filters().getFirst().values().getFirst();
assertEquals("literal*", value.value());
assertFalse(value.prefixMatch());
}
@Test
void escapedColonDoesNotSplitOffAFilterPrefix() {
ParsedQuery query = QueryParser.parse("not\\:a\\:filter");
assertEquals(1, query.keywords().size());
assertEquals("not:a:filter", query.keywords().getFirst().value());
assertTrue(query.filters().isEmpty());
}
@Test
void aQuotedPhraseNeutralisesEveryOperatorInside() {
// Nothing in the quotes is an operator: no negation, no comma-OR, no wildcard.
ParsedQuery query = QueryParser.parse("tag.key:\"-a,b*\"");
var filter = query.filters().getFirst();
assertFalse(filter.negated());
assertEquals(1, filter.values().size());
assertEquals("-a,b*", filter.values().getFirst().value());
assertFalse(filter.values().getFirst().prefixMatch());
}
}
@Nested
class QuotedStrings {
@Test
void quotedFilterValue() {
ParsedQuery query = QueryParser.parse("tag:\"key=value with spaces\"");
assertEquals("key=value with spaces", query.filters().getFirst().values().getFirst().value());
}
@Test
void escapedQuoteInsideQuotes() {
ParsedQuery query = QueryParser.parse("\"escaped \\\"inner\\\" quote\"");
assertEquals("escaped \"inner\" quote", query.keywords().getFirst().value());
}
@Test
void emptyQuotedStringAsToken() {
ParsedQuery query = QueryParser.parse("service:ec2 \"\" region:us-east-1");
assertEquals(2, query.filters().size());
assertEquals(1, query.keywords().size());
assertEquals("", query.keywords().getFirst().value());
}
}
@Nested
class Combined {
@Test
void keywordsAndFilters() {
ParsedQuery query = QueryParser.parse("test instance service:EC2 region:us-west-2");
assertEquals(2, query.keywords().size());
assertEquals("test", query.keywords().get(0).value());
assertEquals("instance", query.keywords().get(1).value());
assertEquals(2, query.filters().size());
}
@Test
void awsDocExample() {
ParsedQuery query = QueryParser.parse("region:us* service:ec2 -tag:stage=prod");
assertEquals(0, query.keywords().size());
assertEquals(3, query.filters().size());
var regionFilter = query.filters().stream()
.filter(f -> f.attribute() == FilterAttribute.REGION).findFirst().orElseThrow();
assertTrue(regionFilter.values().getFirst().prefixMatch());
assertEquals("us", regionFilter.values().getFirst().value());
assertFalse(regionFilter.negated());
var serviceFilter = query.filters().stream()
.filter(f -> f.attribute() == FilterAttribute.SERVICE).findFirst().orElseThrow();
assertEquals("ec2", serviceFilter.values().getFirst().value());
var tagFilter = query.filters().stream()
.filter(f -> f.attribute() == FilterAttribute.TAG).findFirst().orElseThrow();
assertTrue(tagFilter.negated());
assertEquals("stage=prod", tagFilter.values().getFirst().value());
}
@Test
void multipleSpacesBetweenTokens() {
ParsedQuery query = QueryParser.parse("service:ec2 region:us-east-1");
assertEquals(2, query.filters().size());
}
@Test
void trailingWhitespace() {
ParsedQuery query = QueryParser.parse("service:ec2 ");
assertEquals(1, query.filters().size());
}
}
@Nested
class FilterWithEmptyValue {
@Test
void filterPrefixWithNoValue() {
ParsedQuery query = QueryParser.parse("service:");
assertEquals(1, query.filters().size());
assertEquals(1, query.filters().getFirst().values().size());
assertEquals("", query.filters().getFirst().values().getFirst().value());
}
}
@Nested
class ListResourcesMode {
@Test
void rejectsFreeFormTextInFilterOnlyMode() {
assertThrows(IllegalArgumentException.class,
() -> QueryParser.parseFilterOnly("hello world"));
}
@Test
void acceptsFiltersInFilterOnlyMode() {
ParsedQuery query = QueryParser.parseFilterOnly("service:ec2 region:us-east-1");
assertEquals(2, query.filters().size());
assertTrue(query.keywords().isEmpty());
}
@Test
void emptyStringAllowedInFilterOnlyMode() {
ParsedQuery query = QueryParser.parseFilterOnly("");
assertTrue(query.filters().isEmpty());
}
}
}
@@ -0,0 +1,309 @@
package io.github.hectorvent.floci.services.resourceexplorer2.query;
import io.github.hectorvent.floci.core.resource.ExplorerResource;
import org.junit.jupiter.api.Nested;
import org.junit.jupiter.api.Test;
import java.time.Instant;
import java.util.Map;
import java.util.Set;
import static org.junit.jupiter.api.Assertions.*;
class ResourceFilterTest {
private static final Instant NOW = Instant.now();
/** Every type these fixtures use is taggable, as it is for every provider floci ships. */
private static final Set<String> TAGGABLE_TYPES =
Set.of("s3:bucket", "rds:db", "dynamodb:table");
private static ExplorerResource resource(String arn, String resourceType, String service,
String region, String accountId, Map<String, String> tags) {
return new ExplorerResource(arn, resourceType, service, region, accountId, NOW, tags);
}
private static final ExplorerResource S3_BUCKET = resource(
"arn:aws:s3:::my-bucket", "s3:bucket", "s3", "us-east-1", "123456789012",
Map.of("env", "prod", "team", "platform"));
private static final ExplorerResource RDS_INSTANCE = resource(
"arn:aws:rds:us-west-2:123456789012:db:orders-db", "rds:db", "rds", "us-west-2", "123456789012",
Map.of());
private static final ExplorerResource DYNAMO_TABLE = resource(
"arn:aws:dynamodb:us-east-1:999999999999:table/users", "dynamodb:table", "dynamodb", "us-east-1", "999999999999",
Map.of("env", "staging"));
@Nested
class EmptyQuery {
@Test
void emptyQueryMatchesEverything() {
ParsedQuery query = QueryParser.parse("");
assertTrue(ResourceFilter.matches(S3_BUCKET, query, TAGGABLE_TYPES));
assertTrue(ResourceFilter.matches(RDS_INSTANCE, query, TAGGABLE_TYPES));
}
}
@Nested
class RegionFilter {
@Test
void exactRegionMatch() {
ParsedQuery query = QueryParser.parse("region:us-east-1");
assertTrue(ResourceFilter.matches(S3_BUCKET, query, TAGGABLE_TYPES));
assertFalse(ResourceFilter.matches(RDS_INSTANCE, query, TAGGABLE_TYPES));
}
@Test
void regionWildcard() {
ParsedQuery query = QueryParser.parse("region:us*");
assertTrue(ResourceFilter.matches(S3_BUCKET, query, TAGGABLE_TYPES));
assertTrue(ResourceFilter.matches(RDS_INSTANCE, query, TAGGABLE_TYPES));
}
@Test
void regionWildcardNoMatch() {
ParsedQuery query = QueryParser.parse("region:eu*");
assertFalse(ResourceFilter.matches(S3_BUCKET, query, TAGGABLE_TYPES));
}
}
@Nested
class ServiceFilter {
@Test
void exactServiceMatch() {
ParsedQuery query = QueryParser.parse("service:s3");
assertTrue(ResourceFilter.matches(S3_BUCKET, query, TAGGABLE_TYPES));
assertFalse(ResourceFilter.matches(RDS_INSTANCE, query, TAGGABLE_TYPES));
}
@Test
void caseInsensitive() {
ParsedQuery query = QueryParser.parse("service:S3");
assertTrue(ResourceFilter.matches(S3_BUCKET, query, TAGGABLE_TYPES));
}
}
@Nested
class ResourceTypeFilter {
@Test
void exactResourceTypeMatch() {
ParsedQuery query = QueryParser.parse("resourcetype:rds:db");
assertFalse(ResourceFilter.matches(S3_BUCKET, query, TAGGABLE_TYPES));
assertTrue(ResourceFilter.matches(RDS_INSTANCE, query, TAGGABLE_TYPES));
}
@Test
void commaOrResourceType() {
ParsedQuery query = QueryParser.parse("resourcetype:rds:db,s3:bucket");
assertTrue(ResourceFilter.matches(S3_BUCKET, query, TAGGABLE_TYPES));
assertTrue(ResourceFilter.matches(RDS_INSTANCE, query, TAGGABLE_TYPES));
assertFalse(ResourceFilter.matches(DYNAMO_TABLE, query, TAGGABLE_TYPES));
}
@Test
void wildcardResourceType() {
ParsedQuery query = QueryParser.parse("resourcetype:rds:*");
assertTrue(ResourceFilter.matches(RDS_INSTANCE, query, TAGGABLE_TYPES));
assertFalse(ResourceFilter.matches(S3_BUCKET, query, TAGGABLE_TYPES));
}
}
@Nested
class TagFilters {
@Test
void tagKeyValue() {
ParsedQuery query = QueryParser.parse("tag:env=prod");
assertTrue(ResourceFilter.matches(S3_BUCKET, query, TAGGABLE_TYPES));
assertFalse(ResourceFilter.matches(RDS_INSTANCE, query, TAGGABLE_TYPES));
assertFalse(ResourceFilter.matches(DYNAMO_TABLE, query, TAGGABLE_TYPES));
}
@Test
void tagKeyOnly() {
ParsedQuery query = QueryParser.parse("tag.key:env");
assertTrue(ResourceFilter.matches(S3_BUCKET, query, TAGGABLE_TYPES));
assertFalse(ResourceFilter.matches(RDS_INSTANCE, query, TAGGABLE_TYPES));
assertTrue(ResourceFilter.matches(DYNAMO_TABLE, query, TAGGABLE_TYPES));
}
@Test
void tagValueOnly() {
ParsedQuery query = QueryParser.parse("tag.value:prod");
assertTrue(ResourceFilter.matches(S3_BUCKET, query, TAGGABLE_TYPES));
assertFalse(ResourceFilter.matches(DYNAMO_TABLE, query, TAGGABLE_TYPES));
}
@Test
void tagAll() {
ParsedQuery query = QueryParser.parse("tag:all");
assertTrue(ResourceFilter.matches(S3_BUCKET, query, TAGGABLE_TYPES));
assertFalse(ResourceFilter.matches(RDS_INSTANCE, query, TAGGABLE_TYPES));
}
@Test
void tagNone() {
ParsedQuery query = QueryParser.parse("tag:none");
assertFalse(ResourceFilter.matches(S3_BUCKET, query, TAGGABLE_TYPES));
assertTrue(ResourceFilter.matches(RDS_INSTANCE, query, TAGGABLE_TYPES));
}
}
@Nested
class NegationFilter {
@Test
void negatedServiceExcludes() {
ParsedQuery query = QueryParser.parse("-service:s3");
assertFalse(ResourceFilter.matches(S3_BUCKET, query, TAGGABLE_TYPES));
assertTrue(ResourceFilter.matches(RDS_INSTANCE, query, TAGGABLE_TYPES));
}
}
@Nested
class KeywordFilter {
@Test
void positiveKeywordMatchingArnNarrowsResults() {
// "orders-db" appears in RDS_INSTANCE arn; S3_BUCKET and DYNAMO_TABLE should be excluded
ParsedQuery query = QueryParser.parse("orders-db");
assertFalse(ResourceFilter.matches(S3_BUCKET, query, TAGGABLE_TYPES));
assertTrue(ResourceFilter.matches(RDS_INSTANCE, query, TAGGABLE_TYPES));
assertFalse(ResourceFilter.matches(DYNAMO_TABLE, query, TAGGABLE_TYPES));
}
@Test
void positiveKeywordMatchingServiceNarrowsResults() {
// "dynamodb" appears in DYNAMO_TABLE service; other resources should be excluded
ParsedQuery query = QueryParser.parse("dynamodb");
assertFalse(ResourceFilter.matches(S3_BUCKET, query, TAGGABLE_TYPES));
assertFalse(ResourceFilter.matches(RDS_INSTANCE, query, TAGGABLE_TYPES));
assertTrue(ResourceFilter.matches(DYNAMO_TABLE, query, TAGGABLE_TYPES));
}
@Test
void positiveKeywordMatchingRegionNarrowsResults() {
// "us-east-1" appears in region of S3_BUCKET and DYNAMO_TABLE
ParsedQuery query = QueryParser.parse("us-east-1");
assertTrue(ResourceFilter.matches(S3_BUCKET, query, TAGGABLE_TYPES));
assertFalse(ResourceFilter.matches(RDS_INSTANCE, query, TAGGABLE_TYPES));
assertTrue(ResourceFilter.matches(DYNAMO_TABLE, query, TAGGABLE_TYPES));
}
@Test
void positiveKeywordMatchingNothingReturnsEmpty() {
ParsedQuery query = QueryParser.parse("xyzzy-no-such-resource");
assertFalse(ResourceFilter.matches(S3_BUCKET, query, TAGGABLE_TYPES));
assertFalse(ResourceFilter.matches(RDS_INSTANCE, query, TAGGABLE_TYPES));
assertFalse(ResourceFilter.matches(DYNAMO_TABLE, query, TAGGABLE_TYPES));
}
@Test
void positiveKeywordIsCaseInsensitive() {
ParsedQuery query = QueryParser.parse("DYNAMODB");
assertFalse(ResourceFilter.matches(S3_BUCKET, query, TAGGABLE_TYPES));
assertFalse(ResourceFilter.matches(RDS_INSTANCE, query, TAGGABLE_TYPES));
assertTrue(ResourceFilter.matches(DYNAMO_TABLE, query, TAGGABLE_TYPES));
}
@Test
void negatedKeywordStillExcludes() {
// regression guard: negated keyword excludes matching resources
ParsedQuery query = QueryParser.parse("-dynamodb");
assertTrue(ResourceFilter.matches(S3_BUCKET, query, TAGGABLE_TYPES));
assertTrue(ResourceFilter.matches(RDS_INSTANCE, query, TAGGABLE_TYPES));
assertFalse(ResourceFilter.matches(DYNAMO_TABLE, query, TAGGABLE_TYPES));
}
@Test
void positiveKeywordAndAttributeFilterAreAnded() {
// "us-east-1" matches S3_BUCKET and DYNAMO_TABLE by region keyword,
// but service:s3 further restricts to only S3_BUCKET
ParsedQuery query = QueryParser.parse("us-east-1 service:s3");
assertTrue(ResourceFilter.matches(S3_BUCKET, query, TAGGABLE_TYPES));
assertFalse(ResourceFilter.matches(RDS_INSTANCE, query, TAGGABLE_TYPES));
assertFalse(ResourceFilter.matches(DYNAMO_TABLE, query, TAGGABLE_TYPES));
}
@Test
void multiplePositiveKeywordsAreOred() {
// AWS reads "s3 us-east-1" as "s3 OR us-east-1", so a resource matching either
// qualifies: the bucket on both counts, the Dynamo table on its Region alone.
ParsedQuery query = QueryParser.parse("s3 us-east-1");
assertTrue(ResourceFilter.matches(S3_BUCKET, query, TAGGABLE_TYPES));
assertTrue(ResourceFilter.matches(DYNAMO_TABLE, query, TAGGABLE_TYPES));
assertFalse(ResourceFilter.matches(RDS_INSTANCE, query, TAGGABLE_TYPES));
}
@Test
void keywordMatchesATagKeyOrValue() {
assertTrue(ResourceFilter.matches(S3_BUCKET, QueryParser.parse("platform"), TAGGABLE_TYPES));
assertFalse(ResourceFilter.matches(RDS_INSTANCE, QueryParser.parse("platform"), TAGGABLE_TYPES));
}
@Test
void negatedKeywordExcludesEvenWhenAPositiveOneMatches() {
ParsedQuery query = QueryParser.parse("us-east-1 -s3");
assertFalse(ResourceFilter.matches(S3_BUCKET, query, TAGGABLE_TYPES));
assertTrue(ResourceFilter.matches(DYNAMO_TABLE, query, TAGGABLE_TYPES));
}
}
@Nested
class AndSemantics {
@Test
void multipleFiltersMustAllMatch() {
ParsedQuery query = QueryParser.parse("service:s3 region:us-east-1");
assertTrue(ResourceFilter.matches(S3_BUCKET, query, TAGGABLE_TYPES));
assertFalse(ResourceFilter.matches(RDS_INSTANCE, query, TAGGABLE_TYPES));
}
@Test
void filterAndNegation() {
ParsedQuery query = QueryParser.parse("region:us-east-1 -service:dynamodb");
assertTrue(ResourceFilter.matches(S3_BUCKET, query, TAGGABLE_TYPES));
assertFalse(ResourceFilter.matches(DYNAMO_TABLE, query, TAGGABLE_TYPES));
}
}
@Nested
class AccountIdFilter {
@Test
void matchesAccountId() {
ParsedQuery query = QueryParser.parse("accountid:123456789012");
assertTrue(ResourceFilter.matches(S3_BUCKET, query, TAGGABLE_TYPES));
assertFalse(ResourceFilter.matches(DYNAMO_TABLE, query, TAGGABLE_TYPES));
}
}
@Nested
class IdFilter {
@Test
void matchesExactArn() {
ParsedQuery query = QueryParser.parse("id:arn:aws:s3:::my-bucket");
assertTrue(ResourceFilter.matches(S3_BUCKET, query, TAGGABLE_TYPES));
assertFalse(ResourceFilter.matches(RDS_INSTANCE, query, TAGGABLE_TYPES));
}
}
@Nested
class ViewFilterMerging {
@Test
void viewFilterAndRequestFilterAnded() {
ParsedQuery viewFilter = QueryParser.parse("service:s3");
ParsedQuery requestFilter = QueryParser.parse("region:us-east-1");
ParsedQuery combined = ResourceFilter.combine(viewFilter, requestFilter);
assertTrue(ResourceFilter.matches(S3_BUCKET, combined, TAGGABLE_TYPES));
assertFalse(ResourceFilter.matches(RDS_INSTANCE, combined, TAGGABLE_TYPES));
}
}
}
@@ -0,0 +1,143 @@
package io.github.hectorvent.floci.services.rum;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import io.github.hectorvent.floci.core.common.RegionResolver;
import io.github.hectorvent.floci.core.resource.ExplorerResource;
import io.github.hectorvent.floci.core.resource.SupportedResourceType;
import io.github.hectorvent.floci.core.storage.InMemoryStorage;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Nested;
import org.junit.jupiter.api.Test;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
class RumResourceProviderTest {
private static final String REGION = "us-east-1";
private static final String ACCOUNT = "000000000000";
private final ObjectMapper mapper = new ObjectMapper();
private RumService service;
@BeforeEach
void setUp() {
service = new RumService(new InMemoryStorage<>(), new RegionResolver(REGION, ACCOUNT));
}
private ObjectNode monitorRequest(String name, String domain) {
return mapper.createObjectNode().put("Name", name).put("Domain", domain);
}
@Nested
class GetResources {
@Test
void emptyWhenNothingStored() {
assertTrue(service.getResources().isEmpty());
}
@Test
void surfacesAppMonitorWithArnTypeRegionAccountAndTags() {
ObjectNode request = monitorRequest("web", "example.com");
request.set("Tags", mapper.createObjectNode().put("env", "prod"));
service.createAppMonitor(REGION, request);
ExplorerResource monitor = only(service.getResources(), "rum:appmonitor");
assertEquals("arn:aws:rum:" + REGION + ":" + ACCOUNT + ":appmonitor/web", monitor.arn());
assertEquals("rum", monitor.service());
assertEquals(REGION, monitor.region());
assertEquals(ACCOUNT, monitor.owningAccountId());
assertEquals(Map.of("env", "prod"), monitor.tags());
}
@Test
void surfacesMonitorsFromMultipleRegions() {
service.createAppMonitor(REGION, monitorRequest("east", "example.com"));
service.createAppMonitor("eu-west-1", monitorRequest("west", "example.com"));
Map<String, String> arnsByType = service.getResources().stream()
.collect(Collectors.toMap(ExplorerResource::region, ExplorerResource::arn));
assertEquals("arn:aws:rum:us-east-1:" + ACCOUNT + ":appmonitor/east",
arnsByType.get("us-east-1"));
assertEquals("arn:aws:rum:eu-west-1:" + ACCOUNT + ":appmonitor/west",
arnsByType.get("eu-west-1"));
}
@Test
void resourceWithoutTagsYieldsEmptyMapNotNull() {
service.createAppMonitor(REGION, monitorRequest("web", "example.com"));
ExplorerResource monitor = only(service.getResources(), "rum:appmonitor");
assertEquals(Map.of(), monitor.tags());
}
@Test
void reportsOwnerAccountCapturedAtCreationNotTheQueryingCaller() {
MutableAccountResolver resolver = new MutableAccountResolver();
RumService svc = new RumService(new InMemoryStorage<>(), resolver);
resolver.accountId = "111111111111";
svc.createAppMonitor(REGION, monitorRequest("web", "example.com"));
// A later ListResources arrives under a different principal.
resolver.accountId = "999999999999";
ExplorerResource monitor = only(svc.getResources(), "rum:appmonitor");
assertEquals("111111111111", monitor.owningAccountId());
assertEquals("arn:aws:rum:" + REGION + ":111111111111:appmonitor/web", monitor.arn());
}
@Test
void updateKeepsTheOwnerAccountCapturedAtCreation() {
MutableAccountResolver resolver = new MutableAccountResolver();
RumService svc = new RumService(new InMemoryStorage<>(), resolver);
resolver.accountId = "111111111111";
svc.createAppMonitor(REGION, monitorRequest("web", "example.com"));
svc.updateAppMonitor(REGION, "web", monitorRequest("web", "updated.example.com"));
resolver.accountId = "999999999999";
ExplorerResource monitor = only(svc.getResources(), "rum:appmonitor");
assertEquals("111111111111", monitor.owningAccountId());
assertEquals("arn:aws:rum:" + REGION + ":111111111111:appmonitor/web", monitor.arn());
}
}
private static final class MutableAccountResolver extends RegionResolver {
private String accountId = ACCOUNT;
MutableAccountResolver() {
super(REGION, ACCOUNT);
}
@Override
public String getAccountId() {
return accountId;
}
}
@Nested
class GetSupportedResourceTypes {
@Test
void advertisesAppMonitorTypeUnderRumService() {
Set<SupportedResourceType> types = service.getSupportedResourceTypes();
assertEquals(Set.of("rum:appmonitor"),
types.stream().map(SupportedResourceType::resourceType).collect(Collectors.toSet()));
assertTrue(types.stream().allMatch(t -> t.service().equals("rum")));
assertTrue(types.stream().allMatch(SupportedResourceType::supportsTags));
}
}
private static ExplorerResource only(List<ExplorerResource> resources, String resourceType) {
return resources.stream()
.filter(r -> r.resourceType().equals(resourceType))
.reduce((a, b) -> { throw new AssertionError("expected exactly one " + resourceType); })
.orElseThrow(() -> new AssertionError("no " + resourceType + " resource"));
}
}
@@ -4,6 +4,7 @@ import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.common.RegionResolver;
import io.github.hectorvent.floci.core.storage.InMemoryStorage;
import io.github.hectorvent.floci.core.storage.PersistentStorage;
import io.github.hectorvent.floci.services.rum.model.AppMonitor;
@@ -23,8 +24,21 @@ import static org.junit.jupiter.api.Assertions.assertTrue;
class RumServiceTest {
private static final String REGION = "us-east-1";
private static final RegionResolver REGION_RESOLVER = new RegionResolver(REGION, "000000000000");
private final ObjectMapper objectMapper = new ObjectMapper();
private final RumService service = new RumService(new InMemoryStorage<>());
private final RumService service = new RumService(new InMemoryStorage<>(), REGION_RESOLVER);
@Test
void ownerAccountIsCapturedButNeverSerializedIntoTheApiBody() {
AppMonitor monitor = service.createAppMonitor(REGION,
objectMapper.createObjectNode().put("Name", "monitor").put("Domain", "example.com"));
assertEquals("000000000000", monitor.getOwnerAccountId());
JsonNode serialized = objectMapper.valueToTree(monitor);
serialized.fieldNames().forEachRemaining(field ->
assertTrue(!field.toLowerCase().contains("account"),
"GetAppMonitor body must not expose the owner account: " + serialized));
}
@Test
void updateAppMonitorAtomicallyReplacesTheStoredSnapshot() throws Exception {
@@ -181,7 +195,7 @@ class RumServiceTest {
file, new TypeReference<Map<String, AppMonitor>>() {
});
firstStore.load();
RumService firstService = new RumService(firstStore);
RumService firstService = new RumService(firstStore, REGION_RESOLVER);
AppMonitor created = firstService.createAppMonitor(REGION, request("""
{
"Name":"persistent-monitor",
@@ -196,7 +210,7 @@ class RumServiceTest {
file, new TypeReference<Map<String, AppMonitor>>() {
});
reloadedStore.load();
AppMonitor reloaded = new RumService(reloadedStore).getAppMonitor(REGION, "persistent-monitor");
AppMonitor reloaded = new RumService(reloadedStore, REGION_RESOLVER).getAppMonitor(REGION, "persistent-monitor");
assertEquals(created.getId(), reloaded.getId());
assertEquals(created.getCreated(), reloaded.getCreated());