mirror of
https://github.com/floci-io/floci.git
synced 2026-11-23 14:10:49 -05:00
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:
86 files changed
+8562
-69
No files matched your search
@@ -226,7 +226,7 @@ Floci supports local emulation for application services, data services, eventing
|
||||
| Data, analytics, and AI | Athena, Glue, EMR, Firehose, Managed Service for Apache Flink, OpenSearch, S3 Tables, S3 Vectors, Textract, Transcribe, Bedrock Runtime, Bedrock AgentCore |
|
||||
| Databases and caching | RDS, RDS Data API, Neptune, DocumentDB, MemoryDB, ElastiCache |
|
||||
| Messaging and transfer | SES, Kinesis, MSK, Amazon MQ, Transfer Family, IoT Core |
|
||||
| Security and governance | WAF v2, CloudTrail, CloudFront, Resource Groups Tagging API, CloudHSM v2, Organizations |
|
||||
| Security and governance | WAF v2, CloudTrail, CloudFront, Resource Groups Tagging API, Resource Explorer 2, CloudHSM v2, Organizations |
|
||||
| Cost and billing | Pricing, Cost Explorer, Cost and Usage Reports, BCM Data Exports |
|
||||
| Resilience, backup, and config | AWS FIS, AWS Backup, AWS Config, AppConfig, AppConfigData, CloudFormation, Cloud Control API |
|
||||
|
||||
@@ -302,6 +302,7 @@ For operation-level compatibility, see the [Services Overview](https://floci.io/
|
||||
| CloudTrail | In-process | Trails, event selectors (S3 data events with bucket/prefix matching), `StartLogging`/`StopLogging`, scheduled gzipped log file emission to the destination bucket at AWS-shaped key paths, IAM-deny path emits `AccessDenied` records |
|
||||
| CloudFront | In-process | Distributions, origins, cache behaviors, invalidations, tagging |
|
||||
| WAF v2 | In-process | Web ACLs, IP sets, regex pattern sets, rule groups, logging configs, resource associations, tagging (REGIONAL and CLOUDFRONT scopes) |
|
||||
| Resource Explorer 2 | In-process | All 32 management APIs — index and view lifecycle, multi-Region setup tasks, the full search query grammar, and tagging; 30 services expose their resources for search, gathered live rather than from an index |
|
||||
| Route53 | In-process | Hosted zones, SOA and NS records, resource record sets, change tracking, tagging |
|
||||
| Cloud Map | In-process | HTTP and DNS namespaces, services, instance registration, discovery queries, operations, tagging |
|
||||
| Transfer Family | In-process | Server lifecycle, user management, SSH key import, tagging |
|
||||
|
||||
@@ -383,6 +383,20 @@
|
||||
<groupId>software.amazon.awssdk</groupId>
|
||||
<artifactId>backup</artifactId>
|
||||
</dependency>
|
||||
<!-- Resource Explorer 2 client -->
|
||||
<dependency>
|
||||
<groupId>software.amazon.awssdk</groupId>
|
||||
<artifactId>resourceexplorer2</artifactId>
|
||||
</dependency>
|
||||
<!-- SSO credential support (needed for FLOCI_TARGET=aws with SSO profiles) -->
|
||||
<dependency>
|
||||
<groupId>software.amazon.awssdk</groupId>
|
||||
<artifactId>sso</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>software.amazon.awssdk</groupId>
|
||||
<artifactId>ssooidc</artifactId>
|
||||
</dependency>
|
||||
<!-- AppSync client -->
|
||||
<dependency>
|
||||
<groupId>software.amazon.awssdk</groupId>
|
||||
|
||||
@@ -30,6 +30,7 @@ import software.amazon.awssdk.services.guardduty.GuardDutyClient;
|
||||
import software.amazon.awssdk.services.fis.FisClient;
|
||||
import software.amazon.awssdk.services.organizations.OrganizationsClient;
|
||||
import software.amazon.awssdk.services.rum.RumClient;
|
||||
import software.amazon.awssdk.services.resourceexplorer2.ResourceExplorer2Client;
|
||||
import software.amazon.awssdk.services.s3.S3Client;
|
||||
import software.amazon.awssdk.endpoints.Endpoint;
|
||||
import software.amazon.awssdk.services.s3control.S3ControlClient;
|
||||
@@ -955,6 +956,23 @@ public final class TestFixtures {
|
||||
.build();
|
||||
}
|
||||
|
||||
public static ResourceExplorer2Client resourceExplorer2Client() {
|
||||
return resourceExplorer2Client(REGION);
|
||||
}
|
||||
|
||||
/**
|
||||
* Resource Explorer 2 client bound to an explicit region. The emulator auto-provisions an
|
||||
* index only in the default region, so CreateIndex/DeleteIndex tests use a different region
|
||||
* to exercise a real create against a region that starts with no index.
|
||||
*/
|
||||
public static ResourceExplorer2Client resourceExplorer2Client(Region region) {
|
||||
var builder = ResourceExplorer2Client.builder().region(region);
|
||||
if (!isRealAws()) {
|
||||
builder.endpointOverride(ENDPOINT).credentialsProvider(CREDENTIALS);
|
||||
}
|
||||
return builder.build();
|
||||
}
|
||||
|
||||
public static AppSyncClient appSyncClient() {
|
||||
return AppSyncClient.builder()
|
||||
.endpointOverride(ENDPOINT)
|
||||
|
||||
+593
@@ -0,0 +1,593 @@
|
||||
package com.floci.test;
|
||||
|
||||
import org.junit.jupiter.api.*;
|
||||
import org.junit.jupiter.api.condition.EnabledIf;
|
||||
import software.amazon.awssdk.regions.Region;
|
||||
import software.amazon.awssdk.services.resourceexplorer2.ResourceExplorer2Client;
|
||||
import software.amazon.awssdk.services.resourceexplorer2.model.*;
|
||||
import software.amazon.awssdk.services.s3.S3Client;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.assertj.core.api.Assertions.assertThatThrownBy;
|
||||
import static org.junit.jupiter.api.Assumptions.assumeFalse;
|
||||
import static org.junit.jupiter.api.Assumptions.assumeTrue;
|
||||
|
||||
/**
|
||||
* SDK compatibility tests for Resource Explorer 2.
|
||||
*
|
||||
* <p>Every test deserializes the response through the real AWS SDK and asserts
|
||||
* on EVERY field. If the wire format is wrong (wrong casing, wrong structure,
|
||||
* missing fields), the SDK will return null for that field and the test fails.
|
||||
*
|
||||
* <p>This is the safety net that prevents wire format regressions.
|
||||
*/
|
||||
@DisplayName("Resource Explorer 2")
|
||||
@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
|
||||
class ResourceExplorer2Test {
|
||||
|
||||
private static ResourceExplorer2Client client;
|
||||
// The emulator auto-provisions an index only in the default region (us-east-1). CreateIndex
|
||||
// there is a no-op/conflict, so index create+delete is exercised against a second region
|
||||
// that starts with no index, matching AWS's one-index-per-region rule.
|
||||
private static ResourceExplorer2Client altRegionClient;
|
||||
private static S3Client s3;
|
||||
|
||||
private static String defaultViewArn;
|
||||
private static String autoProvisionedIndexArn;
|
||||
private static String createdViewArn;
|
||||
private static String createdIndexArn;
|
||||
|
||||
@BeforeAll
|
||||
static void setup() {
|
||||
client = TestFixtures.resourceExplorer2Client();
|
||||
altRegionClient = TestFixtures.resourceExplorer2Client(Region.US_WEST_2);
|
||||
s3 = TestFixtures.s3Client();
|
||||
}
|
||||
|
||||
@AfterAll
|
||||
static void cleanup() {
|
||||
if (client != null) {
|
||||
client.close();
|
||||
}
|
||||
if (altRegionClient != null) {
|
||||
altRegionClient.close();
|
||||
}
|
||||
if (s3 != null) {
|
||||
s3.close();
|
||||
}
|
||||
}
|
||||
|
||||
// -----------------------------------------------------------------------
|
||||
// GetIndex — every field must deserialize
|
||||
// -----------------------------------------------------------------------
|
||||
|
||||
@Test
|
||||
@Order(1)
|
||||
void getIndexDeserializesAllFields() {
|
||||
GetIndexResponse response = client.getIndex(GetIndexRequest.builder().build());
|
||||
|
||||
// Every field the SDK model exposes must be non-null and correctly typed
|
||||
assertThat(response.arn()).as("GetIndex.Arn").isNotBlank();
|
||||
assertThat(response.type()).as("GetIndex.Type").isNotNull();
|
||||
assertThat(response.type()).isIn(IndexType.LOCAL, IndexType.AGGREGATOR);
|
||||
assertThat(response.state()).as("GetIndex.State").isNotNull();
|
||||
assertThat(response.state()).isEqualTo(IndexState.ACTIVE);
|
||||
assertThat(response.createdAt()).as("GetIndex.CreatedAt").isNotNull();
|
||||
assertThat(response.lastUpdatedAt()).as("GetIndex.LastUpdatedAt").isNotNull();
|
||||
assertThat(response.tags()).as("GetIndex.Tags").isNotNull();
|
||||
assertThat(response.replicatingFrom()).as("GetIndex.ReplicatingFrom").isNotNull();
|
||||
assertThat(response.replicatingTo()).as("GetIndex.ReplicatingTo").isNotNull();
|
||||
|
||||
autoProvisionedIndexArn = response.arn();
|
||||
}
|
||||
|
||||
// -----------------------------------------------------------------------
|
||||
// GetDefaultView
|
||||
// -----------------------------------------------------------------------
|
||||
|
||||
@Test
|
||||
@Order(2)
|
||||
void getDefaultViewReturnsViewArn() {
|
||||
GetDefaultViewResponse response = client.getDefaultView(GetDefaultViewRequest.builder().build());
|
||||
assertThat(response.viewArn()).as("GetDefaultView.ViewArn").isNotBlank();
|
||||
defaultViewArn = response.viewArn();
|
||||
}
|
||||
|
||||
// -----------------------------------------------------------------------
|
||||
// GetView — every field of the View object
|
||||
// -----------------------------------------------------------------------
|
||||
|
||||
@Test
|
||||
@Order(3)
|
||||
void getViewDeserializesAllFields() {
|
||||
GetViewResponse response = client.getView(GetViewRequest.builder()
|
||||
.viewArn(defaultViewArn).build());
|
||||
View view = response.view();
|
||||
|
||||
assertThat(view).as("GetView.View").isNotNull();
|
||||
assertThat(view.viewArn()).as("View.ViewArn").isEqualTo(defaultViewArn);
|
||||
assertThat(view.viewName()).as("View.ViewName").isNotBlank();
|
||||
assertThat(view.owner()).as("View.Owner").isNotBlank();
|
||||
assertThat(view.scope()).as("View.Scope").isNotBlank();
|
||||
assertThat(view.lastUpdatedAt()).as("View.LastUpdatedAt").isNotNull();
|
||||
assertThat(view.includedProperties()).as("View.IncludedProperties").isNotNull();
|
||||
assertThat(view.filters()).as("View.Filters").isNotNull();
|
||||
assertThat(view.filters().filterString()).as("View.Filters.FilterString").isNotNull();
|
||||
|
||||
// GetViewResponse has root-level Tags (separate from View)
|
||||
assertThat(response.tags()).as("GetViewResponse.Tags").isNotNull();
|
||||
}
|
||||
|
||||
// -----------------------------------------------------------------------
|
||||
// ListSupportedResourceTypes — field-level assertions
|
||||
// -----------------------------------------------------------------------
|
||||
|
||||
@Test
|
||||
@Order(4)
|
||||
void listSupportedResourceTypesDeserializesAllFields() {
|
||||
ListSupportedResourceTypesResponse response = client.listSupportedResourceTypes(
|
||||
ListSupportedResourceTypesRequest.builder().maxResults(50).build());
|
||||
|
||||
assertThat(response.resourceTypes()).as("ResourceTypes").isNotEmpty();
|
||||
for (var rt : response.resourceTypes()) {
|
||||
assertThat(rt.resourceType()).as("SupportedResourceType.ResourceType").isNotBlank();
|
||||
assertThat(rt.service()).as("SupportedResourceType.Service").isNotBlank();
|
||||
// Verify format: "service:type"
|
||||
assertThat(rt.resourceType()).contains(":");
|
||||
}
|
||||
}
|
||||
|
||||
// -----------------------------------------------------------------------
|
||||
// Cross-service setup
|
||||
// -----------------------------------------------------------------------
|
||||
|
||||
@Test
|
||||
@Order(5)
|
||||
void createS3BucketForDiscovery() {
|
||||
assumeFalse(TestFixtures.isRealAws(), "Skip resource creation against real AWS");
|
||||
String bucketName = TestFixtures.uniqueName("re2");
|
||||
s3.createBucket(b -> b.bucket(bucketName));
|
||||
}
|
||||
|
||||
// -----------------------------------------------------------------------
|
||||
// ListResources — every field of Resource objects
|
||||
// -----------------------------------------------------------------------
|
||||
|
||||
@Test
|
||||
@Order(10)
|
||||
void listResourcesDeserializesAllResourceFields() {
|
||||
ListResourcesResponse response = client.listResources(ListResourcesRequest.builder().build());
|
||||
|
||||
assertThat(response.viewArn()).as("ListResources.ViewArn").isNotBlank();
|
||||
assertThat(response.resources()).as("ListResources.Resources").isNotNull();
|
||||
|
||||
// Must have at least one resource (the S3 bucket we created)
|
||||
assertThat(response.resources()).isNotEmpty();
|
||||
|
||||
for (Resource resource : response.resources()) {
|
||||
assertThat(resource.arn()).as("Resource.Arn").isNotBlank();
|
||||
assertThat(resource.resourceType()).as("Resource.ResourceType").isNotBlank();
|
||||
assertThat(resource.service()).as("Resource.Service").isNotBlank();
|
||||
assertThat(resource.region()).as("Resource.Region").isNotBlank();
|
||||
assertThat(resource.owningAccountId()).as("Resource.OwningAccountId").isNotBlank();
|
||||
assertThat(resource.lastReportedAt()).as("Resource.LastReportedAt").isNotNull();
|
||||
assertThat(resource.properties()).as("Resource.Properties").isNotNull();
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(11)
|
||||
void listResourcesWithFilterReturnsCorrectTypes() {
|
||||
ListResourcesResponse response = client.listResources(ListResourcesRequest.builder()
|
||||
.filters(SearchFilter.builder().filterString("service:s3").build())
|
||||
.build());
|
||||
|
||||
assertThat(response.resources()).isNotEmpty();
|
||||
for (Resource resource : response.resources()) {
|
||||
assertThat(resource.service()).as("Filtered resource service").isEqualTo("s3");
|
||||
assertThat(resource.resourceType()).startsWith("s3:");
|
||||
}
|
||||
}
|
||||
|
||||
// -----------------------------------------------------------------------
|
||||
// Search — Count object structure is critical
|
||||
// -----------------------------------------------------------------------
|
||||
|
||||
@Test
|
||||
@Order(12)
|
||||
void searchCountIsObjectWithTotalResourcesAndComplete() {
|
||||
SearchResponse response = client.search(SearchRequest.builder()
|
||||
.queryString("service:s3")
|
||||
.build());
|
||||
|
||||
// Count must be an object, not an integer
|
||||
assertThat(response.count()).as("Search.Count").isNotNull();
|
||||
assertThat(response.count().totalResources()).as("Count.TotalResources").isNotNull();
|
||||
assertThat(response.count().totalResources()).isGreaterThanOrEqualTo(0L);
|
||||
assertThat(response.count().complete()).as("Count.Complete").isNotNull();
|
||||
|
||||
assertThat(response.resources()).as("Search.Resources").isNotNull();
|
||||
assertThat(response.viewArn()).as("Search.ViewArn").isNotBlank();
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(13)
|
||||
void searchCountTotalMatchesActualResourceCount() {
|
||||
SearchResponse response = client.search(SearchRequest.builder()
|
||||
.queryString("service:s3")
|
||||
.build());
|
||||
|
||||
// TotalResources should match the number of matching resources
|
||||
assertThat(response.count().totalResources())
|
||||
.as("Count.TotalResources matches filtered count")
|
||||
.isEqualTo((long) response.resources().size());
|
||||
}
|
||||
|
||||
// -----------------------------------------------------------------------
|
||||
// CreateView — response shape
|
||||
// -----------------------------------------------------------------------
|
||||
|
||||
@Test
|
||||
@Order(20)
|
||||
void createViewResponseContainsViewObject() {
|
||||
assumeFalse(TestFixtures.isRealAws(), "Skip view mutation against real AWS");
|
||||
CreateViewResponse response = client.createView(CreateViewRequest.builder()
|
||||
.viewName("sdk-compat-view")
|
||||
.filters(SearchFilter.builder().filterString("service:s3").build())
|
||||
.includedProperties(IncludedProperty.builder().name("tags").build())
|
||||
.tags(Map.of("testKey", "testValue"))
|
||||
.build());
|
||||
|
||||
View view = response.view();
|
||||
assertThat(view).as("CreateView.View").isNotNull();
|
||||
assertThat(view.viewArn()).as("View.ViewArn").isNotBlank();
|
||||
assertThat(view.owner()).as("View.Owner").isNotBlank();
|
||||
assertThat(view.lastUpdatedAt()).as("View.LastUpdatedAt").isNotNull();
|
||||
assertThat(view.includedProperties()).as("View.IncludedProperties").isNotEmpty();
|
||||
|
||||
createdViewArn = view.viewArn();
|
||||
}
|
||||
|
||||
// -----------------------------------------------------------------------
|
||||
// ListViews
|
||||
// -----------------------------------------------------------------------
|
||||
|
||||
@Test
|
||||
@Order(21)
|
||||
void listViewsReturnsArns() {
|
||||
ListViewsResponse response = client.listViews(ListViewsRequest.builder().build());
|
||||
assertThat(response.views()).as("ListViews.Views").isNotEmpty();
|
||||
if (!TestFixtures.isRealAws()) {
|
||||
assertThat(response.views()).contains(createdViewArn);
|
||||
}
|
||||
}
|
||||
|
||||
// -----------------------------------------------------------------------
|
||||
// BatchGetView — must have both Views and Errors
|
||||
// -----------------------------------------------------------------------
|
||||
|
||||
@Test
|
||||
@Order(22)
|
||||
void batchGetViewReturnsViewsAndErrorsForMissing() {
|
||||
assumeFalse(TestFixtures.isRealAws(), "Depends on created view");
|
||||
String bogusArn = "arn:aws:resource-explorer-2:us-east-1:000000000000:view/does-not-exist/00000000-0000-0000-0000-000000000000";
|
||||
|
||||
BatchGetViewResponse response = client.batchGetView(BatchGetViewRequest.builder()
|
||||
.viewArns(createdViewArn, bogusArn)
|
||||
.build());
|
||||
|
||||
// Found views
|
||||
assertThat(response.views()).as("BatchGetView.Views").isNotEmpty();
|
||||
assertThat(response.views().get(0).viewArn())
|
||||
.as("BatchGetView found view")
|
||||
.isEqualTo(createdViewArn);
|
||||
|
||||
// Errors for missing
|
||||
assertThat(response.errors()).as("BatchGetView.Errors").isNotEmpty();
|
||||
assertThat(response.errors().get(0).viewArn())
|
||||
.as("BatchGetView error ViewArn")
|
||||
.isEqualTo(bogusArn);
|
||||
assertThat(response.errors().get(0).errorMessage())
|
||||
.as("BatchGetView error message")
|
||||
.isNotBlank();
|
||||
}
|
||||
|
||||
// -----------------------------------------------------------------------
|
||||
// UpdateView
|
||||
// -----------------------------------------------------------------------
|
||||
|
||||
@Test
|
||||
@Order(23)
|
||||
void updateViewReturnsUpdatedView() {
|
||||
assumeFalse(TestFixtures.isRealAws(), "Depends on created view");
|
||||
UpdateViewResponse response = client.updateView(UpdateViewRequest.builder()
|
||||
.viewArn(createdViewArn)
|
||||
.includedProperties(IncludedProperty.builder().name("tags").build())
|
||||
.build());
|
||||
|
||||
assertThat(response.view()).as("UpdateView.View").isNotNull();
|
||||
assertThat(response.view().viewArn()).isEqualTo(createdViewArn);
|
||||
assertThat(response.view().lastUpdatedAt()).as("Updated.LastUpdatedAt").isNotNull();
|
||||
}
|
||||
|
||||
// -----------------------------------------------------------------------
|
||||
// DeleteView
|
||||
// -----------------------------------------------------------------------
|
||||
|
||||
@Test
|
||||
@Order(24)
|
||||
void deleteViewReturnsViewArn() {
|
||||
assumeFalse(TestFixtures.isRealAws(), "Depends on created view");
|
||||
DeleteViewResponse response = client.deleteView(DeleteViewRequest.builder()
|
||||
.viewArn(createdViewArn).build());
|
||||
assertThat(response.viewArn()).as("DeleteView.ViewArn").isEqualTo(createdViewArn);
|
||||
}
|
||||
|
||||
// -----------------------------------------------------------------------
|
||||
// CreateIndex — response must be trimmed to {Arn, State, CreatedAt}
|
||||
// -----------------------------------------------------------------------
|
||||
|
||||
@Test
|
||||
@Order(30)
|
||||
void createIndexReturnsArnStateCreatedAt() {
|
||||
assumeFalse(TestFixtures.isRealAws(), "Skip index mutation against real AWS");
|
||||
CreateIndexResponse response = altRegionClient.createIndex(CreateIndexRequest.builder()
|
||||
.tags(Map.of("env", "test"))
|
||||
.build());
|
||||
|
||||
assertThat(response.arn()).as("CreateIndex.Arn").isNotBlank();
|
||||
assertThat(response.state()).as("CreateIndex.State").isNotNull();
|
||||
assertThat(response.createdAt()).as("CreateIndex.CreatedAt").isNotNull();
|
||||
|
||||
createdIndexArn = response.arn();
|
||||
}
|
||||
|
||||
// -----------------------------------------------------------------------
|
||||
// ListIndexes — each item has Arn, Region, Type
|
||||
// -----------------------------------------------------------------------
|
||||
|
||||
@Test
|
||||
@Order(31)
|
||||
void listIndexesDeserializesItemFields() {
|
||||
ListIndexesResponse response = client.listIndexes(ListIndexesRequest.builder().build());
|
||||
|
||||
assertThat(response.indexes()).as("ListIndexes.Indexes").isNotEmpty();
|
||||
for (var idx : response.indexes()) {
|
||||
assertThat(idx.arn()).as("Index.Arn").isNotBlank();
|
||||
assertThat(idx.region()).as("Index.Region").isNotBlank();
|
||||
assertThat(idx.type()).as("Index.Type").isNotNull();
|
||||
}
|
||||
}
|
||||
|
||||
// -----------------------------------------------------------------------
|
||||
// UpdateIndexType — PascalCase response fields
|
||||
// -----------------------------------------------------------------------
|
||||
|
||||
@Test
|
||||
@Order(32)
|
||||
void updateIndexTypeDeserializesAllFields() {
|
||||
assumeFalse(TestFixtures.isRealAws(), "Skip index mutation against real AWS");
|
||||
UpdateIndexTypeResponse response = client.updateIndexType(UpdateIndexTypeRequest.builder()
|
||||
.arn(autoProvisionedIndexArn)
|
||||
.type(IndexType.AGGREGATOR)
|
||||
.build());
|
||||
|
||||
assertThat(response.arn()).as("UpdateIndexType.Arn").isNotBlank();
|
||||
assertThat(response.state()).as("UpdateIndexType.State").isNotNull();
|
||||
assertThat(response.type()).as("UpdateIndexType.Type").isNotNull();
|
||||
assertThat(response.lastUpdatedAt()).as("UpdateIndexType.LastUpdatedAt").isNotNull();
|
||||
}
|
||||
|
||||
// -----------------------------------------------------------------------
|
||||
// DeleteIndex — must include LastUpdatedAt
|
||||
// -----------------------------------------------------------------------
|
||||
|
||||
@Test
|
||||
@Order(33)
|
||||
void deleteIndexReturnsArnLastUpdatedAtState() {
|
||||
assumeFalse(TestFixtures.isRealAws(), "Depends on created index");
|
||||
DeleteIndexResponse response = altRegionClient.deleteIndex(DeleteIndexRequest.builder()
|
||||
.arn(createdIndexArn)
|
||||
.build());
|
||||
|
||||
assertThat(response.arn()).as("DeleteIndex.Arn").isEqualTo(createdIndexArn);
|
||||
assertThat(response.state()).as("DeleteIndex.State").isNotNull();
|
||||
assertThat(response.lastUpdatedAt()).as("DeleteIndex.LastUpdatedAt").isNotNull();
|
||||
}
|
||||
|
||||
// -----------------------------------------------------------------------
|
||||
// Error handling — invalid input must return proper error, not 500
|
||||
// -----------------------------------------------------------------------
|
||||
|
||||
@Test
|
||||
@Order(40)
|
||||
void getMissingViewReturnsError() {
|
||||
// Real AWS: 401 UnauthorizedException (auth checked before existence for wrong-account ARN)
|
||||
// Floci: 404 ResourceNotFoundException
|
||||
assertThatThrownBy(() -> client.getView(GetViewRequest.builder()
|
||||
.viewArn("arn:aws:resource-explorer-2:us-east-1:000000000000:view/nope/00000000-0000-0000-0000-000000000000")
|
||||
.build()))
|
||||
.isInstanceOf(ResourceExplorer2Exception.class);
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(41)
|
||||
void deleteMissingIndexReturnsError() {
|
||||
// Real AWS: 403 AccessDeniedException (auth checked before existence for wrong-account ARN)
|
||||
// Floci: 404 ResourceNotFoundException
|
||||
assertThatThrownBy(() -> client.deleteIndex(DeleteIndexRequest.builder()
|
||||
.arn("arn:aws:resource-explorer-2:us-east-1:000000000000:index/nonexistent")
|
||||
.build()))
|
||||
.isInstanceOf(ResourceExplorer2Exception.class);
|
||||
}
|
||||
|
||||
// -----------------------------------------------------------------------
|
||||
// CLASS 3: Wire Format — Nested Structure Deserialization
|
||||
// Drills into nested objects to verify the SDK can parse every level.
|
||||
// If any nested field uses wrong casing or wrong structure, the SDK
|
||||
// returns null and these tests fail.
|
||||
// -----------------------------------------------------------------------
|
||||
|
||||
@Test
|
||||
@Order(50)
|
||||
void viewFiltersFilterStringDeserializes() {
|
||||
assumeFalse(TestFixtures.isRealAws(), "Creates/deletes views");
|
||||
// Create view with filter, then get it and drill into nested Filters object
|
||||
CreateViewResponse createResp = client.createView(CreateViewRequest.builder()
|
||||
.viewName("nested-test-view")
|
||||
.filters(SearchFilter.builder().filterString("service:s3").build())
|
||||
.includedProperties(IncludedProperty.builder().name("tags").build())
|
||||
.build());
|
||||
String arn = createResp.view().viewArn();
|
||||
|
||||
GetViewResponse getResp = client.getView(GetViewRequest.builder().viewArn(arn).build());
|
||||
View view = getResp.view();
|
||||
|
||||
// Drill into nested Filters.FilterString
|
||||
assertThat(view.filters()).as("View.Filters").isNotNull();
|
||||
assertThat(view.filters().filterString()).as("Filters.FilterString").isEqualTo("service:s3");
|
||||
|
||||
// Drill into nested IncludedProperties[].Name
|
||||
assertThat(view.includedProperties()).as("View.IncludedProperties").hasSize(1);
|
||||
assertThat(view.includedProperties().get(0).name())
|
||||
.as("IncludedProperty.Name").isEqualTo("tags");
|
||||
|
||||
// Drill into scope
|
||||
assertThat(view.scope()).as("View.Scope").contains("arn:aws:iam:");
|
||||
|
||||
// Cleanup
|
||||
client.deleteView(DeleteViewRequest.builder().viewArn(arn).build());
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(51)
|
||||
void resourcePropertiesTagDataDeserializes() {
|
||||
// List resources — S3 bucket should have tag Properties
|
||||
ListResourcesResponse response = client.listResources(ListResourcesRequest.builder()
|
||||
.filters(SearchFilter.builder().filterString("service:s3").build())
|
||||
.build());
|
||||
|
||||
assertThat(response.resources()).isNotEmpty();
|
||||
Resource s3Resource = response.resources().get(0);
|
||||
|
||||
// Properties is a list of ResourceProperty
|
||||
assertThat(s3Resource.properties()).as("Resource.Properties").isNotNull();
|
||||
// Note: Properties may be empty if no tags — we just verify the list itself deserializes.
|
||||
// The integration test handles tag-specific assertions.
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(52)
|
||||
void searchCountNestedFieldsDeserialize() {
|
||||
SearchResponse response = client.search(SearchRequest.builder()
|
||||
.queryString("")
|
||||
.maxResults(1)
|
||||
.build());
|
||||
|
||||
ResourceCount count = response.count();
|
||||
assertThat(count).as("Search.Count object").isNotNull();
|
||||
|
||||
// These would be null if Count was an integer instead of an object
|
||||
assertThat(count.totalResources()).as("Count.TotalResources").isNotNull();
|
||||
assertThat(count.totalResources()).isGreaterThanOrEqualTo(0L);
|
||||
|
||||
// Complete is a boolean — just verify it deserializes (not null)
|
||||
// Value depends on whether there are >1 matching resources
|
||||
assertThat(count.complete()).as("Count.Complete").isNotNull();
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(53)
|
||||
void searchCountCompleteIsTrueWhenAllResultsFit() {
|
||||
SearchResponse response = client.search(SearchRequest.builder()
|
||||
.queryString("")
|
||||
.maxResults(1000)
|
||||
.build());
|
||||
|
||||
assertThat(response.count().complete())
|
||||
.as("Count.Complete when not paginating").isTrue();
|
||||
assertThat(response.nextToken()).as("NextToken absent on last page").isNull();
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(54)
|
||||
void indexReplicatingFieldsAreEmptyLists() {
|
||||
GetIndexResponse response = client.getIndex(GetIndexRequest.builder().build());
|
||||
|
||||
// ReplicatingFrom and ReplicatingTo should deserialize as lists, not null
|
||||
assertThat(response.replicatingFrom())
|
||||
.as("GetIndex.ReplicatingFrom").isNotNull().isEmpty();
|
||||
assertThat(response.replicatingTo())
|
||||
.as("GetIndex.ReplicatingTo").isNotNull().isEmpty();
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(55)
|
||||
void batchGetViewErrorFieldsDeserialize() {
|
||||
assumeFalse(TestFixtures.isRealAws(), "Uses floci-specific bogus ARN format");
|
||||
String bogus = "arn:aws:resource-explorer-2:us-east-1:000000000000:view/x/00000000-0000-0000-0000-000000000000";
|
||||
|
||||
BatchGetViewResponse response = client.batchGetView(BatchGetViewRequest.builder()
|
||||
.viewArns(bogus)
|
||||
.build());
|
||||
|
||||
assertThat(response.errors()).as("Errors list").hasSize(1);
|
||||
BatchGetViewError error = response.errors().get(0);
|
||||
assertThat(error.viewArn()).as("Error.ViewArn").isEqualTo(bogus);
|
||||
assertThat(error.errorMessage()).as("Error.ErrorMessage").isNotBlank();
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(56)
|
||||
void listResourcesPaginationTokenRoundTrips() {
|
||||
assumeFalse(TestFixtures.isRealAws(), "Floci-specific pagination behavior");
|
||||
// Page 1
|
||||
ListResourcesResponse page1 = client.listResources(ListResourcesRequest.builder()
|
||||
.maxResults(1)
|
||||
.build());
|
||||
assertThat(page1.resources()).hasSize(1);
|
||||
assertThat(page1.nextToken()).as("Page1 NextToken").isNotNull();
|
||||
|
||||
// Page 2 using token from page 1
|
||||
ListResourcesResponse page2 = client.listResources(ListResourcesRequest.builder()
|
||||
.maxResults(1)
|
||||
.nextToken(page1.nextToken())
|
||||
.build());
|
||||
assertThat(page2.resources()).hasSize(1);
|
||||
|
||||
// Page 1 and Page 2 should return different resources
|
||||
assertThat(page2.resources().get(0).arn())
|
||||
.as("Page 2 returns different resource")
|
||||
.isNotEqualTo(page1.resources().get(0).arn());
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(57)
|
||||
void updateViewNestedFieldsDeserialize() {
|
||||
assumeFalse(TestFixtures.isRealAws(), "Creates/deletes views");
|
||||
// Create, update, verify nested fields roundtrip
|
||||
CreateViewResponse created = client.createView(CreateViewRequest.builder()
|
||||
.viewName("update-nested-test")
|
||||
.build());
|
||||
String arn = created.view().viewArn();
|
||||
|
||||
UpdateViewResponse updated = client.updateView(UpdateViewRequest.builder()
|
||||
.viewArn(arn)
|
||||
.filters(SearchFilter.builder().filterString("region:us-east-1").build())
|
||||
.includedProperties(IncludedProperty.builder().name("tags").build())
|
||||
.build());
|
||||
|
||||
View view = updated.view();
|
||||
assertThat(view.viewArn()).isEqualTo(arn);
|
||||
assertThat(view.filters()).as("Updated Filters").isNotNull();
|
||||
assertThat(view.filters().filterString())
|
||||
.as("Updated FilterString").isEqualTo("region:us-east-1");
|
||||
assertThat(view.includedProperties()).hasSize(1);
|
||||
assertThat(view.includedProperties().get(0).name()).isEqualTo("tags");
|
||||
|
||||
client.deleteView(DeleteViewRequest.builder().viewArn(arn).build());
|
||||
}
|
||||
}
|
||||
@@ -460,5 +460,6 @@ These services spawn Docker containers. They require access to the Docker socket
|
||||
| `FLOCI_SERVICES_BACKUP_ENABLED` | `true` | Enable the AWS Backup service |
|
||||
| `FLOCI_SERVICES_BACKUP_JOB_COMPLETION_DELAY_SECONDS` | `3` | Simulated delay before backup jobs transition to `COMPLETED` |
|
||||
| `FLOCI_SERVICES_FIS_ENABLED` | `true` | Enable the AWS Fault Injection Service management API |
|
||||
| `FLOCI_SERVICES_RESOURCEEXPLORER2_ENABLED` | `true` | Enable the Resource Explorer 2 service |
|
||||
| `FLOCI_SERVICES_APPCONFIG_ENABLED` | `true` | Enable the AppConfig service |
|
||||
| `FLOCI_SERVICES_APPCONFIGDATA_ENABLED` | `true` | Enable the AppConfig Data service |
|
||||
@@ -21,7 +21,7 @@ The management API shares the RDS Query endpoint (`POST /` with an `Action=` par
|
||||
| --- | --- |
|
||||
| `CreateDBCluster` | Create a DocumentDB cluster and start a MongoDB container |
|
||||
| `DescribeDBClusters` | List clusters and their connection details |
|
||||
| `DescribeDBClusterSnapshots` | - |
|
||||
| `DescribeDBClusterSnapshots` | Return an empty cluster-snapshot list (snapshots are not modeled) |
|
||||
| `DescribeGlobalClusters` | List global clusters — always empty, as none are modeled |
|
||||
| `DeleteDBCluster` | Stop and remove a cluster (must have no instances) |
|
||||
| `ModifyDBCluster` | Update engine version or IAM auth setting |
|
||||
@@ -143,6 +143,6 @@ print(cluster["DBCluster"]["Endpoint"])
|
||||
|
||||
- IAM database authentication for MongoDB connections (the flag is stored and echoed back, but connections are not SigV4-proxied).
|
||||
- TLS / `--tls` enforced connections.
|
||||
- Snapshot creation and restore (`DescribeDBClusterSnapshots` returns an empty stub result; snapshots are not modeled).
|
||||
- Snapshot and restore operations.
|
||||
- Global clusters, replicas, and read-scaling beyond a single MongoDB container per cluster.
|
||||
- Parameter groups, subnet groups, and maintenance windows.
|
||||
@@ -64,6 +64,7 @@ Operation counts are exact. For dispatch-table services (Query and JSON 1.1) eac
|
||||
| [ACM](acm.md) | `POST /` + `X-Amz-Target: CertificateManager.*` | JSON 1.1 | 12 |
|
||||
| [ECR](ecr.md) | `POST /` + `X-Amz-Target: AmazonEC2ContainerRegistry_V20150921.*` (control plane) and `/v2/...` (data plane via `registry:2`) | JSON 1.1 + OCI Distribution | 17 |
|
||||
| [Resource Groups Tagging API](resource-groups-tagging.md) | `POST /` + `X-Amz-Target: ResourceGroupsTaggingAPI_20170126.*` | JSON 1.1 | 5 |
|
||||
| [Resource Explorer](resource-explorer.md) | `POST /{OperationName}`, rewritten to `/re2/*` for the four paths S3 Vectors also claims | REST JSON | 32 |
|
||||
| [SES](ses.md) | `POST /` with `Action=` param | Query | 16 |
|
||||
| [SES v2](ses.md#v2) | `/v2/email/*` | REST JSON | 10 |
|
||||
| [OpenSearch](opensearch.md) | `/2021-01-01/opensearch/...` | REST JSON | 24 |
|
||||
|
||||
@@ -41,7 +41,7 @@ RDS Data API (`rds-data`) is documented separately because it uses REST JSON rou
|
||||
| `DescribeOptionGroups` | List option groups, including the implicit `default:` groups |
|
||||
| `ModifyOptionGroup` | Add, update, or remove options in an option group |
|
||||
| `DeleteOptionGroup` | Delete an option group |
|
||||
| `DescribeDBSnapshots` | - |
|
||||
| `DescribeDBSnapshots` | Return an empty snapshot list (snapshots are not modeled) |
|
||||
| `DescribeDBProxies` | List DB proxies |
|
||||
| `CreateDBProxy` | Create a DB proxy |
|
||||
| `ModifyDBProxy` | Update mutable DB proxy authentication, logging, timeout, TLS, role, and security-group settings |
|
||||
@@ -51,7 +51,7 @@ RDS Data API (`rds-data`) is documented separately because it uses REST JSON rou
|
||||
| `DescribeDBProxyTargetGroups` | List a proxy's target groups |
|
||||
| `ModifyDBProxyTargetGroup` | Update target-group connection-pool configuration |
|
||||
| `DescribeDBProxyTargets` | List a proxy target group's registered targets |
|
||||
| `DescribeDBClusterSnapshots` | - |
|
||||
| `DescribeDBClusterSnapshots` | Return an empty cluster-snapshot list (snapshots are not modeled) |
|
||||
| `DescribeGlobalClusters` | List global clusters — always empty, as none are modeled |
|
||||
| `AddTagsToResource` | Add tags to a DB resource |
|
||||
| `ListTagsForResource` | List tags for a DB resource |
|
||||
|
||||
@@ -0,0 +1,182 @@
|
||||
# Resource Explorer 2
|
||||
|
||||
AWS Resource Explorer 2 (`resource-explorer-2`) makes the resources other floci services hold
|
||||
searchable from one place: `Search` and `ListResources` answer the Resource Explorer query
|
||||
language across every enabled service, and index and view management works as it does in AWS.
|
||||
|
||||
The API is REST JSON — operation names are URI paths (`POST /Search`) — and floci serves it on
|
||||
the shared port 4566.
|
||||
|
||||
## Supported actions
|
||||
|
||||
<!-- floci:actions:start -->
|
||||
| Action | Description |
|
||||
| --- | --- |
|
||||
| `ListResources` | Search with filters only; pages through every match |
|
||||
| `Search` | Search with filters and free-form keywords; returns at most the first 1000 matches |
|
||||
| `ListSupportedResourceTypes` | List the resource types the enabled services expose |
|
||||
| `CreateIndex` | Turn Resource Explorer on in a Region |
|
||||
| `GetIndex` | Details of the Region's index |
|
||||
| `DeleteIndex` | Turn Resource Explorer off in a Region |
|
||||
| `ListIndexes` | List indexes, optionally by type or Region |
|
||||
| `UpdateIndexType` | Promote a local index to aggregator, or demote it |
|
||||
| `CreateView` | Create a view, optionally with a filter and tag data |
|
||||
| `GetView` | A view's definition and tags |
|
||||
| `DeleteView` | Delete a view, clearing it as a default if it was one |
|
||||
| `UpdateView` | Replace a view's filter or included properties |
|
||||
| `ListViews` | ARNs of the calling Region's views |
|
||||
| `BatchGetView` | Several views at once, reporting the ones that are missing |
|
||||
| `AssociateDefaultView` | Make a view the Region's default |
|
||||
| `DisassociateDefaultView` | Leave the Region without a default view |
|
||||
| `GetDefaultView` | The Region's default view ARN, if it has one |
|
||||
| `GetAccountLevelServiceConfiguration` | Organization status — always `DISABLED`, as no organization is modeled |
|
||||
| `ListIndexesForMembers` | Member accounts' indexes — this account's own, or empty |
|
||||
| `ListManagedViews` | AWS-managed views — always empty, as none are modeled |
|
||||
| `GetManagedView` | Always reports the managed view as not found |
|
||||
| `ListServiceViews` | Service-owned views — always empty, as none are modeled |
|
||||
| `GetServiceView` | Always reports the service view as not found |
|
||||
| `ListServiceIndexes` | Indexes across Regions, in the service-index shape |
|
||||
| `GetServiceIndex` | The Region's index ARN and type |
|
||||
| `ListStreamingAccessForServices` | Services granted streaming access — always empty, as none are modeled |
|
||||
| `CreateResourceExplorerSetup` | Create indexes and views across several Regions in one task |
|
||||
| `DeleteResourceExplorerSetup` | Remove indexes and views from named Regions, or from all of them |
|
||||
| `GetResourceExplorerSetup` | A setup task's per-Region index and view status |
|
||||
| `ListTagsForResource` | An index's or view's tags |
|
||||
| `TagResource` | Add or overwrite tags on an index or view |
|
||||
| `UntagResource` | Remove tags by key from an index or view |
|
||||
<!-- floci:actions:end -->
|
||||
|
||||
## Indexes and views
|
||||
|
||||
An index turns Resource Explorer on in a Region; a view decides which resources a search can
|
||||
return and whether tag data comes back with them. floci auto-provisions an `AGGREGATOR` index
|
||||
and a `default-view` in the default Region at startup, so `Search` works with no setup. Other
|
||||
Regions need `CreateIndex` (or `CreateResourceExplorerSetup`) first.
|
||||
|
||||
`CreateResourceExplorerSetup` configures several Regions in one call — an index and a view per
|
||||
Region, optionally promoting one Region to aggregator — and returns a `TaskId` that
|
||||
`GetResourceExplorerSetup` reads back. Each Region's index and view step is recorded
|
||||
independently, so a Region that fails reports its AWS error code through that Region's
|
||||
`ErrorDetails` instead of abandoning the rest of the task.
|
||||
|
||||
## Making a service discoverable
|
||||
|
||||
A service exposes its resources by implementing `core/resource/ResourceProvider`:
|
||||
|
||||
```java
|
||||
public interface ResourceProvider {
|
||||
List<ExplorerResource> getResources();
|
||||
Set<SupportedResourceType> getSupportedResourceTypes();
|
||||
}
|
||||
```
|
||||
|
||||
`ResourceExplorer2Service` collects every implementation through CDI. `LambdaService` is the
|
||||
shortest example; `Ec2Service` is the largest, mapping eight resource types.
|
||||
|
||||
There is no index behind this: every `Search` and `ListResources` calls each provider's
|
||||
`getResources()`, so results always match live service state. A provider must therefore be
|
||||
cheap and must tolerate a resource that is mid-creation — skip a null ARN, and treat a null tag
|
||||
map as empty.
|
||||
|
||||
### Discoverable services
|
||||
|
||||
| Service | Resource types |
|
||||
|---|---|
|
||||
| ACM | `acm:certificate` |
|
||||
| Amazon MQ | `mq:broker` |
|
||||
| CloudFormation | `cloudformation:stack` |
|
||||
| CloudWatch Logs | `logs:log-group` |
|
||||
| Cognito | `cognito-idp:userpool` |
|
||||
| DynamoDB | `dynamodb:table` |
|
||||
| EC2 | `ec2:instance`, `ec2:vpc`, `ec2:subnet`, `ec2:security-group`, `ec2:volume`, `ec2:internet-gateway`, `ec2:natgateway`, `ec2:route-table` |
|
||||
| ECR | `ecr:repository` |
|
||||
| ECS | `ecs:cluster`, `ecs:service` |
|
||||
| EKS | `eks:cluster` |
|
||||
| ElastiCache | `elasticache:cluster` |
|
||||
| ELB v2 | `elasticloadbalancing:loadbalancer`, `elasticloadbalancing:targetgroup` |
|
||||
| EventBridge | `events:event-bus`, `events:rule` |
|
||||
| Firehose | `firehose:deliverystream` |
|
||||
| IAM | `iam:user`, `iam:role` |
|
||||
| Kinesis | `kinesis:stream` |
|
||||
| KMS | `kms:key` |
|
||||
| Lambda | `lambda:function` |
|
||||
| Lightsail | `lightsail:instance`, `lightsail:database`, `lightsail:bucket` |
|
||||
| MSK | `kafka:cluster` |
|
||||
| OpenSearch | `es:domain` |
|
||||
| Pipes | `pipes:pipe` |
|
||||
| RDS | `rds:db` |
|
||||
| RUM | `rum:appmonitor` |
|
||||
| S3 | `s3:bucket` |
|
||||
| Secrets Manager | `secretsmanager:secret` |
|
||||
| SNS | `sns:topic` |
|
||||
| SQS | `sqs:queue` |
|
||||
| SSM | `ssm:parameter` |
|
||||
| Step Functions | `states:statemachine` |
|
||||
|
||||
API Gateway and Route 53 are not discoverable yet, each for its own reason: `RestApi` carries no
|
||||
Region, and `Route53Service` resolves no account id — a hosted zone's ARN has neither. Both are
|
||||
waiting on a field, not on new query support.
|
||||
|
||||
## Query syntax
|
||||
|
||||
The filter grammar is implemented in full: the `accountid:`, `application:`, `id:`, `region:`,
|
||||
`resourcetype:`, `resourcetype.supports:`, `service:`, `tag:`, `tag.key:` and `tag.value:`
|
||||
filters, the `tag:all` and `tag:none` special cases, comma-OR within a filter, `-` negation,
|
||||
trailing `*` prefix matching, quoted phrases, and `\` escaping.
|
||||
|
||||
`ListResources` accepts only filters — free-form text is rejected with a `ValidationException`,
|
||||
as AWS rejects it. `Search` accepts both.
|
||||
|
||||
Tag filters (`tag:`, `tag.key:`, `tag.value:` and `application:`, which reads the
|
||||
`awsApplication` tag) require a view whose `IncludedProperties` name `tags`. Against a view
|
||||
without it the query is rejected rather than evaluated on data the view may not expose, and
|
||||
results carry no tag data.
|
||||
|
||||
## Configuration
|
||||
|
||||
| Variable | Default | Description |
|
||||
|---|---|---|
|
||||
| `FLOCI_SERVICES_RESOURCEEXPLORER2_ENABLED` | `true` | Enable or disable Resource Explorer 2 |
|
||||
| `FLOCI_STORAGE_SERVICES_RESOURCEEXPLORER2_MODE` | _(global storage mode)_ | Override the storage mode for indexes, views, and setup tasks |
|
||||
|
||||
## Where floci differs from AWS
|
||||
|
||||
- **Free-form keywords select rather than rank.** AWS reads `ec2 billing` as `ec2 OR billing`
|
||||
and never excludes a resource for missing a keyword — it ranks it lower and still returns it,
|
||||
so a keyword-only search in a live account returns everything. floci keeps the `OR` reading
|
||||
but returns only matches, since it has no relevance model and an unfiltered result set is not
|
||||
a useful answer locally. Filters, which AWS documents as deterministic, match exactly.
|
||||
- **An index is `ACTIVE` immediately.** `CreateIndex` reports `CREATING` on its own response, as
|
||||
the API contract requires, but floci is synchronous and there is no provisioning window to
|
||||
fake, so the very next `GetIndex` reports `ACTIVE`.
|
||||
- **Setup tasks finish before the call returns.** `CreateResourceExplorerSetup` and
|
||||
`DeleteResourceExplorerSetup` run synchronously, so a task's per-Region status is already
|
||||
terminal — `SUCCEEDED` or `FAILED` — the first time `GetResourceExplorerSetup` reads it.
|
||||
- **A stale `NextToken` returns an empty page.** A token pointing past a result set that shrank
|
||||
between calls is answered with an empty page rather than an error, which is how AWS handles a
|
||||
replayed token.
|
||||
- **Paginated results are ordered by ARN.** AWS treats `NextToken` as opaque and documents no
|
||||
result order — `Search` is relevance-ranked. floci's token is an offset into a list rebuilt on
|
||||
every call from provider and storage iteration, neither of which is ordered, so the results are
|
||||
sorted by ARN before the page is cut. Without that total order the second page would index into
|
||||
a differently arranged list and silently drop or repeat resources. The same ordering applies to
|
||||
`ListIndexes`, `ListViews` and `ListSupportedResourceTypes`.
|
||||
- **The default view is stored, not inferred.** The per-Region default is persisted on its own
|
||||
rather than derived from a view's name, so `DisassociateDefaultView` survives a restart.
|
||||
- **IAM tags are indexed.** AWS does not index tags attached to IAM users and roles; floci does,
|
||||
because hiding them would make locally tagged roles unfindable for no benefit.
|
||||
- **Organization and trusted-service surfaces are empty.** floci models neither AWS
|
||||
Organizations nor trusted-service integrations, so `ListManagedViews`, `ListServiceViews` and
|
||||
`ListStreamingAccessForServices` answer with empty lists, `GetManagedView` and `GetServiceView`
|
||||
report `ResourceNotFoundException`, `GetAccountLevelServiceConfiguration` reports
|
||||
`AWSServiceAccessStatus: DISABLED`, and `ListIndexesForMembers` returns this account's indexes
|
||||
when its id is among those asked for and nothing otherwise.
|
||||
|
||||
## Routing note
|
||||
|
||||
Resource Explorer 2 and S3 Vectors are both REST-JSON services rooted at `/`, and both declare
|
||||
`/CreateIndex`, `/GetIndex`, `/ListIndexes` and `/DeleteIndex`. JAX-RS cannot route those by
|
||||
path, so `ResourceExplorer2PathRewriteFilter` disambiguates on the SigV4 credential scope — the
|
||||
same signal `AwsQueryController` routes Query services by — and rewrites the path for Resource
|
||||
Explorer 2 callers. Requests that carry no `Authorization` header reach S3 Vectors; every AWS
|
||||
SDK and the CLI sign their requests, so this only affects hand-rolled `curl` calls.
|
||||
@@ -120,6 +120,7 @@ nav:
|
||||
- ECS: services/ecs.md
|
||||
- ECR: services/ecr.md
|
||||
- Resource Groups Tagging API: services/resource-groups-tagging.md
|
||||
- Resource Explorer 2: services/resource-explorer.md
|
||||
- EKS: services/eks.md
|
||||
- MWAA: services/mwaa.md
|
||||
- OpenSearch: services/opensearch.md
|
||||
|
||||
@@ -268,6 +268,7 @@ public interface EmulatorConfig {
|
||||
BackupStorageConfig backup();
|
||||
FisStorageConfig fis();
|
||||
CloudFrontStorageConfig cloudfront();
|
||||
ResourceExplorer2StorageConfig resourceexplorer2();
|
||||
AppSyncStorageConfig appsync();
|
||||
BatchStorageConfig batch();
|
||||
LightsailStorageConfig lightsail();
|
||||
@@ -417,6 +418,13 @@ public interface EmulatorConfig {
|
||||
Optional<String> mode();
|
||||
}
|
||||
|
||||
interface ResourceExplorer2StorageConfig {
|
||||
Optional<String> mode();
|
||||
|
||||
@WithDefault("5000")
|
||||
long flushIntervalMs();
|
||||
}
|
||||
|
||||
interface AppSyncStorageConfig {
|
||||
Optional<String> mode();
|
||||
|
||||
@@ -632,6 +640,7 @@ public interface EmulatorConfig {
|
||||
ConfigServiceConfig configservice();
|
||||
CloudTrailServiceConfig cloudtrail();
|
||||
CloudControlServiceConfig cloudcontrol();
|
||||
ResourceExplorer2ServiceConfig resourceexplorer2();
|
||||
CloudFrontServiceConfig cloudfront();
|
||||
AppSyncServiceConfig appsync();
|
||||
BatchServiceConfig batch();
|
||||
@@ -765,6 +774,11 @@ public interface EmulatorConfig {
|
||||
int flushIntervalSeconds();
|
||||
}
|
||||
|
||||
interface ResourceExplorer2ServiceConfig {
|
||||
@WithDefault("true")
|
||||
boolean enabled();
|
||||
}
|
||||
|
||||
interface AutoScalingServiceConfig {
|
||||
@WithDefault("true")
|
||||
boolean enabled();
|
||||
|
||||
@@ -289,8 +289,8 @@ public class AwsQueryController {
|
||||
case "sns" -> snsQueryHandler.handle(action, formParams, region);
|
||||
case "iam" -> iamQueryHandler.handle(action, formParams, authorization);
|
||||
case "sts" -> stsQueryHandler.handle(action, formParams);
|
||||
case "elasticache" -> elastiCacheQueryHandler.handle(action, formParams);
|
||||
case "rds" -> {
|
||||
case "elasticache" -> elastiCacheQueryHandler.handle(action, formParams, region);
|
||||
case "rds" -> {
|
||||
// Neptune signs requests with "rds" credential scope (same wire protocol).
|
||||
// Route to Neptune when Engine=neptune (create ops) or when the cluster/instance
|
||||
// already exists in Neptune storage (describe/modify/delete ops).
|
||||
|
||||
@@ -118,6 +118,10 @@ public class RegionResolver {
|
||||
return defaultRegion;
|
||||
}
|
||||
|
||||
public String getDefaultAccountId() {
|
||||
return defaultAccountId;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the region for the current request when called from a request context,
|
||||
* or the configured default region otherwise (async workers, startup, tests).
|
||||
|
||||
@@ -3,6 +3,7 @@ package io.github.hectorvent.floci.core.common;
|
||||
import io.github.hectorvent.floci.config.EmulatorConfig;
|
||||
import io.github.hectorvent.floci.services.appconfig.AppConfigController;
|
||||
import io.github.hectorvent.floci.services.backup.BackupController;
|
||||
import io.github.hectorvent.floci.services.resourceexplorer2.ResourceExplorer2Controller;
|
||||
import io.github.hectorvent.floci.services.appconfig.AppConfigDataController;
|
||||
import io.github.hectorvent.floci.services.batch.BatchController;
|
||||
import io.github.hectorvent.floci.services.bedrockruntime.BedrockRuntimeController;
|
||||
@@ -397,6 +398,15 @@ public class ResolvedServiceCatalog {
|
||||
config.storage().services().backup().flushIntervalMs(), null, ServiceProtocol.REST_JSON,
|
||||
protocols(ServiceProtocol.REST_JSON),
|
||||
Set.of(), Set.of("backup"), Set.of(), Set.of(BackupController.class)),
|
||||
descriptor("resource-explorer-2", "resourceexplorer2",
|
||||
config.services().resourceexplorer2().enabled(), true,
|
||||
"resourceexplorer2",
|
||||
storageMode(config.storage().services().resourceexplorer2().mode(), config.storage().mode()),
|
||||
config.storage().services().resourceexplorer2().flushIntervalMs(),
|
||||
null, ServiceProtocol.REST_JSON,
|
||||
protocols(ServiceProtocol.REST_JSON),
|
||||
Set.of(), Set.of("resource-explorer-2"), Set.of(),
|
||||
Set.of(ResourceExplorer2Controller.class)),
|
||||
descriptor("fis", "fis", config.services().fis().enabled(), true,
|
||||
"fis", storageMode(config.storage().services().fis().mode(), config.storage().mode()),
|
||||
config.storage().services().fis().flushIntervalMs(), null, ServiceProtocol.REST_JSON,
|
||||
|
||||
@@ -9,14 +9,14 @@ import java.util.regex.Pattern;
|
||||
* Extracts the SigV4 signing service name from an Authorization header's
|
||||
* credential scope ({@code Credential=<key>/<date>/<region>/<service>/aws4_request}).
|
||||
*/
|
||||
final class SigV4CredentialScope {
|
||||
public final class SigV4CredentialScope {
|
||||
|
||||
private static final Pattern SERVICE_PATTERN = Pattern.compile("Credential=\\S+/\\d{8}/[^/]+/([^/]+)/");
|
||||
|
||||
private SigV4CredentialScope() {
|
||||
}
|
||||
|
||||
static Optional<String> serviceName(String authorization) {
|
||||
public static Optional<String> serviceName(String authorization) {
|
||||
if (authorization == null) {
|
||||
return Optional.empty();
|
||||
}
|
||||
|
||||
@@ -0,0 +1,54 @@
|
||||
package io.github.hectorvent.floci.core.resource;
|
||||
|
||||
import io.quarkus.runtime.annotations.RegisterForReflection;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* A single resource made visible to Resource Explorer 2.
|
||||
* <p>
|
||||
* One instance describes one AWS resource (a certificate, a queue, a cluster, etc.)
|
||||
*
|
||||
* <p>The fields are what the query language filters and keywords match against, so they
|
||||
* must be populated with real, consistent values for search to work. Filterable attributes:
|
||||
* {@code resourcetype:}, {@code service:}, {@code region:}, {@code accountid:}, {@code id:} (the
|
||||
* ARN), and the tag attributes ({@code tag:}, {@code tag.key:}, {@code tag.value:},
|
||||
* {@code application:} — the last reads the {@code awsApplication} tag). A bare keyword matches a
|
||||
* case-insensitive substring of {@link #arn}, {@link #resourceType}, {@link #service}, or
|
||||
* {@link #region}. See {@code ResourceFilter} for the exact matching rules.
|
||||
*
|
||||
* @param arn full ARN of the resource, e.g.
|
||||
* {@code arn:aws:acm:us-east-1:123456789012:certificate/abc}. Doubles as the
|
||||
* resource's unique id ({@code id:} filter) and is matched by keyword search.
|
||||
* @param resourceType Resource Explorer's type identifier in {@code service:subtype} form, e.g.
|
||||
* {@code acm:certificate}, {@code kafka:cluster}, {@code iam:user}. Must be
|
||||
* identical to the {@link SupportedResourceType#resourceType()} the provider
|
||||
* advertises for this resource, and unique across all providers.
|
||||
* @param service AWS service namespace — the service segment of the ARN, e.g. {@code acm},
|
||||
* {@code kafka}, {@code cognito-idp}. This is the prefix of
|
||||
* {@link #resourceType}, not necessarily the floci module name.
|
||||
* @param region AWS region the resource lives in, e.g. {@code us-east-1}; usually
|
||||
* {@code AwsArnUtils.parse(arn).region()}.
|
||||
* @param owningAccountId 12-digit account id that owns the resource; usually
|
||||
* {@code AwsArnUtils.parse(arn).accountId()}.
|
||||
* @param lastReportedAt when Resource Explorer last observed the resource. floci has no scan
|
||||
* pipeline, so providers pass the resource's creation timestamp (falling back
|
||||
* to {@code Instant.now()} when unknown).
|
||||
* @param tags resource tags as key→value; drives the tag filters and is emitted as the
|
||||
* {@code tags} property. Never {@code null} — pass {@code Map.of()} when the
|
||||
* resource has no tags.
|
||||
* @see SupportedResourceType
|
||||
* @see <a href="https://docs.aws.amazon.com/resource-explorer/latest/apireference/API_Resource.html">AWS API: Resource</a>
|
||||
* @see <a href="https://docs.aws.amazon.com/resource-explorer/latest/userguide/using-search-query-syntax.html">Resource Explorer search query syntax</a>
|
||||
*/
|
||||
@RegisterForReflection
|
||||
public record ExplorerResource(
|
||||
String arn,
|
||||
String resourceType,
|
||||
String service,
|
||||
String region,
|
||||
String owningAccountId,
|
||||
Instant lastReportedAt,
|
||||
Map<String, String> tags
|
||||
) {}
|
||||
@@ -0,0 +1,63 @@
|
||||
package io.github.hectorvent.floci.core.resource;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
|
||||
/**
|
||||
* Extension point that lets an individual AWS service emulator expose its resources to the Resource
|
||||
* Explorer 2 emulator. Implement this on a service that owns resources you want to be discoverable
|
||||
* via {@code Search}, {@code ListResources}, and {@code ListSupportedResourceTypes}.
|
||||
* <p>
|
||||
* Implementations must be CDI beans (usually {@code @ApplicationScoped} service classes).
|
||||
* {@code ResourceExplorer2Service} iterates {@code ResourceProvider}s:
|
||||
* <ul>
|
||||
* <li>{@code Search} / {@code ListResources} concatenate {@link #getResources()} from all
|
||||
* providers, apply the query filter, then paginate. {@code Search} returns at most the first
|
||||
* 1000 matches; {@code ListResources} has no such cap and pages through every match, but omits
|
||||
* its {@code NextToken} when {@code MaxResults} is 1000. floci mirrors both behaviors.</li>
|
||||
* <li>{@code ListSupportedResourceTypes} concatenates {@link #getSupportedResourceTypes()} from
|
||||
* all providers and deduplicates by {@link SupportedResourceType#resourceType()}.</li>
|
||||
* </ul>
|
||||
*
|
||||
* <h2>Implementing</h2>
|
||||
* <ol>
|
||||
* <li>{@link #getResources()}: scan your storage backend and map each stored entity to an
|
||||
* {@link ExplorerResource}.</li>
|
||||
* <li>{@link #getSupportedResourceTypes()}: return one {@link SupportedResourceType} per distinct
|
||||
* {@code resourceType} string you emit.</li>
|
||||
* <li>Keep the {@code resourceType} string identical between the two methods — a resource whose
|
||||
* type is not advertised will still be searchable, but callers listing supported types would
|
||||
* not see it, which is inconsistent with AWS.</li>
|
||||
* </ol>
|
||||
*
|
||||
* <p>See {@code AcmService}, {@code MskService}, or {@code IamService} (which exposes two types)
|
||||
* for reference implementations.
|
||||
*
|
||||
* @see ExplorerResource
|
||||
* @see SupportedResourceType
|
||||
* @see <a href="https://docs.aws.amazon.com/resource-explorer/latest/userguide/getting-started-terms-and-concepts.html">Resource Explorer terms and concepts</a>
|
||||
* @see <a href="https://docs.aws.amazon.com/resource-explorer/latest/apireference/API_Search.html">AWS API: Search</a>
|
||||
*/
|
||||
public interface ResourceProvider {
|
||||
|
||||
/**
|
||||
* All resources this service currently own.
|
||||
* <p>
|
||||
* Build the list from live storage rather
|
||||
* than caching. Return an empty list when the service holds nothing; never return {@code null}.
|
||||
* Ordering is not significant — Resource Explorer sorts by ARN before paginating, so an
|
||||
* unordered store scan is safe to return as-is.
|
||||
*/
|
||||
List<ExplorerResource> getResources();
|
||||
|
||||
/**
|
||||
* The resource types this provider can produce.
|
||||
* <p>
|
||||
* One entry per distinct
|
||||
* {@link ExplorerResource#resourceType()} value returned by {@link #getResources()}.
|
||||
* The set is fixed for a given service, so returning a
|
||||
* literal {@code Set.of(...)} is the norm. Each {@code resourceType} must be globally unique
|
||||
* across providers.
|
||||
*/
|
||||
Set<SupportedResourceType> getSupportedResourceTypes();
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
package io.github.hectorvent.floci.core.resource;
|
||||
|
||||
import io.quarkus.runtime.annotations.RegisterForReflection;
|
||||
|
||||
/**
|
||||
* One resource type a {@link ResourceProvider} can produce.
|
||||
* <p>
|
||||
* This is the type-level counterpart to {@link ExplorerResource}
|
||||
* (which is an instance): a provider returns one of these per distinct
|
||||
* {@link ExplorerResource#resourceType()} value it emits.
|
||||
*
|
||||
* <p>The Resource Explorer 2 service collects these from every provider, deduplicates by {@link #resourceType}.
|
||||
*
|
||||
* @param resourceType type identifier in {@code service:subtype} form, e.g. {@code acm:certificate},
|
||||
* {@code kafka:cluster}, {@code iam:user}. Must exactly match the
|
||||
* {@link ExplorerResource#resourceType()} used for the corresponding resources,
|
||||
* and be unique across all providers — the service uses this string as the
|
||||
* deduplication key.
|
||||
* @param service AWS service namespace, i.e. the segment before the colon in
|
||||
* {@link #resourceType} (e.g. {@code acm}, {@code kafka}, {@code cognito-idp}).
|
||||
* @param supportsTags whether this type carries tags. Advisory metadata describing the type; the
|
||||
* Resource Explorer emulator currently treats every exposed type as taggable
|
||||
* regardless (the {@code resourcetype:supports=tags} filter is a pass-through),
|
||||
* so set it truthfully but do not expect it to gate behavior today.
|
||||
* @see ExplorerResource
|
||||
* @see <a href="https://docs.aws.amazon.com/resource-explorer/latest/apireference/API_ListSupportedResourceTypes.html">AWS API: ListSupportedResourceTypes</a>
|
||||
*/
|
||||
@RegisterForReflection
|
||||
public record SupportedResourceType(
|
||||
String resourceType,
|
||||
String service,
|
||||
boolean supportsTags
|
||||
) {}
|
||||
@@ -4,6 +4,9 @@ import io.github.hectorvent.floci.config.EmulatorConfig;
|
||||
import io.github.hectorvent.floci.core.common.AwsArnUtils;
|
||||
import io.github.hectorvent.floci.core.common.AwsException;
|
||||
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.StorageBackend;
|
||||
import io.github.hectorvent.floci.core.storage.StorageFactory;
|
||||
import io.github.hectorvent.floci.services.acm.model.*;
|
||||
@@ -35,7 +38,7 @@ import java.util.stream.Collectors;
|
||||
* @see <a href="https://docs.aws.amazon.com/acm/latest/APIReference/Welcome.html">AWS ACM API Reference</a>
|
||||
*/
|
||||
@ApplicationScoped
|
||||
public class AcmService {
|
||||
public class AcmService implements ResourceProvider {
|
||||
|
||||
private static final Logger LOG = Logger.getLogger(AcmService.class);
|
||||
private static final int MAX_TAGS = 50;
|
||||
@@ -481,6 +484,29 @@ public class AcmService {
|
||||
this.accountDaysBeforeExpiry.set(daysBeforeExpiry);
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<ExplorerResource> getResources() {
|
||||
List<ExplorerResource> resources = new ArrayList<>();
|
||||
for (Certificate cert : store.scan(k -> true)) {
|
||||
String arn = cert.getArn();
|
||||
if (arn == null) {
|
||||
continue;
|
||||
}
|
||||
AwsArnUtils.Arn parsed = AwsArnUtils.parse(arn);
|
||||
resources.add(new ExplorerResource(
|
||||
arn, "acm:certificate", "acm",
|
||||
parsed.region(), parsed.accountId(),
|
||||
cert.getCreatedAt() != null ? cert.getCreatedAt() : Instant.now(),
|
||||
cert.getTags() != null ? cert.getTags() : Map.of()));
|
||||
}
|
||||
return resources;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Set<SupportedResourceType> getSupportedResourceTypes() {
|
||||
return Set.of(new SupportedResourceType("acm:certificate", "acm", true));
|
||||
}
|
||||
|
||||
// ============ Helper Methods ============
|
||||
|
||||
private Certificate getCertificateByArn(String arn, String region) {
|
||||
|
||||
@@ -5,6 +5,9 @@ import io.github.hectorvent.floci.config.EmulatorConfig;
|
||||
import io.github.hectorvent.floci.core.common.AwsArnUtils;
|
||||
import io.github.hectorvent.floci.core.common.AwsException;
|
||||
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.AccountAwareStorageBackend;
|
||||
import io.github.hectorvent.floci.core.storage.StorageBackend;
|
||||
import io.github.hectorvent.floci.core.storage.StorageFactory;
|
||||
@@ -20,17 +23,19 @@ import jakarta.inject.Inject;
|
||||
import org.jboss.logging.Logger;
|
||||
|
||||
import java.security.SecureRandom;
|
||||
import java.time.Instant;
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.Executors;
|
||||
import java.util.concurrent.ScheduledExecutorService;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
@ApplicationScoped
|
||||
public class AmazonMqService {
|
||||
public class AmazonMqService implements ResourceProvider {
|
||||
|
||||
private static final Logger LOG = Logger.getLogger(AmazonMqService.class);
|
||||
private static final String ENGINE_RABBITMQ = "RABBITMQ";
|
||||
@@ -154,6 +159,29 @@ public class AmazonMqService {
|
||||
return storage.scan(k -> true);
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<ExplorerResource> getResources() {
|
||||
List<ExplorerResource> resources = new ArrayList<>();
|
||||
for (Broker broker : storage.scan(k -> true)) {
|
||||
String arn = broker.getBrokerArn();
|
||||
if (arn == null) {
|
||||
continue;
|
||||
}
|
||||
AwsArnUtils.Arn parsed = AwsArnUtils.parse(arn);
|
||||
resources.add(new ExplorerResource(
|
||||
arn, "mq:broker", "mq",
|
||||
parsed.region(), parsed.accountId(),
|
||||
broker.getCreated() != null ? broker.getCreated() : Instant.now(),
|
||||
broker.getTags() != null ? broker.getTags() : Map.of()));
|
||||
}
|
||||
return resources;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Set<SupportedResourceType> getSupportedResourceTypes() {
|
||||
return Set.of(new SupportedResourceType("mq:broker", "mq", true));
|
||||
}
|
||||
|
||||
public void deleteBroker(String brokerId) {
|
||||
Broker broker = describeBroker(brokerId);
|
||||
broker.setBrokerState(BrokerState.DELETION_IN_PROGRESS);
|
||||
|
||||
+33
-1
@@ -38,12 +38,19 @@ import java.util.concurrent.ExecutionException;
|
||||
import java.util.concurrent.ExecutorService;
|
||||
import java.util.concurrent.Executors;
|
||||
import java.util.concurrent.Future;
|
||||
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 java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
|
||||
/**
|
||||
* CloudFormation stack lifecycle management — Create, Update, Delete stacks via ChangeSets.
|
||||
*/
|
||||
@ApplicationScoped
|
||||
public class CloudFormationService {
|
||||
public class CloudFormationService implements ResourceProvider {
|
||||
|
||||
private static final Logger LOG = Logger.getLogger(CloudFormationService.class);
|
||||
|
||||
@@ -2063,4 +2070,29 @@ public class CloudFormationService {
|
||||
private static String key(String stackName, String region) {
|
||||
return region + ":" + stackName;
|
||||
}
|
||||
|
||||
// ─── Resource Explorer 2 ───────────────────────────────────────────────────
|
||||
|
||||
@Override
|
||||
public List<ExplorerResource> getResources() {
|
||||
List<ExplorerResource> resources = new ArrayList<>();
|
||||
for (Stack stack : stacks.values()) {
|
||||
String arn = stack.getStackId();
|
||||
if (arn == null) {
|
||||
continue;
|
||||
}
|
||||
AwsArnUtils.Arn parsed = AwsArnUtils.parse(arn);
|
||||
resources.add(new ExplorerResource(
|
||||
arn, "cloudformation:stack", "cloudformation",
|
||||
parsed.region(), parsed.accountId(),
|
||||
stack.getCreationTime() != null ? stack.getCreationTime() : Instant.now(),
|
||||
stack.getTags() != null ? stack.getTags() : Map.of()));
|
||||
}
|
||||
return resources;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Set<SupportedResourceType> getSupportedResourceTypes() {
|
||||
return Set.of(new SupportedResourceType("cloudformation:stack", "cloudformation", true));
|
||||
}
|
||||
}
|
||||
+41
-1
@@ -29,9 +29,14 @@ import java.util.UUID;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.concurrent.atomic.AtomicLong;
|
||||
import java.util.function.LongSupplier;
|
||||
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 java.time.Instant;
|
||||
import java.util.Set;
|
||||
|
||||
@ApplicationScoped
|
||||
public class CloudWatchLogsService {
|
||||
public class CloudWatchLogsService implements ResourceProvider {
|
||||
|
||||
private static final Logger LOG = Logger.getLogger(CloudWatchLogsService.class);
|
||||
|
||||
@@ -967,4 +972,39 @@ public class CloudWatchLogsService {
|
||||
return defaultValue;
|
||||
}
|
||||
}
|
||||
|
||||
// ─── Resource Explorer 2 ───────────────────────────────────────────────────
|
||||
|
||||
/**
|
||||
* Log groups carry no Region of their own — the store keys them {@code region::name} — so the
|
||||
* key is the only place the Region can come from.
|
||||
*/
|
||||
@Override
|
||||
public List<ExplorerResource> getResources() {
|
||||
List<ExplorerResource> resources = new ArrayList<>();
|
||||
for (String key : groupStore.keys()) {
|
||||
int separator = key.indexOf("::");
|
||||
if (separator < 0) {
|
||||
continue;
|
||||
}
|
||||
LogGroup group = groupStore.get(key).orElse(null);
|
||||
if (group == null || group.getLogGroupName() == null) {
|
||||
continue;
|
||||
}
|
||||
String region = key.substring(0, separator);
|
||||
resources.add(new ExplorerResource(
|
||||
"arn:aws:logs:" + region + ":" + regionResolver.getAccountId()
|
||||
+ ":log-group:" + group.getLogGroupName() + ":*",
|
||||
"logs:log-group", "logs",
|
||||
region, regionResolver.getAccountId(),
|
||||
group.getCreatedTime() > 0 ? Instant.ofEpochMilli(group.getCreatedTime()) : Instant.now(),
|
||||
group.getTags() != null ? group.getTags() : Map.of()));
|
||||
}
|
||||
return resources;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Set<SupportedResourceType> getSupportedResourceTypes() {
|
||||
return Set.of(new SupportedResourceType("logs:log-group", "logs", true));
|
||||
}
|
||||
}
|
||||
@@ -10,6 +10,9 @@ import io.github.hectorvent.floci.core.common.AwsArnUtils;
|
||||
import io.github.hectorvent.floci.core.common.AwsException;
|
||||
import io.github.hectorvent.floci.core.common.RegionResolver;
|
||||
import io.github.hectorvent.floci.core.common.ReservedTags;
|
||||
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.StorageBackend;
|
||||
import io.github.hectorvent.floci.core.storage.StorageFactory;
|
||||
import io.github.hectorvent.floci.services.cognito.model.CognitoGroup;
|
||||
@@ -48,6 +51,7 @@ import java.security.spec.PKCS8EncodedKeySpec;
|
||||
import java.security.spec.X509EncodedKeySpec;
|
||||
import java.time.Clock;
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.Base64;
|
||||
@@ -66,7 +70,7 @@ import java.util.UUID;
|
||||
import static io.github.hectorvent.floci.core.common.ReservedTags.rejectUnknownReservedTags;
|
||||
|
||||
@ApplicationScoped
|
||||
public class CognitoService {
|
||||
public class CognitoService implements ResourceProvider {
|
||||
private static final int DEFAULT_REFRESH_TOKEN_VALIDITY_DAYS = 30;
|
||||
|
||||
private static final Logger LOG = Logger.getLogger(CognitoService.class);
|
||||
@@ -313,6 +317,29 @@ public class CognitoService {
|
||||
return poolStore.scan(k -> true);
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<ExplorerResource> getResources() {
|
||||
List<ExplorerResource> resources = new ArrayList<>();
|
||||
for (UserPool pool : poolStore.scan(k -> true)) {
|
||||
String arn = pool.getArn();
|
||||
if (arn == null) {
|
||||
continue;
|
||||
}
|
||||
AwsArnUtils.Arn parsed = AwsArnUtils.parse(arn);
|
||||
resources.add(new ExplorerResource(
|
||||
arn, "cognito-idp:userpool", "cognito-idp",
|
||||
parsed.region(), parsed.accountId(),
|
||||
pool.getCreationDate() > 0 ? Instant.ofEpochSecond(pool.getCreationDate()) : Instant.now(),
|
||||
pool.getUserPoolTags() != null ? pool.getUserPoolTags() : Map.of()));
|
||||
}
|
||||
return resources;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Set<SupportedResourceType> getSupportedResourceTypes() {
|
||||
return Set.of(new SupportedResourceType("cognito-idp:userpool", "cognito-idp", true));
|
||||
}
|
||||
|
||||
private UserPool describeUserPoolByArn(String resourceArn) {
|
||||
String poolId = extractUserPoolIdFromArn(resourceArn);
|
||||
return describeUserPool(poolId);
|
||||
|
||||
@@ -49,9 +49,12 @@ import java.util.concurrent.ConcurrentSkipListMap;
|
||||
import java.util.concurrent.locks.ReentrantLock;
|
||||
import java.util.function.Supplier;
|
||||
import java.util.zip.GZIPOutputStream;
|
||||
import io.github.hectorvent.floci.core.resource.ExplorerResource;
|
||||
import io.github.hectorvent.floci.core.resource.ResourceProvider;
|
||||
import io.github.hectorvent.floci.core.resource.SupportedResourceType;
|
||||
|
||||
@ApplicationScoped
|
||||
public class DynamoDbService {
|
||||
public class DynamoDbService implements ResourceProvider {
|
||||
|
||||
private static final String LOCAL_REPLICA_UPDATE_ERROR =
|
||||
"Cannot add, delete, or update the local region through ReplicaUpdates. "
|
||||
@@ -3014,4 +3017,26 @@ public class DynamoDbService {
|
||||
|
||||
return new ListExportsResult(summaries, newNextToken);
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<ExplorerResource> getResources() {
|
||||
List<ExplorerResource> resources = new ArrayList<>();
|
||||
for (TableDefinition table : tableStore.scan(k -> true)) {
|
||||
if (table.getTableArn() == null) {
|
||||
continue;
|
||||
}
|
||||
AwsArnUtils.Arn parsed = AwsArnUtils.parse(table.getTableArn());
|
||||
resources.add(new ExplorerResource(
|
||||
table.getTableArn(), "dynamodb:table", "dynamodb",
|
||||
parsed.region(), parsed.accountId(),
|
||||
table.getCreationDateTime() != null ? table.getCreationDateTime() : Instant.now(),
|
||||
table.getTags() != null ? table.getTags() : Map.of()));
|
||||
}
|
||||
return resources;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Set<SupportedResourceType> getSupportedResourceTypes() {
|
||||
return Set.of(new SupportedResourceType("dynamodb:table", "dynamodb", true));
|
||||
}
|
||||
}
|
||||
@@ -20,6 +20,7 @@ import java.util.Random;
|
||||
import java.util.Set;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.concurrent.atomic.AtomicInteger;
|
||||
import java.util.function.Function;
|
||||
import java.util.regex.Pattern;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
@@ -31,6 +32,9 @@ import io.github.hectorvent.floci.core.common.AwsArnUtils;
|
||||
import io.github.hectorvent.floci.core.common.AwsException;
|
||||
import io.github.hectorvent.floci.core.common.AwsRegions;
|
||||
import io.github.hectorvent.floci.core.common.ContainerTeardown;
|
||||
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.core.storage.StorageFactory;
|
||||
@@ -95,7 +99,7 @@ import jakarta.enterprise.context.ApplicationScoped;
|
||||
import jakarta.inject.Inject;
|
||||
|
||||
@ApplicationScoped
|
||||
public class Ec2Service implements ContainerTeardown {
|
||||
public class Ec2Service implements ContainerTeardown, ResourceProvider {
|
||||
|
||||
private static final Logger LOG = Logger.getLogger(Ec2Service.class);
|
||||
private static final DateTimeFormatter ISO_FMT = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'")
|
||||
@@ -5527,4 +5531,80 @@ public class Ec2Service implements ContainerTeardown {
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
// ─── Resource Explorer 2 ───────────────────────────────────────────────────
|
||||
|
||||
/**
|
||||
* The EC2 resources Resource Explorer indexes. Each store is scanned across every Region,
|
||||
* because a provider answers for the whole emulator rather than for the request's Region.
|
||||
*
|
||||
* <p>Types not listed here — images, snapshots, key pairs, transit gateways — are omitted
|
||||
* deliberately: they are either AWS-owned catalogue entries rather than account resources, or
|
||||
* carry no tags and no identity worth searching on.
|
||||
*/
|
||||
@Override
|
||||
public List<ExplorerResource> getResources() {
|
||||
List<ExplorerResource> resources = new ArrayList<>();
|
||||
collectExplorerResources(resources, instances.scan(k -> true), "instance",
|
||||
Instance::getInstanceId, Instance::getRegion, Instance::getLaunchTime, Instance::getTags);
|
||||
collectExplorerResources(resources, vpcs.scan(k -> true), "vpc",
|
||||
Vpc::getVpcId, Vpc::getRegion, v -> null, Vpc::getTags);
|
||||
collectExplorerResources(resources, subnets.scan(k -> true), "subnet",
|
||||
Subnet::getSubnetId, Subnet::getRegion, s -> null, Subnet::getTags);
|
||||
collectExplorerResources(resources, securityGroups.scan(k -> true), "security-group",
|
||||
SecurityGroup::getGroupId, SecurityGroup::getRegion, g -> null, SecurityGroup::getTags);
|
||||
collectExplorerResources(resources, volumes.scan(k -> true), "volume",
|
||||
Volume::getVolumeId, Volume::getRegion, Volume::getCreateTime, Volume::getTags);
|
||||
collectExplorerResources(resources, internetGateways.scan(k -> true), "internet-gateway",
|
||||
InternetGateway::getInternetGatewayId, InternetGateway::getRegion, g -> null, InternetGateway::getTags);
|
||||
collectExplorerResources(resources, natGateways.scan(k -> true), "natgateway",
|
||||
NatGateway::getNatGatewayId, NatGateway::getRegion, NatGateway::getCreateTime, NatGateway::getTags);
|
||||
collectExplorerResources(resources, routeTables.scan(k -> true), "route-table",
|
||||
RouteTable::getRouteTableId, RouteTable::getRegion, t -> null, RouteTable::getTags);
|
||||
return resources;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Set<SupportedResourceType> getSupportedResourceTypes() {
|
||||
return Set.of(
|
||||
new SupportedResourceType("ec2:instance", "ec2", true),
|
||||
new SupportedResourceType("ec2:vpc", "ec2", true),
|
||||
new SupportedResourceType("ec2:subnet", "ec2", true),
|
||||
new SupportedResourceType("ec2:security-group", "ec2", true),
|
||||
new SupportedResourceType("ec2:volume", "ec2", true),
|
||||
new SupportedResourceType("ec2:internet-gateway", "ec2", true),
|
||||
new SupportedResourceType("ec2:natgateway", "ec2", true),
|
||||
new SupportedResourceType("ec2:route-table", "ec2", true));
|
||||
}
|
||||
|
||||
private <T> void collectExplorerResources(List<ExplorerResource> out, List<T> stored, String resourceType,
|
||||
Function<T, String> id, Function<T, String> region,
|
||||
Function<T, Instant> createdAt, Function<T, List<Tag>> tags) {
|
||||
for (T resource : stored) {
|
||||
String resourceId = id.apply(resource);
|
||||
String resourceRegion = region.apply(resource);
|
||||
if (resourceId == null || resourceRegion == null) {
|
||||
continue;
|
||||
}
|
||||
Instant created = createdAt.apply(resource);
|
||||
out.add(new ExplorerResource(
|
||||
"arn:aws:ec2:" + resourceRegion + ":" + accountId + ":" + resourceType + "/" + resourceId,
|
||||
"ec2:" + resourceType, "ec2", resourceRegion, accountId,
|
||||
created != null ? created : Instant.now(),
|
||||
explorerTags(tags.apply(resource))));
|
||||
}
|
||||
}
|
||||
|
||||
private static Map<String, String> explorerTags(List<Tag> tags) {
|
||||
if (tags == null) {
|
||||
return Map.of();
|
||||
}
|
||||
Map<String, String> converted = new LinkedHashMap<>();
|
||||
for (Tag tag : tags) {
|
||||
if (tag.getKey() != null) {
|
||||
converted.put(tag.getKey(), tag.getValue() != null ? tag.getValue() : "");
|
||||
}
|
||||
}
|
||||
return converted;
|
||||
}
|
||||
}
|
||||
@@ -4,6 +4,9 @@ import io.github.hectorvent.floci.config.EmulatorConfig;
|
||||
import io.github.hectorvent.floci.core.common.RegionResolver;
|
||||
import io.github.hectorvent.floci.core.common.AwsArnUtils;
|
||||
import io.github.hectorvent.floci.core.common.AwsException;
|
||||
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.StorageBackend;
|
||||
import io.github.hectorvent.floci.core.storage.StorageFactory;
|
||||
import io.github.hectorvent.floci.services.ecr.model.AuthorizationData;
|
||||
@@ -26,10 +29,11 @@ import java.util.ArrayList;
|
||||
import java.util.Base64;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
@ApplicationScoped
|
||||
public class EcrService {
|
||||
public class EcrService implements ResourceProvider {
|
||||
|
||||
private static final Logger LOG = Logger.getLogger(EcrService.class);
|
||||
private static final Pattern REPO_NAME = Pattern.compile(
|
||||
@@ -485,6 +489,29 @@ public class EcrService {
|
||||
return repo;
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<ExplorerResource> getResources() {
|
||||
List<ExplorerResource> resources = new ArrayList<>();
|
||||
for (Repository repo : repoStore.scan(k -> true)) {
|
||||
String arn = repo.getRepositoryArn();
|
||||
if (arn == null) {
|
||||
continue;
|
||||
}
|
||||
AwsArnUtils.Arn parsed = AwsArnUtils.parse(arn);
|
||||
resources.add(new ExplorerResource(
|
||||
arn, "ecr:repository", "ecr",
|
||||
parsed.region(), parsed.accountId(),
|
||||
repo.getCreatedAt() != null ? repo.getCreatedAt() : Instant.now(),
|
||||
repo.getTags() != null ? repo.getTags() : Map.of()));
|
||||
}
|
||||
return resources;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Set<SupportedResourceType> getSupportedResourceTypes() {
|
||||
return Set.of(new SupportedResourceType("ecr:repository", "ecr", true));
|
||||
}
|
||||
|
||||
// ============================================================
|
||||
// Result records
|
||||
// ============================================================
|
||||
|
||||
@@ -50,9 +50,14 @@ import java.util.concurrent.Executors;
|
||||
import java.util.concurrent.ScheduledExecutorService;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.stream.Stream;
|
||||
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.common.AwsArnUtils;
|
||||
import java.util.Set;
|
||||
|
||||
@ApplicationScoped
|
||||
public class EcsService implements ContainerTeardown {
|
||||
public class EcsService implements ContainerTeardown, ResourceProvider {
|
||||
|
||||
private static final Logger LOG = Logger.getLogger(EcsService.class);
|
||||
private static final String DEFAULT_CLUSTER = "default";
|
||||
@@ -1776,4 +1781,38 @@ public class EcsService implements ContainerTeardown {
|
||||
int slash = after.indexOf('/');
|
||||
return slash >= 0 ? after.substring(0, slash) : after;
|
||||
}
|
||||
|
||||
// ─── Resource Explorer 2 ───────────────────────────────────────────────────
|
||||
|
||||
@Override
|
||||
public List<ExplorerResource> getResources() {
|
||||
List<ExplorerResource> resources = new ArrayList<>();
|
||||
for (EcsCluster cluster : clusters.values()) {
|
||||
addExplorerResource(resources, cluster.getClusterArn(), "ecs:cluster", null, cluster.getTags());
|
||||
}
|
||||
for (EcsServiceModel service : services.values()) {
|
||||
addExplorerResource(resources, service.getServiceArn(), "ecs:service",
|
||||
service.getCreatedAt(), service.getTags());
|
||||
}
|
||||
return resources;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Set<SupportedResourceType> getSupportedResourceTypes() {
|
||||
return Set.of(
|
||||
new SupportedResourceType("ecs:cluster", "ecs", true),
|
||||
new SupportedResourceType("ecs:service", "ecs", true));
|
||||
}
|
||||
|
||||
private static void addExplorerResource(List<ExplorerResource> out, String arn, String resourceType,
|
||||
Instant createdAt, Map<String, String> tags) {
|
||||
if (arn == null) {
|
||||
return;
|
||||
}
|
||||
AwsArnUtils.Arn parsed = AwsArnUtils.parse(arn);
|
||||
out.add(new ExplorerResource(arn, resourceType, "ecs",
|
||||
parsed.region(), parsed.accountId(),
|
||||
createdAt != null ? createdAt : Instant.now(),
|
||||
tags != null ? tags : Map.of()));
|
||||
}
|
||||
}
|
||||
@@ -42,9 +42,13 @@ import java.util.concurrent.Executors;
|
||||
import java.util.concurrent.ScheduledExecutorService;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.stream.Collectors;
|
||||
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 java.util.Set;
|
||||
|
||||
@ApplicationScoped
|
||||
public class EksService implements TagHandler {
|
||||
public class EksService implements TagHandler, ResourceProvider {
|
||||
|
||||
private static final Logger LOG = Logger.getLogger(EksService.class);
|
||||
|
||||
@@ -571,4 +575,29 @@ public class EksService implements TagHandler {
|
||||
storage.put(cluster.getName(), cluster);
|
||||
}
|
||||
}
|
||||
|
||||
// ─── Resource Explorer 2 ───────────────────────────────────────────────────
|
||||
|
||||
@Override
|
||||
public List<ExplorerResource> getResources() {
|
||||
List<ExplorerResource> resources = new ArrayList<>();
|
||||
for (Cluster cluster : storage.scan(k -> true)) {
|
||||
String arn = cluster.getArn();
|
||||
if (arn == null) {
|
||||
continue;
|
||||
}
|
||||
AwsArnUtils.Arn parsed = AwsArnUtils.parse(arn);
|
||||
resources.add(new ExplorerResource(
|
||||
arn, "eks:cluster", "eks",
|
||||
parsed.region(), parsed.accountId(),
|
||||
cluster.getCreatedAt() != null ? cluster.getCreatedAt() : Instant.now(),
|
||||
cluster.getTags() != null ? cluster.getTags() : Map.of()));
|
||||
}
|
||||
return resources;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Set<SupportedResourceType> getSupportedResourceTypes() {
|
||||
return Set.of(new SupportedResourceType("eks:cluster", "eks", true));
|
||||
}
|
||||
}
|
||||
+4
-4
@@ -51,11 +51,11 @@ public class ElastiCacheQueryHandler {
|
||||
this.regionResolver = regionResolver;
|
||||
}
|
||||
|
||||
public Response handle(String action, MultivaluedMap<String, String> params) {
|
||||
public Response handle(String action, MultivaluedMap<String, String> params, String region) {
|
||||
LOG.debugv("ElastiCache action: {0}", action);
|
||||
return switch (action) {
|
||||
case "ValidateIamAuthToken" -> handleValidateIamAuthToken(params);
|
||||
case "CreateReplicationGroup" -> handleCreateReplicationGroup(params);
|
||||
case "CreateReplicationGroup" -> handleCreateReplicationGroup(params, region);
|
||||
case "DescribeReplicationGroups" -> handleDescribeReplicationGroups(params);
|
||||
case "ModifyReplicationGroup" -> handleModifyReplicationGroup(params);
|
||||
case "DeleteReplicationGroup" -> handleDeleteReplicationGroup(params);
|
||||
@@ -83,7 +83,7 @@ public class ElastiCacheQueryHandler {
|
||||
|
||||
// ── Replication Groups ────────────────────────────────────────────────────
|
||||
|
||||
private Response handleCreateReplicationGroup(MultivaluedMap<String, String> params) {
|
||||
private Response handleCreateReplicationGroup(MultivaluedMap<String, String> params, String region) {
|
||||
String groupId = params.getFirst("ReplicationGroupId");
|
||||
String description = params.getFirst("ReplicationGroupDescription");
|
||||
String authToken = params.getFirst("AuthToken");
|
||||
@@ -105,7 +105,7 @@ public class ElastiCacheQueryHandler {
|
||||
|
||||
try {
|
||||
ReplicationGroup group = service.createReplicationGroup(
|
||||
groupId, description != null ? description : "", authMode, authToken);
|
||||
groupId, description != null ? description : "", authMode, authToken, region);
|
||||
String result = replicationGroupXml(group);
|
||||
return Response.ok(AwsQueryResponse.envelope("CreateReplicationGroup", AwsNamespaces.EC, result)).build();
|
||||
} catch (AwsException e) {
|
||||
|
||||
+30
-2
@@ -2,8 +2,12 @@ package io.github.hectorvent.floci.services.elasticache;
|
||||
|
||||
import com.fasterxml.jackson.core.type.TypeReference;
|
||||
import io.github.hectorvent.floci.config.EmulatorConfig;
|
||||
import io.github.hectorvent.floci.core.common.AwsArnUtils;
|
||||
import io.github.hectorvent.floci.core.common.AwsException;
|
||||
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.StorageBackend;
|
||||
import io.github.hectorvent.floci.core.storage.StorageFactory;
|
||||
import io.github.hectorvent.floci.services.elasticache.container.ElastiCacheContainerHandle;
|
||||
@@ -38,7 +42,7 @@ import java.util.regex.Pattern;
|
||||
* Creates Valkey containers and auth proxies on group creation.
|
||||
*/
|
||||
@ApplicationScoped
|
||||
public class ElastiCacheService {
|
||||
public class ElastiCacheService implements ResourceProvider {
|
||||
|
||||
private static final Logger LOG = Logger.getLogger(ElastiCacheService.class);
|
||||
|
||||
@@ -78,7 +82,7 @@ public class ElastiCacheService {
|
||||
}
|
||||
|
||||
public ReplicationGroup createReplicationGroup(String groupId, String description,
|
||||
AuthMode authMode, String authToken) {
|
||||
AuthMode authMode, String authToken, String region) {
|
||||
if (groups.get(groupId).isPresent()) {
|
||||
throw new AwsException("ReplicationGroupAlreadyExistsFault",
|
||||
"Replication group " + groupId + " already exists.", 400);
|
||||
@@ -110,6 +114,8 @@ public class ElastiCacheService {
|
||||
group.setContainerHost(handle.getHost());
|
||||
group.setContainerPort(handle.getPort());
|
||||
group.setAuthToken(authToken);
|
||||
group.setArn(regionResolver.buildArn("elasticache", region, "replicationgroup:" + groupId));
|
||||
group.setRegion(region);
|
||||
|
||||
proxyManager.startProxy(groupId, authMode, proxyPort,
|
||||
handle.getHost(), handle.getPort(),
|
||||
@@ -610,4 +616,26 @@ public class ElastiCacheService {
|
||||
}
|
||||
LOG.infov("Deleted cache parameter group {0}", name);
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<ExplorerResource> getResources() {
|
||||
List<ExplorerResource> resources = new ArrayList<>();
|
||||
for (ReplicationGroup group : groups.scan(k -> true)) {
|
||||
if (group.getArn() == null) {
|
||||
continue;
|
||||
}
|
||||
AwsArnUtils.Arn parsed = AwsArnUtils.parse(group.getArn());
|
||||
resources.add(new ExplorerResource(
|
||||
group.getArn(), "elasticache:cluster", "elasticache",
|
||||
parsed.region(), parsed.accountId(),
|
||||
group.getCreatedAt() != null ? group.getCreatedAt() : Instant.now(),
|
||||
Map.of()));
|
||||
}
|
||||
return resources;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Set<SupportedResourceType> getSupportedResourceTypes() {
|
||||
return Set.of(new SupportedResourceType("elasticache:cluster", "elasticache", true));
|
||||
}
|
||||
}
|
||||
+8
@@ -18,6 +18,8 @@ public class ReplicationGroup {
|
||||
private int proxyPort;
|
||||
private String authToken; // stored plain-text for PASSWORD auth validation in the proxy
|
||||
private Set<String> associatedUserIds = new HashSet<>();
|
||||
private String arn;
|
||||
private String region;
|
||||
|
||||
// Transient fields — not persisted, restored on container restart
|
||||
private transient String containerId;
|
||||
@@ -75,4 +77,10 @@ public class ReplicationGroup {
|
||||
|
||||
public int getContainerPort() { return containerPort; }
|
||||
public void setContainerPort(int containerPort) { this.containerPort = containerPort; }
|
||||
|
||||
public String getArn() { return arn; }
|
||||
public void setArn(String arn) { this.arn = arn; }
|
||||
|
||||
public String getRegion() { return region; }
|
||||
public void setRegion(String region) { this.region = region; }
|
||||
}
|
||||
@@ -19,9 +19,16 @@ import java.time.Instant;
|
||||
import java.util.*;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.stream.Collectors;
|
||||
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 java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
|
||||
@ApplicationScoped
|
||||
public class ElbV2Service {
|
||||
public class ElbV2Service implements ResourceProvider {
|
||||
|
||||
@Inject
|
||||
ElbV2DataPlane dataPlane;
|
||||
@@ -1145,4 +1152,43 @@ public class ElbV2Service {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ─── Resource Explorer 2 ───────────────────────────────────────────────────
|
||||
|
||||
@Override
|
||||
public List<ExplorerResource> getResources() {
|
||||
List<ExplorerResource> resources = new ArrayList<>();
|
||||
for (Map<String, LoadBalancer> regionLoadBalancers : loadBalancers.values()) {
|
||||
for (LoadBalancer loadBalancer : regionLoadBalancers.values()) {
|
||||
addExplorerResource(resources, loadBalancer.getLoadBalancerArn(),
|
||||
"elasticloadbalancing:loadbalancer", loadBalancer.getCreatedTime());
|
||||
}
|
||||
}
|
||||
for (Map<String, TargetGroup> regionTargetGroups : targetGroups.values()) {
|
||||
for (TargetGroup targetGroup : regionTargetGroups.values()) {
|
||||
addExplorerResource(resources, targetGroup.getTargetGroupArn(),
|
||||
"elasticloadbalancing:targetgroup", null);
|
||||
}
|
||||
}
|
||||
return resources;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Set<SupportedResourceType> getSupportedResourceTypes() {
|
||||
return Set.of(
|
||||
new SupportedResourceType("elasticloadbalancing:loadbalancer", "elasticloadbalancing", true),
|
||||
new SupportedResourceType("elasticloadbalancing:targetgroup", "elasticloadbalancing", true));
|
||||
}
|
||||
|
||||
private void addExplorerResource(List<ExplorerResource> out, String arn, String resourceType,
|
||||
Instant createdAt) {
|
||||
if (arn == null) {
|
||||
return;
|
||||
}
|
||||
AwsArnUtils.Arn parsed = AwsArnUtils.parse(arn);
|
||||
out.add(new ExplorerResource(arn, resourceType, "elasticloadbalancing",
|
||||
parsed.region(), parsed.accountId(),
|
||||
createdAt != null ? createdAt : Instant.now(),
|
||||
tags.getOrDefault(arn, Map.of())));
|
||||
}
|
||||
}
|
||||
+39
-1
@@ -39,9 +39,13 @@ import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.UUID;
|
||||
import java.util.regex.Pattern;
|
||||
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 java.util.Set;
|
||||
|
||||
@ApplicationScoped
|
||||
public class EventBridgeService {
|
||||
public class EventBridgeService implements ResourceProvider {
|
||||
|
||||
private static final Logger LOG = Logger.getLogger(EventBridgeService.class);
|
||||
|
||||
@@ -1579,4 +1583,38 @@ public class EventBridgeService {
|
||||
}
|
||||
}
|
||||
|
||||
// ─── Resource Explorer 2 ───────────────────────────────────────────────────
|
||||
|
||||
@Override
|
||||
public List<ExplorerResource> getResources() {
|
||||
List<ExplorerResource> resources = new ArrayList<>();
|
||||
for (EventBus bus : busStore.scan(k -> true)) {
|
||||
addExplorerResource(resources, bus.getArn(), "events:event-bus",
|
||||
bus.getCreatedTime(), bus.getTags());
|
||||
}
|
||||
for (Rule rule : ruleStore.scan(k -> true)) {
|
||||
addExplorerResource(resources, rule.getArn(), "events:rule",
|
||||
rule.getCreatedAt(), rule.getTags());
|
||||
}
|
||||
return resources;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Set<SupportedResourceType> getSupportedResourceTypes() {
|
||||
return Set.of(
|
||||
new SupportedResourceType("events:event-bus", "events", true),
|
||||
new SupportedResourceType("events:rule", "events", true));
|
||||
}
|
||||
|
||||
private static void addExplorerResource(List<ExplorerResource> out, String arn, String resourceType,
|
||||
Instant createdAt, Map<String, String> tags) {
|
||||
if (arn == null) {
|
||||
return;
|
||||
}
|
||||
AwsArnUtils.Arn parsed = AwsArnUtils.parse(arn);
|
||||
out.add(new ExplorerResource(arn, resourceType, "events",
|
||||
parsed.region(), parsed.accountId(),
|
||||
createdAt != null ? createdAt : Instant.now(),
|
||||
tags != null ? tags : Map.of()));
|
||||
}
|
||||
}
|
||||
@@ -28,9 +28,17 @@ import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.concurrent.Executors;
|
||||
import java.util.concurrent.ScheduledExecutorService;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
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 java.util.LinkedHashMap;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
|
||||
@ApplicationScoped
|
||||
public class FirehoseService {
|
||||
public class FirehoseService implements ResourceProvider {
|
||||
|
||||
private static final Logger LOG = Logger.getLogger(FirehoseService.class);
|
||||
private static final String DEFAULT_BUCKET = "floci-firehose-results";
|
||||
@@ -416,4 +424,35 @@ public class FirehoseService {
|
||||
s3Service.createBucket(bucket, regionResolver.getDefaultRegion());
|
||||
} catch (Exception ignored) {}
|
||||
}
|
||||
|
||||
// ─── Resource Explorer 2 ───────────────────────────────────────────────────
|
||||
|
||||
@Override
|
||||
public List<ExplorerResource> getResources() {
|
||||
List<ExplorerResource> resources = new ArrayList<>();
|
||||
for (DeliveryStreamDescription stream : streamStore.scan(k -> true)) {
|
||||
String arn = stream.getDeliveryStreamARN();
|
||||
if (arn == null) {
|
||||
continue;
|
||||
}
|
||||
AwsArnUtils.Arn parsed = AwsArnUtils.parse(arn);
|
||||
Map<String, String> tags = new LinkedHashMap<>();
|
||||
if (stream.getTags() != null) {
|
||||
for (DeliveryStreamDescription.Tag tag : stream.getTags()) {
|
||||
tags.put(tag.getKey(), tag.getValue() != null ? tag.getValue() : "");
|
||||
}
|
||||
}
|
||||
resources.add(new ExplorerResource(
|
||||
arn, "firehose:deliverystream", "firehose",
|
||||
parsed.region(), parsed.accountId(),
|
||||
stream.getCreateTimestamp() != null ? stream.getCreateTimestamp() : Instant.now(),
|
||||
tags));
|
||||
}
|
||||
return resources;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Set<SupportedResourceType> getSupportedResourceTypes() {
|
||||
return Set.of(new SupportedResourceType("firehose:deliverystream", "firehose", true));
|
||||
}
|
||||
}
|
||||
@@ -5,6 +5,9 @@ import io.github.hectorvent.floci.core.common.AwsArnUtils;
|
||||
import io.github.hectorvent.floci.core.common.AwsException;
|
||||
import io.github.hectorvent.floci.core.common.RegionResolver;
|
||||
import io.github.hectorvent.floci.core.common.SessionAccountLookup;
|
||||
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.AccountAwareStorageBackend;
|
||||
import io.github.hectorvent.floci.core.storage.InMemoryStorage;
|
||||
import io.github.hectorvent.floci.core.storage.StorageBackend;
|
||||
@@ -28,6 +31,7 @@ import org.jboss.logging.Logger;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.util.Optional;
|
||||
import java.util.Set;
|
||||
import java.util.concurrent.ThreadLocalRandom;
|
||||
import java.util.ArrayList;
|
||||
import java.util.LinkedHashMap;
|
||||
@@ -48,7 +52,7 @@ import java.util.regex.Pattern;
|
||||
*/
|
||||
@Startup
|
||||
@ApplicationScoped
|
||||
public class IamService implements SessionAccountLookup {
|
||||
public class IamService implements SessionAccountLookup, ResourceProvider {
|
||||
|
||||
private static final Logger LOG = Logger.getLogger(IamService.class);
|
||||
private static final String CHARS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
|
||||
@@ -1269,6 +1273,43 @@ public class IamService implements SessionAccountLookup {
|
||||
.toList();
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<ExplorerResource> getResources() {
|
||||
List<ExplorerResource> resources = new ArrayList<>();
|
||||
for (IamUser user : users.scan(k -> true)) {
|
||||
addIamResource(resources, user.getArn(), "iam:user", user.getCreateDate(), user.getTags());
|
||||
}
|
||||
for (IamRole role : roles.scan(k -> true)) {
|
||||
addIamResource(resources, role.getArn(), "iam:role", role.getCreateDate(), role.getTags());
|
||||
}
|
||||
return resources;
|
||||
}
|
||||
|
||||
private void addIamResource(List<ExplorerResource> out, String arn, String type,
|
||||
Instant createDate, Map<String, String> tags) {
|
||||
if (arn == null) {
|
||||
return;
|
||||
}
|
||||
AwsArnUtils.Arn parsed = AwsArnUtils.parse(arn);
|
||||
// IAM is a global service: its ARNs carry no region. Resource Explorer reports
|
||||
// global resources with the region "global" (not an empty string).
|
||||
String region = parsed.region() == null || parsed.region().isEmpty()
|
||||
? "global"
|
||||
: parsed.region();
|
||||
out.add(new ExplorerResource(
|
||||
arn, type, "iam",
|
||||
region, parsed.accountId(),
|
||||
createDate != null ? createDate : Instant.now(),
|
||||
tags != null ? tags : Map.of()));
|
||||
}
|
||||
|
||||
@Override
|
||||
public Set<SupportedResourceType> getSupportedResourceTypes() {
|
||||
return Set.of(
|
||||
new SupportedResourceType("iam:user", "iam", true),
|
||||
new SupportedResourceType("iam:role", "iam", true));
|
||||
}
|
||||
|
||||
// =========================================================================
|
||||
// Account Aliases
|
||||
// ==================================================================
|
||||
|
||||
@@ -18,9 +18,15 @@ import java.nio.charset.StandardCharsets;
|
||||
import java.time.Instant;
|
||||
import java.util.*;
|
||||
import java.util.concurrent.atomic.AtomicLong;
|
||||
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.common.AwsArnUtils;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Set;
|
||||
|
||||
@ApplicationScoped
|
||||
public class KinesisService {
|
||||
public class KinesisService implements ResourceProvider {
|
||||
private static final Logger LOG = Logger.getLogger(KinesisService.class);
|
||||
private static final Set<String> VALID_SHARD_LEVEL_METRICS = Set.of(
|
||||
"IncomingBytes", "IncomingRecords", "OutgoingBytes", "OutgoingRecords",
|
||||
@@ -779,4 +785,30 @@ public class KinesisService {
|
||||
private String regionKey(String region, String name) {
|
||||
return region + "::" + name;
|
||||
}
|
||||
|
||||
// ─── Resource Explorer 2 ───────────────────────────────────────────────────
|
||||
|
||||
@Override
|
||||
public List<ExplorerResource> getResources() {
|
||||
List<ExplorerResource> resources = new ArrayList<>();
|
||||
for (KinesisStream stream : store.scan(k -> true)) {
|
||||
String arn = stream.getStreamArn();
|
||||
if (arn == null) {
|
||||
continue;
|
||||
}
|
||||
AwsArnUtils.Arn parsed = AwsArnUtils.parse(arn);
|
||||
resources.add(new ExplorerResource(
|
||||
arn, "kinesis:stream", "kinesis",
|
||||
parsed.region(), parsed.accountId(),
|
||||
stream.getStreamCreationTimestamp() != null
|
||||
? stream.getStreamCreationTimestamp() : Instant.now(),
|
||||
stream.getTags() != null ? stream.getTags() : Map.of()));
|
||||
}
|
||||
return resources;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Set<SupportedResourceType> getSupportedResourceTypes() {
|
||||
return Set.of(new SupportedResourceType("kinesis:stream", "kinesis", true));
|
||||
}
|
||||
}
|
||||
@@ -1,9 +1,13 @@
|
||||
package io.github.hectorvent.floci.services.kms;
|
||||
|
||||
import com.fasterxml.jackson.core.type.TypeReference;
|
||||
import io.github.hectorvent.floci.core.common.AwsArnUtils;
|
||||
import io.github.hectorvent.floci.core.common.AwsException;
|
||||
import io.github.hectorvent.floci.core.common.RegionResolver;
|
||||
import io.github.hectorvent.floci.core.common.ReservedTags;
|
||||
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.StorageBackend;
|
||||
import io.github.hectorvent.floci.core.storage.StorageFactory;
|
||||
import io.github.hectorvent.floci.services.kms.model.KmsAlias;
|
||||
@@ -58,7 +62,7 @@ import static io.github.hectorvent.floci.services.kms.model.KmsMessageType.DIGES
|
||||
import static io.github.hectorvent.floci.services.kms.model.KmsMessageType.RAW;
|
||||
|
||||
@ApplicationScoped
|
||||
public class KmsService {
|
||||
public class KmsService implements ResourceProvider {
|
||||
|
||||
private static final Logger LOG = Logger.getLogger(KmsService.class);
|
||||
|
||||
@@ -1165,4 +1169,26 @@ public class KmsService {
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<ExplorerResource> getResources() {
|
||||
List<ExplorerResource> resources = new ArrayList<>();
|
||||
for (KmsKey key : keyStore.scan(k -> true)) {
|
||||
String arn = key.getArn();
|
||||
if (arn == null) {
|
||||
continue;
|
||||
}
|
||||
AwsArnUtils.Arn parsed = AwsArnUtils.parse(arn);
|
||||
resources.add(new ExplorerResource(
|
||||
arn, "kms:key", "kms",
|
||||
parsed.region(), parsed.accountId(),
|
||||
key.getCreationDate() > 0 ? Instant.ofEpochSecond(key.getCreationDate()) : Instant.now(),
|
||||
key.getTags() != null ? key.getTags() : Map.of()));
|
||||
}
|
||||
return resources;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Set<SupportedResourceType> getSupportedResourceTypes() {
|
||||
return Set.of(new SupportedResourceType("kms:key", "kms", true));
|
||||
}
|
||||
}
|
||||
@@ -7,6 +7,9 @@ import io.github.hectorvent.floci.core.common.AwsException;
|
||||
import io.github.hectorvent.floci.core.common.RegionResolver;
|
||||
import io.github.hectorvent.floci.core.storage.StorageBackedMap;
|
||||
import io.github.hectorvent.floci.core.storage.StorageFactory;
|
||||
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.services.lambda.model.EventSourceMapping;
|
||||
import io.github.hectorvent.floci.services.lambda.model.FunctionEventInvokeConfig;
|
||||
import io.github.hectorvent.floci.services.lambda.model.InvocationType;
|
||||
@@ -39,6 +42,7 @@ import java.util.Base64;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.Set;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.regex.Pattern;
|
||||
@@ -47,7 +51,7 @@ import java.util.regex.Pattern;
|
||||
* Business logic for Lambda function management and invocation.
|
||||
*/
|
||||
@ApplicationScoped
|
||||
public class LambdaService {
|
||||
public class LambdaService implements ResourceProvider {
|
||||
|
||||
private static final Logger LOG = Logger.getLogger(LambdaService.class);
|
||||
private static final Pattern EFS_ACCESS_POINT_ARN = Pattern.compile(
|
||||
@@ -252,6 +256,32 @@ public class LambdaService {
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<ExplorerResource> getResources() {
|
||||
List<ExplorerResource> resources = new ArrayList<>();
|
||||
for (LambdaFunction fn : functionStore.listAll()) {
|
||||
if (!"$LATEST".equals(fn.getVersion())) {
|
||||
continue;
|
||||
}
|
||||
String arn = fn.getFunctionArn();
|
||||
if (arn == null) {
|
||||
continue;
|
||||
}
|
||||
AwsArnUtils.Arn parsed = AwsArnUtils.parse(arn);
|
||||
resources.add(new ExplorerResource(
|
||||
arn, "lambda:function", "lambda",
|
||||
parsed.region(), parsed.accountId(),
|
||||
fn.getLastModified() > 0 ? Instant.ofEpochMilli(fn.getLastModified()) : Instant.now(),
|
||||
fn.getTags() != null ? fn.getTags() : Map.of()));
|
||||
}
|
||||
return resources;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Set<SupportedResourceType> getSupportedResourceTypes() {
|
||||
return Set.of(new SupportedResourceType("lambda:function", "lambda", true));
|
||||
}
|
||||
|
||||
public LambdaFunction createFunction(String region, Map<String, Object> request) {
|
||||
String functionName = (String) request.get("FunctionName");
|
||||
String role = (String) request.get("Role");
|
||||
|
||||
@@ -5,8 +5,12 @@ import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.databind.node.ArrayNode;
|
||||
import com.fasterxml.jackson.databind.node.ObjectNode;
|
||||
import io.github.hectorvent.floci.core.common.AwsArnUtils;
|
||||
import io.github.hectorvent.floci.core.common.AwsException;
|
||||
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.StorageBackend;
|
||||
import io.github.hectorvent.floci.core.storage.StorageFactory;
|
||||
import jakarta.enterprise.context.ApplicationScoped;
|
||||
@@ -17,12 +21,14 @@ import java.time.Instant;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Base64;
|
||||
import java.util.Comparator;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.UUID;
|
||||
|
||||
@ApplicationScoped
|
||||
public class LightsailService {
|
||||
public class LightsailService implements ResourceProvider {
|
||||
|
||||
private static final String SERVICE = "lightsail";
|
||||
private static final String RESOURCE_INSTANCE = "Instance";
|
||||
@@ -497,6 +503,53 @@ public class LightsailService {
|
||||
return mapper.createObjectNode().put("isPeered", false);
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<ExplorerResource> getResources() {
|
||||
List<ExplorerResource> resources = new ArrayList<>();
|
||||
for (ObjectNode node : resourceStore.scan(key -> true)) {
|
||||
String arn = node.path("arn").asText(null);
|
||||
if (arn == null) {
|
||||
continue;
|
||||
}
|
||||
AwsArnUtils.Arn parsed = AwsArnUtils.parse(arn);
|
||||
resources.add(new ExplorerResource(
|
||||
arn,
|
||||
SERVICE + ":" + node.path("resourceType").asText(),
|
||||
SERVICE,
|
||||
parsed.region(),
|
||||
parsed.accountId(),
|
||||
reportedAt(node),
|
||||
tagsOf(node)));
|
||||
}
|
||||
return resources;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Set<SupportedResourceType> getSupportedResourceTypes() {
|
||||
return Set.of(
|
||||
new SupportedResourceType(SERVICE + ":" + RESOURCE_INSTANCE, SERVICE, true),
|
||||
new SupportedResourceType(SERVICE + ":" + RESOURCE_DISK, SERVICE, true),
|
||||
new SupportedResourceType(SERVICE + ":" + RESOURCE_KEY_PAIR, SERVICE, true),
|
||||
// Lightsail static IPs are not taggable in AWS.
|
||||
new SupportedResourceType(SERVICE + ":" + RESOURCE_STATIC_IP, SERVICE, false));
|
||||
}
|
||||
|
||||
private static Instant reportedAt(ObjectNode node) {
|
||||
double createdAt = node.path("createdAt").asDouble(0);
|
||||
return createdAt > 0 ? Instant.ofEpochMilli(Math.round(createdAt * 1000)) : Instant.now();
|
||||
}
|
||||
|
||||
private static Map<String, String> tagsOf(ObjectNode node) {
|
||||
Map<String, String> tags = new LinkedHashMap<>();
|
||||
for (JsonNode tag : node.path("tags")) {
|
||||
String key = tag.path("key").asText(null);
|
||||
if (key != null) {
|
||||
tags.put(key, tag.path("value").asText(""));
|
||||
}
|
||||
}
|
||||
return tags;
|
||||
}
|
||||
|
||||
private ObjectNode baseResource(String region, String availabilityZone, String resourceType, String name) {
|
||||
Instant now = Instant.now();
|
||||
ObjectNode resource = mapper.createObjectNode();
|
||||
|
||||
@@ -6,6 +6,9 @@ import io.github.hectorvent.floci.core.common.AwsException;
|
||||
import io.github.hectorvent.floci.core.common.Pagination;
|
||||
import io.github.hectorvent.floci.core.common.PaginatedResult;
|
||||
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.AccountAwareStorageBackend;
|
||||
import io.github.hectorvent.floci.core.storage.StorageBackend;
|
||||
import io.github.hectorvent.floci.core.storage.StorageFactory;
|
||||
@@ -24,15 +27,17 @@ import org.jboss.logging.Logger;
|
||||
|
||||
import java.security.SecureRandom;
|
||||
import java.time.Instant;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.Executors;
|
||||
import java.util.concurrent.ScheduledExecutorService;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
@ApplicationScoped
|
||||
public class MskService {
|
||||
public class MskService implements ResourceProvider {
|
||||
|
||||
private static final Logger LOG = Logger.getLogger(MskService.class);
|
||||
private static final String DEFAULT_KAFKA_VERSION = "3.6.0";
|
||||
@@ -279,4 +284,27 @@ public class MskService {
|
||||
storage.put(cluster.getClusterArn(), cluster);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<ExplorerResource> getResources() {
|
||||
List<ExplorerResource> resources = new ArrayList<>();
|
||||
for (MskCluster cluster : storage.scan(k -> true)) {
|
||||
String arn = cluster.getClusterArn();
|
||||
if (arn == null) {
|
||||
continue;
|
||||
}
|
||||
AwsArnUtils.Arn parsed = AwsArnUtils.parse(arn);
|
||||
resources.add(new ExplorerResource(
|
||||
arn, "kafka:cluster", "kafka",
|
||||
parsed.region(), parsed.accountId(),
|
||||
cluster.getCreationTime() != null ? cluster.getCreationTime() : Instant.now(),
|
||||
cluster.getTags() != null ? cluster.getTags() : Map.of()));
|
||||
}
|
||||
return resources;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Set<SupportedResourceType> getSupportedResourceTypes() {
|
||||
return Set.of(new SupportedResourceType("kafka:cluster", "kafka", true));
|
||||
}
|
||||
}
|
||||
+28
-1
@@ -24,14 +24,19 @@ import org.jboss.logging.Logger;
|
||||
|
||||
import java.security.SecureRandom;
|
||||
import java.time.Instant;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.concurrent.Executors;
|
||||
import java.util.concurrent.ScheduledExecutorService;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import io.github.hectorvent.floci.core.resource.ExplorerResource;
|
||||
import io.github.hectorvent.floci.core.resource.ResourceProvider;
|
||||
import io.github.hectorvent.floci.core.resource.SupportedResourceType;
|
||||
|
||||
@ApplicationScoped
|
||||
public class OpenSearchService {
|
||||
public class OpenSearchService implements ResourceProvider {
|
||||
|
||||
private static final Logger LOG = Logger.getLogger(OpenSearchService.class);
|
||||
|
||||
@@ -366,4 +371,26 @@ public class OpenSearchService {
|
||||
domainStore.put(domain.getDomainName(), domain);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<ExplorerResource> getResources() {
|
||||
List<ExplorerResource> resources = new ArrayList<>();
|
||||
for (Domain domain : listDomainNames(null)) {
|
||||
if (domain.getArn() == null) {
|
||||
continue;
|
||||
}
|
||||
AwsArnUtils.Arn parsed = AwsArnUtils.parse(domain.getArn());
|
||||
resources.add(new ExplorerResource(
|
||||
domain.getArn(), "es:domain", "es",
|
||||
parsed.region(), parsed.accountId(),
|
||||
domain.getCreatedAt() != null ? domain.getCreatedAt() : Instant.now(),
|
||||
domain.getTags() != null ? domain.getTags() : Map.of()));
|
||||
}
|
||||
return resources;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Set<SupportedResourceType> getSupportedResourceTypes() {
|
||||
return Set.of(new SupportedResourceType("es:domain", "es", true));
|
||||
}
|
||||
}
|
||||
@@ -4,6 +4,9 @@ import io.github.hectorvent.floci.core.common.AwsArnUtils;
|
||||
import io.github.hectorvent.floci.core.common.AwsException;
|
||||
import io.github.hectorvent.floci.core.common.RegionResolver;
|
||||
import io.github.hectorvent.floci.core.common.TagHandler;
|
||||
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.AccountAwareStorageBackend;
|
||||
import io.github.hectorvent.floci.core.storage.StorageBackend;
|
||||
import io.github.hectorvent.floci.core.storage.StorageFactory;
|
||||
@@ -17,13 +20,15 @@ import jakarta.inject.Inject;
|
||||
import org.jboss.logging.Logger;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
@ApplicationScoped
|
||||
public class PipesService implements TagHandler {
|
||||
public class PipesService implements TagHandler, ResourceProvider {
|
||||
|
||||
private static final Logger LOG = Logger.getLogger(PipesService.class);
|
||||
|
||||
@@ -204,6 +209,29 @@ public class PipesService implements TagHandler {
|
||||
return pipe;
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<ExplorerResource> getResources() {
|
||||
List<ExplorerResource> resources = new ArrayList<>();
|
||||
for (Pipe pipe : storage.scan(k -> true)) {
|
||||
String arn = pipe.getArn();
|
||||
if (arn == null) {
|
||||
continue;
|
||||
}
|
||||
AwsArnUtils.Arn parsed = AwsArnUtils.parse(arn);
|
||||
resources.add(new ExplorerResource(
|
||||
arn, "pipes:pipe", "pipes",
|
||||
parsed.region(), parsed.accountId(),
|
||||
pipe.getCreationTime() != null ? pipe.getCreationTime() : Instant.now(),
|
||||
pipe.getTags() != null ? pipe.getTags() : Map.of()));
|
||||
}
|
||||
return resources;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Set<SupportedResourceType> getSupportedResourceTypes() {
|
||||
return Set.of(new SupportedResourceType("pipes:pipe", "pipes", true));
|
||||
}
|
||||
|
||||
@Override
|
||||
public String serviceKey() {
|
||||
return "pipes";
|
||||
|
||||
@@ -10,6 +10,9 @@ import io.github.hectorvent.floci.core.common.RegionResolver;
|
||||
import io.github.hectorvent.floci.core.common.docker.ContainerStorageHelper;
|
||||
import io.github.hectorvent.floci.core.common.docker.CurrentContainerNetworkResolver;
|
||||
import io.github.hectorvent.floci.core.common.docker.DockerHostResolver;
|
||||
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.AccountAwareStorageBackend;
|
||||
import io.github.hectorvent.floci.core.storage.InMemoryStorage;
|
||||
import io.github.hectorvent.floci.core.storage.StorageBackend;
|
||||
@@ -33,6 +36,7 @@ import io.github.hectorvent.floci.services.rds.model.DbSubnetGroup;
|
||||
import io.github.hectorvent.floci.services.rds.model.OptionGroup;
|
||||
import io.github.hectorvent.floci.services.rds.model.OptionGroupOption;
|
||||
import io.github.hectorvent.floci.services.rds.proxy.RdsProxyManager;
|
||||
import io.github.hectorvent.floci.services.resourcegroupstagging.ResourceGroupsTaggingService;
|
||||
import io.github.hectorvent.floci.services.secretsmanager.SecretsManagerService;
|
||||
import io.github.hectorvent.floci.services.secretsmanager.model.Secret;
|
||||
import io.github.hectorvent.floci.core.common.Resettable;
|
||||
@@ -61,7 +65,7 @@ import java.util.regex.Pattern;
|
||||
* Starts DB containers and auth proxies on creation.
|
||||
*/
|
||||
@ApplicationScoped
|
||||
public class RdsService implements Resettable {
|
||||
public class RdsService implements Resettable, ResourceProvider {
|
||||
|
||||
private static final Logger LOG = Logger.getLogger(RdsService.class);
|
||||
private static final ObjectMapper JSON = new ObjectMapper();
|
||||
@@ -132,6 +136,7 @@ public class RdsService implements Resettable {
|
||||
private final SecretsManagerService secretsManagerService;
|
||||
private final DockerHostResolver dockerHostResolver;
|
||||
private final CurrentContainerNetworkResolver currentContainerNetworkResolver;
|
||||
private final ResourceGroupsTaggingService taggingService;
|
||||
private final Set<Integer> usedPorts = ConcurrentHashMap.newKeySet();
|
||||
private static final Pattern IMAGE_TAG_VERSION_PATTERN = Pattern.compile("^(\\d+(?:\\.\\d+)*)(.*)$");
|
||||
private static final Pattern SAFE_IMAGE_TAG_PATTERN = Pattern.compile("[A-Za-z0-9._-]+");
|
||||
@@ -163,7 +168,8 @@ public class RdsService implements Resettable {
|
||||
StorageFactory storageFactory,
|
||||
SecretsManagerService secretsManagerService,
|
||||
DockerHostResolver dockerHostResolver,
|
||||
CurrentContainerNetworkResolver currentContainerNetworkResolver) {
|
||||
CurrentContainerNetworkResolver currentContainerNetworkResolver,
|
||||
ResourceGroupsTaggingService taggingService) {
|
||||
this.containerManager = containerManager;
|
||||
this.proxyManager = proxyManager;
|
||||
this.ec2Service = ec2Service;
|
||||
@@ -172,6 +178,7 @@ public class RdsService implements Resettable {
|
||||
this.secretsManagerService = secretsManagerService;
|
||||
this.dockerHostResolver = dockerHostResolver;
|
||||
this.currentContainerNetworkResolver = currentContainerNetworkResolver;
|
||||
this.taggingService = taggingService;
|
||||
this.instances = storageFactory.create("rds", "rds-instances.json",
|
||||
new TypeReference<Map<String, DbInstance>>() {});
|
||||
this.clusters = storageFactory.create("rds", "rds-clusters.json",
|
||||
@@ -280,7 +287,7 @@ public class RdsService implements Resettable {
|
||||
this(containerManager, proxyManager, ec2Service, regionResolver, config,
|
||||
instances, clusters, parameterGroups, clusterParameterGroups, subnetGroups,
|
||||
secretsManagerService, dockerHostResolver, currentContainerNetworkResolver,
|
||||
proxies, proxyTargetGroups, new InMemoryStorage<>());
|
||||
proxies, proxyTargetGroups, new InMemoryStorage<>(), null);
|
||||
}
|
||||
|
||||
RdsService(RdsContainerManager containerManager,
|
||||
@@ -298,7 +305,8 @@ public class RdsService implements Resettable {
|
||||
CurrentContainerNetworkResolver currentContainerNetworkResolver,
|
||||
StorageBackend<String, DbProxy> proxies,
|
||||
StorageBackend<String, DbProxyTargetGroup> proxyTargetGroups,
|
||||
StorageBackend<String, OptionGroup> optionGroups) {
|
||||
StorageBackend<String, OptionGroup> optionGroups,
|
||||
ResourceGroupsTaggingService taggingService) {
|
||||
this.containerManager = containerManager;
|
||||
this.proxyManager = proxyManager;
|
||||
this.ec2Service = ec2Service;
|
||||
@@ -315,6 +323,7 @@ public class RdsService implements Resettable {
|
||||
this.subnetGroups = subnetGroups;
|
||||
this.proxies = proxies;
|
||||
this.proxyTargetGroups = proxyTargetGroups;
|
||||
this.taggingService = taggingService;
|
||||
}
|
||||
|
||||
public void restorePersistedRuntime() {
|
||||
@@ -5039,4 +5048,48 @@ public class RdsService implements Resettable {
|
||||
cluster.getSubnetAvailabilityZones());
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<ExplorerResource> getResources() {
|
||||
List<ExplorerResource> resources = new ArrayList<>();
|
||||
for (DbInstance instance : listDbInstances(null)) {
|
||||
String arn = instance.getDbInstanceArn();
|
||||
if (arn == null) {
|
||||
continue;
|
||||
}
|
||||
AwsArnUtils.Arn parsed = AwsArnUtils.parse(arn);
|
||||
resources.add(new ExplorerResource(arn, "rds:db", "rds",
|
||||
parsed.region(), parsed.accountId(),
|
||||
instance.getCreatedAt() != null ? instance.getCreatedAt() : Instant.now(),
|
||||
tagsFor(parsed.region(), arn)));
|
||||
}
|
||||
for (DbCluster cluster : listDbClusters(null)) {
|
||||
String arn = cluster.getDbClusterArn();
|
||||
if (arn == null) {
|
||||
continue;
|
||||
}
|
||||
AwsArnUtils.Arn parsed = AwsArnUtils.parse(arn);
|
||||
resources.add(new ExplorerResource(arn, "rds:cluster", "rds",
|
||||
parsed.region(), parsed.accountId(),
|
||||
cluster.getCreatedAt() != null ? cluster.getCreatedAt() : Instant.now(),
|
||||
tagsFor(parsed.region(), arn)));
|
||||
}
|
||||
return resources;
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolves tags for a resource, tolerating a null taggingService. The CDI constructor always
|
||||
* supplies one; the storage-backed test constructors pass null, and unit tests that exercise
|
||||
* getResources() would otherwise NPE.
|
||||
*/
|
||||
private Map<String, String> tagsFor(String region, String arn) {
|
||||
return taggingService != null ? taggingService.getTagsForResource(region, arn) : Map.of();
|
||||
}
|
||||
|
||||
@Override
|
||||
public Set<SupportedResourceType> getSupportedResourceTypes() {
|
||||
return Set.of(
|
||||
new SupportedResourceType("rds:db", "rds", true),
|
||||
new SupportedResourceType("rds:cluster", "rds", true));
|
||||
}
|
||||
}
|
||||
+463
@@ -0,0 +1,463 @@
|
||||
package io.github.hectorvent.floci.services.resourceexplorer2;
|
||||
|
||||
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.services.resourceexplorer2.model.*;
|
||||
import jakarta.inject.Inject;
|
||||
import jakarta.ws.rs.*;
|
||||
import jakarta.ws.rs.core.Context;
|
||||
import jakarta.ws.rs.core.HttpHeaders;
|
||||
import jakarta.ws.rs.core.MediaType;
|
||||
import jakarta.ws.rs.core.Response;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
@Path("/")
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
@Consumes(MediaType.APPLICATION_JSON)
|
||||
public class ResourceExplorer2Controller {
|
||||
|
||||
/**
|
||||
* Per-operation MaxResults ceilings. AWS models a different maximum for each of these, and a
|
||||
* value above it is a ValidationException — so a single shared constant would either reject
|
||||
* page sizes AWS accepts or accept ones it rejects.
|
||||
*/
|
||||
private static final int MAX_RESULTS_RESOURCES = 1000;
|
||||
private static final int MAX_RESULTS_INDEXES = 100;
|
||||
private static final int MAX_RESULTS_VIEWS = 50;
|
||||
private static final int MAX_RESULTS_MEMBER_INDEXES = 10;
|
||||
|
||||
private final ResourceExplorer2Service service;
|
||||
private final RegionResolver regionResolver;
|
||||
private final ObjectMapper objectMapper;
|
||||
|
||||
@Inject
|
||||
public ResourceExplorer2Controller(ResourceExplorer2Service service,
|
||||
RegionResolver regionResolver,
|
||||
ObjectMapper objectMapper) {
|
||||
this.service = service;
|
||||
this.regionResolver = regionResolver;
|
||||
this.objectMapper = objectMapper;
|
||||
}
|
||||
|
||||
@POST
|
||||
@Path("/ListResources")
|
||||
public Response listResources(@Context HttpHeaders headers, String body) throws IOException {
|
||||
JsonNode req = parseBody(body);
|
||||
String region = regionResolver.resolveRegion(headers);
|
||||
String filterString = req.has("Filters") && req.get("Filters").has("FilterString")
|
||||
? req.get("Filters").get("FilterString").asText(null) : null;
|
||||
Integer maxResults = validatedMaxResults(req, MAX_RESULTS_RESOURCES);
|
||||
String nextToken = optString(req, "NextToken");
|
||||
String viewArn = optString(req, "ViewArn");
|
||||
try {
|
||||
return Response.ok(service.listResources(filterString, maxResults, nextToken, viewArn, region)).build();
|
||||
} catch (IllegalArgumentException e) {
|
||||
throw new AwsException("ValidationException", e.getMessage(), 400);
|
||||
}
|
||||
}
|
||||
|
||||
@POST
|
||||
@Path("/Search")
|
||||
public Response search(@Context HttpHeaders headers, String body) throws IOException {
|
||||
JsonNode req = parseBody(body);
|
||||
if (!req.has("QueryString")) {
|
||||
throw new AwsException("ValidationException", "QueryString is required", 400);
|
||||
}
|
||||
String queryString = req.get("QueryString").asText(null);
|
||||
Integer maxResults = validatedMaxResults(req, MAX_RESULTS_RESOURCES);
|
||||
String nextToken = optString(req, "NextToken");
|
||||
String viewArn = optString(req, "ViewArn");
|
||||
String region = regionResolver.resolveRegion(headers);
|
||||
return Response.ok(service.search(queryString, maxResults, nextToken, viewArn, region)).build();
|
||||
}
|
||||
|
||||
@POST
|
||||
@Path("/ListSupportedResourceTypes")
|
||||
public Response listSupportedResourceTypes(String body) throws IOException {
|
||||
JsonNode req = parseBody(body);
|
||||
Integer maxResults = validatedMaxResults(req, MAX_RESULTS_RESOURCES);
|
||||
String nextToken = optString(req, "NextToken");
|
||||
return Response.ok(service.listSupportedResourceTypes(maxResults, nextToken)).build();
|
||||
}
|
||||
|
||||
@POST
|
||||
@Path("/re2/CreateIndex")
|
||||
public Response createIndex(@Context HttpHeaders headers, String body) throws IOException {
|
||||
JsonNode req = parseBody(body);
|
||||
String region = regionResolver.resolveRegion(headers);
|
||||
Map<String, String> tags = parseTags(req);
|
||||
Index index = service.createIndex(region, tags);
|
||||
var result = objectMapper.createObjectNode();
|
||||
result.put("Arn", index.arn());
|
||||
result.put("CreatedAt", index.createdAt().toString());
|
||||
// Real AWS returns CREATING immediately; we store ACTIVE synchronously but the
|
||||
// caller must see CREATING as the initial state per the AWS API contract.
|
||||
result.put("State", "CREATING");
|
||||
return Response.ok(result).build();
|
||||
}
|
||||
|
||||
@POST
|
||||
@Path("/re2/GetIndex")
|
||||
public Response getIndex(@Context HttpHeaders headers) {
|
||||
String region = regionResolver.resolveRegion(headers);
|
||||
Index index = service.getIndex(region);
|
||||
var result = objectMapper.createObjectNode();
|
||||
result.put("Arn", index.arn());
|
||||
result.put("CreatedAt", index.createdAt().toString());
|
||||
result.put("LastUpdatedAt", index.lastUpdatedAt().toString());
|
||||
result.set("ReplicatingFrom", objectMapper.valueToTree(index.replicatingFrom()));
|
||||
result.set("ReplicatingTo", objectMapper.valueToTree(index.replicatingTo()));
|
||||
result.put("State", index.state().name());
|
||||
result.set("Tags", objectMapper.valueToTree(index.tags()));
|
||||
result.put("Type", index.type().name());
|
||||
return Response.ok(result).build();
|
||||
}
|
||||
|
||||
@POST
|
||||
@Path("/re2/DeleteIndex")
|
||||
public Response deleteIndex(String body) throws IOException {
|
||||
JsonNode req = parseBody(body);
|
||||
String indexArn = optString(req, "Arn");
|
||||
if (indexArn == null) {
|
||||
throw new AwsException("ValidationException", "Arn is required", 400);
|
||||
}
|
||||
Index deleted = service.deleteIndex(indexArn);
|
||||
var result = objectMapper.createObjectNode();
|
||||
result.put("Arn", deleted.arn());
|
||||
result.put("LastUpdatedAt", deleted.lastUpdatedAt().toString());
|
||||
result.put("State", deleted.state().name());
|
||||
return Response.ok(result).build();
|
||||
}
|
||||
|
||||
@POST
|
||||
@Path("/re2/ListIndexes")
|
||||
public Response listIndexes(String body) throws IOException {
|
||||
JsonNode req = parseBody(body);
|
||||
String type = optString(req, "Type");
|
||||
List<String> regions = stringArray(req, "Regions");
|
||||
Integer maxResults = validatedMaxResults(req, MAX_RESULTS_INDEXES);
|
||||
String nextToken = optString(req, "NextToken");
|
||||
return Response.ok(service.listIndexes(type, regions, maxResults, nextToken)).build();
|
||||
}
|
||||
|
||||
@POST
|
||||
@Path("/UpdateIndexType")
|
||||
public Response updateIndexType(String body) throws IOException {
|
||||
JsonNode req = parseBody(body);
|
||||
String arn = optString(req, "Arn");
|
||||
if (arn == null) {
|
||||
throw new AwsException("ValidationException", "Arn is required", 400);
|
||||
}
|
||||
if (!req.has("Type")) {
|
||||
throw new AwsException("ValidationException", "Type is required", 400);
|
||||
}
|
||||
IndexType type;
|
||||
try {
|
||||
type = IndexType.valueOf(req.get("Type").asText());
|
||||
} catch (IllegalArgumentException e) {
|
||||
throw new AwsException("ValidationException", "Invalid index type: " + req.get("Type").asText(), 400);
|
||||
}
|
||||
Index index = service.updateIndexType(arn, type);
|
||||
var result = objectMapper.createObjectNode();
|
||||
result.put("Arn", index.arn());
|
||||
result.put("LastUpdatedAt", index.lastUpdatedAt().toString());
|
||||
result.put("State", index.state().name());
|
||||
result.put("Type", index.type().name());
|
||||
return Response.ok(result).build();
|
||||
}
|
||||
|
||||
@POST
|
||||
@Path("/CreateView")
|
||||
public Response createView(@Context HttpHeaders headers, String body) throws IOException {
|
||||
JsonNode req = parseBody(body);
|
||||
String region = regionResolver.resolveRegion(headers);
|
||||
String viewName = optString(req, "ViewName");
|
||||
String scope = optString(req, "Scope");
|
||||
SearchFilter filters = parseFilters(req);
|
||||
List<IncludedProperty> includedProperties = parseIncludedProperties(req);
|
||||
Map<String, String> tags = parseTags(req);
|
||||
View view = service.createView(region, viewName, scope, filters, includedProperties, tags);
|
||||
var result = objectMapper.createObjectNode();
|
||||
result.set("View", service.buildViewNode(view));
|
||||
return Response.ok(result).build();
|
||||
}
|
||||
|
||||
@POST
|
||||
@Path("/GetView")
|
||||
public Response getView(String body) throws IOException {
|
||||
JsonNode req = parseBody(body);
|
||||
String viewArn = optString(req, "ViewArn");
|
||||
if (viewArn == null) {
|
||||
throw new AwsException("ValidationException", "ViewArn is required", 400);
|
||||
}
|
||||
View view = service.getView(viewArn);
|
||||
var result = objectMapper.createObjectNode();
|
||||
result.set("View", service.buildViewNode(view));
|
||||
result.set("Tags", objectMapper.valueToTree(
|
||||
view.tags() != null ? view.tags() : Map.of()));
|
||||
return Response.ok(result).build();
|
||||
}
|
||||
|
||||
@POST
|
||||
@Path("/DeleteView")
|
||||
public Response deleteView(String body) throws IOException {
|
||||
JsonNode req = parseBody(body);
|
||||
String viewArn = optString(req, "ViewArn");
|
||||
if (viewArn == null) {
|
||||
throw new AwsException("ValidationException", "ViewArn is required", 400);
|
||||
}
|
||||
service.deleteView(viewArn);
|
||||
var result = objectMapper.createObjectNode();
|
||||
result.put("ViewArn", viewArn);
|
||||
return Response.ok(result).build();
|
||||
}
|
||||
|
||||
@POST
|
||||
@Path("/UpdateView")
|
||||
public Response updateView(String body) throws IOException {
|
||||
JsonNode req = parseBody(body);
|
||||
String viewArn = optString(req, "ViewArn");
|
||||
if (viewArn == null) {
|
||||
throw new AwsException("ValidationException", "ViewArn is required", 400);
|
||||
}
|
||||
SearchFilter filters = parseFilters(req);
|
||||
List<IncludedProperty> includedProperties = parseIncludedProperties(req);
|
||||
View view = service.updateView(viewArn, filters, includedProperties);
|
||||
var result = objectMapper.createObjectNode();
|
||||
result.set("View", service.buildViewNode(view));
|
||||
return Response.ok(result).build();
|
||||
}
|
||||
|
||||
@POST
|
||||
@Path("/ListViews")
|
||||
public Response listViews(@Context HttpHeaders headers, String body) throws IOException {
|
||||
JsonNode req = parseBody(body);
|
||||
Integer maxResults = validatedMaxResults(req, MAX_RESULTS_VIEWS);
|
||||
String nextToken = optString(req, "NextToken");
|
||||
String region = regionResolver.resolveRegion(headers);
|
||||
return Response.ok(service.listViews(region, maxResults, nextToken)).build();
|
||||
}
|
||||
|
||||
@POST
|
||||
@Path("/BatchGetView")
|
||||
public Response batchGetView(String body) throws IOException {
|
||||
JsonNode req = parseBody(body);
|
||||
return Response.ok(service.batchGetView(stringArray(req, "ViewArns"))).build();
|
||||
}
|
||||
|
||||
@POST
|
||||
@Path("/AssociateDefaultView")
|
||||
public Response associateDefaultView(@Context HttpHeaders headers, String body) throws IOException {
|
||||
JsonNode req = parseBody(body);
|
||||
String viewArn = optString(req, "ViewArn");
|
||||
if (viewArn == null) {
|
||||
throw new AwsException("ValidationException", "ViewArn is required", 400);
|
||||
}
|
||||
service.associateDefaultView(regionResolver.resolveRegion(headers), viewArn);
|
||||
var result = objectMapper.createObjectNode();
|
||||
result.put("ViewArn", viewArn);
|
||||
return Response.ok(result).build();
|
||||
}
|
||||
|
||||
@POST
|
||||
@Path("/DisassociateDefaultView")
|
||||
public Response disassociateDefaultView(@Context HttpHeaders headers) {
|
||||
service.disassociateDefaultView(regionResolver.resolveRegion(headers));
|
||||
return Response.ok("{}").build();
|
||||
}
|
||||
|
||||
@POST
|
||||
@Path("/GetDefaultView")
|
||||
public Response getDefaultView(@Context HttpHeaders headers) {
|
||||
String viewArn = service.getDefaultView(regionResolver.resolveRegion(headers));
|
||||
var result = objectMapper.createObjectNode();
|
||||
if (viewArn != null) {
|
||||
result.put("ViewArn", viewArn);
|
||||
}
|
||||
return Response.ok(result).build();
|
||||
}
|
||||
|
||||
|
||||
@POST
|
||||
@Path("/GetAccountLevelServiceConfiguration")
|
||||
public Response getAccountLevelServiceConfiguration() {
|
||||
return Response.ok(service.getAccountLevelServiceConfiguration()).build();
|
||||
}
|
||||
|
||||
@POST
|
||||
@Path("/ListIndexesForMembers")
|
||||
public Response listIndexesForMembers(String body) throws IOException {
|
||||
JsonNode req = parseBody(body);
|
||||
List<String> accountIds = stringArray(req, "AccountIdList");
|
||||
if (accountIds.isEmpty()) {
|
||||
throw new AwsException("ValidationException", "AccountIdList is required", 400);
|
||||
}
|
||||
Integer maxResults = validatedMaxResults(req, MAX_RESULTS_MEMBER_INDEXES);
|
||||
String nextToken = optString(req, "NextToken");
|
||||
return Response.ok(service.listIndexesForMembers(accountIds, maxResults, nextToken)).build();
|
||||
}
|
||||
|
||||
@POST
|
||||
@Path("/ListManagedViews")
|
||||
public Response listManagedViews(String body) throws IOException {
|
||||
JsonNode req = parseBody(body);
|
||||
Integer maxResults = validatedMaxResults(req, MAX_RESULTS_VIEWS);
|
||||
String nextToken = optString(req, "NextToken");
|
||||
return Response.ok(service.listManagedViews(maxResults, nextToken)).build();
|
||||
}
|
||||
|
||||
@POST
|
||||
@Path("/GetManagedView")
|
||||
public Response getManagedView(String body) throws IOException {
|
||||
JsonNode req = parseBody(body);
|
||||
String managedViewArn = optString(req, "ManagedViewArn");
|
||||
if (managedViewArn == null) {
|
||||
throw new AwsException("ValidationException", "ManagedViewArn is required", 400);
|
||||
}
|
||||
return Response.ok(service.getManagedView(managedViewArn)).build();
|
||||
}
|
||||
|
||||
@POST
|
||||
@Path("/ListServiceViews")
|
||||
public Response listServiceViews(String body) throws IOException {
|
||||
JsonNode req = parseBody(body);
|
||||
Integer maxResults = validatedMaxResults(req, MAX_RESULTS_VIEWS);
|
||||
String nextToken = optString(req, "NextToken");
|
||||
return Response.ok(service.listServiceViews(maxResults, nextToken)).build();
|
||||
}
|
||||
|
||||
@POST
|
||||
@Path("/GetServiceView")
|
||||
public Response getServiceView(String body) throws IOException {
|
||||
JsonNode req = parseBody(body);
|
||||
String serviceViewArn = optString(req, "ServiceViewArn");
|
||||
if (serviceViewArn == null) {
|
||||
throw new AwsException("ValidationException", "ServiceViewArn is required", 400);
|
||||
}
|
||||
return Response.ok(service.getServiceView(serviceViewArn)).build();
|
||||
}
|
||||
|
||||
@POST
|
||||
@Path("/ListServiceIndexes")
|
||||
public Response listServiceIndexes(String body) throws IOException {
|
||||
JsonNode req = parseBody(body);
|
||||
List<String> regions = stringArray(req, "Regions");
|
||||
Integer maxResults = validatedMaxResults(req, MAX_RESULTS_INDEXES);
|
||||
String nextToken = optString(req, "NextToken");
|
||||
return Response.ok(service.listServiceIndexes(regions, maxResults, nextToken)).build();
|
||||
}
|
||||
|
||||
@POST
|
||||
@Path("/GetServiceIndex")
|
||||
public Response getServiceIndex(@Context HttpHeaders headers) {
|
||||
return Response.ok(service.getServiceIndex(regionResolver.resolveRegion(headers))).build();
|
||||
}
|
||||
|
||||
@POST
|
||||
@Path("/ListStreamingAccessForServices")
|
||||
public Response listStreamingAccessForServices(String body) throws IOException {
|
||||
JsonNode req = parseBody(body);
|
||||
Integer maxResults = validatedMaxResults(req, MAX_RESULTS_VIEWS);
|
||||
String nextToken = optString(req, "NextToken");
|
||||
return Response.ok(service.listStreamingAccessForServices(maxResults, nextToken)).build();
|
||||
}
|
||||
|
||||
@POST
|
||||
@Path("/CreateResourceExplorerSetup")
|
||||
public Response createResourceExplorerSetup(String body) throws IOException {
|
||||
JsonNode req = parseBody(body);
|
||||
String taskId = service.createResourceExplorerSetup(
|
||||
stringArray(req, "RegionList"),
|
||||
optString(req, "ViewName"),
|
||||
stringArray(req, "AggregatorRegions"));
|
||||
var result = objectMapper.createObjectNode();
|
||||
result.put("TaskId", taskId);
|
||||
return Response.ok(result).build();
|
||||
}
|
||||
|
||||
@POST
|
||||
@Path("/DeleteResourceExplorerSetup")
|
||||
public Response deleteResourceExplorerSetup(String body) throws IOException {
|
||||
JsonNode req = parseBody(body);
|
||||
Boolean deleteInAllRegions = req.has("DeleteInAllRegions")
|
||||
? req.get("DeleteInAllRegions").asBoolean() : null;
|
||||
String taskId = service.deleteResourceExplorerSetup(
|
||||
deleteInAllRegions, stringArray(req, "RegionList"));
|
||||
var result = objectMapper.createObjectNode();
|
||||
result.put("TaskId", taskId);
|
||||
return Response.ok(result).build();
|
||||
}
|
||||
|
||||
@POST
|
||||
@Path("/GetResourceExplorerSetup")
|
||||
public Response getResourceExplorerSetup(String body) throws IOException {
|
||||
JsonNode req = parseBody(body);
|
||||
String taskId = optString(req, "TaskId");
|
||||
if (taskId == null) {
|
||||
throw new AwsException("ValidationException", "TaskId is required", 400);
|
||||
}
|
||||
Integer maxResults = validatedMaxResults(req, MAX_RESULTS_INDEXES);
|
||||
String nextToken = optString(req, "NextToken");
|
||||
return Response.ok(service.getResourceExplorerSetup(taskId, maxResults, nextToken)).build();
|
||||
}
|
||||
|
||||
private static List<String> stringArray(JsonNode req, String field) {
|
||||
List<String> values = new ArrayList<>();
|
||||
if (req.has(field) && req.get(field).isArray()) {
|
||||
for (JsonNode value : req.get(field)) {
|
||||
values.add(value.asText());
|
||||
}
|
||||
}
|
||||
return values;
|
||||
}
|
||||
|
||||
private static String optString(JsonNode req, String field) {
|
||||
return req.has(field) ? req.get(field).asText(null) : null;
|
||||
}
|
||||
|
||||
private JsonNode parseBody(String body) throws IOException {
|
||||
return objectMapper.readTree(body == null || body.isBlank() ? "{}" : body);
|
||||
}
|
||||
|
||||
private Map<String, String> parseTags(JsonNode req) {
|
||||
Map<String, String> tags = new HashMap<>();
|
||||
if (req.has("Tags") && req.get("Tags").isObject()) {
|
||||
req.get("Tags").fields().forEachRemaining(e -> tags.put(e.getKey(), e.getValue().asText()));
|
||||
}
|
||||
return tags;
|
||||
}
|
||||
|
||||
private SearchFilter parseFilters(JsonNode req) {
|
||||
return req.has("Filters") && req.get("Filters").has("FilterString")
|
||||
? new SearchFilter(req.get("Filters").get("FilterString").asText()) : null;
|
||||
}
|
||||
|
||||
private List<IncludedProperty> parseIncludedProperties(JsonNode req) {
|
||||
List<IncludedProperty> includedProperties = new ArrayList<>();
|
||||
if (req.has("IncludedProperties") && req.get("IncludedProperties").isArray()) {
|
||||
for (var p : req.get("IncludedProperties")) {
|
||||
includedProperties.add(new IncludedProperty(p.has("Name") ? p.get("Name").asText() : ""));
|
||||
}
|
||||
}
|
||||
return includedProperties;
|
||||
}
|
||||
|
||||
private Integer validatedMaxResults(JsonNode req, int max) {
|
||||
if (!req.has("MaxResults")) {
|
||||
return null;
|
||||
}
|
||||
int value = req.get("MaxResults").intValue();
|
||||
if (value < 1 || value > max) {
|
||||
throw new AwsException("ValidationException", "MaxResults must be between 1 and " + max, 400);
|
||||
}
|
||||
return value;
|
||||
}
|
||||
|
||||
}
|
||||
+75
@@ -0,0 +1,75 @@
|
||||
package io.github.hectorvent.floci.services.resourceexplorer2;
|
||||
|
||||
import io.github.hectorvent.floci.core.common.ResolvedServiceCatalog;
|
||||
import io.github.hectorvent.floci.core.common.ServiceDescriptor;
|
||||
import io.github.hectorvent.floci.core.common.SigV4CredentialScope;
|
||||
import jakarta.inject.Inject;
|
||||
import jakarta.ws.rs.container.ContainerRequestContext;
|
||||
import jakarta.ws.rs.container.ContainerRequestFilter;
|
||||
import jakarta.ws.rs.container.PreMatching;
|
||||
import jakarta.ws.rs.ext.Provider;
|
||||
|
||||
import java.util.Set;
|
||||
|
||||
/**
|
||||
* Pre-matching filter that disambiguates Resource Explorer 2 endpoints from S3 Vectors
|
||||
* endpoints that share the same JAX-RS path names ({@code /CreateIndex}, {@code /GetIndex},
|
||||
* {@code /ListIndexes}, {@code /DeleteIndex}).
|
||||
*
|
||||
* <p>Both are REST-JSON services rooted at {@code /}, so JAX-RS cannot tell their identically
|
||||
* named operations apart. Floci resolves this the same way {@code AwsQueryController} resolves
|
||||
* query-protocol services: by the SigV4 credential scope, looked up in the
|
||||
* {@link ResolvedServiceCatalog}. When the scope resolves to the Resource Explorer 2 service,
|
||||
* the conflicting path is rewritten to the {@code /re2/} prefix so it reaches
|
||||
* {@link ResourceExplorer2Controller}; otherwise it falls through to the S3 Vectors controller.
|
||||
*
|
||||
* <p>All other Resource Explorer 2 paths (e.g. {@code /ListResources}, {@code /Search}) are
|
||||
* unique across controllers and need no rewriting.
|
||||
*/
|
||||
@Provider
|
||||
@PreMatching
|
||||
public class ResourceExplorer2PathRewriteFilter implements ContainerRequestFilter {
|
||||
|
||||
private static final String RESOURCE_EXPLORER_2 = "resource-explorer-2";
|
||||
|
||||
// Mirror of the index operation paths declared by S3VectorsController. A colliding path missing
|
||||
// from this set falls through to S3 Vectors even for Resource Explorer 2 callers.
|
||||
private static final Set<String> AMBIGUOUS_PATHS = Set.of(
|
||||
"/CreateIndex",
|
||||
"/GetIndex",
|
||||
"/ListIndexes",
|
||||
"/DeleteIndex"
|
||||
);
|
||||
|
||||
private final ResolvedServiceCatalog catalog;
|
||||
|
||||
@Inject
|
||||
public ResourceExplorer2PathRewriteFilter(ResolvedServiceCatalog catalog) {
|
||||
this.catalog = catalog;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void filter(ContainerRequestContext ctx) {
|
||||
String path = ctx.getUriInfo().getPath();
|
||||
String normalizedPath = path.startsWith("/") ? path : "/" + path;
|
||||
|
||||
if (!AMBIGUOUS_PATHS.contains(normalizedPath)) {
|
||||
return;
|
||||
}
|
||||
|
||||
boolean targetsResourceExplorer2 =
|
||||
SigV4CredentialScope.serviceName(ctx.getHeaderString("Authorization"))
|
||||
.flatMap(catalog::byCredentialScope)
|
||||
.map(ServiceDescriptor::externalKey)
|
||||
.filter(RESOURCE_EXPLORER_2::equals)
|
||||
.isPresent();
|
||||
|
||||
if (!targetsResourceExplorer2) {
|
||||
return;
|
||||
}
|
||||
|
||||
ctx.setRequestUri(ctx.getUriInfo().getRequestUriBuilder()
|
||||
.replacePath("/re2" + normalizedPath)
|
||||
.build());
|
||||
}
|
||||
}
|
||||
+1039
File diff suppressed because it is too large.
Load diff
+46
@@ -0,0 +1,46 @@
|
||||
package io.github.hectorvent.floci.services.resourceexplorer2;
|
||||
|
||||
import io.github.hectorvent.floci.core.common.TagHandler;
|
||||
import jakarta.enterprise.context.ApplicationScoped;
|
||||
import jakarta.inject.Inject;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* Handles tag operations on Resource Explorer 2 indexes and views.
|
||||
*
|
||||
* <p>Discovered by {@link io.github.hectorvent.floci.core.common.SharedTagsController}
|
||||
* via CDI. Routes {@code /tags/{arn}} requests where the ARN service segment is
|
||||
* {@code "resource-explorer-2"}.
|
||||
*/
|
||||
@ApplicationScoped
|
||||
public class ResourceExplorer2TagHandler implements TagHandler {
|
||||
|
||||
private final ResourceExplorer2Service service;
|
||||
|
||||
@Inject
|
||||
public ResourceExplorer2TagHandler(ResourceExplorer2Service service) {
|
||||
this.service = service;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String serviceKey() {
|
||||
return "resource-explorer-2";
|
||||
}
|
||||
|
||||
@Override
|
||||
public Map<String, String> listTags(String region, String arn) {
|
||||
return service.listTags(arn);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void tagResource(String region, String arn, Map<String, String> tags) {
|
||||
service.tagResource(arn, tags);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void untagResource(String region, String arn, List<String> tagKeys) {
|
||||
service.untagResource(arn, tagKeys);
|
||||
}
|
||||
}
|
||||
+7
@@ -0,0 +1,7 @@
|
||||
package io.github.hectorvent.floci.services.resourceexplorer2.model;
|
||||
|
||||
import io.quarkus.runtime.annotations.RegisterForReflection;
|
||||
|
||||
/** A property included in search results. Currently only {@code "tags"} is supported. */
|
||||
@RegisterForReflection
|
||||
public record IncludedProperty(String name) {}
|
||||
@@ -0,0 +1,43 @@
|
||||
package io.github.hectorvent.floci.services.resourceexplorer2.model;
|
||||
|
||||
import io.quarkus.runtime.annotations.RegisterForReflection;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
@RegisterForReflection
|
||||
public record Index(
|
||||
String arn,
|
||||
String region,
|
||||
IndexType type,
|
||||
IndexState state,
|
||||
Map<String, String> tags,
|
||||
Instant createdAt,
|
||||
Instant lastUpdatedAt,
|
||||
List<String> replicatingFrom,
|
||||
List<String> replicatingTo) implements Taggable {
|
||||
|
||||
/** New index: lastUpdatedAt tracks createdAt, replication lists start empty. */
|
||||
public Index(String arn, String region, IndexType type, IndexState state,
|
||||
Map<String, String> tags, Instant createdAt) {
|
||||
this(arn, region, type, state, tags, createdAt, createdAt, List.of(), List.of());
|
||||
}
|
||||
|
||||
public Index withState(IndexState state) {
|
||||
return new Index(arn, region, type, state, tags, createdAt, lastUpdatedAt, replicatingFrom, replicatingTo);
|
||||
}
|
||||
|
||||
public Index withType(IndexType type) {
|
||||
return new Index(arn, region, type, state, tags, createdAt, lastUpdatedAt, replicatingFrom, replicatingTo);
|
||||
}
|
||||
|
||||
public Index withLastUpdatedAt(Instant lastUpdatedAt) {
|
||||
return new Index(arn, region, type, state, tags, createdAt, lastUpdatedAt, replicatingFrom, replicatingTo);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Index withTags(Map<String, String> tags) {
|
||||
return new Index(arn, region, type, state, tags, createdAt, lastUpdatedAt, replicatingFrom, replicatingTo);
|
||||
}
|
||||
}
|
||||
+24
@@ -0,0 +1,24 @@
|
||||
package io.github.hectorvent.floci.services.resourceexplorer2.model;
|
||||
|
||||
import io.quarkus.runtime.annotations.RegisterForReflection;
|
||||
|
||||
@RegisterForReflection
|
||||
public enum IndexState {
|
||||
/** The index is being created and is not yet available for use. */
|
||||
CREATING,
|
||||
|
||||
/** The index exists and is available to receive and respond to search queries. */
|
||||
ACTIVE,
|
||||
|
||||
/** The index is being deleted and can no longer be used. */
|
||||
DELETING,
|
||||
|
||||
/** The index has been deleted. */
|
||||
DELETED,
|
||||
|
||||
/**
|
||||
* The index is being changed, typically when converting between {@link IndexType#LOCAL} and
|
||||
* {@link IndexType#AGGREGATOR}. The index remains usable during this transition.
|
||||
*/
|
||||
UPDATING
|
||||
}
|
||||
+19
@@ -0,0 +1,19 @@
|
||||
package io.github.hectorvent.floci.services.resourceexplorer2.model;
|
||||
|
||||
import io.quarkus.runtime.annotations.RegisterForReflection;
|
||||
|
||||
@RegisterForReflection
|
||||
public enum IndexType {
|
||||
/**
|
||||
* A local index holds information only about resources in the same AWS Region as the index. An account can have one
|
||||
* local index per Region.
|
||||
*/
|
||||
LOCAL,
|
||||
|
||||
/**
|
||||
* The aggregator index receives replicated copies of the local index data from all Regions in which the account has
|
||||
* a local index. An account can have only one aggregator index, and it enables Resource Explorer to run
|
||||
* cross-Region searches.
|
||||
*/
|
||||
AGGREGATOR
|
||||
}
|
||||
+7
@@ -0,0 +1,7 @@
|
||||
package io.github.hectorvent.floci.services.resourceexplorer2.model;
|
||||
|
||||
import io.quarkus.runtime.annotations.RegisterForReflection;
|
||||
|
||||
/** Filter string attached to a view or {@code ListResources} request. */
|
||||
@RegisterForReflection
|
||||
public record SearchFilter(String filterString) {}
|
||||
+34
@@ -0,0 +1,34 @@
|
||||
package io.github.hectorvent.floci.services.resourceexplorer2.model;
|
||||
|
||||
import io.quarkus.runtime.annotations.RegisterForReflection;
|
||||
|
||||
/**
|
||||
* The result of one step (index or view) of a Resource Explorer setup task in one AWS Region.
|
||||
*
|
||||
* <p>floci runs a setup task synchronously, so a step is finished the moment
|
||||
* {@code CreateResourceExplorerSetup} or {@code DeleteResourceExplorerSetup} returns and the
|
||||
* status is terminal — {@code SUCCEEDED} or {@code FAILED}. On a failure the AWS
|
||||
* {@code ErrorDetails} fields carry the same code and message the equivalent single-Region call
|
||||
* would have thrown, which is why one Region failing does not abandon the rest of the task.
|
||||
*
|
||||
* @param status {@code SUCCEEDED} or {@code FAILED}
|
||||
* @param arn the index or view ARN the step produced; null for a delete or a failure
|
||||
* @param errorCode AWS error code when {@code status} is {@code FAILED}, else null
|
||||
* @param errorMessage AWS error message when {@code status} is {@code FAILED}, else null
|
||||
* @see <a href="https://docs.aws.amazon.com/resource-explorer/latest/apireference/API_GetResourceExplorerSetup.html">
|
||||
* AWS API: GetResourceExplorerSetup</a>
|
||||
*/
|
||||
@RegisterForReflection
|
||||
public record SetupOutcome(String status, String arn, String errorCode, String errorMessage) {
|
||||
|
||||
public static final String SUCCEEDED = "SUCCEEDED";
|
||||
public static final String FAILED = "FAILED";
|
||||
|
||||
public static SetupOutcome succeeded(String arn) {
|
||||
return new SetupOutcome(SUCCEEDED, arn, null, null);
|
||||
}
|
||||
|
||||
public static SetupOutcome failed(String errorCode, String errorMessage) {
|
||||
return new SetupOutcome(FAILED, null, errorCode, errorMessage);
|
||||
}
|
||||
}
|
||||
+25
@@ -0,0 +1,25 @@
|
||||
package io.github.hectorvent.floci.services.resourceexplorer2.model;
|
||||
|
||||
import io.quarkus.runtime.annotations.RegisterForReflection;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* A completed multi-Region setup task, addressable by {@code TaskId} through
|
||||
* {@code GetResourceExplorerSetup}.
|
||||
*
|
||||
* <p>The per-Region outcomes are recorded when the task runs rather than recomputed on read: a
|
||||
* delete task removes the very indexes and views its status describes, so there would be nothing
|
||||
* left to derive them from afterwards.
|
||||
*
|
||||
* @see <a href="https://docs.aws.amazon.com/resource-explorer/latest/apireference/API_CreateResourceExplorerSetup.html">
|
||||
* AWS API: CreateResourceExplorerSetup</a>
|
||||
*/
|
||||
@RegisterForReflection
|
||||
public record SetupTask(String taskId, List<RegionOutcome> regions, Instant createdAt) {
|
||||
|
||||
/** One Region's index and view outcome. Either may be null when the task did not touch it. */
|
||||
@RegisterForReflection
|
||||
public record RegionOutcome(String region, SetupOutcome index, SetupOutcome view) {}
|
||||
}
|
||||
+9
@@ -0,0 +1,9 @@
|
||||
package io.github.hectorvent.floci.services.resourceexplorer2.model;
|
||||
|
||||
import java.util.Map;
|
||||
|
||||
/** A resource carrying mutable tags. Implementations are immutable records; {@link #withTags} returns a copy. */
|
||||
public interface Taggable {
|
||||
Map<String, String> tags();
|
||||
Taggable withTags(Map<String, String> tags);
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
package io.github.hectorvent.floci.services.resourceexplorer2.model;
|
||||
|
||||
import io.quarkus.runtime.annotations.RegisterForReflection;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
@RegisterForReflection
|
||||
public record View(
|
||||
String viewArn,
|
||||
String viewName,
|
||||
String owner,
|
||||
String scope,
|
||||
SearchFilter filters,
|
||||
List<IncludedProperty> includedProperties,
|
||||
Map<String, String> tags,
|
||||
Instant lastUpdatedAt) implements Taggable {
|
||||
|
||||
public View withFilters(SearchFilter filters) {
|
||||
return new View(viewArn, viewName, owner, scope, filters, includedProperties, tags, lastUpdatedAt);
|
||||
}
|
||||
|
||||
public View withIncludedProperties(List<IncludedProperty> includedProperties) {
|
||||
return new View(viewArn, viewName, owner, scope, filters, includedProperties, tags, lastUpdatedAt);
|
||||
}
|
||||
|
||||
public View withLastUpdatedAt(Instant lastUpdatedAt) {
|
||||
return new View(viewArn, viewName, owner, scope, filters, includedProperties, tags, lastUpdatedAt);
|
||||
}
|
||||
|
||||
@Override
|
||||
public View withTags(Map<String, String> tags) {
|
||||
return new View(viewArn, viewName, owner, scope, filters, includedProperties, tags, lastUpdatedAt);
|
||||
}
|
||||
|
||||
/** Whether this view includes tag data in results. */
|
||||
public boolean includesTags() {
|
||||
return includedProperties != null &&
|
||||
includedProperties.stream().anyMatch(p -> "tags".equals(p.name()));
|
||||
}
|
||||
}
|
||||
+43
@@ -0,0 +1,43 @@
|
||||
package io.github.hectorvent.floci.services.resourceexplorer2.query;
|
||||
|
||||
import io.quarkus.runtime.annotations.RegisterForReflection;
|
||||
|
||||
import java.util.Locale;
|
||||
import java.util.Map;
|
||||
import java.util.stream.Collectors;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
/**
|
||||
* Known filter attributes in Resource Explorer query syntax.
|
||||
*/
|
||||
@RegisterForReflection
|
||||
public enum FilterAttribute {
|
||||
ACCOUNT_ID("accountid"),
|
||||
APPLICATION("application"),
|
||||
ID("id"),
|
||||
REGION("region"),
|
||||
RESOURCE_TYPE("resourcetype"),
|
||||
RESOURCE_TYPE_SUPPORTS("resourcetype.supports"),
|
||||
SERVICE("service"),
|
||||
TAG("tag"),
|
||||
TAG_KEY("tag.key"),
|
||||
TAG_VALUE("tag.value");
|
||||
|
||||
private static final Map<String, FilterAttribute> BY_PREFIX =
|
||||
Stream.of(values()).collect(Collectors.toMap(
|
||||
a -> a.prefix.toLowerCase(Locale.ROOT), a -> a));
|
||||
|
||||
private final String prefix;
|
||||
|
||||
FilterAttribute(String prefix) {
|
||||
this.prefix = prefix;
|
||||
}
|
||||
|
||||
public String prefix() {
|
||||
return prefix;
|
||||
}
|
||||
|
||||
public static FilterAttribute fromPrefix(String prefix) {
|
||||
return BY_PREFIX.get(prefix.toLowerCase(Locale.ROOT));
|
||||
}
|
||||
}
|
||||
+25
@@ -0,0 +1,25 @@
|
||||
package io.github.hectorvent.floci.services.resourceexplorer2.query;
|
||||
|
||||
import io.quarkus.runtime.annotations.RegisterForReflection;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
@RegisterForReflection
|
||||
public record ParsedQuery(
|
||||
List<Keyword> keywords,
|
||||
List<Filter> filters
|
||||
) {
|
||||
|
||||
@RegisterForReflection
|
||||
public record Keyword(String value, boolean negated) {}
|
||||
|
||||
@RegisterForReflection
|
||||
public record Filter(
|
||||
FilterAttribute attribute,
|
||||
List<FilterValue> values,
|
||||
boolean negated
|
||||
) {}
|
||||
|
||||
@RegisterForReflection
|
||||
public record FilterValue(String value, boolean prefixMatch) {}
|
||||
}
|
||||
+211
@@ -0,0 +1,211 @@
|
||||
package io.github.hectorvent.floci.services.resourceexplorer2.query;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* Hand-written character-by-character parser for Resource Explorer query syntax.
|
||||
*
|
||||
* <p>Supports: filter prefixes ({@code service:}, {@code region:}, etc.),
|
||||
* comma-OR, negation ({@code -}), wildcards ({@code *}), quoted strings,
|
||||
* backslash escaping, and free-form text keywords.
|
||||
*
|
||||
* <p>Escapes survive tokenization intact and are resolved only where the meaning of the
|
||||
* character is decided — splitting a filter's comma-separated values, finding the colon that
|
||||
* separates a filter prefix from its value, and recognising a trailing wildcard. That ordering
|
||||
* is what makes {@code tag.key:comma\,literal} one value rather than two, and
|
||||
* {@code "my\-key\-word"} a keyword rather than a negation.
|
||||
*
|
||||
* @see <a href="https://docs.aws.amazon.com/resource-explorer/latest/userguide/using-search-query-syntax.html">
|
||||
* Search query syntax reference</a>
|
||||
*/
|
||||
public final class QueryParser {
|
||||
|
||||
/**
|
||||
* Characters that carry meaning to the parser and therefore have to be neutralised when they
|
||||
* appear inside a quoted phrase, which AWS defines as literal text.
|
||||
*/
|
||||
private static final String OPERATOR_CHARACTERS = "*\"-:=\\,";
|
||||
|
||||
private QueryParser() {}
|
||||
|
||||
public static ParsedQuery parse(String input) {
|
||||
if (input == null || input.isBlank()) {
|
||||
return new ParsedQuery(List.of(), List.of());
|
||||
}
|
||||
List<String> tokens = tokenize(input);
|
||||
return classify(tokens);
|
||||
}
|
||||
|
||||
// Rejects free-form text — ListResources only accepts filter prefixes.
|
||||
public static ParsedQuery parseFilterOnly(String input) {
|
||||
ParsedQuery query = parse(input);
|
||||
if (!query.keywords().isEmpty()) {
|
||||
throw new IllegalArgumentException(
|
||||
"ListResources FilterString does not support free-form text. " +
|
||||
"Use only filter prefixes (e.g., service:ec2, region:us-east-1).");
|
||||
}
|
||||
return query;
|
||||
}
|
||||
|
||||
static List<String> tokenize(String input) {
|
||||
List<String> tokens = new ArrayList<>();
|
||||
StringBuilder current = new StringBuilder();
|
||||
boolean inQuotes = false;
|
||||
// Tracks whether the current token has any content, including a quoted empty string.
|
||||
boolean hadContent = false;
|
||||
|
||||
for (int i = 0; i < input.length(); i++) {
|
||||
char c = input.charAt(i);
|
||||
|
||||
if (c == '\\' && i + 1 < input.length()) {
|
||||
current.append(c).append(input.charAt(i + 1));
|
||||
i++;
|
||||
hadContent = true;
|
||||
continue;
|
||||
}
|
||||
|
||||
if (c == '"') {
|
||||
inQuotes = !inQuotes;
|
||||
hadContent = true;
|
||||
continue;
|
||||
}
|
||||
|
||||
if (!inQuotes && Character.isWhitespace(c)) {
|
||||
if (hadContent) {
|
||||
tokens.add(current.toString());
|
||||
current.setLength(0);
|
||||
hadContent = false;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
if (inQuotes && OPERATOR_CHARACTERS.indexOf(c) >= 0) {
|
||||
current.append('\\');
|
||||
}
|
||||
current.append(c);
|
||||
hadContent = true;
|
||||
}
|
||||
|
||||
if (hadContent) {
|
||||
tokens.add(current.toString());
|
||||
}
|
||||
|
||||
return tokens;
|
||||
}
|
||||
|
||||
private static ParsedQuery classify(List<String> tokens) {
|
||||
List<ParsedQuery.Keyword> keywords = new ArrayList<>();
|
||||
List<ParsedQuery.Filter> filters = new ArrayList<>();
|
||||
|
||||
for (String token : tokens) {
|
||||
boolean negated = false;
|
||||
String working = token;
|
||||
|
||||
if (working.startsWith("-")) {
|
||||
negated = true;
|
||||
working = working.substring(1);
|
||||
}
|
||||
|
||||
int colonIndex = indexOfUnescaped(working, ':');
|
||||
FilterAttribute attribute = colonIndex >= 0
|
||||
? FilterAttribute.fromPrefix(unescape(working.substring(0, colonIndex)))
|
||||
: null;
|
||||
if (attribute != null) {
|
||||
String valuePortion = working.substring(colonIndex + 1);
|
||||
List<ParsedQuery.FilterValue> values = parseFilterValues(valuePortion);
|
||||
filters.add(new ParsedQuery.Filter(attribute, values, negated));
|
||||
} else {
|
||||
keywords.add(new ParsedQuery.Keyword(toKeywordValue(working), negated));
|
||||
}
|
||||
}
|
||||
|
||||
return new ParsedQuery(keywords, filters);
|
||||
}
|
||||
|
||||
/**
|
||||
* A trailing wildcard is dropped rather than recorded: keyword matching is a substring test,
|
||||
* so {@code ec2*} and {@code ec2} already select the same resources. Dropping it only where it
|
||||
* is unescaped keeps a literal {@code \*} searchable.
|
||||
*/
|
||||
private static String toKeywordValue(String raw) {
|
||||
String value = endsWithUnescaped(raw, '*') ? raw.substring(0, raw.length() - 1) : raw;
|
||||
return unescape(value);
|
||||
}
|
||||
|
||||
private static List<ParsedQuery.FilterValue> parseFilterValues(String valuePortion) {
|
||||
List<ParsedQuery.FilterValue> values = new ArrayList<>();
|
||||
for (String raw : splitUnescaped(valuePortion, ',')) {
|
||||
values.add(toFilterValue(raw));
|
||||
}
|
||||
return values;
|
||||
}
|
||||
|
||||
private static ParsedQuery.FilterValue toFilterValue(String raw) {
|
||||
if (endsWithUnescaped(raw, '*')) {
|
||||
return new ParsedQuery.FilterValue(unescape(raw.substring(0, raw.length() - 1)), true);
|
||||
}
|
||||
return new ParsedQuery.FilterValue(unescape(raw), false);
|
||||
}
|
||||
|
||||
private static int indexOfUnescaped(String value, char target) {
|
||||
for (int i = 0; i < value.length(); i++) {
|
||||
char c = value.charAt(i);
|
||||
if (c == '\\') {
|
||||
i++;
|
||||
continue;
|
||||
}
|
||||
if (c == target) {
|
||||
return i;
|
||||
}
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
|
||||
private static List<String> splitUnescaped(String value, char separator) {
|
||||
List<String> parts = new ArrayList<>();
|
||||
StringBuilder current = new StringBuilder();
|
||||
for (int i = 0; i < value.length(); i++) {
|
||||
char c = value.charAt(i);
|
||||
if (c == '\\' && i + 1 < value.length()) {
|
||||
current.append(c).append(value.charAt(i + 1));
|
||||
i++;
|
||||
continue;
|
||||
}
|
||||
if (c == separator) {
|
||||
parts.add(current.toString());
|
||||
current.setLength(0);
|
||||
continue;
|
||||
}
|
||||
current.append(c);
|
||||
}
|
||||
parts.add(current.toString());
|
||||
return parts;
|
||||
}
|
||||
|
||||
private static boolean endsWithUnescaped(String value, char target) {
|
||||
if (value.isEmpty() || value.charAt(value.length() - 1) != target) {
|
||||
return false;
|
||||
}
|
||||
int backslashes = 0;
|
||||
for (int i = value.length() - 2; i >= 0 && value.charAt(i) == '\\'; i--) {
|
||||
backslashes++;
|
||||
}
|
||||
return backslashes % 2 == 0;
|
||||
}
|
||||
|
||||
/** Resolves escape sequences. A backslash with nothing after it is literal text, as AWS treats it. */
|
||||
private static String unescape(String value) {
|
||||
StringBuilder out = new StringBuilder(value.length());
|
||||
for (int i = 0; i < value.length(); i++) {
|
||||
char c = value.charAt(i);
|
||||
if (c == '\\' && i + 1 < value.length()) {
|
||||
out.append(value.charAt(i + 1));
|
||||
i++;
|
||||
continue;
|
||||
}
|
||||
out.append(c);
|
||||
}
|
||||
return out.toString();
|
||||
}
|
||||
}
|
||||
+224
@@ -0,0 +1,224 @@
|
||||
package io.github.hectorvent.floci.services.resourceexplorer2.query;
|
||||
|
||||
import io.github.hectorvent.floci.core.resource.ExplorerResource;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
|
||||
/**
|
||||
* Evaluates whether a resource matches a parsed query.
|
||||
*
|
||||
* <p>Filters are AND'd and values within one filter are OR'd, as AWS documents. Free-form
|
||||
* keywords are OR'd with each other: {@code ec2 billing} selects a resource matching either.
|
||||
* A negated keyword or filter excludes.
|
||||
*
|
||||
* <p><strong>Deviation.</strong> AWS never excludes a resource for failing to match a free-form
|
||||
* keyword — it ranks it lower and still returns it, so a keyword-only query in a live account
|
||||
* returns everything. floci has no relevance model and returns matches only, which is the
|
||||
* behaviour that makes {@code Search} useful locally. Filter matching, which AWS documents as
|
||||
* deterministic, is exact.
|
||||
*
|
||||
* @see <a href="https://docs.aws.amazon.com/resource-explorer/latest/userguide/using-search-query-syntax.html">
|
||||
* Search query syntax reference</a>
|
||||
*/
|
||||
public final class ResourceFilter {
|
||||
|
||||
/** The one value AWS accepts for {@code resourcetype.supports:}. */
|
||||
private static final String SUPPORTS_TAGS = "tags";
|
||||
|
||||
/** Tag key AWS writes on resources that belong to an application (myApplications). */
|
||||
private static final String APPLICATION_TAG = "awsApplication";
|
||||
|
||||
private ResourceFilter() {}
|
||||
|
||||
/**
|
||||
* @param taggableResourceTypes resource types whose provider advertises tag support, used by
|
||||
* the {@code resourcetype.supports:tags} filter. Pass the set gathered from every
|
||||
* {@link io.github.hectorvent.floci.core.resource.ResourceProvider}.
|
||||
*/
|
||||
public static boolean matches(ExplorerResource resource, ParsedQuery query,
|
||||
Set<String> taggableResourceTypes) {
|
||||
for (var filter : query.filters()) {
|
||||
boolean anyValueMatches = filter.values().stream()
|
||||
.anyMatch(v -> matchesValue(resource, filter.attribute(), v, taggableResourceTypes));
|
||||
if (filter.negated()) {
|
||||
anyValueMatches = !anyValueMatches;
|
||||
}
|
||||
if (!anyValueMatches) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
return matchesKeywords(resource, query.keywords());
|
||||
}
|
||||
|
||||
/**
|
||||
* Positive keywords are OR'd, so a resource matching any one of them qualifies; a negated
|
||||
* keyword excludes regardless of the others. A query of negations alone matches everything
|
||||
* they do not exclude.
|
||||
*/
|
||||
private static boolean matchesKeywords(ExplorerResource resource, List<ParsedQuery.Keyword> keywords) {
|
||||
boolean sawPositive = false;
|
||||
boolean anyPositiveMatched = false;
|
||||
for (var keyword : keywords) {
|
||||
boolean matched = matchesKeyword(resource, keyword.value());
|
||||
if (keyword.negated()) {
|
||||
if (matched) {
|
||||
return false;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
sawPositive = true;
|
||||
anyPositiveMatched = anyPositiveMatched || matched;
|
||||
}
|
||||
return !sawPositive || anyPositiveMatched;
|
||||
}
|
||||
|
||||
public static ParsedQuery combine(ParsedQuery viewFilter, ParsedQuery requestFilter) {
|
||||
List<ParsedQuery.Keyword> keywords = new ArrayList<>(viewFilter.keywords());
|
||||
keywords.addAll(requestFilter.keywords());
|
||||
List<ParsedQuery.Filter> filters = new ArrayList<>(viewFilter.filters());
|
||||
filters.addAll(requestFilter.filters());
|
||||
return new ParsedQuery(keywords, filters);
|
||||
}
|
||||
|
||||
/** Whether the query names a filter that AWS only honours on a view carrying tag data. */
|
||||
public static boolean usesTagData(ParsedQuery query) {
|
||||
return query.filters().stream().anyMatch(f -> switch (f.attribute()) {
|
||||
case TAG, TAG_KEY, TAG_VALUE, APPLICATION -> true;
|
||||
default -> false;
|
||||
});
|
||||
}
|
||||
|
||||
private static boolean matchesValue(ExplorerResource resource, FilterAttribute attr,
|
||||
ParsedQuery.FilterValue filterValue,
|
||||
Set<String> taggableResourceTypes) {
|
||||
return switch (attr) {
|
||||
case REGION -> compareString(resource.region(), filterValue);
|
||||
case SERVICE -> compareString(resource.service(), filterValue);
|
||||
case RESOURCE_TYPE -> compareString(resource.resourceType(), filterValue);
|
||||
case ACCOUNT_ID -> compareString(resource.owningAccountId(), filterValue);
|
||||
case ID -> compareString(resource.arn(), filterValue);
|
||||
case APPLICATION -> matchesApplication(resource, filterValue);
|
||||
case TAG -> matchesTag(resource, filterValue);
|
||||
case TAG_KEY -> matchesTagKey(resource, filterValue);
|
||||
case TAG_VALUE -> matchesTagValue(resource, filterValue);
|
||||
case RESOURCE_TYPE_SUPPORTS -> SUPPORTS_TAGS.equalsIgnoreCase(filterValue.value())
|
||||
&& taggableResourceTypes.contains(resource.resourceType());
|
||||
};
|
||||
}
|
||||
|
||||
private static boolean compareString(String actual, ParsedQuery.FilterValue filter) {
|
||||
if (actual == null) {
|
||||
return false;
|
||||
}
|
||||
String actualLower = actual.toLowerCase(Locale.ROOT);
|
||||
String filterLower = filter.value().toLowerCase(Locale.ROOT);
|
||||
if (filter.prefixMatch()) {
|
||||
return actualLower.startsWith(filterLower);
|
||||
}
|
||||
return actualLower.equals(filterLower);
|
||||
}
|
||||
|
||||
private static boolean matchesTag(ExplorerResource resource, ParsedQuery.FilterValue filterValue) {
|
||||
String val = filterValue.value();
|
||||
if ("all".equalsIgnoreCase(val)) {
|
||||
return resource.tags() != null && !resource.tags().isEmpty();
|
||||
}
|
||||
if ("none".equalsIgnoreCase(val)) {
|
||||
return resource.tags() == null || resource.tags().isEmpty();
|
||||
}
|
||||
int eq = val.indexOf('=');
|
||||
if (eq < 0) {
|
||||
return false;
|
||||
}
|
||||
String tagKey = val.substring(0, eq);
|
||||
String tagValue = val.substring(eq + 1);
|
||||
Map<String, String> tags = resource.tags();
|
||||
if (tags == null) {
|
||||
return false;
|
||||
}
|
||||
return tags.entrySet().stream().anyMatch(e ->
|
||||
e.getKey().equalsIgnoreCase(tagKey) && e.getValue().equalsIgnoreCase(tagValue));
|
||||
}
|
||||
|
||||
private static boolean matchesTagKey(ExplorerResource resource, ParsedQuery.FilterValue filterValue) {
|
||||
Map<String, String> tags = resource.tags();
|
||||
if (tags == null) {
|
||||
return false;
|
||||
}
|
||||
return tags.keySet().stream().anyMatch(k -> compareTagString(k, filterValue));
|
||||
}
|
||||
|
||||
private static boolean matchesTagValue(ExplorerResource resource, ParsedQuery.FilterValue filterValue) {
|
||||
Map<String, String> tags = resource.tags();
|
||||
if (tags == null) {
|
||||
return false;
|
||||
}
|
||||
return tags.values().stream().anyMatch(v -> compareTagString(v, filterValue));
|
||||
}
|
||||
|
||||
private static boolean compareTagString(String actual, ParsedQuery.FilterValue filter) {
|
||||
String actualLower = actual.toLowerCase(Locale.ROOT);
|
||||
String filterLower = filter.value().toLowerCase(Locale.ROOT);
|
||||
if (filter.prefixMatch()) {
|
||||
return actualLower.startsWith(filterLower);
|
||||
}
|
||||
return actualLower.equals(filterLower);
|
||||
}
|
||||
|
||||
/**
|
||||
* AWS accepts either the application's resource-group ARN or its name, so both are compared
|
||||
* against the {@code awsApplication} tag — which itself always holds the ARN.
|
||||
*/
|
||||
private static boolean matchesApplication(ExplorerResource resource, ParsedQuery.FilterValue filterValue) {
|
||||
Map<String, String> tags = resource.tags();
|
||||
if (tags == null) {
|
||||
return false;
|
||||
}
|
||||
String appTag = tags.get(APPLICATION_TAG);
|
||||
if (appTag == null) {
|
||||
return false;
|
||||
}
|
||||
return compareString(appTag, filterValue)
|
||||
|| compareString(applicationNameOf(appTag), filterValue);
|
||||
}
|
||||
|
||||
/** Extracts {@code MyApp} from {@code arn:aws:resource-groups:…:group/MyApp/0123abc}. */
|
||||
private static String applicationNameOf(String applicationArn) {
|
||||
int groupIndex = applicationArn.indexOf("group/");
|
||||
if (groupIndex < 0) {
|
||||
return null;
|
||||
}
|
||||
String remainder = applicationArn.substring(groupIndex + "group/".length());
|
||||
int separator = remainder.indexOf('/');
|
||||
return separator < 0 ? remainder : remainder.substring(0, separator);
|
||||
}
|
||||
|
||||
/**
|
||||
* A free-form keyword matches any part of the resource's identity or its tags — AWS states it
|
||||
* can "match things like a tag key name or a piece of an ARN".
|
||||
*/
|
||||
private static boolean matchesKeyword(ExplorerResource resource, String keyword) {
|
||||
String lower = keyword.toLowerCase(Locale.ROOT);
|
||||
if (containsIgnoreCase(resource.arn(), lower)
|
||||
|| containsIgnoreCase(resource.resourceType(), lower)
|
||||
|| containsIgnoreCase(resource.service(), lower)
|
||||
|| containsIgnoreCase(resource.region(), lower)) {
|
||||
return true;
|
||||
}
|
||||
Map<String, String> tags = resource.tags();
|
||||
if (tags == null) {
|
||||
return false;
|
||||
}
|
||||
return tags.entrySet().stream().anyMatch(e ->
|
||||
containsIgnoreCase(e.getKey(), lower) || containsIgnoreCase(e.getValue(), lower));
|
||||
}
|
||||
|
||||
private static boolean containsIgnoreCase(String actual, String lowercaseNeedle) {
|
||||
return actual != null && actual.toLowerCase(Locale.ROOT).contains(lowercaseNeedle);
|
||||
}
|
||||
}
|
||||
+8
@@ -41,6 +41,14 @@ public class ResourceGroupsTaggingService implements Resettable {
|
||||
return region + "::" + arn;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the tags for a single resource, or an empty map if no tags have been applied.
|
||||
*/
|
||||
public Map<String, String> getTagsForResource(String region, String arn) {
|
||||
ResourceTagMapping mapping = store.get(key(region, arn));
|
||||
return mapping != null ? Collections.unmodifiableMap(mapping.getTags()) : Map.of();
|
||||
}
|
||||
|
||||
// ─── TagResources ──────────────────────────────────────────────────────────
|
||||
|
||||
// Mutators are synchronized: StorageBackedMap has no atomic computeIfAbsent, so
|
||||
|
||||
@@ -4,7 +4,12 @@ import com.fasterxml.jackson.core.type.TypeReference;
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.node.JsonNodeFactory;
|
||||
import com.fasterxml.jackson.databind.node.ObjectNode;
|
||||
import io.github.hectorvent.floci.core.common.AwsArnUtils;
|
||||
import io.github.hectorvent.floci.core.common.AwsException;
|
||||
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.StorageBackend;
|
||||
import io.github.hectorvent.floci.core.storage.StorageFactory;
|
||||
import io.github.hectorvent.floci.services.rum.model.AppMonitor;
|
||||
@@ -13,6 +18,7 @@ import jakarta.inject.Inject;
|
||||
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.time.Instant;
|
||||
import java.time.LocalDateTime;
|
||||
import java.time.ZoneOffset;
|
||||
import java.time.format.DateTimeFormatter;
|
||||
import java.util.ArrayList;
|
||||
@@ -27,7 +33,10 @@ import java.util.regex.Pattern;
|
||||
|
||||
/** CloudWatch RUM app-monitor lifecycle backed by the configured Floci storage mode. */
|
||||
@ApplicationScoped
|
||||
public class RumService {
|
||||
public class RumService implements ResourceProvider {
|
||||
|
||||
private static final String SERVICE = "rum";
|
||||
private static final String RESOURCE_APP_MONITOR = "appmonitor";
|
||||
|
||||
private static final int DEFAULT_MAX_RESULTS = 50;
|
||||
private static final int MAX_RESULTS = 100;
|
||||
@@ -49,18 +58,20 @@ public class RumService {
|
||||
private static final Set<String> PLATFORMS = Set.of("Web", "Android", "iOS");
|
||||
|
||||
private final StorageBackend<String, AppMonitor> monitorStore;
|
||||
private final RegionResolver regionResolver;
|
||||
|
||||
@Inject
|
||||
public RumService(StorageFactory storageFactory) {
|
||||
public RumService(StorageFactory storageFactory, RegionResolver regionResolver) {
|
||||
this(storageFactory.create(
|
||||
"rum",
|
||||
"rum-app-monitors.json",
|
||||
new TypeReference<Map<String, AppMonitor>>() {
|
||||
}));
|
||||
}), regionResolver);
|
||||
}
|
||||
|
||||
RumService(StorageBackend<String, AppMonitor> monitorStore) {
|
||||
RumService(StorageBackend<String, AppMonitor> monitorStore, RegionResolver regionResolver) {
|
||||
this.monitorStore = monitorStore;
|
||||
this.regionResolver = regionResolver;
|
||||
}
|
||||
|
||||
public synchronized AppMonitor createAppMonitor(String region, JsonNode request) {
|
||||
@@ -97,6 +108,7 @@ public class RumService {
|
||||
dataStorage(cwLogEnabled),
|
||||
customEvents,
|
||||
deobfuscation);
|
||||
monitor.setOwnerAccountId(regionResolver.getAccountId());
|
||||
monitorStore.put(key, monitor);
|
||||
return monitor;
|
||||
}
|
||||
@@ -152,6 +164,7 @@ public class RumService {
|
||||
storage,
|
||||
customEvents,
|
||||
deobfuscation);
|
||||
updated.setOwnerAccountId(current.getOwnerAccountId());
|
||||
monitorStore.put(key, updated);
|
||||
}
|
||||
|
||||
@@ -175,6 +188,57 @@ public class RumService {
|
||||
return new Page(monitors.subList(offset, end), responseToken);
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<ExplorerResource> getResources() {
|
||||
// RUM's stored model carries neither an ARN nor a region (its GetAppMonitor response has no
|
||||
// such fields), so the region is recovered from the storage key and the ARN is rebuilt here.
|
||||
// The owning account is the one captured when the monitor was created, not the account of the
|
||||
// caller listing resources. Monitors reloaded from disk carry no owner account (the field is
|
||||
// transient), but monitorStore.keys() is already scoped to the calling account by the
|
||||
// account-aware backend, so a monitor reachable here is owned by that caller by construction.
|
||||
List<ExplorerResource> resources = new ArrayList<>();
|
||||
for (String key : monitorStore.keys()) {
|
||||
AppMonitor monitor = monitorStore.get(key).orElse(null);
|
||||
if (monitor == null) {
|
||||
continue;
|
||||
}
|
||||
String region = regionFromKey(key);
|
||||
String accountId = monitor.getOwnerAccountId() != null
|
||||
? monitor.getOwnerAccountId()
|
||||
: regionResolver.getAccountId();
|
||||
String arn = AwsArnUtils.Arn.of(SERVICE, region, accountId,
|
||||
RESOURCE_APP_MONITOR + "/" + monitor.getName()).toString();
|
||||
resources.add(new ExplorerResource(
|
||||
arn, SERVICE + ":" + RESOURCE_APP_MONITOR, SERVICE,
|
||||
region, accountId,
|
||||
reportedAt(monitor.getCreated()),
|
||||
monitor.getTags() != null ? monitor.getTags() : Map.of()));
|
||||
}
|
||||
return resources;
|
||||
}
|
||||
|
||||
private static String regionFromKey(String key) {
|
||||
int separator = key.indexOf("::");
|
||||
return separator > 0 ? key.substring(0, separator) : key;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Set<SupportedResourceType> getSupportedResourceTypes() {
|
||||
return Set.of(new SupportedResourceType(
|
||||
SERVICE + ":" + RESOURCE_APP_MONITOR, SERVICE, true));
|
||||
}
|
||||
|
||||
private static Instant reportedAt(String created) {
|
||||
if (created == null) {
|
||||
return Instant.now();
|
||||
}
|
||||
try {
|
||||
return LocalDateTime.parse(created, TIMESTAMP_FORMATTER).toInstant(ZoneOffset.UTC);
|
||||
} catch (RuntimeException e) {
|
||||
return Instant.now();
|
||||
}
|
||||
}
|
||||
|
||||
private static String storageKey(String region, String name) {
|
||||
return region + "::" + name;
|
||||
}
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
package io.github.hectorvent.floci.services.rum.model;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonIgnore;
|
||||
import com.fasterxml.jackson.annotation.JsonInclude;
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.PropertyNamingStrategies;
|
||||
@@ -28,6 +29,14 @@ public class AppMonitor {
|
||||
private JsonNode customEvents;
|
||||
private JsonNode deobfuscationConfiguration;
|
||||
|
||||
// The account that created this monitor, captured so Resource Explorer 2 can report the true
|
||||
// owning account in the reconstructed ARN. RUM's GetAppMonitor response has no ARN or account
|
||||
// field, so this is @JsonIgnore'd to keep it out of the API body; it is likewise not persisted,
|
||||
// so getResources() recovers the owner from the account-scoped storage key for monitors
|
||||
// reloaded from disk.
|
||||
@JsonIgnore
|
||||
private String ownerAccountId;
|
||||
|
||||
public AppMonitor() {
|
||||
}
|
||||
|
||||
@@ -164,6 +173,16 @@ public class AppMonitor {
|
||||
this.deobfuscationConfiguration = copy(deobfuscationConfiguration);
|
||||
}
|
||||
|
||||
@JsonIgnore
|
||||
public String getOwnerAccountId() {
|
||||
return ownerAccountId;
|
||||
}
|
||||
|
||||
@JsonIgnore
|
||||
public void setOwnerAccountId(String ownerAccountId) {
|
||||
this.ownerAccountId = ownerAccountId;
|
||||
}
|
||||
|
||||
private static JsonNode copy(JsonNode value) {
|
||||
return value == null ? null : value.deepCopy();
|
||||
}
|
||||
|
||||
@@ -44,9 +44,12 @@ import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.concurrent.locks.ReentrantLock;
|
||||
import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
import io.github.hectorvent.floci.core.resource.ExplorerResource;
|
||||
import io.github.hectorvent.floci.core.resource.ResourceProvider;
|
||||
import io.github.hectorvent.floci.core.resource.SupportedResourceType;
|
||||
|
||||
@ApplicationScoped
|
||||
public class S3Service implements Resettable {
|
||||
public class S3Service implements Resettable, ResourceProvider {
|
||||
private String ownerId() { return regionResolver != null ? regionResolver.getAccountId() : "000000000000"; }
|
||||
private static final String DEFAULT_OWNER_DISPLAY_NAME = "floci";
|
||||
private static final String AUTHENTICATED_USERS_GROUP_URI = "http://acs.amazonaws.com/groups/global/AuthenticatedUsers";
|
||||
@@ -3423,4 +3426,25 @@ public class S3Service implements Resettable {
|
||||
fireNotifications(destBucket, destKey, "ObjectCreated:Copy", copy);
|
||||
return copy;
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<ExplorerResource> getResources() {
|
||||
List<ExplorerResource> resources = new ArrayList<>();
|
||||
for (Bucket bucket : listBuckets()) {
|
||||
resources.add(new ExplorerResource(
|
||||
"arn:aws:s3:::" + bucket.getName(),
|
||||
"s3:bucket",
|
||||
"s3",
|
||||
bucket.getRegion() != null ? bucket.getRegion() : regionResolver.getDefaultRegion(),
|
||||
regionResolver.getAccountId(),
|
||||
bucket.getCreationDate() != null ? bucket.getCreationDate() : Instant.now(),
|
||||
bucket.getTags() != null ? bucket.getTags() : Map.of()));
|
||||
}
|
||||
return resources;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Set<SupportedResourceType> getSupportedResourceTypes() {
|
||||
return Set.of(new SupportedResourceType("s3:bucket", "s3", true));
|
||||
}
|
||||
}
|
||||
+37
-1
@@ -34,9 +34,14 @@ import java.util.Objects;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.ThreadLocalRandom;
|
||||
import java.util.function.Predicate;
|
||||
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 java.util.LinkedHashMap;
|
||||
import java.util.Set;
|
||||
|
||||
@ApplicationScoped
|
||||
public class SecretsManagerService {
|
||||
public class SecretsManagerService implements ResourceProvider {
|
||||
|
||||
private static final Logger LOG = Logger.getLogger(SecretsManagerService.class);
|
||||
|
||||
@@ -995,4 +1000,35 @@ public class SecretsManagerService {
|
||||
}
|
||||
return sb.toString();
|
||||
}
|
||||
|
||||
// ─── Resource Explorer 2 ───────────────────────────────────────────────────
|
||||
|
||||
@Override
|
||||
public List<ExplorerResource> getResources() {
|
||||
List<ExplorerResource> resources = new ArrayList<>();
|
||||
for (Secret secret : store.scan(k -> true)) {
|
||||
String arn = secret.getArn();
|
||||
if (arn == null) {
|
||||
continue;
|
||||
}
|
||||
AwsArnUtils.Arn parsed = AwsArnUtils.parse(arn);
|
||||
Map<String, String> tags = new LinkedHashMap<>();
|
||||
if (secret.getTags() != null) {
|
||||
for (Secret.Tag tag : secret.getTags()) {
|
||||
tags.put(tag.key(), tag.value() != null ? tag.value() : "");
|
||||
}
|
||||
}
|
||||
resources.add(new ExplorerResource(
|
||||
arn, "secretsmanager:secret", "secretsmanager",
|
||||
parsed.region(), parsed.accountId(),
|
||||
secret.getCreatedDate() != null ? secret.getCreatedDate() : Instant.now(),
|
||||
tags));
|
||||
}
|
||||
return resources;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Set<SupportedResourceType> getSupportedResourceTypes() {
|
||||
return Set.of(new SupportedResourceType("secretsmanager:secret", "secretsmanager", true));
|
||||
}
|
||||
}
|
||||
@@ -5,6 +5,9 @@ import io.github.hectorvent.floci.core.common.AwsArnUtils;
|
||||
import io.github.hectorvent.floci.core.common.AwsException;
|
||||
import io.github.hectorvent.floci.core.common.RegionResolver;
|
||||
import io.github.hectorvent.floci.core.common.Resettable;
|
||||
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.StorageBackend;
|
||||
import io.github.hectorvent.floci.core.storage.StorageFactory;
|
||||
import io.github.hectorvent.floci.services.lambda.LambdaService;
|
||||
@@ -51,7 +54,7 @@ import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.concurrent.ConcurrentLinkedDeque;
|
||||
|
||||
@ApplicationScoped
|
||||
public class SnsService implements Resettable {
|
||||
public class SnsService implements Resettable, ResourceProvider {
|
||||
|
||||
private static final Logger LOG = Logger.getLogger(SnsService.class);
|
||||
private static final Duration FIFO_DEDUP_WINDOW = Duration.ofMinutes(5);
|
||||
@@ -903,6 +906,29 @@ public class SnsService implements Resettable {
|
||||
return new java.util.LinkedHashMap<>(topic.getTags());
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<ExplorerResource> getResources() {
|
||||
List<ExplorerResource> resources = new ArrayList<>();
|
||||
for (Topic topic : topicStore.scan(k -> true)) {
|
||||
String arn = topic.getTopicArn();
|
||||
if (arn == null) {
|
||||
continue;
|
||||
}
|
||||
AwsArnUtils.Arn parsed = AwsArnUtils.parse(arn);
|
||||
resources.add(new ExplorerResource(
|
||||
arn, "sns:topic", "sns",
|
||||
parsed.region(), parsed.accountId(),
|
||||
topic.getCreatedAt() != null ? topic.getCreatedAt() : Instant.now(),
|
||||
topic.getTags() != null ? topic.getTags() : Map.of()));
|
||||
}
|
||||
return resources;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Set<SupportedResourceType> getSupportedResourceTypes() {
|
||||
return Set.of(new SupportedResourceType("sns:topic", "sns", true));
|
||||
}
|
||||
|
||||
/**
|
||||
* Evaluates whether a message satisfies the subscription's filter policy.
|
||||
* Returns {@code true} if no filter policy is set.
|
||||
|
||||
@@ -5,6 +5,9 @@ import io.github.hectorvent.floci.core.common.AwsArnUtils;
|
||||
import io.github.hectorvent.floci.core.common.AwsException;
|
||||
import io.github.hectorvent.floci.core.common.RegionResolver;
|
||||
import io.github.hectorvent.floci.core.common.Resettable;
|
||||
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.AccountAwareStorageBackend;
|
||||
import io.github.hectorvent.floci.core.storage.StorageBackend;
|
||||
import io.github.hectorvent.floci.core.storage.StorageFactory;
|
||||
@@ -28,7 +31,7 @@ import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.concurrent.atomic.AtomicLong;
|
||||
|
||||
@ApplicationScoped
|
||||
public class SqsService implements Resettable {
|
||||
public class SqsService implements Resettable, ResourceProvider {
|
||||
|
||||
private static final Logger LOG = Logger.getLogger(SqsService.class);
|
||||
private static final int DEDUP_WINDOW_SECONDS = 300; // 5 minutes
|
||||
@@ -207,6 +210,35 @@ public class SqsService implements Resettable {
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<ExplorerResource> getResources() {
|
||||
List<ExplorerResource> resources = new ArrayList<>();
|
||||
for (String key : queueStore.keys()) {
|
||||
int sep = key.indexOf("::");
|
||||
if (sep < 0) {
|
||||
continue;
|
||||
}
|
||||
String region = key.substring(0, sep);
|
||||
Queue queue = queueStore.get(key).orElse(null);
|
||||
if (queue == null) {
|
||||
continue;
|
||||
}
|
||||
String account = queue.getAccountId() != null ? queue.getAccountId() : regionResolver.getAccountId();
|
||||
String arn = AwsArnUtils.Arn.of("sqs", region, account, queue.getQueueName()).toString();
|
||||
resources.add(new ExplorerResource(
|
||||
arn, "sqs:queue", "sqs",
|
||||
region, account,
|
||||
queue.getCreatedTimestamp() != null ? queue.getCreatedTimestamp() : Instant.now(),
|
||||
queue.getTags() != null ? queue.getTags() : Map.of()));
|
||||
}
|
||||
return resources;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Set<SupportedResourceType> getSupportedResourceTypes() {
|
||||
return Set.of(new SupportedResourceType("sqs:queue", "sqs", true));
|
||||
}
|
||||
|
||||
public Queue createQueue(String queueName, Map<String, String> attributes, String region) {
|
||||
return createQueue(queueName, attributes, null, region);
|
||||
}
|
||||
|
||||
@@ -15,9 +15,15 @@ import org.jboss.logging.Logger;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.util.*;
|
||||
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.common.AwsArnUtils;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Set;
|
||||
|
||||
@ApplicationScoped
|
||||
public class SsmService {
|
||||
public class SsmService implements ResourceProvider {
|
||||
|
||||
private static final Logger LOG = Logger.getLogger(SsmService.class);
|
||||
|
||||
@@ -335,4 +341,29 @@ public class SsmService {
|
||||
|
||||
historyStore.put(storageKey, history);
|
||||
}
|
||||
|
||||
// ─── Resource Explorer 2 ───────────────────────────────────────────────────
|
||||
|
||||
@Override
|
||||
public List<ExplorerResource> getResources() {
|
||||
List<ExplorerResource> resources = new ArrayList<>();
|
||||
for (Parameter parameter : parameterStore.scan(k -> true)) {
|
||||
String arn = parameter.getArn();
|
||||
if (arn == null) {
|
||||
continue;
|
||||
}
|
||||
AwsArnUtils.Arn parsed = AwsArnUtils.parse(arn);
|
||||
resources.add(new ExplorerResource(
|
||||
arn, "ssm:parameter", "ssm",
|
||||
parsed.region(), parsed.accountId(),
|
||||
parameter.getLastModifiedDate() != null ? parameter.getLastModifiedDate() : Instant.now(),
|
||||
parameter.getTags() != null ? parameter.getTags() : Map.of()));
|
||||
}
|
||||
return resources;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Set<SupportedResourceType> getSupportedResourceTypes() {
|
||||
return Set.of(new SupportedResourceType("ssm:parameter", "ssm", true));
|
||||
}
|
||||
}
|
||||
+28
-1
@@ -1,8 +1,12 @@
|
||||
package io.github.hectorvent.floci.services.stepfunctions;
|
||||
|
||||
import io.github.hectorvent.floci.core.common.AwsArnUtils;
|
||||
import io.github.hectorvent.floci.core.common.AwsException;
|
||||
import io.github.hectorvent.floci.core.common.AwsArnUtils;
|
||||
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.StorageBackend;
|
||||
import io.github.hectorvent.floci.core.storage.StorageFactory;
|
||||
import com.fasterxml.jackson.core.type.TypeReference;
|
||||
@@ -33,7 +37,7 @@ import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
@ApplicationScoped
|
||||
public class StepFunctionsService implements Resettable {
|
||||
public class StepFunctionsService implements Resettable, ResourceProvider {
|
||||
|
||||
private static final Logger LOG = Logger.getLogger(StepFunctionsService.class);
|
||||
|
||||
@@ -85,6 +89,29 @@ public class StepFunctionsService implements Resettable {
|
||||
pendingTaskTokens.clear();
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<ExplorerResource> getResources() {
|
||||
List<ExplorerResource> resources = new ArrayList<>();
|
||||
for (StateMachine sm : stateMachineStore.scan(k -> true)) {
|
||||
String arn = sm.getStateMachineArn();
|
||||
if (arn == null) {
|
||||
continue;
|
||||
}
|
||||
AwsArnUtils.Arn parsed = AwsArnUtils.parse(arn);
|
||||
resources.add(new ExplorerResource(
|
||||
arn, "states:stateMachine", "states",
|
||||
parsed.region(), parsed.accountId(),
|
||||
sm.getCreationDate() > 0 ? Instant.ofEpochMilli((long) (sm.getCreationDate() * 1000)) : Instant.now(),
|
||||
sm.getTags() != null ? sm.getTags() : Map.of()));
|
||||
}
|
||||
return resources;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Set<SupportedResourceType> getSupportedResourceTypes() {
|
||||
return Set.of(new SupportedResourceType("states:stateMachine", "states", true));
|
||||
}
|
||||
|
||||
// ──────────────────────────── State Machines ────────────────────────────
|
||||
|
||||
public StateMachine createStateMachine(String name, String definition, String roleArn, String type,
|
||||
|
||||
@@ -157,6 +157,9 @@ floci:
|
||||
flush-interval-ms: 5000
|
||||
rum:
|
||||
flush-interval-ms: 5000
|
||||
resourceexplorer2:
|
||||
mode: hybrid
|
||||
flush-interval-ms: 5000
|
||||
fis:
|
||||
flush-interval-ms: 5000
|
||||
guardduty:
|
||||
@@ -508,6 +511,8 @@ floci:
|
||||
enabled: true
|
||||
cloudcontrol:
|
||||
enabled: true
|
||||
resourceexplorer2:
|
||||
enabled: true
|
||||
cloudfront:
|
||||
enabled: true
|
||||
allowed-private-origin-hosts: []
|
||||
|
||||
+3
-3
@@ -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"));
|
||||
|
||||
+11
-12
@@ -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());
|
||||
|
||||
+118
@@ -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(
|
||||
|
||||
+118
@@ -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));
|
||||
}
|
||||
}
|
||||
+2396
File diff suppressed because it is too large.
Load diff
+180
@@ -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());
|
||||
}
|
||||
}
|
||||
+227
@@ -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);
|
||||
}
|
||||
}
|
||||
+121
@@ -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));
|
||||
}
|
||||
}
|
||||
+422
@@ -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());
|
||||
}
|
||||
}
|
||||
}
|
||||
+309
@@ -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());
|
||||
|
||||
@@ -73,6 +73,9 @@ floci:
|
||||
flush-interval-ms: 60000
|
||||
rum:
|
||||
flush-interval-ms: 60000
|
||||
resourceexplorer2:
|
||||
mode: memory
|
||||
flush-interval-ms: 60000
|
||||
fis:
|
||||
flush-interval-ms: 60000
|
||||
guardduty:
|
||||
@@ -302,6 +305,8 @@ floci:
|
||||
enabled: true
|
||||
cloudcontrol:
|
||||
enabled: true
|
||||
resourceexplorer2:
|
||||
enabled: true
|
||||
cloudfront:
|
||||
enabled: true
|
||||
allowed-private-origin-hosts: []
|
||||
|
||||
@@ -37,6 +37,7 @@ aliases:
|
||||
elasticbeanstalk: elastic-beanstalk
|
||||
ec2messages: ssm # SSM Messages facet, documented alongside ssm.md
|
||||
iotdata: iot # IoT Data row shares iot.md with IoT Core
|
||||
resource-explorer-2: resource-explorer # API version suffix; the page is resource-explorer.md
|
||||
|
||||
# A NEW switch/REST descriptor not listed here and not resolvable via an alias fails
|
||||
# `--strict`. Every entry MUST carry a `by:` expiry date (ISO, YYYY-MM-DD): once that
|
||||
|
||||
@@ -62,6 +62,19 @@ services:
|
||||
doc: docs/services/firehose.md
|
||||
sources:
|
||||
- { path: src/main/java/io/github/hectorvent/floci/services/firehose/FirehoseJsonHandler.java, mode: switch }
|
||||
- service: resource-explorer-2
|
||||
doc: docs/services/resource-explorer.md
|
||||
sources:
|
||||
- { path: src/main/java/io/github/hectorvent/floci/services/resourceexplorer2/ResourceExplorer2Controller.java, mode: rest }
|
||||
- { path: src/main/java/io/github/hectorvent/floci/core/common/SharedTagsController.java, mode: rest }
|
||||
rename_actions:
|
||||
ListTags: ListTagsForResource
|
||||
TagResourcePost: TagResource
|
||||
exclude_actions:
|
||||
- ListTagsByQuery
|
||||
- TagResourceByBody
|
||||
- TagResourcePut
|
||||
- UntagResourceByQuery
|
||||
- service: fis
|
||||
doc: docs/services/fis.md
|
||||
sources:
|
||||
|
||||
Reference in new issue
Block a user