diff --git a/README.md b/README.md index 3d0267b84c..b596d7a8b7 100644 --- a/README.md +++ b/README.md @@ -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 | diff --git a/compatibility-tests/sdk-test-java/pom.xml b/compatibility-tests/sdk-test-java/pom.xml index ba62dd2efb..8dc1b6a6d3 100644 --- a/compatibility-tests/sdk-test-java/pom.xml +++ b/compatibility-tests/sdk-test-java/pom.xml @@ -383,6 +383,20 @@ software.amazon.awssdk backup + + + software.amazon.awssdk + resourceexplorer2 + + + + software.amazon.awssdk + sso + + + software.amazon.awssdk + ssooidc + software.amazon.awssdk diff --git a/compatibility-tests/sdk-test-java/src/main/java/com/floci/test/TestFixtures.java b/compatibility-tests/sdk-test-java/src/main/java/com/floci/test/TestFixtures.java index 68389f7289..eae8bac528 100644 --- a/compatibility-tests/sdk-test-java/src/main/java/com/floci/test/TestFixtures.java +++ b/compatibility-tests/sdk-test-java/src/main/java/com/floci/test/TestFixtures.java @@ -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) diff --git a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/ResourceExplorer2Test.java b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/ResourceExplorer2Test.java new file mode 100644 index 0000000000..8c412abd8d --- /dev/null +++ b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/ResourceExplorer2Test.java @@ -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. + * + *

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. + * + *

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()); + } +} diff --git a/docs/configuration/environment-variables.md b/docs/configuration/environment-variables.md index 2e484fa2e9..2ff3c6e231 100644 --- a/docs/configuration/environment-variables.md +++ b/docs/configuration/environment-variables.md @@ -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 | diff --git a/docs/services/docdb.md b/docs/services/docdb.md index 7baf2a7964..1fafe82c0d 100644 --- a/docs/services/docdb.md +++ b/docs/services/docdb.md @@ -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. diff --git a/docs/services/index.md b/docs/services/index.md index 168c30c34d..d77bf8b149 100644 --- a/docs/services/index.md +++ b/docs/services/index.md @@ -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 | diff --git a/docs/services/rds.md b/docs/services/rds.md index 1fa2f831a9..8d44e9cf65 100644 --- a/docs/services/rds.md +++ b/docs/services/rds.md @@ -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 | diff --git a/docs/services/resource-explorer.md b/docs/services/resource-explorer.md new file mode 100644 index 0000000000..2e091fc0b1 --- /dev/null +++ b/docs/services/resource-explorer.md @@ -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 + + +| 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 | + + +## 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 getResources(); + Set 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. diff --git a/mkdocs.yml b/mkdocs.yml index 441fba53ee..2198742f13 100644 --- a/mkdocs.yml +++ b/mkdocs.yml @@ -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 diff --git a/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java b/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java index eb75dc2ac0..89720aeeb2 100644 --- a/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java +++ b/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java @@ -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 mode(); } + interface ResourceExplorer2StorageConfig { + Optional mode(); + + @WithDefault("5000") + long flushIntervalMs(); + } + interface AppSyncStorageConfig { Optional 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(); diff --git a/src/main/java/io/github/hectorvent/floci/core/common/AwsQueryController.java b/src/main/java/io/github/hectorvent/floci/core/common/AwsQueryController.java index a24e4fd527..b5615f990e 100644 --- a/src/main/java/io/github/hectorvent/floci/core/common/AwsQueryController.java +++ b/src/main/java/io/github/hectorvent/floci/core/common/AwsQueryController.java @@ -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). diff --git a/src/main/java/io/github/hectorvent/floci/core/common/RegionResolver.java b/src/main/java/io/github/hectorvent/floci/core/common/RegionResolver.java index dbfaf0abdd..6e43af617e 100644 --- a/src/main/java/io/github/hectorvent/floci/core/common/RegionResolver.java +++ b/src/main/java/io/github/hectorvent/floci/core/common/RegionResolver.java @@ -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). diff --git a/src/main/java/io/github/hectorvent/floci/core/common/ResolvedServiceCatalog.java b/src/main/java/io/github/hectorvent/floci/core/common/ResolvedServiceCatalog.java index a39063d457..684f253d29 100644 --- a/src/main/java/io/github/hectorvent/floci/core/common/ResolvedServiceCatalog.java +++ b/src/main/java/io/github/hectorvent/floci/core/common/ResolvedServiceCatalog.java @@ -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, diff --git a/src/main/java/io/github/hectorvent/floci/core/common/SigV4CredentialScope.java b/src/main/java/io/github/hectorvent/floci/core/common/SigV4CredentialScope.java index f01c1d6ca0..1dce84d5dc 100644 --- a/src/main/java/io/github/hectorvent/floci/core/common/SigV4CredentialScope.java +++ b/src/main/java/io/github/hectorvent/floci/core/common/SigV4CredentialScope.java @@ -9,14 +9,14 @@ import java.util.regex.Pattern; * Extracts the SigV4 signing service name from an Authorization header's * credential scope ({@code Credential=////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 serviceName(String authorization) { + public static Optional serviceName(String authorization) { if (authorization == null) { return Optional.empty(); } diff --git a/src/main/java/io/github/hectorvent/floci/core/resource/ExplorerResource.java b/src/main/java/io/github/hectorvent/floci/core/resource/ExplorerResource.java new file mode 100644 index 0000000000..ccd80f89ed --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/core/resource/ExplorerResource.java @@ -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. + *

+ * One instance describes one AWS resource (a certificate, a queue, a cluster, etc.) + * + *

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 AWS API: Resource + * @see Resource Explorer search query syntax + */ +@RegisterForReflection +public record ExplorerResource( + String arn, + String resourceType, + String service, + String region, + String owningAccountId, + Instant lastReportedAt, + Map tags +) {} diff --git a/src/main/java/io/github/hectorvent/floci/core/resource/ResourceProvider.java b/src/main/java/io/github/hectorvent/floci/core/resource/ResourceProvider.java new file mode 100644 index 0000000000..543c53b4ec --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/core/resource/ResourceProvider.java @@ -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}. + *

+ * Implementations must be CDI beans (usually {@code @ApplicationScoped} service classes). + * {@code ResourceExplorer2Service} iterates {@code ResourceProvider}s: + *

+ * + *

Implementing

+ *
    + *
  1. {@link #getResources()}: scan your storage backend and map each stored entity to an + * {@link ExplorerResource}.
  2. + *
  3. {@link #getSupportedResourceTypes()}: return one {@link SupportedResourceType} per distinct + * {@code resourceType} string you emit.
  4. + *
  5. 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.
  6. + *
+ * + *

See {@code AcmService}, {@code MskService}, or {@code IamService} (which exposes two types) + * for reference implementations. + * + * @see ExplorerResource + * @see SupportedResourceType + * @see Resource Explorer terms and concepts + * @see AWS API: Search + */ +public interface ResourceProvider { + + /** + * All resources this service currently own. + *

+ * 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 getResources(); + + /** + * The resource types this provider can produce. + *

+ * 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 getSupportedResourceTypes(); +} diff --git a/src/main/java/io/github/hectorvent/floci/core/resource/SupportedResourceType.java b/src/main/java/io/github/hectorvent/floci/core/resource/SupportedResourceType.java new file mode 100644 index 0000000000..b4e85bfaa7 --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/core/resource/SupportedResourceType.java @@ -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. + *

+ * 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. + * + *

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 AWS API: ListSupportedResourceTypes + */ +@RegisterForReflection +public record SupportedResourceType( + String resourceType, + String service, + boolean supportsTags +) {} diff --git a/src/main/java/io/github/hectorvent/floci/services/acm/AcmService.java b/src/main/java/io/github/hectorvent/floci/services/acm/AcmService.java index d6a373e842..7f911e04a9 100644 --- a/src/main/java/io/github/hectorvent/floci/services/acm/AcmService.java +++ b/src/main/java/io/github/hectorvent/floci/services/acm/AcmService.java @@ -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 AWS ACM API Reference */ @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 getResources() { + List 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 getSupportedResourceTypes() { + return Set.of(new SupportedResourceType("acm:certificate", "acm", true)); + } + // ============ Helper Methods ============ private Certificate getCertificateByArn(String arn, String region) { diff --git a/src/main/java/io/github/hectorvent/floci/services/amazonmq/AmazonMqService.java b/src/main/java/io/github/hectorvent/floci/services/amazonmq/AmazonMqService.java index 3308dc3d43..8b51ddd87b 100644 --- a/src/main/java/io/github/hectorvent/floci/services/amazonmq/AmazonMqService.java +++ b/src/main/java/io/github/hectorvent/floci/services/amazonmq/AmazonMqService.java @@ -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 getResources() { + List 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 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); diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationService.java b/src/main/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationService.java index 8396fc2dc1..46eecc101f 100644 --- a/src/main/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationService.java +++ b/src/main/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationService.java @@ -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 getResources() { + List 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 getSupportedResourceTypes() { + return Set.of(new SupportedResourceType("cloudformation:stack", "cloudformation", true)); + } } diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudwatch/logs/CloudWatchLogsService.java b/src/main/java/io/github/hectorvent/floci/services/cloudwatch/logs/CloudWatchLogsService.java index faa70c4e9c..e18e8d215e 100644 --- a/src/main/java/io/github/hectorvent/floci/services/cloudwatch/logs/CloudWatchLogsService.java +++ b/src/main/java/io/github/hectorvent/floci/services/cloudwatch/logs/CloudWatchLogsService.java @@ -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 getResources() { + List 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 getSupportedResourceTypes() { + return Set.of(new SupportedResourceType("logs:log-group", "logs", true)); + } } diff --git a/src/main/java/io/github/hectorvent/floci/services/cognito/CognitoService.java b/src/main/java/io/github/hectorvent/floci/services/cognito/CognitoService.java index 93e80e2ac9..7d40eed1c4 100644 --- a/src/main/java/io/github/hectorvent/floci/services/cognito/CognitoService.java +++ b/src/main/java/io/github/hectorvent/floci/services/cognito/CognitoService.java @@ -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 getResources() { + List 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 getSupportedResourceTypes() { + return Set.of(new SupportedResourceType("cognito-idp:userpool", "cognito-idp", true)); + } + private UserPool describeUserPoolByArn(String resourceArn) { String poolId = extractUserPoolIdFromArn(resourceArn); return describeUserPool(poolId); diff --git a/src/main/java/io/github/hectorvent/floci/services/dynamodb/DynamoDbService.java b/src/main/java/io/github/hectorvent/floci/services/dynamodb/DynamoDbService.java index 59e1dfd740..92f0ff3f5e 100644 --- a/src/main/java/io/github/hectorvent/floci/services/dynamodb/DynamoDbService.java +++ b/src/main/java/io/github/hectorvent/floci/services/dynamodb/DynamoDbService.java @@ -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 getResources() { + List 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 getSupportedResourceTypes() { + return Set.of(new SupportedResourceType("dynamodb:table", "dynamodb", true)); + } } diff --git a/src/main/java/io/github/hectorvent/floci/services/ec2/Ec2Service.java b/src/main/java/io/github/hectorvent/floci/services/ec2/Ec2Service.java index 8a2d4cc67b..f0a4301f4c 100644 --- a/src/main/java/io/github/hectorvent/floci/services/ec2/Ec2Service.java +++ b/src/main/java/io/github/hectorvent/floci/services/ec2/Ec2Service.java @@ -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. + * + *

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 getResources() { + List 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 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 void collectExplorerResources(List out, List stored, String resourceType, + Function id, Function region, + Function createdAt, Function> 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 explorerTags(List tags) { + if (tags == null) { + return Map.of(); + } + Map converted = new LinkedHashMap<>(); + for (Tag tag : tags) { + if (tag.getKey() != null) { + converted.put(tag.getKey(), tag.getValue() != null ? tag.getValue() : ""); + } + } + return converted; + } } diff --git a/src/main/java/io/github/hectorvent/floci/services/ecr/EcrService.java b/src/main/java/io/github/hectorvent/floci/services/ecr/EcrService.java index 9eaa765c52..476362f4b1 100644 --- a/src/main/java/io/github/hectorvent/floci/services/ecr/EcrService.java +++ b/src/main/java/io/github/hectorvent/floci/services/ecr/EcrService.java @@ -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 getResources() { + List 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 getSupportedResourceTypes() { + return Set.of(new SupportedResourceType("ecr:repository", "ecr", true)); + } + // ============================================================ // Result records // ============================================================ diff --git a/src/main/java/io/github/hectorvent/floci/services/ecs/EcsService.java b/src/main/java/io/github/hectorvent/floci/services/ecs/EcsService.java index 385b0bd5c0..ef3e3d5cd7 100644 --- a/src/main/java/io/github/hectorvent/floci/services/ecs/EcsService.java +++ b/src/main/java/io/github/hectorvent/floci/services/ecs/EcsService.java @@ -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 getResources() { + List 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 getSupportedResourceTypes() { + return Set.of( + new SupportedResourceType("ecs:cluster", "ecs", true), + new SupportedResourceType("ecs:service", "ecs", true)); + } + + private static void addExplorerResource(List out, String arn, String resourceType, + Instant createdAt, Map 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())); + } } diff --git a/src/main/java/io/github/hectorvent/floci/services/eks/EksService.java b/src/main/java/io/github/hectorvent/floci/services/eks/EksService.java index 98ac02c95e..35d7b109c1 100644 --- a/src/main/java/io/github/hectorvent/floci/services/eks/EksService.java +++ b/src/main/java/io/github/hectorvent/floci/services/eks/EksService.java @@ -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 getResources() { + List 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 getSupportedResourceTypes() { + return Set.of(new SupportedResourceType("eks:cluster", "eks", true)); + } } diff --git a/src/main/java/io/github/hectorvent/floci/services/elasticache/ElastiCacheQueryHandler.java b/src/main/java/io/github/hectorvent/floci/services/elasticache/ElastiCacheQueryHandler.java index 3b1edf357e..a20ae29c3d 100644 --- a/src/main/java/io/github/hectorvent/floci/services/elasticache/ElastiCacheQueryHandler.java +++ b/src/main/java/io/github/hectorvent/floci/services/elasticache/ElastiCacheQueryHandler.java @@ -51,11 +51,11 @@ public class ElastiCacheQueryHandler { this.regionResolver = regionResolver; } - public Response handle(String action, MultivaluedMap params) { + public Response handle(String action, MultivaluedMap 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 params) { + private Response handleCreateReplicationGroup(MultivaluedMap 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) { diff --git a/src/main/java/io/github/hectorvent/floci/services/elasticache/ElastiCacheService.java b/src/main/java/io/github/hectorvent/floci/services/elasticache/ElastiCacheService.java index fa9c9631aa..2bb19d0dab 100644 --- a/src/main/java/io/github/hectorvent/floci/services/elasticache/ElastiCacheService.java +++ b/src/main/java/io/github/hectorvent/floci/services/elasticache/ElastiCacheService.java @@ -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 getResources() { + List 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 getSupportedResourceTypes() { + return Set.of(new SupportedResourceType("elasticache:cluster", "elasticache", true)); + } } diff --git a/src/main/java/io/github/hectorvent/floci/services/elasticache/model/ReplicationGroup.java b/src/main/java/io/github/hectorvent/floci/services/elasticache/model/ReplicationGroup.java index 3effd18ec9..ca2197913f 100644 --- a/src/main/java/io/github/hectorvent/floci/services/elasticache/model/ReplicationGroup.java +++ b/src/main/java/io/github/hectorvent/floci/services/elasticache/model/ReplicationGroup.java @@ -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 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; } } diff --git a/src/main/java/io/github/hectorvent/floci/services/elbv2/ElbV2Service.java b/src/main/java/io/github/hectorvent/floci/services/elbv2/ElbV2Service.java index 6936ccd34b..99e9532c17 100644 --- a/src/main/java/io/github/hectorvent/floci/services/elbv2/ElbV2Service.java +++ b/src/main/java/io/github/hectorvent/floci/services/elbv2/ElbV2Service.java @@ -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 getResources() { + List resources = new ArrayList<>(); + for (Map regionLoadBalancers : loadBalancers.values()) { + for (LoadBalancer loadBalancer : regionLoadBalancers.values()) { + addExplorerResource(resources, loadBalancer.getLoadBalancerArn(), + "elasticloadbalancing:loadbalancer", loadBalancer.getCreatedTime()); + } + } + for (Map regionTargetGroups : targetGroups.values()) { + for (TargetGroup targetGroup : regionTargetGroups.values()) { + addExplorerResource(resources, targetGroup.getTargetGroupArn(), + "elasticloadbalancing:targetgroup", null); + } + } + return resources; + } + + @Override + public Set getSupportedResourceTypes() { + return Set.of( + new SupportedResourceType("elasticloadbalancing:loadbalancer", "elasticloadbalancing", true), + new SupportedResourceType("elasticloadbalancing:targetgroup", "elasticloadbalancing", true)); + } + + private void addExplorerResource(List 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()))); + } } diff --git a/src/main/java/io/github/hectorvent/floci/services/eventbridge/EventBridgeService.java b/src/main/java/io/github/hectorvent/floci/services/eventbridge/EventBridgeService.java index 89b2da08be..0bbe0a5390 100644 --- a/src/main/java/io/github/hectorvent/floci/services/eventbridge/EventBridgeService.java +++ b/src/main/java/io/github/hectorvent/floci/services/eventbridge/EventBridgeService.java @@ -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 getResources() { + List 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 getSupportedResourceTypes() { + return Set.of( + new SupportedResourceType("events:event-bus", "events", true), + new SupportedResourceType("events:rule", "events", true)); + } + + private static void addExplorerResource(List out, String arn, String resourceType, + Instant createdAt, Map 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())); + } } diff --git a/src/main/java/io/github/hectorvent/floci/services/firehose/FirehoseService.java b/src/main/java/io/github/hectorvent/floci/services/firehose/FirehoseService.java index 788f1acd1f..62812ce544 100644 --- a/src/main/java/io/github/hectorvent/floci/services/firehose/FirehoseService.java +++ b/src/main/java/io/github/hectorvent/floci/services/firehose/FirehoseService.java @@ -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 getResources() { + List 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 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 getSupportedResourceTypes() { + return Set.of(new SupportedResourceType("firehose:deliverystream", "firehose", true)); + } } diff --git a/src/main/java/io/github/hectorvent/floci/services/iam/IamService.java b/src/main/java/io/github/hectorvent/floci/services/iam/IamService.java index 5728d30fbb..d88bbe3378 100644 --- a/src/main/java/io/github/hectorvent/floci/services/iam/IamService.java +++ b/src/main/java/io/github/hectorvent/floci/services/iam/IamService.java @@ -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 getResources() { + List 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 out, String arn, String type, + Instant createDate, Map 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 getSupportedResourceTypes() { + return Set.of( + new SupportedResourceType("iam:user", "iam", true), + new SupportedResourceType("iam:role", "iam", true)); + } + // ========================================================================= // Account Aliases // ================================================================== diff --git a/src/main/java/io/github/hectorvent/floci/services/kinesis/KinesisService.java b/src/main/java/io/github/hectorvent/floci/services/kinesis/KinesisService.java index 78ee4cd864..72b4ba42d3 100644 --- a/src/main/java/io/github/hectorvent/floci/services/kinesis/KinesisService.java +++ b/src/main/java/io/github/hectorvent/floci/services/kinesis/KinesisService.java @@ -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 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 getResources() { + List 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 getSupportedResourceTypes() { + return Set.of(new SupportedResourceType("kinesis:stream", "kinesis", true)); + } } diff --git a/src/main/java/io/github/hectorvent/floci/services/kms/KmsService.java b/src/main/java/io/github/hectorvent/floci/services/kms/KmsService.java index 225f688b1c..7d113332ff 100644 --- a/src/main/java/io/github/hectorvent/floci/services/kms/KmsService.java +++ b/src/main/java/io/github/hectorvent/floci/services/kms/KmsService.java @@ -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 getResources() { + List 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 getSupportedResourceTypes() { + return Set.of(new SupportedResourceType("kms:key", "kms", true)); + } } diff --git a/src/main/java/io/github/hectorvent/floci/services/lambda/LambdaService.java b/src/main/java/io/github/hectorvent/floci/services/lambda/LambdaService.java index c4cd479e42..2a5de66562 100644 --- a/src/main/java/io/github/hectorvent/floci/services/lambda/LambdaService.java +++ b/src/main/java/io/github/hectorvent/floci/services/lambda/LambdaService.java @@ -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 getResources() { + List 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 getSupportedResourceTypes() { + return Set.of(new SupportedResourceType("lambda:function", "lambda", true)); + } + public LambdaFunction createFunction(String region, Map request) { String functionName = (String) request.get("FunctionName"); String role = (String) request.get("Role"); diff --git a/src/main/java/io/github/hectorvent/floci/services/lightsail/LightsailService.java b/src/main/java/io/github/hectorvent/floci/services/lightsail/LightsailService.java index 235a052655..73508a3489 100644 --- a/src/main/java/io/github/hectorvent/floci/services/lightsail/LightsailService.java +++ b/src/main/java/io/github/hectorvent/floci/services/lightsail/LightsailService.java @@ -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 getResources() { + List 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 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 tagsOf(ObjectNode node) { + Map 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(); diff --git a/src/main/java/io/github/hectorvent/floci/services/msk/MskService.java b/src/main/java/io/github/hectorvent/floci/services/msk/MskService.java index e26e41bbbf..f27bd831a7 100644 --- a/src/main/java/io/github/hectorvent/floci/services/msk/MskService.java +++ b/src/main/java/io/github/hectorvent/floci/services/msk/MskService.java @@ -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 getResources() { + List 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 getSupportedResourceTypes() { + return Set.of(new SupportedResourceType("kafka:cluster", "kafka", true)); + } } diff --git a/src/main/java/io/github/hectorvent/floci/services/opensearch/OpenSearchService.java b/src/main/java/io/github/hectorvent/floci/services/opensearch/OpenSearchService.java index a9efa87fed..d99840672c 100644 --- a/src/main/java/io/github/hectorvent/floci/services/opensearch/OpenSearchService.java +++ b/src/main/java/io/github/hectorvent/floci/services/opensearch/OpenSearchService.java @@ -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 getResources() { + List 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 getSupportedResourceTypes() { + return Set.of(new SupportedResourceType("es:domain", "es", true)); + } } diff --git a/src/main/java/io/github/hectorvent/floci/services/pipes/PipesService.java b/src/main/java/io/github/hectorvent/floci/services/pipes/PipesService.java index ea212b32b6..a846757300 100644 --- a/src/main/java/io/github/hectorvent/floci/services/pipes/PipesService.java +++ b/src/main/java/io/github/hectorvent/floci/services/pipes/PipesService.java @@ -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 getResources() { + List 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 getSupportedResourceTypes() { + return Set.of(new SupportedResourceType("pipes:pipe", "pipes", true)); + } + @Override public String serviceKey() { return "pipes"; diff --git a/src/main/java/io/github/hectorvent/floci/services/rds/RdsService.java b/src/main/java/io/github/hectorvent/floci/services/rds/RdsService.java index 47e6a20f30..c6fc2a4173 100644 --- a/src/main/java/io/github/hectorvent/floci/services/rds/RdsService.java +++ b/src/main/java/io/github/hectorvent/floci/services/rds/RdsService.java @@ -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 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>() {}); 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 proxies, StorageBackend proxyTargetGroups, - StorageBackend optionGroups) { + StorageBackend 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 getResources() { + List 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 tagsFor(String region, String arn) { + return taggingService != null ? taggingService.getTagsForResource(region, arn) : Map.of(); + } + + @Override + public Set getSupportedResourceTypes() { + return Set.of( + new SupportedResourceType("rds:db", "rds", true), + new SupportedResourceType("rds:cluster", "rds", true)); + } } diff --git a/src/main/java/io/github/hectorvent/floci/services/resourceexplorer2/ResourceExplorer2Controller.java b/src/main/java/io/github/hectorvent/floci/services/resourceexplorer2/ResourceExplorer2Controller.java new file mode 100644 index 0000000000..86b5620a68 --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/resourceexplorer2/ResourceExplorer2Controller.java @@ -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 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 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 includedProperties = parseIncludedProperties(req); + Map 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 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 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 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 stringArray(JsonNode req, String field) { + List 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 parseTags(JsonNode req) { + Map 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 parseIncludedProperties(JsonNode req) { + List 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; + } + +} diff --git a/src/main/java/io/github/hectorvent/floci/services/resourceexplorer2/ResourceExplorer2PathRewriteFilter.java b/src/main/java/io/github/hectorvent/floci/services/resourceexplorer2/ResourceExplorer2PathRewriteFilter.java new file mode 100644 index 0000000000..d2debba682 --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/resourceexplorer2/ResourceExplorer2PathRewriteFilter.java @@ -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}). + * + *

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. + * + *

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 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()); + } +} diff --git a/src/main/java/io/github/hectorvent/floci/services/resourceexplorer2/ResourceExplorer2Service.java b/src/main/java/io/github/hectorvent/floci/services/resourceexplorer2/ResourceExplorer2Service.java new file mode 100644 index 0000000000..992e342f81 --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/resourceexplorer2/ResourceExplorer2Service.java @@ -0,0 +1,1039 @@ +package io.github.hectorvent.floci.services.resourceexplorer2; + +import com.fasterxml.jackson.core.type.TypeReference; +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.InMemoryStorage; +import io.github.hectorvent.floci.core.storage.StorageBackend; +import io.github.hectorvent.floci.core.storage.StorageFactory; +import io.github.hectorvent.floci.services.resourceexplorer2.model.IncludedProperty; +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.SearchFilter; +import io.github.hectorvent.floci.services.resourceexplorer2.model.SetupOutcome; +import io.github.hectorvent.floci.services.resourceexplorer2.model.SetupTask; +import io.github.hectorvent.floci.services.resourceexplorer2.model.Taggable; +import io.github.hectorvent.floci.services.resourceexplorer2.model.View; +import io.github.hectorvent.floci.services.resourceexplorer2.query.ParsedQuery; +import io.github.hectorvent.floci.services.resourceexplorer2.query.QueryParser; +import io.github.hectorvent.floci.services.resourceexplorer2.query.ResourceFilter; +import io.quarkus.runtime.StartupEvent; +import jakarta.enterprise.context.ApplicationScoped; +import jakarta.enterprise.event.Observes; +import jakarta.enterprise.inject.Instance; +import jakarta.inject.Inject; +import org.jboss.logging.Logger; + +import java.time.Instant; +import java.util.ArrayList; +import java.util.Base64; +import java.util.Comparator; +import java.util.HashMap; +import java.util.HashSet; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.Set; +import java.util.UUID; +import java.util.function.Consumer; +import java.util.regex.Pattern; + +@ApplicationScoped +public class ResourceExplorer2Service { + + private static final Logger LOG = Logger.getLogger(ResourceExplorer2Service.class); + + private final Instance providers; + private final RegionResolver regionResolver; + private final ObjectMapper objectMapper; + private final StorageBackend indexStore; + private final StorageBackend viewStore; + /** Default view ARN per region. Persisted, not derived, so an explicit choice survives restarts. */ + private final StorageBackend defaultViewStore; + /** Completed setup tasks, keyed by the TaskId GetResourceExplorerSetup reads back. */ + private final StorageBackend setupTaskStore; + + /** + * The maximum number of matching resources {@code Search} returns across all pages. Per the AWS + * API reference: "The operation can return only the first 1,000 results." Also the maximum + * {@code MaxResults} page size accepted by both operations, and the page size at which + * {@code ListResources} suppresses its {@code NextToken}. + * + * @see AWS API: Search + */ + static final int MAX_RESOURCE_RESULTS = 1000; + + /** + * Sentinel result cap for {@code ListResources}, which — unlike {@code Search} — has no total cap + * and pages through every match. {@code Integer.MAX_VALUE} is safe as "unlimited": {@code pageBounds} + * caps {@code total} at {@code min(size, cap)}, and a {@link java.util.List} size can never exceed + * it, so {@code total == size}. Passing this instead of {@link #MAX_RESOURCE_RESULTS} is what + * distinguishes ListResources' contract from Search's. + * + * @see AWS API: ListResources + */ + private static final int UNLIMITED_RESULTS = Integer.MAX_VALUE; + /** Allowed view name characters per the CreateView API: letters, digits, hyphen, 1-64 chars. */ + private static final Pattern VIEW_NAME_PATTERN = Pattern.compile("[a-zA-Z0-9\\-]{1,64}"); + /** Region pattern the setup APIs apply to every entry of RegionList and AggregatorRegions. */ + private static final Pattern REGION_PATTERN = Pattern.compile("[a-z-]+-[a-z]+-[0-9]"); + /** AWS caps AggregatorRegions at one entry, since an account has at most one aggregator index. */ + private static final int MAX_AGGREGATOR_REGIONS = 1; + + @Inject + public ResourceExplorer2Service(Instance providers, + RegionResolver regionResolver, + ObjectMapper objectMapper, + StorageFactory storageFactory) { + this.providers = providers; + this.regionResolver = regionResolver; + this.objectMapper = objectMapper; + this.indexStore = storageFactory.create("resourceexplorer2", + "resourceexplorer2-indexes.json", + new TypeReference<>() {}); + this.viewStore = storageFactory.create("resourceexplorer2", + "resourceexplorer2-views.json", + new TypeReference<>() {}); + this.defaultViewStore = storageFactory.create("resourceexplorer2", + "resourceexplorer2-default-views.json", + new TypeReference<>() {}); + this.setupTaskStore = storageFactory.create("resourceexplorer2", + "resourceexplorer2-setup-tasks.json", + new TypeReference<>() {}); + } + + /** + * Visible for testing. Injects storage backends directly so a test can share them across two + * service instances — modeling a restart where persisted state survives but in-memory state does not. + */ + ResourceExplorer2Service(Instance providers, + RegionResolver regionResolver, + ObjectMapper objectMapper, + StorageBackend indexStore, + StorageBackend viewStore, + StorageBackend defaultViewStore) { + this(providers, regionResolver, objectMapper, indexStore, viewStore, defaultViewStore, + new InMemoryStorage<>()); + } + + ResourceExplorer2Service(Instance providers, + RegionResolver regionResolver, + ObjectMapper objectMapper, + StorageBackend indexStore, + StorageBackend viewStore, + StorageBackend defaultViewStore, + StorageBackend setupTaskStore) { + this.providers = providers; + this.regionResolver = regionResolver; + this.objectMapper = objectMapper; + this.indexStore = indexStore; + this.viewStore = viewStore; + this.defaultViewStore = defaultViewStore; + this.setupTaskStore = setupTaskStore; + } + + void onStartup(@Observes StartupEvent event) { + ensureDefaultRegionProvisioned(); + } + + /** + * Ensures the default region has an active index and default view. Called at startup and lazily + * before every operation that needs that baseline. The lazy calls matter because a LocalStack + * {@code state/reset} wipes all storage in-process (see {@code EmulatorInfoController}) without a + * restart, so {@code onStartup} never re-runs; without this, GetIndex/GetDefaultView/Search/ + * ListResources would fail for the whole service until the process is restarted. + * + *

The guard keys on an ACTIVE index, not "store is empty": a restart with persisted storage + * keeps the index active, so this is a no-op and an explicit DisassociateDefaultView stays in + * effect. Only a genuine loss of the index (fresh boot or a reset) triggers re-provisioning. + */ + private void ensureDefaultRegionProvisioned() { + String region = regionResolver.getDefaultRegion(); + String accountId = regionResolver.getAccountId(); + boolean hasActiveDefaultRegionIndex = indexStore.scan(_ -> true).stream() + .anyMatch(i -> region.equals(i.region()) && i.state() != IndexState.DELETED); + if (hasActiveDefaultRegionIndex) { + return; + } + String indexArn = regionResolver.buildArn("resource-explorer-2", region, + "index/" + UUID.randomUUID()); + Index index = new Index(indexArn, region, IndexType.AGGREGATOR, + IndexState.ACTIVE, new HashMap<>(), Instant.now()); + indexStore.put(indexArn, index); + + String viewId = UUID.randomUUID().toString(); + String viewArn = regionResolver.buildArn("resource-explorer-2", region, + "view/default-view/" + viewId); + View view = new View(viewArn, "default-view", accountId, + "arn:aws:iam::" + accountId + ":root", + null, + List.of(new IncludedProperty("tags")), + new HashMap<>(), Instant.now()); + viewStore.put(viewArn, view); + defaultViewStore.put(region, viewArn); + } + + private static String regionOf(View view) { + return AwsArnUtils.parse(view.viewArn()).region(); + } + + private List activeIndexes(String type, List regions) { + return indexStore.scan(_ -> true).stream() + .filter(i -> i.state() != IndexState.DELETED) + .filter(i -> type == null || type.equalsIgnoreCase(i.type().name())) + .filter(i -> regions == null || regions.isEmpty() + || regions.stream().anyMatch(r -> r.equalsIgnoreCase(i.region()))) + .sorted(Comparator.comparing(Index::arn)) + .toList(); + } + + private Optional activeIndex(String region) { + return indexStore.scan(_ -> true).stream() + .filter(i -> region.equals(i.region()) && i.state() != IndexState.DELETED) + .findFirst(); + } + + /** Creates a LOCAL index. Real AWS always creates LOCAL; promote via {@link #updateIndexType}. */ + public Index createIndex(String region, Map tags) { + if (activeIndex(region).isPresent()) { + throw new AwsException("ConflictException", + "An index already exists for region: " + region, 409); + } + String indexArn = regionResolver.buildArn("resource-explorer-2", region, + "index/" + UUID.randomUUID()); + // Stored ACTIVE (floci is synchronous); the controller emits CREATING on the create response. + Index index = new Index(indexArn, region, IndexType.LOCAL, IndexState.ACTIVE, + tags != null ? new HashMap<>(tags) : new HashMap<>(), Instant.now()); + indexStore.put(indexArn, index); + return index; + } + + public Index getIndex(String region) { + ensureDefaultRegionProvisioned(); + return activeIndex(region) + .orElseThrow(() -> new AwsException("ResourceNotFoundException", + "No index found for region: " + region, 404)); + } + + public Index deleteIndex(String indexArn) { + Index index = indexStore.get(indexArn) + .orElseThrow(() -> new AwsException("ResourceNotFoundException", + "Index not found: " + indexArn, 404)); + Index deleted = index.withState(IndexState.DELETED).withLastUpdatedAt(Instant.now()); + indexStore.put(indexArn, deleted); + + boolean hasOtherIndexes = indexStore.scan(_ -> true).stream() + .anyMatch(i -> !indexArn.equals(i.arn()) && i.state() != IndexState.DELETED); + if (!hasOtherIndexes) { + viewStore.scan(_ -> true).forEach(v -> viewStore.delete(v.viewArn())); + defaultViewStore.clear(); + } + return deleted; + } + + public Index updateIndexType(String indexArn, IndexType type) { + Index index = indexStore.get(indexArn) + .orElseThrow(() -> new AwsException("ResourceNotFoundException", + "Index not found: " + indexArn, 404)); + if (type == IndexType.AGGREGATOR) { + boolean aggregatorExistsElsewhere = indexStore.scan(_ -> true).stream() + .anyMatch(i -> !indexArn.equals(i.arn()) + && i.type() == IndexType.AGGREGATOR + && i.state() != IndexState.DELETED); + if (aggregatorExistsElsewhere) { + throw new AwsException("ConflictException", + "You already have an AGGREGATOR index in a different AWS Region. " + + "Only one aggregator index is allowed per account.", 409); + } + } + Index updated = index.withType(type).withLastUpdatedAt(Instant.now()); + indexStore.put(indexArn, updated); + return updated; + } + + private record Paginated(List items, String nextToken) {} + + /** + * Slices one page out of {@code all} at the offset carried by {@code nextToken}. + *

+ * The offset only identifies the same element across two calls if {@code all} is in a + * deterministic order, so every caller sorts on a unique key before calling this. The lists + * come from {@code StorageBackend.scan} or from iterating {@code Instance}, + * neither of which promises an order. + */ + private Paginated paginate(List all, Integer maxResults, String nextToken, int defaultMax) { + int effectiveMax = (maxResults != null && maxResults > 0) ? maxResults : defaultMax; + int offset = Math.min(decodeNextToken(nextToken), all.size()); + int end = Math.min(offset + effectiveMax, all.size()); + String outToken = (end < all.size()) ? encodeNextToken(end) : null; + return new Paginated<>(all.subList(offset, end), outToken); + } + + public ObjectNode listIndexes(String type, List regions, Integer maxResults, String nextToken) { + ensureDefaultRegionProvisioned(); + List all = activeIndexes(type, regions); + Paginated page = paginate(all, maxResults, nextToken, 100); + + ObjectNode result = objectMapper.createObjectNode(); + ArrayNode arr = result.putArray("Indexes"); + for (Index idx : page.items()) { + arr.add(indexNode(idx)); + } + if (page.nextToken() != null) { + result.put("NextToken", page.nextToken()); + } + return result; + } + + private ObjectNode indexNode(Index index) { + ObjectNode node = objectMapper.createObjectNode(); + node.put("Arn", index.arn()); + node.put("Region", index.region()); + node.put("Type", index.type().name()); + return node; + } + + public View createView(String region, String viewName, String scope, SearchFilter filters, + List includedProperties, Map tags) { + if (viewName == null || !VIEW_NAME_PATTERN.matcher(viewName).matches()) { + throw new AwsException("ValidationException", + "View name must match [a-zA-Z0-9-] and be 1-64 characters: " + viewName, 400); + } + validateIncludedProperties(includedProperties); + boolean nameTaken = viewStore.scan(_ -> true).stream() + .anyMatch(v -> viewName.equals(v.viewName()) && region.equals(regionOf(v))); + if (nameTaken) { + throw new AwsException("ConflictException", + "A view with the name " + viewName + " already exists in this AWS Region.", 409); + } + String accountId = regionResolver.getAccountId(); + String viewArn = regionResolver.buildArn("resource-explorer-2", region, + "view/" + viewName + "/" + UUID.randomUUID()); + String effectiveScope = (scope != null) ? scope : "arn:aws:iam::" + accountId + ":root"; + View view = new View(viewArn, viewName, accountId, + effectiveScope, + filters, includedProperties, + tags != null ? new HashMap<>(tags) : new HashMap<>(), + Instant.now()); + viewStore.put(viewArn, view); + return view; + } + + private static void validateIncludedProperties(List includedProperties) { + if (includedProperties == null) { + return; + } + for (IncludedProperty p : includedProperties) { + if (!"tags".equals(p.name())) { + throw new AwsException("ValidationException", + "Invalid included property name: " + p.name() + ". The only valid value is 'tags'.", 400); + } + } + } + + public View getView(String viewArn) { + return viewStore.get(viewArn) + .orElseThrow(() -> new AwsException("ResourceNotFoundException", + "View not found: " + viewArn, 404)); + } + + public void deleteView(String viewArn) { + viewStore.get(viewArn) + .orElseThrow(() -> new AwsException("ResourceNotFoundException", + "View not found: " + viewArn, 404)); + viewStore.delete(viewArn); + // AWS allows deleting a view that is the default; the region is simply left without one. + for (String region : Set.copyOf(defaultViewStore.keys())) { + if (defaultViewStore.get(region).filter(viewArn::equals).isPresent()) { + defaultViewStore.delete(region); + } + } + } + + public View updateView(String viewArn, SearchFilter filters, + List includedProperties) { + validateIncludedProperties(includedProperties); + View view = viewStore.get(viewArn) + .orElseThrow(() -> new AwsException("ResourceNotFoundException", + "View not found: " + viewArn, 404)); + View updated = view.withFilters(filters) + .withIncludedProperties(includedProperties) + .withLastUpdatedAt(Instant.now()); + viewStore.put(viewArn, updated); + return updated; + } + + /** + * Lists the views in one Region. AWS scopes this to "the AWS Region in which you call this + * operation", so a view created in another Region is not listed here even though floci keeps + * every Region's views in one store. + * + * @see AWS API: ListViews + */ + public ObjectNode listViews(String region, Integer maxResults, String nextToken) { + ensureDefaultRegionProvisioned(); + List all = viewStore.scan(_ -> true).stream() + .filter(v -> region.equals(regionOf(v))) + .map(View::viewArn) + .sorted() + .toList(); + Paginated page = paginate(all, maxResults, nextToken, 100); + + ObjectNode result = objectMapper.createObjectNode(); + result.set("Views", objectMapper.valueToTree(page.items())); + if (page.nextToken() != null) { + result.put("NextToken", page.nextToken()); + } + return result; + } + + public ObjectNode batchGetView(List viewArns) { + ObjectNode result = objectMapper.createObjectNode(); + ArrayNode views = result.putArray("Views"); + ArrayNode errors = result.putArray("Errors"); + for (String arn : viewArns) { + Optional view = viewStore.get(arn); + if (view.isPresent()) { + views.add(buildViewNode(view.get())); + } else { + ObjectNode error = objectMapper.createObjectNode(); + error.put("ErrorMessage", "View not found: " + arn); + error.put("ViewArn", arn); + errors.add(error); + } + } + return result; + } + + ObjectNode buildViewNode(View view) { + ObjectNode node = objectMapper.createObjectNode(); + node.put("ViewArn", view.viewArn()); + if (view.viewName() != null) { + node.put("ViewName", view.viewName()); + } + node.put("Owner", view.owner()); + node.put("Scope", view.scope()); + node.put("LastUpdatedAt", view.lastUpdatedAt().toString()); + ObjectNode filters = objectMapper.createObjectNode(); + filters.put("FilterString", + view.filters() != null ? view.filters().filterString() : ""); + node.set("Filters", filters); + if (view.includedProperties() != null) { + ArrayNode props = objectMapper.createArrayNode(); + for (IncludedProperty p : view.includedProperties()) { + ObjectNode propNode = objectMapper.createObjectNode(); + propNode.put("Name", p.name()); + props.add(propNode); + } + node.set("IncludedProperties", props); + } + return node; + } + + public void associateDefaultView(String region, String viewArn) { + View view = viewStore.get(viewArn) + .orElseThrow(() -> new AwsException("ResourceNotFoundException", + "View not found: " + viewArn, 404)); + // AWS scopes the default view per region: the view ARN's region must match the request + // region, otherwise it rejects the association with a ValidationException. + if (!region.equals(regionOf(view))) { + throw new AwsException("ValidationException", + "View " + viewArn + " is in region " + regionOf(view) + + " and cannot be the default view for region " + region + ".", 400); + } + defaultViewStore.put(region, viewArn); + } + + public void disassociateDefaultView(String region) { + defaultViewStore.delete(region); + } + + public String getDefaultView(String region) { + ensureDefaultRegionProvisioned(); + return defaultViewStore.get(region).orElse(null); + } + + public ObjectNode listResources(String filterString, Integer maxResults, + String nextToken, String viewArn, String region) { + View view = resolveView(viewArn, region); + ParsedQuery requestFilter = (filterString != null && !filterString.isBlank()) + ? QueryParser.parseFilterOnly(filterString) : new ParsedQuery(List.of(), List.of()); + ParsedQuery viewFilter = (view.filters() != null && view.filters().filterString() != null) + ? QueryParser.parseFilterOnly(view.filters().filterString()) + : new ParsedQuery(List.of(), List.of()); + ParsedQuery combined = ResourceFilter.combine(viewFilter, requestFilter); + rejectTagFilterWithoutTagData(combined, view); + Page p = paginateResources(combined, maxResults, nextToken, UNLIMITED_RESULTS); + + ObjectNode result = objectMapper.createObjectNode(); + ArrayNode resources = result.putArray("Resources"); + for (ExplorerResource r : p.page()) { + resources.add(buildResourceNode(r, view.includesTags())); + } + if (listResourcesEmitsToken(p.end(), p.total(), maxResults)) { + result.put("NextToken", encodeNextToken(p.end())); + } + result.put("ViewArn", view.viewArn()); + return result; + } + + public ObjectNode search(String queryString, Integer maxResults, + String nextToken, String viewArn, String region) { + View view = resolveView(viewArn, region); + ParsedQuery requestFilter = (queryString != null && !queryString.isBlank()) + ? QueryParser.parse(queryString) : new ParsedQuery(List.of(), List.of()); + ParsedQuery viewFilter = (view.filters() != null && view.filters().filterString() != null) + ? QueryParser.parse(view.filters().filterString()) + : new ParsedQuery(List.of(), List.of()); + ParsedQuery combined = ResourceFilter.combine(viewFilter, requestFilter); + rejectTagFilterWithoutTagData(combined, view); + Page p = paginateResources(combined, maxResults, nextToken, MAX_RESOURCE_RESULTS); + + ObjectNode result = objectMapper.createObjectNode(); + ArrayNode resources = result.putArray("Resources"); + for (ExplorerResource r : p.page()) { + resources.add(buildResourceNode(r, view.includesTags())); + } + ObjectNode count = objectMapper.createObjectNode(); + count.put("TotalResources", p.total()); + count.put("Complete", p.uncappedTotal() <= MAX_RESOURCE_RESULTS); + result.set("Count", count); + if (p.end() < p.total()) { + result.put("NextToken", encodeNextToken(p.end())); + } + result.put("ViewArn", view.viewArn()); + return result; + } + + /** + * AWS documents every tag filter — {@code tag:}, {@code tag.key:}, {@code tag.value:} and + * {@code application:}, which reads a tag — as requiring a view whose {@code IncludedProperties} + * name {@code tags}. Against a view without it the query is rejected rather than silently + * evaluated on data the view is not allowed to expose. + * + * @see + * Search query syntax reference + */ + private static void rejectTagFilterWithoutTagData(ParsedQuery query, View view) { + if (!ResourceFilter.usesTagData(query) || view.includesTags()) { + return; + } + throw new AwsException("ValidationException", + "The view " + view.viewArn() + " does not include tag data, so the query cannot " + + "filter on tags. Add an IncludedProperty named 'tags' to the view.", 400); + } + + /** Resource types whose provider advertises tag support, for {@code resourcetype.supports:tags}. */ + private Set taggableResourceTypes() { + Set taggable = new HashSet<>(); + for (ResourceProvider provider : providers) { + for (SupportedResourceType type : provider.getSupportedResourceTypes()) { + if (type.supportsTags()) { + taggable.add(type.resourceType()); + } + } + } + return taggable; + } + + private record Page(List page, int end, int total, int uncappedTotal) {} + + /** + * Gathers every provider's resources, applies {@code combined}, and returns one page. + *

+ * Sorted by ARN before slicing. {@code NextToken} is an offset, and the list is rebuilt on + * every call by iterating {@code Instance} and each provider's store scan — + * neither ordered — so without a total order over a unique key the second page would index + * into a differently arranged list and silently drop or repeat resources. + * + * @param resultCap the maximum number of matching resources the operation returns across all + * pages. This is a real per-operation difference in the AWS API, not an internal tuning knob: + * {@code Search} caps at {@link #MAX_RESOURCE_RESULTS}, while {@code ListResources} is uncapped + * and passes {@link #UNLIMITED_RESULTS}. It is a parameter precisely because hardcoding a single + * value here previously imposed Search's 1000-result cap on ListResources, silently dropping + * every match beyond the first 1000. + * @see AWS API: Search + * @see AWS API: ListResources + */ + private Page paginateResources(ParsedQuery combined, Integer maxResults, String nextToken, int resultCap) { + List all = new ArrayList<>(); + for (ResourceProvider provider : providers) { + try { + all.addAll(provider.getResources()); + } catch (RuntimeException e) { + // One misbehaving provider must not fail discovery for every other service. Skip it + // and continue — Search/ListResources is best-effort, so a partial view beats a 500. + LOG.warnf(e, "ResourceProvider %s failed to supply resources; excluding it from this result", + provider.getClass().getSimpleName()); + } + } + Set taggableResourceTypes = taggableResourceTypes(); + List filtered = all.stream() + .filter(r -> ResourceFilter.matches(r, combined, taggableResourceTypes)) + .sorted(Comparator.comparing(ExplorerResource::arn)) + .toList(); + int uncappedTotal = filtered.size(); + PageBounds b = pageBounds(filtered.size(), maxResults, nextToken, resultCap); + return new Page(filtered.subList(b.start(), b.end()), b.end(), b.total(), uncappedTotal); + } + + record PageBounds(int start, int end, int total) {} + + /** + * Computes pagination bounds: clamps the decoded offset into range (the live result set can shrink + * between paginated calls) and caps the total at {@code hardCap}. {@code Search} passes + * {@link #MAX_RESOURCE_RESULTS} — it "can return only the first 1,000 results"; {@code ListResources} + * has no total cap and passes {@link #UNLIMITED_RESULTS}. + * + * @see AWS API: Search + */ + static PageBounds pageBounds(int size, Integer maxResults, String nextToken, int hardCap) { + int total = Math.min(size, hardCap); + int effectiveMax = (maxResults != null && maxResults > 0) ? maxResults : 100; + int start = Math.min(decodeNextToken(nextToken), total); + int end = Math.min(start + effectiveMax, total); + return new PageBounds(start, end, total); + } + + /** + * Whether {@code ListResources} emits a {@code NextToken} for a page ending at {@code end} within + * {@code total} results. Reproduces a documented AWS quirk: "The ListResources operation does not + * generate a NextToken if you set MaxResults to 1000." At the maximum page size the caller silently + * receives at most 1000 results with no way to page further. + * + * @see AWS API: ListResources (NextToken) + */ + static boolean listResourcesEmitsToken(int end, int total, Integer maxResults) { + if (maxResults != null && maxResults == MAX_RESOURCE_RESULTS) { + return false; + } + return end < total; + } + + public ObjectNode listSupportedResourceTypes(Integer maxResults, String nextToken) { + List all = new ArrayList<>(); + for (ResourceProvider provider : providers) { + all.addAll(provider.getSupportedResourceTypes()); + } + Map deduplicated = new LinkedHashMap<>(); + for (SupportedResourceType t : all) { + deduplicated.put(t.resourceType(), t); + } + List list = deduplicated.values().stream() + .sorted(Comparator.comparing(SupportedResourceType::resourceType)) + .toList(); + Paginated page = paginate(list, maxResults, nextToken, 100); + + ObjectNode result = objectMapper.createObjectNode(); + ArrayNode arr = result.putArray("ResourceTypes"); + for (SupportedResourceType t : page.items()) { + ObjectNode node = objectMapper.createObjectNode(); + node.put("ResourceType", t.resourceType()); + node.put("Service", t.service()); + arr.add(node); + } + if (page.nextToken() != null) { + result.put("NextToken", page.nextToken()); + } + return result; + } + + // ── Managed, service-owned, and organization-scoped reads ──────────────── + // + // These describe resources only AWS itself creates: views a trusted service registers + // (managed and service views), streaming grants it holds, and indexes belonging to other + // accounts in an organization. floci models neither trusted services nor Organizations, so + // each answers with the wire-accurate empty result rather than an error — a caller + // enumerating them completes, and one asking for a specific ARN gets the same + // ResourceNotFoundException a live account with no such view would return. + + public ObjectNode listManagedViews(Integer maxResults, String nextToken) { + return emptyList("ManagedViews", maxResults, nextToken); + } + + public ObjectNode getManagedView(String managedViewArn) { + throw new AwsException("ResourceNotFoundException", + "Managed view not found: " + managedViewArn, 404); + } + + public ObjectNode listServiceViews(Integer maxResults, String nextToken) { + return emptyList("ServiceViews", maxResults, nextToken); + } + + public ObjectNode getServiceView(String serviceViewArn) { + throw new AwsException("ResourceNotFoundException", + "Service view not found: " + serviceViewArn, 404); + } + + public ObjectNode listStreamingAccessForServices(Integer maxResults, String nextToken) { + return emptyList("StreamingAccessForServices", maxResults, nextToken); + } + + /** + * The index a trusted service reads in the request Region. Same index {@code GetIndex} + * returns, reported with the narrower {@code ServiceIndex} shape. + */ + public ObjectNode getServiceIndex(String region) { + ensureDefaultRegionProvisioned(); + Index index = activeIndex(region) + .orElseThrow(() -> new AwsException("ResourceNotFoundException", + "No index found for region: " + region, 404)); + ObjectNode result = objectMapper.createObjectNode(); + result.put("Arn", index.arn()); + result.put("Type", index.type().name()); + return result; + } + + public ObjectNode listServiceIndexes(List regions, Integer maxResults, String nextToken) { + ensureDefaultRegionProvisioned(); + Paginated page = paginate(activeIndexes(null, regions), maxResults, nextToken, 100); + ObjectNode result = objectMapper.createObjectNode(); + ArrayNode indexes = result.putArray("Indexes"); + for (Index index : page.items()) { + indexes.add(indexNode(index)); + } + if (page.nextToken() != null) { + result.put("NextToken", page.nextToken()); + } + return result; + } + + /** + * Indexes belonging to the listed member accounts. floci emulates a single account, so the + * result is this account's indexes when its id is among those asked for, and empty otherwise — + * which is what a management account sees for an account with no index. + */ + public ObjectNode listIndexesForMembers(List accountIds, Integer maxResults, String nextToken) { + ensureDefaultRegionProvisioned(); + String accountId = regionResolver.getAccountId(); + List owned = accountIds.contains(accountId) ? activeIndexes(null, null) : List.of(); + Paginated page = paginate(owned, maxResults, nextToken, 10); + + ObjectNode result = objectMapper.createObjectNode(); + ArrayNode indexes = result.putArray("Indexes"); + for (Index index : page.items()) { + ObjectNode node = indexNode(index); + node.put("AccountId", accountId); + indexes.add(node); + } + if (page.nextToken() != null) { + result.put("NextToken", page.nextToken()); + } + return result; + } + + /** + * floci models no AWS Organization, so multi-account search is reported as {@code DISABLED} + * and no service-linked role is returned — the answer a standalone account gives. + */ + public ObjectNode getAccountLevelServiceConfiguration() { + ObjectNode result = objectMapper.createObjectNode(); + result.putObject("OrgConfiguration").put("AWSServiceAccessStatus", "DISABLED"); + return result; + } + + private ObjectNode emptyList(String field, Integer maxResults, String nextToken) { + Paginated page = paginate(List.of(), maxResults, nextToken, 50); + ObjectNode result = objectMapper.createObjectNode(); + result.putArray(field); + if (page.nextToken() != null) { + result.put("NextToken", page.nextToken()); + } + return result; + } + + // ── Multi-Region setup ─────────────────────────────────────────────────── + + /** + * Turns Resource Explorer on across several Regions in one call: an index per Region, a view + * per Region, and at most one Region promoted to aggregator. + * + *

A Region that already has an index reuses it rather than failing, because the operation + * describes a target state rather than a create. Each Region's index and view step is recorded + * independently, so one Region's failure — a name already taken, an aggregator already + * elsewhere — is reported through that Region's {@code ErrorDetails} instead of abandoning the + * rest of the task. + * + * @return the task id to read back with {@link #getResourceExplorerSetup} + * @see + * AWS API: CreateResourceExplorerSetup + */ + public String createResourceExplorerSetup(List regionList, String viewName, + List aggregatorRegions) { + if (regionList == null || regionList.isEmpty()) { + throw new AwsException("ValidationException", "RegionList must contain at least one Region.", 400); + } + validateRegions(regionList, "RegionList"); + List aggregators = aggregatorRegions != null ? aggregatorRegions : List.of(); + if (aggregators.size() > MAX_AGGREGATOR_REGIONS) { + throw new AwsException("ValidationException", + "AggregatorRegions accepts at most " + MAX_AGGREGATOR_REGIONS + " Region.", 400); + } + validateRegions(aggregators, "AggregatorRegions"); + for (String aggregator : aggregators) { + if (!regionList.contains(aggregator)) { + throw new AwsException("ValidationException", + "AggregatorRegions entry " + aggregator + " must also appear in RegionList.", 400); + } + } + if (viewName == null || !VIEW_NAME_PATTERN.matcher(viewName).matches()) { + throw new AwsException("ValidationException", + "View name must match [a-zA-Z0-9-] and be 1-64 characters: " + viewName, 400); + } + + List outcomes = new ArrayList<>(); + for (String region : regionList) { + outcomes.add(setUpRegion(region, viewName, aggregators.contains(region))); + } + return recordTask(outcomes); + } + + private SetupTask.RegionOutcome setUpRegion(String region, String viewName, boolean aggregator) { + SetupOutcome indexOutcome; + Index index; + try { + index = activeIndex(region).orElseGet(() -> createIndex(region, Map.of())); + if (aggregator && index.type() != IndexType.AGGREGATOR) { + index = updateIndexType(index.arn(), IndexType.AGGREGATOR); + } + indexOutcome = SetupOutcome.succeeded(index.arn()); + } catch (AwsException e) { + LOG.warnf("Setup failed to prepare the index in %s: %s", region, e.getMessage()); + return new SetupTask.RegionOutcome(region, SetupOutcome.failed(e.getErrorCode(), e.getMessage()), null); + } + + SetupOutcome viewOutcome; + try { + View view = createView(region, viewName, null, null, + List.of(new IncludedProperty("tags")), Map.of()); + if (defaultViewStore.get(region).isEmpty()) { + defaultViewStore.put(region, view.viewArn()); + } + viewOutcome = SetupOutcome.succeeded(view.viewArn()); + } catch (AwsException e) { + LOG.warnf("Setup failed to create view %s in %s: %s", viewName, region, e.getMessage()); + viewOutcome = SetupOutcome.failed(e.getErrorCode(), e.getMessage()); + } + return new SetupTask.RegionOutcome(region, indexOutcome, viewOutcome); + } + + /** + * Turns Resource Explorer off in the given Regions, or everywhere it is on. + * + * @see + * AWS API: DeleteResourceExplorerSetup + */ + public String deleteResourceExplorerSetup(Boolean deleteInAllRegions, List regionList) { + boolean allRegions = Boolean.TRUE.equals(deleteInAllRegions); + boolean hasRegionList = regionList != null && !regionList.isEmpty(); + if (allRegions && hasRegionList) { + throw new AwsException("ValidationException", + "RegionList must not be provided when DeleteInAllRegions is true.", 400); + } + if (!allRegions && !hasRegionList) { + throw new AwsException("ValidationException", + "Provide either RegionList or DeleteInAllRegions.", 400); + } + List regions; + if (allRegions) { + regions = activeIndexes(null, null).stream().map(Index::region).distinct().toList(); + } else { + validateRegions(regionList, "RegionList"); + regions = regionList; + } + + List outcomes = new ArrayList<>(); + for (String region : regions) { + outcomes.add(tearDownRegion(region)); + } + return recordTask(outcomes); + } + + private SetupTask.RegionOutcome tearDownRegion(String region) { + SetupOutcome viewOutcome = SetupOutcome.succeeded(null); + for (View view : viewStore.scan(_ -> true)) { + if (region.equals(regionOf(view))) { + deleteView(view.viewArn()); + } + } + Optional index = activeIndex(region); + if (index.isEmpty()) { + return new SetupTask.RegionOutcome(region, + SetupOutcome.failed("ResourceNotFoundException", "No index found for region: " + region), + viewOutcome); + } + deleteIndex(index.get().arn()); + return new SetupTask.RegionOutcome(region, SetupOutcome.succeeded(index.get().arn()), viewOutcome); + } + + private String recordTask(List outcomes) { + String taskId = UUID.randomUUID().toString(); + setupTaskStore.put(taskId, new SetupTask(taskId, outcomes, Instant.now())); + return taskId; + } + + private void validateRegions(List regions, String field) { + for (String region : regions) { + if (region == null || !REGION_PATTERN.matcher(region).matches()) { + throw new AwsException("ValidationException", + field + " contains an invalid AWS Region: " + region, 400); + } + } + } + + /** + * Reports a setup task's per-Region outcome. floci runs the task synchronously, so the status + * is already terminal by the time the task id can be used here. + */ + public ObjectNode getResourceExplorerSetup(String taskId, Integer maxResults, String nextToken) { + SetupTask task = setupTaskStore.get(taskId) + .orElseThrow(() -> new AwsException("ResourceNotFoundException", + "Setup task not found: " + taskId, 404)); + Paginated page = paginate(task.regions(), maxResults, nextToken, 100); + + ObjectNode result = objectMapper.createObjectNode(); + ArrayNode regions = result.putArray("Regions"); + for (SetupTask.RegionOutcome outcome : page.items()) { + ObjectNode node = objectMapper.createObjectNode(); + node.put("Region", outcome.region()); + if (outcome.index() != null) { + node.set("Index", setupStatusNode(outcome.index(), "Index", storedIndexNode(outcome.index().arn()))); + } + if (outcome.view() != null) { + node.set("View", setupStatusNode(outcome.view(), "View", storedViewNode(outcome.view().arn()))); + } + regions.add(node); + } + if (page.nextToken() != null) { + result.put("NextToken", page.nextToken()); + } + return result; + } + + /** The index a create step produced, or null once a delete step has removed it. */ + private ObjectNode storedIndexNode(String arn) { + return arn == null ? null : indexStore.get(arn).map(this::indexNode).orElse(null); + } + + /** The view a create step produced, or null once a delete step has removed it. */ + private ObjectNode storedViewNode(String arn) { + return arn == null ? null : viewStore.get(arn).map(this::buildViewNode).orElse(null); + } + + /** Wraps a step's status with the resource it produced, when that resource still exists. */ + private ObjectNode setupStatusNode(SetupOutcome outcome, String resourceField, ObjectNode resource) { + ObjectNode node = objectMapper.createObjectNode(); + node.put("Status", outcome.status()); + if (resource != null) { + node.set(resourceField, resource); + } + if (outcome.errorCode() != null) { + ObjectNode error = objectMapper.createObjectNode(); + error.put("Code", outcome.errorCode()); + error.put("Message", outcome.errorMessage()); + node.set("ErrorDetails", error); + } + return node; + } + + public Map listTags(String arn) { + Map tags = resolveTaggable(arn).entity().tags(); + return tags != null ? tags : Map.of(); + } + + public void tagResource(String arn, Map tags) { + mutateTags(arn, current -> current.putAll(tags)); + } + + public void untagResource(String arn, List tagKeys) { + mutateTags(arn, current -> tagKeys.forEach(current::remove)); + } + + private void mutateTags(String arn, Consumer> mutation) { + StoredTaggable stored = resolveTaggable(arn); + Map updated = stored.entity().tags() != null + ? new HashMap<>(stored.entity().tags()) : new HashMap<>(); + mutation.accept(updated); + stored.persist().accept(stored.entity().withTags(updated)); + } + + /** A tagged entity (index or view) paired with the action that writes the updated copy back to its store. */ + private record StoredTaggable(Taggable entity, Consumer persist) {} + + private StoredTaggable resolveTaggable(String arn) { + Optional index = indexStore.get(arn); + if (index.isPresent()) { + return new StoredTaggable(index.get(), updated -> indexStore.put(arn, (Index) updated)); + } + Optional view = viewStore.get(arn); + if (view.isPresent()) { + return new StoredTaggable(view.get(), updated -> viewStore.put(arn, (View) updated)); + } + throw new AwsException("ResourceNotFoundException", "Resource not found: " + arn, 404); + } + + private View resolveView(String viewArn, String region) { + ensureDefaultRegionProvisioned(); + String arn = (viewArn != null) ? viewArn : defaultViewStore.get(region).orElse(null); + if (arn == null) { + throw new AwsException("UnauthorizedException", + "No default view is configured for region " + region + + " and no view was specified.", 401); + } + return viewStore.get(arn) + .orElseThrow(() -> new AwsException("ResourceNotFoundException", + "View not found: " + arn, 404)); + } + + private static int decodeNextToken(String token) { + if (token == null) { + return 0; + } + try { + return Integer.parseInt(new String(Base64.getDecoder().decode(token))); + } catch (Exception e) { + LOG.debugf("Invalid NextToken '%s', restarting from offset 0: %s", token, e.getMessage()); + return 0; + } + } + + private static String encodeNextToken(int offset) { + return Base64.getEncoder().encodeToString(String.valueOf(offset).getBytes()); + } + + private ObjectNode buildResourceNode(ExplorerResource r, boolean includeTags) { + ObjectNode node = objectMapper.createObjectNode(); + node.put("Arn", r.arn()); + node.put("LastReportedAt", r.lastReportedAt().toString()); + node.put("OwningAccountId", r.owningAccountId()); + node.put("Region", r.region()); + node.put("ResourceType", r.resourceType()); + node.put("Service", r.service()); + + ArrayNode properties = node.putArray("Properties"); + if (includeTags && r.tags() != null && !r.tags().isEmpty()) { + ObjectNode tagProp = objectMapper.createObjectNode(); + ArrayNode tagData = objectMapper.createArrayNode(); + for (var entry : r.tags().entrySet()) { + ObjectNode tagEntry = objectMapper.createObjectNode(); + tagEntry.put("Key", entry.getKey()); + tagEntry.put("Value", entry.getValue()); + tagData.add(tagEntry); + } + tagProp.set("Data", tagData); + tagProp.put("LastReportedAt", r.lastReportedAt().toString()); + tagProp.put("Name", "tags"); + properties.add(tagProp); + } + return node; + } +} diff --git a/src/main/java/io/github/hectorvent/floci/services/resourceexplorer2/ResourceExplorer2TagHandler.java b/src/main/java/io/github/hectorvent/floci/services/resourceexplorer2/ResourceExplorer2TagHandler.java new file mode 100644 index 0000000000..5e65c12e04 --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/resourceexplorer2/ResourceExplorer2TagHandler.java @@ -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. + * + *

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 listTags(String region, String arn) { + return service.listTags(arn); + } + + @Override + public void tagResource(String region, String arn, Map tags) { + service.tagResource(arn, tags); + } + + @Override + public void untagResource(String region, String arn, List tagKeys) { + service.untagResource(arn, tagKeys); + } +} diff --git a/src/main/java/io/github/hectorvent/floci/services/resourceexplorer2/model/IncludedProperty.java b/src/main/java/io/github/hectorvent/floci/services/resourceexplorer2/model/IncludedProperty.java new file mode 100644 index 0000000000..8c0a80787d --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/resourceexplorer2/model/IncludedProperty.java @@ -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) {} diff --git a/src/main/java/io/github/hectorvent/floci/services/resourceexplorer2/model/Index.java b/src/main/java/io/github/hectorvent/floci/services/resourceexplorer2/model/Index.java new file mode 100644 index 0000000000..3b05ac9013 --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/resourceexplorer2/model/Index.java @@ -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 tags, + Instant createdAt, + Instant lastUpdatedAt, + List replicatingFrom, + List replicatingTo) implements Taggable { + + /** New index: lastUpdatedAt tracks createdAt, replication lists start empty. */ + public Index(String arn, String region, IndexType type, IndexState state, + Map 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 tags) { + return new Index(arn, region, type, state, tags, createdAt, lastUpdatedAt, replicatingFrom, replicatingTo); + } +} diff --git a/src/main/java/io/github/hectorvent/floci/services/resourceexplorer2/model/IndexState.java b/src/main/java/io/github/hectorvent/floci/services/resourceexplorer2/model/IndexState.java new file mode 100644 index 0000000000..296e889947 --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/resourceexplorer2/model/IndexState.java @@ -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 +} diff --git a/src/main/java/io/github/hectorvent/floci/services/resourceexplorer2/model/IndexType.java b/src/main/java/io/github/hectorvent/floci/services/resourceexplorer2/model/IndexType.java new file mode 100644 index 0000000000..d990cec997 --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/resourceexplorer2/model/IndexType.java @@ -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 +} diff --git a/src/main/java/io/github/hectorvent/floci/services/resourceexplorer2/model/SearchFilter.java b/src/main/java/io/github/hectorvent/floci/services/resourceexplorer2/model/SearchFilter.java new file mode 100644 index 0000000000..f8ff34f8f3 --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/resourceexplorer2/model/SearchFilter.java @@ -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) {} diff --git a/src/main/java/io/github/hectorvent/floci/services/resourceexplorer2/model/SetupOutcome.java b/src/main/java/io/github/hectorvent/floci/services/resourceexplorer2/model/SetupOutcome.java new file mode 100644 index 0000000000..b02655580f --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/resourceexplorer2/model/SetupOutcome.java @@ -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. + * + *

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 + * AWS API: GetResourceExplorerSetup + */ +@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); + } +} diff --git a/src/main/java/io/github/hectorvent/floci/services/resourceexplorer2/model/SetupTask.java b/src/main/java/io/github/hectorvent/floci/services/resourceexplorer2/model/SetupTask.java new file mode 100644 index 0000000000..061e1332c9 --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/resourceexplorer2/model/SetupTask.java @@ -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}. + * + *

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 + * AWS API: CreateResourceExplorerSetup + */ +@RegisterForReflection +public record SetupTask(String taskId, List 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) {} +} diff --git a/src/main/java/io/github/hectorvent/floci/services/resourceexplorer2/model/Taggable.java b/src/main/java/io/github/hectorvent/floci/services/resourceexplorer2/model/Taggable.java new file mode 100644 index 0000000000..0d8ac91c76 --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/resourceexplorer2/model/Taggable.java @@ -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 tags(); + Taggable withTags(Map tags); +} diff --git a/src/main/java/io/github/hectorvent/floci/services/resourceexplorer2/model/View.java b/src/main/java/io/github/hectorvent/floci/services/resourceexplorer2/model/View.java new file mode 100644 index 0000000000..e086c1533a --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/resourceexplorer2/model/View.java @@ -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 includedProperties, + Map 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 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 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())); + } +} diff --git a/src/main/java/io/github/hectorvent/floci/services/resourceexplorer2/query/FilterAttribute.java b/src/main/java/io/github/hectorvent/floci/services/resourceexplorer2/query/FilterAttribute.java new file mode 100644 index 0000000000..2eaba58a83 --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/resourceexplorer2/query/FilterAttribute.java @@ -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 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)); + } +} diff --git a/src/main/java/io/github/hectorvent/floci/services/resourceexplorer2/query/ParsedQuery.java b/src/main/java/io/github/hectorvent/floci/services/resourceexplorer2/query/ParsedQuery.java new file mode 100644 index 0000000000..10e6cc6836 --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/resourceexplorer2/query/ParsedQuery.java @@ -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 keywords, + List filters +) { + + @RegisterForReflection + public record Keyword(String value, boolean negated) {} + + @RegisterForReflection + public record Filter( + FilterAttribute attribute, + List values, + boolean negated + ) {} + + @RegisterForReflection + public record FilterValue(String value, boolean prefixMatch) {} +} diff --git a/src/main/java/io/github/hectorvent/floci/services/resourceexplorer2/query/QueryParser.java b/src/main/java/io/github/hectorvent/floci/services/resourceexplorer2/query/QueryParser.java new file mode 100644 index 0000000000..420dea9709 --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/resourceexplorer2/query/QueryParser.java @@ -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. + * + *

Supports: filter prefixes ({@code service:}, {@code region:}, etc.), + * comma-OR, negation ({@code -}), wildcards ({@code *}), quoted strings, + * backslash escaping, and free-form text keywords. + * + *

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 + * Search query syntax reference + */ +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 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 tokenize(String input) { + List 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 tokens) { + List keywords = new ArrayList<>(); + List 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 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 parseFilterValues(String valuePortion) { + List 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 splitUnescaped(String value, char separator) { + List 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(); + } +} diff --git a/src/main/java/io/github/hectorvent/floci/services/resourceexplorer2/query/ResourceFilter.java b/src/main/java/io/github/hectorvent/floci/services/resourceexplorer2/query/ResourceFilter.java new file mode 100644 index 0000000000..53f690103e --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/resourceexplorer2/query/ResourceFilter.java @@ -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. + * + *

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. + * + *

Deviation. 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 + * Search query syntax reference + */ +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 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 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 keywords = new ArrayList<>(viewFilter.keywords()); + keywords.addAll(requestFilter.keywords()); + List 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 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 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 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 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 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 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); + } +} diff --git a/src/main/java/io/github/hectorvent/floci/services/resourcegroupstagging/ResourceGroupsTaggingService.java b/src/main/java/io/github/hectorvent/floci/services/resourcegroupstagging/ResourceGroupsTaggingService.java index 6fdbbe528c..ff6d4fa181 100644 --- a/src/main/java/io/github/hectorvent/floci/services/resourcegroupstagging/ResourceGroupsTaggingService.java +++ b/src/main/java/io/github/hectorvent/floci/services/resourcegroupstagging/ResourceGroupsTaggingService.java @@ -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 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 diff --git a/src/main/java/io/github/hectorvent/floci/services/rum/RumService.java b/src/main/java/io/github/hectorvent/floci/services/rum/RumService.java index 5f2f40e21d..382399acc1 100644 --- a/src/main/java/io/github/hectorvent/floci/services/rum/RumService.java +++ b/src/main/java/io/github/hectorvent/floci/services/rum/RumService.java @@ -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 PLATFORMS = Set.of("Web", "Android", "iOS"); private final StorageBackend 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>() { - })); + }), regionResolver); } - RumService(StorageBackend monitorStore) { + RumService(StorageBackend 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 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 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 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; } diff --git a/src/main/java/io/github/hectorvent/floci/services/rum/model/AppMonitor.java b/src/main/java/io/github/hectorvent/floci/services/rum/model/AppMonitor.java index 2e55919e71..29af1ef4ef 100644 --- a/src/main/java/io/github/hectorvent/floci/services/rum/model/AppMonitor.java +++ b/src/main/java/io/github/hectorvent/floci/services/rum/model/AppMonitor.java @@ -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(); } diff --git a/src/main/java/io/github/hectorvent/floci/services/s3/S3Service.java b/src/main/java/io/github/hectorvent/floci/services/s3/S3Service.java index a95101d020..dd9397b6a5 100644 --- a/src/main/java/io/github/hectorvent/floci/services/s3/S3Service.java +++ b/src/main/java/io/github/hectorvent/floci/services/s3/S3Service.java @@ -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 getResources() { + List 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 getSupportedResourceTypes() { + return Set.of(new SupportedResourceType("s3:bucket", "s3", true)); + } } diff --git a/src/main/java/io/github/hectorvent/floci/services/secretsmanager/SecretsManagerService.java b/src/main/java/io/github/hectorvent/floci/services/secretsmanager/SecretsManagerService.java index 8149478680..04b1d44d05 100644 --- a/src/main/java/io/github/hectorvent/floci/services/secretsmanager/SecretsManagerService.java +++ b/src/main/java/io/github/hectorvent/floci/services/secretsmanager/SecretsManagerService.java @@ -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 getResources() { + List 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 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 getSupportedResourceTypes() { + return Set.of(new SupportedResourceType("secretsmanager:secret", "secretsmanager", true)); + } } diff --git a/src/main/java/io/github/hectorvent/floci/services/sns/SnsService.java b/src/main/java/io/github/hectorvent/floci/services/sns/SnsService.java index db7af234f2..f8406461af 100644 --- a/src/main/java/io/github/hectorvent/floci/services/sns/SnsService.java +++ b/src/main/java/io/github/hectorvent/floci/services/sns/SnsService.java @@ -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 getResources() { + List 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 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. diff --git a/src/main/java/io/github/hectorvent/floci/services/sqs/SqsService.java b/src/main/java/io/github/hectorvent/floci/services/sqs/SqsService.java index 29a575a5de..f4250fa666 100644 --- a/src/main/java/io/github/hectorvent/floci/services/sqs/SqsService.java +++ b/src/main/java/io/github/hectorvent/floci/services/sqs/SqsService.java @@ -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 getResources() { + List 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 getSupportedResourceTypes() { + return Set.of(new SupportedResourceType("sqs:queue", "sqs", true)); + } + public Queue createQueue(String queueName, Map attributes, String region) { return createQueue(queueName, attributes, null, region); } diff --git a/src/main/java/io/github/hectorvent/floci/services/ssm/SsmService.java b/src/main/java/io/github/hectorvent/floci/services/ssm/SsmService.java index 791980737e..406d580206 100644 --- a/src/main/java/io/github/hectorvent/floci/services/ssm/SsmService.java +++ b/src/main/java/io/github/hectorvent/floci/services/ssm/SsmService.java @@ -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 getResources() { + List 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 getSupportedResourceTypes() { + return Set.of(new SupportedResourceType("ssm:parameter", "ssm", true)); + } } diff --git a/src/main/java/io/github/hectorvent/floci/services/stepfunctions/StepFunctionsService.java b/src/main/java/io/github/hectorvent/floci/services/stepfunctions/StepFunctionsService.java index e71dae0d5a..9ad33b7bd7 100644 --- a/src/main/java/io/github/hectorvent/floci/services/stepfunctions/StepFunctionsService.java +++ b/src/main/java/io/github/hectorvent/floci/services/stepfunctions/StepFunctionsService.java @@ -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 getResources() { + List 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 getSupportedResourceTypes() { + return Set.of(new SupportedResourceType("states:stateMachine", "states", true)); + } + // ──────────────────────────── State Machines ──────────────────────────── public StateMachine createStateMachine(String name, String definition, String roleArn, String type, diff --git a/src/main/resources/application.yml b/src/main/resources/application.yml index 514d3f4427..76dbab39b6 100644 --- a/src/main/resources/application.yml +++ b/src/main/resources/application.yml @@ -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: [] diff --git a/src/test/java/io/github/hectorvent/floci/services/elasticache/ElastiCacheQueryHandlerTest.java b/src/test/java/io/github/hectorvent/floci/services/elasticache/ElastiCacheQueryHandlerTest.java index 9ff59b059c..9c9d06bf3d 100644 --- a/src/test/java/io/github/hectorvent/floci/services/elasticache/ElastiCacheQueryHandlerTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/elasticache/ElastiCacheQueryHandlerTest.java @@ -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")); diff --git a/src/test/java/io/github/hectorvent/floci/services/elasticache/ElastiCacheServiceTest.java b/src/test/java/io/github/hectorvent/floci/services/elasticache/ElastiCacheServiceTest.java index f7c45781c1..ea3321c008 100644 --- a/src/test/java/io/github/hectorvent/floci/services/elasticache/ElastiCacheServiceTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/elasticache/ElastiCacheServiceTest.java @@ -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()); diff --git a/src/test/java/io/github/hectorvent/floci/services/lightsail/LightsailResourceProviderTest.java b/src/test/java/io/github/hectorvent/floci/services/lightsail/LightsailResourceProviderTest.java new file mode 100644 index 0000000000..d632868c94 --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/lightsail/LightsailResourceProviderTest.java @@ -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 AccountAwareStorageBackend create(String serviceName, String fileName, + TypeReference> 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 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 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 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")); + } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/rds/RdsServiceTest.java b/src/test/java/io/github/hectorvent/floci/services/rds/RdsServiceTest.java index 40a0938cbb..dff2a1b3d7 100644 --- a/src/test/java/io/github/hectorvent/floci/services/rds/RdsServiceTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/rds/RdsServiceTest.java @@ -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( diff --git a/src/test/java/io/github/hectorvent/floci/services/resourceexplorer2/ResourceExplorer2DefaultViewPersistenceTest.java b/src/test/java/io/github/hectorvent/floci/services/resourceexplorer2/ResourceExplorer2DefaultViewPersistenceTest.java new file mode 100644 index 0000000000..e928010362 --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/resourceexplorer2/ResourceExplorer2DefaultViewPersistenceTest.java @@ -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 indexStore = new InMemoryStorage<>(); + private final StorageBackend viewStore = new InMemoryStorage<>(); + private final StorageBackend defaultViewStore = new InMemoryStorage<>(); + + @SuppressWarnings("unchecked") + private final Instance 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)); + } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/resourceexplorer2/ResourceExplorer2IntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/resourceexplorer2/ResourceExplorer2IntegrationTest.java new file mode 100644 index 0000000000..a9fdfc5352 --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/resourceexplorer2/ResourceExplorer2IntegrationTest.java @@ -0,0 +1,2396 @@ +package io.github.hectorvent.floci.services.resourceexplorer2; + +import io.github.hectorvent.floci.testing.RestAssuredJsonUtils; +import io.quarkus.test.junit.QuarkusTest; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.MethodOrderer; +import org.junit.jupiter.api.Nested; +import org.junit.jupiter.api.Order; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestInstance; +import org.junit.jupiter.api.TestMethodOrder; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.CsvSource; + +import java.util.ArrayList; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import static io.restassured.RestAssured.given; +import static org.hamcrest.Matchers.*; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; + +@QuarkusTest +class ResourceExplorer2IntegrationTest { + + private static final String AUTH = + "AWS4-HMAC-SHA256 Credential=test/20260528/us-east-1/resource-explorer-2/aws4_request"; + private static final String DYNAMO_TYPE = "application/x-amz-json-1.0"; + + /** + * A bounded slice of the emulator, for the tests whose arithmetic needs to know the whole + * result set. The suite shares one emulator instance across every service, and thirty services + * now expose their resources here — comfortably more than the thousand results Search returns, + * so an unscoped query hits the cap and totals stop being comparable to each other. These two + * services keep the slice small and never empty: the fixtures above create a bucket and a table. + */ + private static final String BOUNDED_SCOPE = "service:s3,dynamodb"; + + private static boolean fixturesProvisioned = false; + + private record IndexRef(String auth, String arn) {} + + private final List viewArnsToCleanup = new ArrayList<>(); + private final List indexArnsToCleanup = new ArrayList<>(); + + private String trackView(String viewArn) { + viewArnsToCleanup.add(viewArn); + return viewArn; + } + + private String trackIndex(String auth, String arn) { + indexArnsToCleanup.add(new IndexRef(auth, arn)); + return arn; + } + + @AfterEach + void cleanupEphemeralResources() { + // Best-effort teardown — no assertions. Runs even when the test failed, + // so ephemeral views/indexes never leak into later tests or reruns. + for (String viewArn : viewArnsToCleanup) { + given() + .header("Authorization", AUTH) + .contentType("application/json") + .body("{\"ViewArn\": \"" + viewArn + "\"}") + .when() + .post("/DeleteView"); + } + viewArnsToCleanup.clear(); + + for (IndexRef ref : indexArnsToCleanup) { + given() + .header("Authorization", ref.auth()) + .contentType("application/json") + .body("{\"Arn\": \"" + ref.arn() + "\"}") + .when() + .post("/DeleteIndex"); + } + indexArnsToCleanup.clear(); + } + + @BeforeEach + void provisionFixturesOnce() { + RestAssuredJsonUtils.configureAwsContentTypes(); + if (fixturesProvisioned) { + return; + } + + // Create S3 bucket used by ListResources, DataProvenance, and FilterSemantics groups + given() + .when() + .put("/re2-test-bucket") + .then() + .statusCode(200); + + // Create DynamoDB table with tags used by ListResources, DataProvenance, and FilterSemantics groups + given() + .header("X-Amz-Target", "DynamoDB_20120810.CreateTable") + .contentType(DYNAMO_TYPE) + .body(""" + { + "TableName": "re2-test-table", + "KeySchema": [{"AttributeName": "pk", "KeyType": "HASH"}], + "AttributeDefinitions": [{"AttributeName": "pk", "AttributeType": "S"}], + "ProvisionedThroughput": {"ReadCapacityUnits": 1, "WriteCapacityUnits": 1}, + "Tags": [{"Key": "env", "Value": "test"}] + } + """) + .when() + .post("/") + .then() + .statusCode(200) + .body("TableDescription.TableName", equalTo("re2-test-table")); + + // Lambda function (Resource Explorer 2 provider coverage) + given() + .contentType("application/json") + .body(""" + { + "FunctionName": "re2-test-fn", + "Runtime": "python3.11", + "Role": "arn:aws:iam::000000000000:role/re2-test-role", + "Handler": "index.handler", + "Tags": {"env": "test"} + } + """) + .when() + .post("/2015-03-31/functions") + .then() + .statusCode(201); + + // SNS topic + given() + .contentType("application/x-www-form-urlencoded") + .formParam("Action", "CreateTopic") + .formParam("Name", "re2-test-topic") + .when() + .post("/") + .then() + .statusCode(200); + + // KMS key + given() + .header("X-Amz-Target", "TrentService.CreateKey") + .contentType("application/x-amz-json-1.1") + .body(""" + {"Description": "re2-test-key", "KeyUsage": "ENCRYPT_DECRYPT", "KeySpec": "SYMMETRIC_DEFAULT"} + """) + .when() + .post("/") + .then() + .statusCode(200); + + // SQS queue + given() + .contentType("application/x-www-form-urlencoded") + .formParam("Action", "CreateQueue") + .formParam("QueueName", "re2-test-queue") + .when() + .post("/") + .then() + .statusCode(200); + + // ECR repository + given() + .header("X-Amz-Target", "AmazonEC2ContainerRegistry_V20150921.CreateRepository") + .contentType("application/x-amz-json-1.1") + .body(""" + {"repositoryName": "re2-test-repo"} + """) + .when() + .post("/") + .then() + .statusCode(200); + + // Step Functions state machine + given() + .header("X-Amz-Target", "AWSStepFunctions.CreateStateMachine") + .contentType("application/x-amz-json-1.0") + .body(""" + { + "name": "re2-test-sm", + "definition": "{\\"StartAt\\":\\"Done\\",\\"States\\":{\\"Done\\":{\\"Type\\":\\"Pass\\",\\"End\\":true}}}", + "roleArn": "arn:aws:iam::000000000000:role/re2-test-role" + } + """) + .when() + .post("/") + .then() + .statusCode(200); + + // MSK cluster + given() + .contentType("application/json") + .body(""" + {"clusterName": "re2-test-cluster", "kafkaVersion": "3.6.0"} + """) + .when() + .post("/v1/clusters") + .then() + .statusCode(200); + + // EventBridge Pipes pipe + given() + .contentType("application/json") + .body(""" + { + "Source": "arn:aws:sqs:us-east-1:000000000000:re2-test-queue", + "Target": "arn:aws:lambda:us-east-1:000000000000:function:re2-test-fn", + "RoleArn": "arn:aws:iam::000000000000:role/re2-test-role" + } + """) + .when() + .post("/v1/pipes/re2-test-pipe") + .then() + .statusCode(200); + + // ACM certificate + given() + .header("X-Amz-Target", "CertificateManager.RequestCertificate") + .contentType("application/x-amz-json-1.1") + .body(""" + {"DomainName": "re2-test.example.com", "ValidationMethod": "DNS"} + """) + .when() + .post("/") + .then() + .statusCode(200); + + // Cognito user pool + given() + .header("X-Amz-Target", "AWSCognitoIdentityProviderService.CreateUserPool") + .contentType("application/x-amz-json-1.1") + .body(""" + {"PoolName": "re2-test-pool"} + """) + .when() + .post("/") + .then() + .statusCode(200); + + // IAM user + role + given() + .contentType("application/x-www-form-urlencoded") + .formParam("Action", "CreateUser") + .formParam("UserName", "re2-test-user") + .when() + .post("/") + .then() + .statusCode(200); + + given() + .contentType("application/x-www-form-urlencoded") + .formParam("Action", "CreateRole") + .formParam("RoleName", "re2-test-role-iam") + .formParam("AssumeRolePolicyDocument", "{\"Version\":\"2012-10-17\",\"Statement\":[]}") + .when() + .post("/") + .then() + .statusCode(200); + + // Amazon MQ broker (mocked in test config, so no backing container) + given() + .contentType("application/json") + .body(""" + { + "brokerName": "re2-test-broker", + "engineType": "RABBITMQ", + "deploymentMode": "SINGLE_INSTANCE", + "hostInstanceType": "mq.t3.micro", + "users": [{"username": "admin", "password": "re2BrokerPass99"}] + } + """) + .when() + .post("/v1/brokers") + .then() + .statusCode(200); + + // Lightsail instance + disk (Resource Explorer 2 provider coverage) + given() + .header("X-Amz-Target", "Lightsail_20161128.CreateInstances") + .contentType("application/x-amz-json-1.1") + .body(""" + { + "instanceNames": ["re2-test-instance"], + "availabilityZone": "us-east-1a", + "blueprintId": "ubuntu_22_04", + "bundleId": "nano_3_0", + "tags": [{"key": "env", "value": "test"}] + } + """) + .when() + .post("/") + .then() + .statusCode(200); + + given() + .header("X-Amz-Target", "Lightsail_20161128.CreateDisk") + .contentType("application/x-amz-json-1.1") + .body(""" + {"diskName": "re2-test-disk", "availabilityZone": "us-east-1a", "sizeInGb": 8} + """) + .when() + .post("/") + .then() + .statusCode(200); + + // CloudWatch RUM app monitor (Resource Explorer 2 provider coverage) + given() + .header("Authorization", AUTH) + .contentType("application/json") + .body(""" + { + "Name": "re2-test-monitor", + "Domain": "example.com", + "Tags": {"env": "test"} + } + """) + .when() + .post("/appmonitor") + .then() + .statusCode(200); + + fixturesProvisioned = true; + } + + @Nested + class AutoProvisioning { + + @Test + void autoProvisionedIndexExists() { + given() + .header("Authorization", AUTH) + .contentType("application/json") + .when() + .post("/GetIndex") + .then() + .statusCode(200) + .body("Arn", notNullValue()) + .body("Type", notNullValue()) + .body("State", equalTo("ACTIVE")) + .body("CreatedAt", notNullValue()) + .body("LastUpdatedAt", notNullValue()) + .body("Tags", notNullValue()) + .body("ReplicatingFrom", notNullValue()) + .body("ReplicatingTo", notNullValue()); + } + + @Test + void autoProvisionedDefaultViewExists() { + given() + .header("Authorization", AUTH) + .contentType("application/json") + .when() + .post("/GetDefaultView") + .then() + .statusCode(200) + .body("ViewArn", notNullValue()); + } + } + + @Nested + class ListResources { + + @Test + void listResourcesWithNoFilterReturnsAll() { + given() + .header("Authorization", AUTH) + .contentType("application/json") + .body("{}") + .when() + .post("/ListResources") + .then() + .statusCode(200) + .body("Resources", notNullValue()) + .body("ViewArn", notNullValue()); + } + + @Test + void listResourcesFilteredByS3ResourceType() { + given() + .header("Authorization", AUTH) + .contentType("application/json") + .body(""" + {"Filters": {"FilterString": "resourcetype:s3:bucket"}} + """) + .when() + .post("/ListResources") + .then() + .statusCode(200) + .body("Resources", notNullValue()) + .body("Resources.findAll { it.ResourceType != 's3:bucket' }.size()", equalTo(0)); + } + + @Test + void listResourcesFilteredByDynamoDbService() { + given() + .header("Authorization", AUTH) + .contentType("application/json") + .body(""" + {"Filters": {"FilterString": "service:dynamodb"}} + """) + .when() + .post("/ListResources") + .then() + .statusCode(200) + .body("Resources.findAll { it.Service != 'dynamodb' }.size()", equalTo(0)); + } + + @Test + void listResourcesNegatedServiceExcludesS3() { + given() + .header("Authorization", AUTH) + .contentType("application/json") + .body(""" + {"Filters": {"FilterString": "-service:s3"}} + """) + .when() + .post("/ListResources") + .then() + .statusCode(200) + .body("Resources.findAll { it.Service == 's3' }.size()", equalTo(0)); + } + + @Test + void listResourcesInvalidFilterReturns400() { + given() + .header("Authorization", AUTH) + .contentType("application/json") + .body(""" + {"Filters": {"FilterString": "hello world"}} + """) + .when() + .post("/ListResources") + .then() + .statusCode(400); + } + } + + @Nested + class Search { + + @Test + void searchWithQueryStringReturnsCountObject() { + given() + .header("Authorization", AUTH) + .contentType("application/json") + .body(""" + {"QueryString": "service:s3"} + """) + .when() + .post("/Search") + .then() + .statusCode(200) + .body("Count.TotalResources", greaterThanOrEqualTo(0)) + .body("Count.Complete", equalTo(true)) + .body("Resources", notNullValue()) + .body("ViewArn", notNullValue()); + } + + @Test + void searchWithEmptyQueryReturnsAllResources() { + var response = given() + .header("Authorization", AUTH) + .contentType("application/json") + .body(""" + {"QueryString": ""} + """) + .when() + .post("/Search") + .then() + .statusCode(200) + .body("Count.TotalResources", greaterThanOrEqualTo(0)) + .body("Resources", notNullValue()) + .extract().response(); + + // Unscoped, so how many resources the shared emulator holds is not knowable here. + // Complete says whether the 1000-result cap bit, which is exactly what TotalResources + // reaching the cap means — assert that relationship rather than a fixed value. + int total = response.path("Count.TotalResources"); + boolean complete = response.path("Count.Complete"); + assertEquals(total < 1000, complete); + } + } + + @Nested + class ListSupportedResourceTypes { + + @Test + void listSupportedResourceTypesReturnsKnownTypes() { + given() + .header("Authorization", AUTH) + .contentType("application/json") + .body("{}") + .when() + .post("/ListSupportedResourceTypes") + .then() + .statusCode(200) + .body("ResourceTypes", notNullValue()) + .body("ResourceTypes.size()", greaterThan(0)) + .body("ResourceTypes.Service", hasItems("s3", "rds", "dynamodb", "elasticache", "es", "lambda", "sns", "kms", "sqs", "ecr", "states", "kafka", "pipes", "acm", "cognito-idp", "iam", "mq", "lightsail", "rum")); + } + } + + @Nested + class ServiceResources { + + @ParameterizedTest(name = "{1} surfaces via ListResources") + @CsvSource({ + "lambda, lambda:function", + "sns, sns:topic", + "kms, kms:key", + "sqs, sqs:queue", + "ecr, ecr:repository", + "states, states:stateMachine", + "kafka, kafka:cluster", + "pipes, pipes:pipe", + "acm, acm:certificate", + "cognito-idp, cognito-idp:userpool", + "mq, mq:broker", + "lightsail, lightsail:Instance", + "lightsail, lightsail:Disk", + "rum, rum:appmonitor" + }) + void resourceSurfacesViaListResources(String service, String resourceType) { + given() + .header("Authorization", AUTH) + .contentType("application/json") + .body("{\"Filters\": {\"FilterString\": \"service:" + service + "\"}}") + .when() + .post("/ListResources") + .then() + .statusCode(200) + .body("Resources.size()", greaterThan(0)) + .body("Resources.findAll { it.Service != '" + service + "' }.size()", equalTo(0)) + .body("Resources.findAll { it.ResourceType == '" + resourceType + + "' && it.Region == 'us-east-1' }.size()", greaterThan(0)); + } + } + + @Nested + class IamResources { + @Test + void iamResourcesSurfaceViaListResources() { + given() + .header("Authorization", AUTH) + .contentType("application/json") + .body(""" + {"Filters": {"FilterString": "service:iam"}} + """) + .when() + .post("/ListResources") + .then() + .statusCode(200) + .body("Resources.size()", greaterThan(0)) + .body("Resources.findAll { it.Service != 'iam' }.size()", equalTo(0)) + // IAM is global: Resource Explorer reports these with Region "global", never empty/null. + .body("Resources.findAll { it.Region != 'global' }.size()", equalTo(0)) + .body("Resources.findAll { it.ResourceType == 'iam:user' && it.Region == 'global' }.size()", greaterThan(0)) + .body("Resources.findAll { it.ResourceType == 'iam:role' && it.Region == 'global' }.size()", greaterThan(0)); + } + } + + @Nested + @TestMethodOrder(MethodOrderer.OrderAnnotation.class) + @TestInstance(TestInstance.Lifecycle.PER_CLASS) + class ViewCrud { + + private String viewArn; + + @Test + @Order(1) + void createViewWithFilter() { + viewArn = given() + .header("Authorization", AUTH) + .contentType("application/json") + .body(""" + { + "ViewName": "test-view", + "Filters": {"FilterString": "service:s3"}, + "IncludedProperties": [{"Name": "tags"}] + } + """) + .when() + .post("/CreateView") + .then() + .statusCode(200) + .body("View.ViewArn", notNullValue()) + .body("View.Filters.FilterString", equalTo("service:s3")) + .extract().path("View.ViewArn"); + } + + @Test + @Order(2) + void getViewReturnsCreatedView() { + given() + .header("Authorization", AUTH) + .contentType("application/json") + .body("{\"ViewArn\": \"" + viewArn + "\"}") + .when() + .post("/GetView") + .then() + .statusCode(200) + .body("View.ViewArn", equalTo(viewArn)); + } + + @Test + @Order(3) + void updateView() { + given() + .header("Authorization", AUTH) + .contentType("application/json") + .body(""" + { + "ViewArn": "%s", + "Filters": {"FilterString": "service:dynamodb"}, + "IncludedProperties": [{"Name": "tags"}] + } + """.formatted(viewArn)) + .when() + .post("/UpdateView") + .then() + .statusCode(200) + .body("View.Filters.FilterString", equalTo("service:dynamodb")); + } + + @Test + @Order(4) + void listViewsContainsCreatedView() { + given() + .header("Authorization", AUTH) + .contentType("application/json") + .body("{}") + .when() + .post("/ListViews") + .then() + .statusCode(200) + .body("Views", hasItem(viewArn)); + } + + @Test + @Order(5) + void batchGetViewReturnsErrorsForMissingArns() { + String bogusArn = "arn:aws:resource-explorer-2:us-east-1:000000000000:view/nope/00000000-0000-0000-0000-000000000000"; + given() + .header("Authorization", AUTH) + .contentType("application/json") + .body("{\"ViewArns\": [\"" + viewArn + "\", \"" + bogusArn + "\"]}") + .when() + .post("/BatchGetView") + .then() + .statusCode(200) + .body("Views.size()", equalTo(1)) + .body("Views[0].ViewArn", equalTo(viewArn)) + .body("Errors.size()", equalTo(1)) + .body("Errors[0].ViewArn", equalTo(bogusArn)) + .body("Errors[0].ErrorMessage", notNullValue()); + } + + @Test + @Order(6) + void associateDefaultView() { + given() + .header("Authorization", AUTH) + .contentType("application/json") + .body("{\"ViewArn\": \"" + viewArn + "\"}") + .when() + .post("/AssociateDefaultView") + .then() + .statusCode(200) + .body("ViewArn", equalTo(viewArn)); + } + + @Test + @Order(7) + void getDefaultViewReturnsMostRecent() { + given() + .header("Authorization", AUTH) + .contentType("application/json") + .when() + .post("/GetDefaultView") + .then() + .statusCode(200) + .body("ViewArn", equalTo(viewArn)); + } + + @Test + @Order(8) + void disassociateDefaultView() { + given() + .header("Authorization", AUTH) + .contentType("application/json") + .when() + .post("/DisassociateDefaultView") + .then() + .statusCode(200); + } + + @Test + @Order(9) + void deleteView() { + given() + .header("Authorization", AUTH) + .contentType("application/json") + .body("{\"ViewArn\": \"" + viewArn + "\"}") + .when() + .post("/DeleteView") + .then() + .statusCode(200) + .body("ViewArn", equalTo(viewArn)); + } + + @Test + @Order(10) + void restoreDefaultViewAfterCrudTests() { + // Re-associate the auto-provisioned default view so other groups work + String autoViewArn = given() + .header("Authorization", AUTH) + .contentType("application/json") + .body("{}") + .when() + .post("/ListViews") + .then() + .extract().path("Views[0]"); + + given() + .header("Authorization", AUTH) + .contentType("application/json") + .body("{\"ViewArn\": \"" + autoViewArn + "\"}") + .when() + .post("/AssociateDefaultView") + .then() + .statusCode(200); + } + } + + @Nested + @TestMethodOrder(MethodOrderer.OrderAnnotation.class) + @TestInstance(TestInstance.Lifecycle.PER_CLASS) + class IndexCrud { + + @Test + @Order(1) + void listIndexesContainsAutoProvisionedIndex() { + given() + .header("Authorization", AUTH) + .contentType("application/json") + .when() + .post("/ListIndexes") + .then() + .statusCode(200) + .body("Indexes", notNullValue()) + .body("Indexes.size()", greaterThan(0)); + } + + @Test + @Order(2) + void updateIndexType() { + String indexArn = given() + .header("Authorization", AUTH) + .contentType("application/json") + .when() + .post("/GetIndex") + .then() + .statusCode(200) + .extract().path("Arn"); + + given() + .header("Authorization", AUTH) + .contentType("application/json") + .body("{\"Arn\": \"" + indexArn + "\", \"Type\": \"LOCAL\"}") + .when() + .post("/UpdateIndexType") + .then() + .statusCode(200) + .body("Arn", equalTo(indexArn)) + .body("Type", equalTo("LOCAL")) + .body("State", notNullValue()) + .body("LastUpdatedAt", notNullValue()); + + // Restore to AGGREGATOR + given() + .header("Authorization", AUTH) + .contentType("application/json") + .body("{\"Arn\": \"" + indexArn + "\", \"Type\": \"AGGREGATOR\"}") + .when() + .post("/UpdateIndexType") + .then() + .statusCode(200); + } + } + + @Nested + class ErrorCases { + + @Test + void getMissingViewReturns404() { + given() + .header("Authorization", AUTH) + .contentType("application/json") + .body("{\"ViewArn\": \"arn:aws:resource-explorer-2:us-east-1:000000000000:view/nonexistent/abc\"}") + .when() + .post("/GetView") + .then() + .statusCode(404); + } + + @Test + void invalidUpdateIndexTypeReturns400Not500() { + given() + .header("Authorization", AUTH) + .contentType("application/json") + .body("{\"Arn\": \"some-arn\", \"Type\": \"INVALID_TYPE\"}") + .when() + .post("/UpdateIndexType") + .then() + .statusCode(400); + } + + @Test + void deleteIndexIncludesLastUpdatedAt() { + String arn = given() + .header("Authorization", "AWS4-HMAC-SHA256 Credential=test/20260528/eu-west-1/resource-explorer-2/aws4_request") + .contentType("application/json") + .body("{}") + .when() + .post("/CreateIndex") + .then() + .statusCode(200) + .body("Arn", notNullValue()) + .body("State", notNullValue()) + .body("CreatedAt", notNullValue()) + .extract().path("Arn"); + + given() + .header("Authorization", AUTH) + .contentType("application/json") + .body("{\"Arn\": \"" + arn + "\"}") + .when() + .post("/DeleteIndex") + .then() + .statusCode(200) + .body("Arn", equalTo(arn)) + .body("State", notNullValue()) + .body("LastUpdatedAt", notNullValue()); + } + } + + @Nested + class ConditionalResponseFields { + + @Test + void searchCountCompleteIsTrueWhenFewResources() { + // Complete=true means total matched resources <= 1000 (no cap was applied). + // Scoped to a handful of resources, Complete must be TRUE on every page, + // even when MaxResults=1 causes pagination (NextToken is still emitted). + given() + .header("Authorization", AUTH) + .contentType("application/json") + .body("{\"QueryString\": \"" + BOUNDED_SCOPE + "\", \"MaxResults\": 1}") + .when() + .post("/Search") + .then() + .statusCode(200) + .body("Count.Complete", equalTo(true)) + .body("Count.TotalResources", greaterThan(1)) + .body("NextToken", notNullValue()); + } + + @Test + void searchCountCompleteIsTrueWhenNotPaginating() { + given() + .header("Authorization", AUTH) + .contentType("application/json") + .body("{\"QueryString\": \"" + BOUNDED_SCOPE + "\", \"MaxResults\": 1000}") + .when() + .post("/Search") + .then() + .statusCode(200) + .body("Count.Complete", equalTo(true)) + .body("NextToken", nullValue()); + } + + @Test + void listResourcesNextTokenSuppressedAtMaxResults1000() { + // First confirm there are multiple pages when MaxResults=1 — this proves + // NextToken absence at MaxResults=1000 is NOT simply "everything fits on + // one page" but is the deliberate suppression rule for MaxResults==1000. + given() + .header("Authorization", AUTH) + .contentType("application/json") + .body(""" + {"MaxResults": 1} + """) + .when() + .post("/ListResources") + .then() + .statusCode(200) + .body("Resources.size()", equalTo(1)) + .body("NextToken", notNullValue()); + + // Now verify that MaxResults=1000 suppresses NextToken even though more + // pages would exist at smaller page sizes. The production rule is: + // NextToken must be absent on ListResources when MaxResults==1000. + given() + .header("Authorization", AUTH) + .contentType("application/json") + .body(""" + {"MaxResults": 1000} + """) + .when() + .post("/ListResources") + .then() + .statusCode(200) + .body("NextToken", nullValue()); + } + + @Test + void listResourcesNextTokenPresentWhenMorePages() { + given() + .header("Authorization", AUTH) + .contentType("application/json") + .body(""" + {"MaxResults": 1} + """) + .when() + .post("/ListResources") + .then() + .statusCode(200) + .body("Resources.size()", equalTo(1)) + .body("NextToken", notNullValue()); + } + + @Test + void propertiesEmptyWhenViewExcludesTags() { + String noTagsViewArn = trackView(given() + .header("Authorization", AUTH) + .contentType("application/json") + .body(""" + {"ViewName": "no-tags-view", "IncludedProperties": []} + """) + .when() + .post("/CreateView") + .then() + .statusCode(200) + .extract().path("View.ViewArn")); + + given() + .header("Authorization", AUTH) + .contentType("application/json") + .body("{\"ViewArn\": \"" + noTagsViewArn + "\"}") + .when() + .post("/ListResources") + .then() + .statusCode(200) + .body("Resources[0].get('Properties').size()", equalTo(0)); + } + + @Test + void propertiesPopulatedWhenViewIncludesTags() { + // Target the known-tagged fixture table by ARN. A positional Resources[0] is + // unsafe: the full test suite shares one emulator instance, so other classes' + // untagged DynamoDB tables land in this same service:dynamodb result set and any + // of them may sort ahead of the tagged fixture. + String table = "Resources.find { it.Arn.contains('re2-test-table') }"; + given() + .header("Authorization", AUTH) + .contentType("application/json") + .body(""" + {"Filters": {"FilterString": "service:dynamodb"}} + """) + .when() + .post("/ListResources") + .then() + .statusCode(200) + .body(table, notNullValue()) + .body(table + ".get('Properties').size()", greaterThan(0)) + .body(table + ".get('Properties')[0].Name", equalTo("tags")) + .body(table + ".get('Properties')[0].Data.size()", greaterThan(0)) + .body(table + ".get('Properties')[0].Data[0].Key", notNullValue()) + .body(table + ".get('Properties')[0].Data[0].Value", notNullValue()) + .body(table + ".get('Properties')[0].LastReportedAt", notNullValue()); + } + } + + @Nested + @TestMethodOrder(MethodOrderer.OrderAnnotation.class) + @TestInstance(TestInstance.Lifecycle.PER_CLASS) + class DataProvenance { + + @Test + @Order(1) + void s3BucketTagsAppearViaTagFilter() { + given() + .contentType("application/xml") + .body(""" + + + + envstaging + + + """) + .when() + .put("/re2-test-bucket?tagging") + .then() + .statusCode(anyOf(equalTo(200), equalTo(204))); + + given() + .header("Authorization", AUTH) + .contentType("application/json") + .body(""" + {"Filters": {"FilterString": "tag:env=staging"}} + """) + .when() + .post("/ListResources") + .then() + .statusCode(200) + .body("Resources.size()", greaterThan(0)) + .body("Resources.findAll { it.Service == 's3' }.size()", greaterThan(0)); + } + + @Test + @Order(2) + void dynamoDbTagsFromCreateTableAppearViaTagFilter() { + given() + .header("Authorization", AUTH) + .contentType("application/json") + .body(""" + {"Filters": {"FilterString": "tag:env=test"}} + """) + .when() + .post("/ListResources") + .then() + .statusCode(200) + .body("Resources.size()", greaterThan(0)) + .body("Resources.findAll { it.Service == 'dynamodb' }.size()", greaterThan(0)); + } + + @Test + @Order(3) + void dynamoDbTagResourceUpdatesResourceExplorer() { + // Scoped to the caller's Region: ListResources spans every Region the view covers, but + // the TagResource below resolves the table in the request's Region, so an out-of-Region + // ARN would be reported as not found. + String tableArn = given() + .header("Authorization", AUTH) + .contentType("application/json") + .body(""" + {"Filters": {"FilterString": "resourcetype:dynamodb:table region:us-east-1"}} + """) + .when() + .post("/ListResources") + .then() + .extract().path("Resources[0].Arn"); + + given() + .header("X-Amz-Target", "DynamoDB_20120810.TagResource") + .contentType(DYNAMO_TYPE) + .body(""" + { + "ResourceArn": "%s", + "Tags": [{"Key": "team", "Value": "platform"}] + } + """.formatted(tableArn)) + .when() + .post("/") + .then() + .statusCode(200); + + given() + .header("Authorization", AUTH) + .contentType("application/json") + .body(""" + {"Filters": {"FilterString": "tag:team=platform"}} + """) + .when() + .post("/ListResources") + .then() + .statusCode(200) + .body("Resources.size()", greaterThan(0)); + } + + @Test + @Order(4) + void tagFilterDoesNotMatchUntaggedResources() { + given() + .header("Authorization", "AWS4-HMAC-SHA256 Credential=test/20260528/us-east-1/rds/aws4_request") + .contentType("application/x-www-form-urlencoded") + .formParam("Action", "CreateDBInstance") + .formParam("DBInstanceIdentifier", "re2-untagged-db") + .formParam("Engine", "postgres") + .formParam("MasterUsername", "admin") + .formParam("MasterUserPassword", "password123") + .formParam("DBInstanceClass", "db.t3.micro") + .when() + .post("/") + .then() + .statusCode(200); + + given() + .header("Authorization", AUTH) + .contentType("application/json") + .body(""" + {"Filters": {"FilterString": "tag:env=staging service:rds"}} + """) + .when() + .post("/ListResources") + .then() + .statusCode(200) + .body("Resources.size()", equalTo(0)); + } + + @Test + @Order(5) + void tagAllMatchesOnlyTaggedResources() { + given() + .header("Authorization", AUTH) + .contentType("application/json") + .body(""" + {"Filters": {"FilterString": "tag:all"}} + """) + .when() + .post("/ListResources") + .then() + .statusCode(200) + .body("Resources.size()", greaterThan(0)) + .body("Resources.findAll { it.get('Properties').size() > 0 }.size()", + equalTo((int) given() + .header("Authorization", AUTH) + .contentType("application/json") + .body("{\"Filters\": {\"FilterString\": \"tag:all\"}}") + .post("/ListResources") + .then().extract().path("Resources.size()"))); + } + + @Test + @Order(6) + void tagNoneMatchesOnlyUntaggedResources() { + given() + .header("Authorization", AUTH) + .contentType("application/json") + .body(""" + {"Filters": {"FilterString": "tag:none"}} + """) + .when() + .post("/ListResources") + .then() + .statusCode(200) + .body("Resources.size()", greaterThan(0)) + .body("Resources.findAll { it.get('Properties').size() > 0 }.size()", equalTo(0)); + } + + @Test + @Order(7) + void tagKeyFilterMatchesAcrossServices() { + given() + .header("Authorization", AUTH) + .contentType("application/json") + .body(""" + {"Filters": {"FilterString": "tag.key:env"}} + """) + .when() + .post("/ListResources") + .then() + .statusCode(200) + .body("Resources.size()", greaterThanOrEqualTo(2)) + .body("Resources.Service", hasItems("s3", "dynamodb")); + } + + @Test + @Order(8) + void tagValueFilterMatchesCorrectValue() { + given() + .header("Authorization", AUTH) + .contentType("application/json") + .body(""" + {"Filters": {"FilterString": "tag.value:staging"}} + """) + .when() + .post("/ListResources") + .then() + .statusCode(200) + .body("Resources.size()", greaterThan(0)) + .body("Resources.findAll { it.Service == 'dynamodb' }.size()", equalTo(0)); + } + + @Test + @Order(9) + void rdsTagsViaResourceGroupsTaggingApi() { + String rdsArn = given() + .header("Authorization", AUTH) + .contentType("application/json") + .body(""" + {"Filters": {"FilterString": "resourcetype:rds:db"}} + """) + .when() + .post("/ListResources") + .then() + .extract().path("Resources[0].Arn"); + + given() + .header("X-Amz-Target", "ResourceGroupsTaggingAPI_20170126.TagResources") + .contentType("application/x-amz-json-1.1") + .body(""" + { + "ResourceARNList": ["%s"], + "Tags": {"rgta-tag": "rgta-value"} + } + """.formatted(rdsArn)) + .when() + .post("/") + .then() + .statusCode(200); + + given() + .header("Authorization", AUTH) + .contentType("application/json") + .body(""" + {"Filters": {"FilterString": "tag:rgta-tag=rgta-value"}} + """) + .when() + .post("/ListResources") + .then() + .statusCode(200) + .body("Resources.size()", greaterThan(0)) + .body("Resources[0].Arn", equalTo(rdsArn)); + } + } + + @Nested + class EdgeBoundaryBehavior { + + @Test + void listResourcesMaxResults1ReturnsSingleResource() { + given() + .header("Authorization", AUTH) + .contentType("application/json") + .body(""" + {"MaxResults": 1} + """) + .when() + .post("/ListResources") + .then() + .statusCode(200) + .body("Resources.size()", equalTo(1)) + .body("NextToken", notNullValue()); + } + + @Test + void listResourcesEmptyResultSet() { + given() + .header("Authorization", AUTH) + .contentType("application/json") + .body(""" + {"Filters": {"FilterString": "service:nonexistent"}} + """) + .when() + .post("/ListResources") + .then() + .statusCode(200) + .body("Resources.size()", equalTo(0)) + .body("NextToken", nullValue()); + } + + @Test + void paginationReturnsAllResourcesAcrossPages() { + // Scoped: paging the whole emulator one resource at a time would need thousands of + // round trips, and the total would not fit the single 1000-result page it is read from. + int totalCount = given() + .header("Authorization", AUTH) + .contentType("application/json") + .body("{\"MaxResults\": 1000, \"Filters\": {\"FilterString\": \"" + BOUNDED_SCOPE + "\"}}") + .when() + .post("/ListResources") + .then() + .extract().path("Resources.size()"); + + Set allArns = new HashSet<>(); + String nextToken = null; + int pages = 0; + int maxPages = totalCount + 5; + + do { + String body = nextToken == null + ? "{\"MaxResults\": 1, \"Filters\": {\"FilterString\": \"" + BOUNDED_SCOPE + "\"}}" + : "{\"MaxResults\": 1, \"NextToken\": \"" + nextToken + + "\", \"Filters\": {\"FilterString\": \"" + BOUNDED_SCOPE + "\"}}"; + + var response = given() + .header("Authorization", AUTH) + .contentType("application/json") + .body(body) + .when() + .post("/ListResources") + .then() + .statusCode(200) + .extract().response(); + + List arns = response.path("Resources.Arn"); + allArns.addAll(arns); + nextToken = response.path("NextToken"); + pages++; + } while (nextToken != null && pages < maxPages); + + assertEquals(totalCount, allArns.size(), "Paginated results should cover all resources"); + } + + @Test + void listResourcesMaxResultsGreaterThanTotalReturnsAll() { + // Scoped, so that a page size of 999 really is larger than the total being asked for. + int totalCount = given() + .header("Authorization", AUTH) + .contentType("application/json") + .body("{\"MaxResults\": 1000, \"Filters\": {\"FilterString\": \"" + BOUNDED_SCOPE + "\"}}") + .when() + .post("/ListResources") + .then() + .extract().path("Resources.size()"); + + given() + .header("Authorization", AUTH) + .contentType("application/json") + .body("{\"MaxResults\": 999, \"Filters\": {\"FilterString\": \"" + BOUNDED_SCOPE + "\"}}") + .when() + .post("/ListResources") + .then() + .statusCode(200) + .body("Resources.size()", equalTo(totalCount)) + .body("NextToken", nullValue()); + } + + @Test + void searchPaginationWithNextToken() { + String nextToken = given() + .header("Authorization", AUTH) + .contentType("application/json") + .body("{\"QueryString\": \"" + BOUNDED_SCOPE + "\", \"MaxResults\": 1}") + .when() + .post("/Search") + .then() + .statusCode(200) + .body("Count.Complete", equalTo(true)) + .body("Resources.size()", equalTo(1)) + .extract().path("NextToken"); + + given() + .header("Authorization", AUTH) + .contentType("application/json") + .body("{\"QueryString\": \"" + BOUNDED_SCOPE + "\", \"MaxResults\": 1, \"NextToken\": \"" + + nextToken + "\"}") + .when() + .post("/Search") + .then() + .statusCode(200) + .body("Resources.size()", equalTo(1)) + .body("Count.TotalResources", greaterThan(1)); + } + + @Test + void listSupportedResourceTypesHasNextTokenWhenNeeded() { + given() + .header("Authorization", AUTH) + .contentType("application/json") + .body(""" + {"MaxResults": 1} + """) + .when() + .post("/ListSupportedResourceTypes") + .then() + .statusCode(200) + .body("ResourceTypes.size()", equalTo(1)) + .body("NextToken", notNullValue()); + } + + @Test + void listViewsHasNextTokenWhenNeeded() { + trackView(given() + .header("Authorization", AUTH) + .contentType("application/json") + .body("{\"ViewName\": \"temp-pagination-view\"}") + .when() + .post("/CreateView") + .then() + .extract().path("View.ViewArn")); + + given() + .header("Authorization", AUTH) + .contentType("application/json") + .body("{\"MaxResults\": 1}") + .when() + .post("/ListViews") + .then() + .statusCode(200) + .body("Views.size()", equalTo(1)) + .body("NextToken", notNullValue()); + } + + @Test + void listIndexesHasNextTokenWhenNeeded() { + given() + .header("Authorization", AUTH) + .contentType("application/json") + .body("{\"MaxResults\": 1}") + .when() + .post("/ListIndexes") + .then() + .statusCode(200) + .body("Indexes.size()", lessThanOrEqualTo(1)); + } + } + + @Nested + class CrossServiceDataConsistency { + + @Test + void allResourcesHaveRequiredFields() { + List> resources = given() + .header("Authorization", AUTH) + .contentType("application/json") + .body("{\"MaxResults\": 1000}") + .when() + .post("/ListResources") + .then() + .statusCode(200) + .extract().path("Resources"); + + for (var resource : resources) { + assertNotNull(resource.get("Arn"), "Resource missing Arn: " + resource); + assertNotNull(resource.get("ResourceType"), "Resource missing ResourceType: " + resource); + assertNotNull(resource.get("Service"), "Resource missing Service: " + resource); + assertNotNull(resource.get("Region"), "Resource missing Region: " + resource); + assertNotNull(resource.get("OwningAccountId"), "Resource missing OwningAccountId: " + resource); + assertNotNull(resource.get("LastReportedAt"), "Resource missing LastReportedAt: " + resource); + assertNotNull(resource.get("Properties"), "Resource missing Properties: " + resource); + } + } + + @Test + void resourceTypeFormatIsServiceColonType() { + List types = given() + .header("Authorization", AUTH) + .contentType("application/json") + .body("{\"MaxResults\": 1000}") + .when() + .post("/ListResources") + .then() + .extract().path("Resources.ResourceType"); + + for (String type : types) { + assertTrue(type.contains(":"), "ResourceType must be in service:type format, got: " + type); + } + } + + @Test + void serviceFieldMatchesResourceTypePrefix() { + List> resources = given() + .header("Authorization", AUTH) + .contentType("application/json") + .body("{\"MaxResults\": 1000}") + .when() + .post("/ListResources") + .then() + .extract().path("Resources"); + + for (var resource : resources) { + String service = (String) resource.get("Service"); + String resourceType = (String) resource.get("ResourceType"); + assertTrue( + resourceType.startsWith(service + ":"), + "Service '" + service + "' doesn't match ResourceType prefix '" + resourceType + "'"); + } + } + + @Test + void arnContainsServiceAndRegion() { + List> resources = given() + .header("Authorization", AUTH) + .contentType("application/json") + .body("{\"MaxResults\": 1000}") + .when() + .post("/ListResources") + .then() + .extract().path("Resources"); + + for (var resource : resources) { + String arn = (String) resource.get("Arn"); + String service = (String) resource.get("Service"); + assertTrue(arn.startsWith("arn:aws:"), + "ARN must start with arn:aws:, got: " + arn); + assertTrue(arn.contains(service), + "ARN should contain service '" + service + "', got: " + arn); + } + } + } + + @Nested + class FilterSemantics { + + @Test + void filterByServiceReturnsOnlyThatService() { + for (String svc : List.of("s3", "dynamodb", "rds")) { + List services = given() + .header("Authorization", AUTH) + .contentType("application/json") + .body("{\"Filters\": {\"FilterString\": \"service:" + svc + "\"}}") + .when() + .post("/ListResources") + .then() + .statusCode(200) + .extract().path("Resources.Service"); + + for (String s : services) { + assertEquals(svc, s, + "service:" + svc + " filter returned wrong service: " + s); + } + } + } + + @Test + void filterByResourceTypeIsExact() { + given() + .header("Authorization", AUTH) + .contentType("application/json") + .body(""" + {"Filters": {"FilterString": "resourcetype:dynamodb:table"}} + """) + .when() + .post("/ListResources") + .then() + .statusCode(200) + .body("Resources.size()", greaterThan(0)) + .body("Resources.findAll { it.ResourceType != 'dynamodb:table' }.size()", equalTo(0)); + } + + @Test + void filterByResourceTypeCommaOr() { + given() + .header("Authorization", AUTH) + .contentType("application/json") + .body(""" + {"Filters": {"FilterString": "resourcetype:s3:bucket,dynamodb:table"}} + """) + .when() + .post("/ListResources") + .then() + .statusCode(200) + .body("Resources.size()", greaterThanOrEqualTo(2)) + .body("Resources.ResourceType", + everyItem(anyOf(equalTo("s3:bucket"), equalTo("dynamodb:table")))); + } + + @Test + void filterByRegionExact() { + given() + .header("Authorization", AUTH) + .contentType("application/json") + .body(""" + {"Filters": {"FilterString": "region:us-east-1"}} + """) + .when() + .post("/ListResources") + .then() + .statusCode(200) + .body("Resources.findAll { it.Region != 'us-east-1' }.size()", equalTo(0)); + } + + @Test + void filterByRegionWildcard() { + given() + .header("Authorization", AUTH) + .contentType("application/json") + .body(""" + {"Filters": {"FilterString": "region:us*"}} + """) + .when() + .post("/ListResources") + .then() + .statusCode(200) + .body("Resources.size()", greaterThan(0)) + .body("Resources.findAll { !it.Region.startsWith('us') }.size()", equalTo(0)); + } + + @Test + void negatedFilterExcludesCorrectly() { + // All three queries must use the same page size and the same universe. ListResources + // defaults to a 100-result page and the shared emulator holds far more than that, so an + // unspecified MaxResults would truncate the counts inconsistently; and the universe has + // to stay inside one 1000-result page, or the total is capped while the parts are not + // and the arithmetic breaks. + int s3Count = given() + .header("Authorization", AUTH) + .contentType("application/json") + .body("{\"MaxResults\": 1000, \"Filters\": {\"FilterString\": \"service:s3\"}}") + .when() + .post("/ListResources") + .then() + .extract().path("Resources.size()"); + + int total = given() + .header("Authorization", AUTH) + .contentType("application/json") + .body("{\"MaxResults\": 1000, \"Filters\": {\"FilterString\": \"" + BOUNDED_SCOPE + "\"}}") + .when() + .post("/ListResources") + .then() + .extract().path("Resources.size()"); + + given() + .header("Authorization", AUTH) + .contentType("application/json") + .body("{\"MaxResults\": 1000, \"Filters\": {\"FilterString\": \"" + + BOUNDED_SCOPE + " -service:s3\"}}") + .when() + .post("/ListResources") + .then() + .statusCode(200) + .body("Resources.size()", equalTo(total - s3Count)) + .body("Resources.findAll { it.Service == 's3' }.size()", equalTo(0)); + } + + @Test + void combinedFiltersAreAnded() { + given() + .header("Authorization", AUTH) + .contentType("application/json") + .body(""" + {"Filters": {"FilterString": "service:s3 region:us-east-1"}} + """) + .when() + .post("/ListResources") + .then() + .statusCode(200) + .body("Resources.findAll { it.Service != 's3' }.size()", equalTo(0)) + .body("Resources.findAll { it.Region != 'us-east-1' }.size()", equalTo(0)); + } + + @Test + void accountIdFilterMatchesCorrectAccount() { + given() + .header("Authorization", AUTH) + .contentType("application/json") + .body(""" + {"Filters": {"FilterString": "accountid:000000000000"}} + """) + .when() + .post("/ListResources") + .then() + .statusCode(200) + .body("Resources.size()", greaterThan(0)) + .body("Resources.findAll { it.OwningAccountId != '000000000000' }.size()", equalTo(0)); + } + + @Test + void idFilterMatchesExactArn() { + String arn = given() + .header("Authorization", AUTH) + .contentType("application/json") + .body("{\"MaxResults\": 1}") + .when() + .post("/ListResources") + .then() + .extract().path("Resources[0].Arn"); + + given() + .header("Authorization", AUTH) + .contentType("application/json") + .body("{\"Filters\": {\"FilterString\": \"id:" + arn + "\"}}") + .when() + .post("/ListResources") + .then() + .statusCode(200) + .body("Resources.size()", equalTo(1)) + .body("Resources[0].Arn", equalTo(arn)); + } + + @Test + void searchFreeFormTextNarrowsResults() { + // AWS Search treats free-form text as a narrowing filter: resources whose + // attributes don't match the keyword are excluded. A keyword that matches + // nothing must therefore return zero resources — not the full set. + given() + .header("Authorization", AUTH) + .contentType("application/json") + .body("{\"QueryString\": \"\", \"MaxResults\": 1000}") + .when() + .post("/Search") + .then() + .body("Resources.size()", greaterThan(0)); + + given() + .header("Authorization", AUTH) + .contentType("application/json") + .body("{\"QueryString\": \"xyznonexistent\", \"MaxResults\": 1000}") + .when() + .post("/Search") + .then() + .statusCode(200) + .body("Resources.size()", equalTo(0)) + .body("Count.TotalResources", equalTo(0)); + } + } + + @Nested + class AwsApiFidelity { + + private static String authFor(String region) { + return "AWS4-HMAC-SHA256 Credential=test/20260528/" + region + "/resource-explorer-2/aws4_request"; + } + + @Test + void listResourcesWithNoDefaultViewInRegionReturns401() { + // Only the startup region (us-east-1) has an auto-provisioned default view. + // A region that never had a default view must return UnauthorizedException (401), + // not ResourceNotFoundException (404). + given() + .header("Authorization", authFor("eu-central-1")) + .contentType("application/json") + .body("{}") + .when() + .post("/ListResources") + .then() + .statusCode(401) + .body("__type", equalTo("UnauthorizedException")); + } + + @Test + void searchWithNoDefaultViewInRegionReturns401() { + given() + .header("Authorization", authFor("eu-central-1")) + .contentType("application/json") + .body("{\"QueryString\": \"\"}") + .when() + .post("/Search") + .then() + .statusCode(401) + .body("__type", equalTo("UnauthorizedException")); + } + + @Test + void createViewWithDuplicateNameReturnsConflict() { + trackView(given() + .header("Authorization", AUTH) + .contentType("application/json") + .body("{\"ViewName\": \"fidelity-dup-view\"}") + .when() + .post("/CreateView") + .then() + .statusCode(200) + .extract().path("View.ViewArn")); + + given() + .header("Authorization", AUTH) + .contentType("application/json") + .body("{\"ViewName\": \"fidelity-dup-view\"}") + .when() + .post("/CreateView") + .then() + .statusCode(409) + .body("__type", equalTo("ConflictException")); + } + + @Test + void createViewWithInvalidNameReturnsValidation() { + given() + .header("Authorization", AUTH) + .contentType("application/json") + .body("{\"ViewName\": \"bad name with spaces!\"}") + .when() + .post("/CreateView") + .then() + .statusCode(400) + .body("__type", equalTo("ValidationException")); + } + + @Test + void createViewWithoutNameReturnsValidation() { + given() + .header("Authorization", AUTH) + .contentType("application/json") + .body("{\"Filters\": {\"FilterString\": \"service:s3\"}}") + .when() + .post("/CreateView") + .then() + .statusCode(400) + .body("__type", equalTo("ValidationException")); + } + + @Test + void createViewWithInvalidIncludedPropertyReturnsValidation() { + given() + .header("Authorization", AUTH) + .contentType("application/json") + .body(""" + {"ViewName": "fidelity-bad-prop-view", + "IncludedProperties": [{"Name": "notavalidproperty"}]} + """) + .when() + .post("/CreateView") + .then() + .statusCode(400) + .body("__type", equalTo("ValidationException")); + } + + @Test + void associateDefaultViewCrossRegionReturnsValidation() { + // A view lives in one region; making it the default for a different region is rejected + // by AWS with a ValidationException (default views are scoped per region). + String euViewArn = trackView(given() + .header("Authorization", authFor("eu-central-1")) + .contentType("application/json") + .body("{\"ViewName\": \"fidelity-crossregion-view\"}") + .when() + .post("/CreateView") + .then() + .statusCode(200) + .extract().path("View.ViewArn")); + + given() + .header("Authorization", AUTH) + .contentType("application/json") + .body("{\"ViewArn\": \"" + euViewArn + "\"}") + .when() + .post("/AssociateDefaultView") + .then() + .statusCode(400) + .body("__type", equalTo("ValidationException")); + } + + @Test + void promotingSecondIndexToAggregatorReturnsConflict() { + // us-east-1 has the auto-provisioned AGGREGATOR. A LOCAL index promoted in + // another region must fail with ConflictException — only one aggregator per account. + String arn = trackIndex(authFor("ap-southeast-2"), given() + .header("Authorization", authFor("ap-southeast-2")) + .contentType("application/json") + .body("{}") + .when() + .post("/CreateIndex") + .then() + .statusCode(200) + .extract().path("Arn")); + + given() + .header("Authorization", authFor("ap-southeast-2")) + .contentType("application/json") + .body("{\"Arn\": \"" + arn + "\", \"Type\": \"AGGREGATOR\"}") + .when() + .post("/UpdateIndexType") + .then() + .statusCode(409) + .body("__type", equalTo("ConflictException")); + } + + @Test + void searchWithoutQueryStringReturnsValidation() { + given() + .header("Authorization", AUTH) + .contentType("application/json") + .body("{}") + .when() + .post("/Search") + .then() + .statusCode(400) + .body("__type", equalTo("ValidationException")); + } + + @Test + void maxResultsAboveLimitReturnsValidation() { + given() + .header("Authorization", AUTH) + .contentType("application/json") + .body("{\"MaxResults\": 1001}") + .when() + .post("/ListResources") + .then() + .statusCode(400) + .body("__type", equalTo("ValidationException")); + } + + @Test + void maxResultsZeroReturnsValidation() { + given() + .header("Authorization", AUTH) + .contentType("application/json") + .body("{\"MaxResults\": 0}") + .when() + .post("/ListResources") + .then() + .statusCode(400) + .body("__type", equalTo("ValidationException")); + } + + @Test + void staleNextTokenBeyondResultSetReturnsEmptyPageNot500() { + // Base64("999999") — an offset far past any live result set. The result set is + // queried live and can shrink between paginated calls, so this must not 500. + given() + .header("Authorization", AUTH) + .contentType("application/json") + .body("{\"NextToken\": \"OTk5OTk5\"}") + .when() + .post("/ListResources") + .then() + .statusCode(200) + .body("Resources.size()", equalTo(0)); + } + + @Test + void createIndexReturns200WithCreatingState() { + // AWS botocore service-2.json: CreateIndex responseCode = 200. + trackIndex(authFor("ca-central-1"), given() + .header("Authorization", authFor("ca-central-1")) + .contentType("application/json") + .body("{}") + .when() + .post("/CreateIndex") + .then() + .statusCode(200) + .body("Arn", notNullValue()) + .body("State", equalTo("CREATING")) + .body("CreatedAt", notNullValue()) + .extract().path("Arn")); + } + + @Test + void createViewResponseViewNodeHasNoTagsField() { + // AWS SDK View shape does NOT include Tags — Tags is only on GetViewResponse top-level. + trackView(given() + .header("Authorization", AUTH) + .contentType("application/json") + .body("{\"ViewName\": \"fidelity-notags-view\", \"Tags\": {\"owner\": \"team-a\"}}") + .when() + .post("/CreateView") + .then() + .statusCode(200) + .body("View", notNullValue()) + .body("View.Tags", nullValue()) + .extract().path("View.ViewArn")); + } + + @Test + void getViewHasTopLevelTagsButViewNodeHasNone() { + // GetView response: top-level "Tags" present, but "View.Tags" absent. + String viewArn = trackView(given() + .header("Authorization", AUTH) + .contentType("application/json") + .body("{\"ViewName\": \"fidelity-topleveltags-view\", \"Tags\": {\"env\": \"prod\"}}") + .when() + .post("/CreateView") + .then() + .statusCode(200) + .extract().path("View.ViewArn")); + + given() + .header("Authorization", AUTH) + .contentType("application/json") + .body("{\"ViewArn\": \"" + viewArn + "\"}") + .when() + .post("/GetView") + .then() + .statusCode(200) + .body("Tags", notNullValue()) + .body("View.Tags", nullValue()); + } + } + + private static String authFor(String region) { + return "AWS4-HMAC-SHA256 Credential=test/20260528/" + region + "/resource-explorer-2/aws4_request"; + } + + /** Creates the index a non-default Region needs before it can hold views. */ + private String createIndexIn(String region) { + return trackIndex(authFor(region), given() + .header("Authorization", authFor(region)) + .contentType("application/json") + .body("{}") + .when() + .post("/CreateIndex") + .then() + .statusCode(200) + .extract().path("Arn")); + } + + @Nested + class ViewRegionScoping { + + @Test + void listViewsReturnsOnlyTheCallingRegionsViews() { + createIndexIn("eu-central-1"); + String remoteView = trackView(given() + .header("Authorization", authFor("eu-central-1")) + .contentType("application/json") + .body("{\"ViewName\": \"scoping-eu-view\"}") + .when() + .post("/CreateView") + .then() + .statusCode(200) + .extract().path("View.ViewArn")); + + given() + .header("Authorization", authFor("eu-central-1")) + .contentType("application/json") + .when() + .post("/ListViews") + .then() + .statusCode(200) + .body("Views", hasItem(remoteView)); + + given() + .header("Authorization", AUTH) + .contentType("application/json") + .when() + .post("/ListViews") + .then() + .statusCode(200) + .body("Views", not(hasItem(remoteView))); + } + } + + @Nested + class MaxResultsCeilings { + + @Test + void listSupportedResourceTypesAcceptsUpToOneThousand() { + given() + .header("Authorization", AUTH) + .contentType("application/json") + .body("{\"MaxResults\": 500}") + .when() + .post("/ListSupportedResourceTypes") + .then() + .statusCode(200) + .body("ResourceTypes", notNullValue()); + } + + @Test + void listViewsRejectsAPageLargerThanFifty() { + given() + .header("Authorization", AUTH) + .contentType("application/json") + .body("{\"MaxResults\": 51}") + .when() + .post("/ListViews") + .then() + .statusCode(400) + .body("__type", containsString("ValidationException")); + + given() + .header("Authorization", AUTH) + .contentType("application/json") + .body("{\"MaxResults\": 50}") + .when() + .post("/ListViews") + .then() + .statusCode(200); + } + + @Test + void listIndexesRejectsAPageLargerThanOneHundred() { + given() + .header("Authorization", AUTH) + .contentType("application/json") + .body("{\"MaxResults\": 101}") + .when() + .post("/ListIndexes") + .then() + .statusCode(400); + } + } + + @Nested + class TagFiltersRequireTagData { + + private String viewWithoutTags() { + return trackView(given() + .header("Authorization", AUTH) + .contentType("application/json") + .body("{\"ViewName\": \"no-tag-data-view\", \"IncludedProperties\": []}") + .when() + .post("/CreateView") + .then() + .statusCode(200) + .extract().path("View.ViewArn")); + } + + @Test + void searchWithATagFilterAgainstAViewWithoutTagsIsRejected() { + String viewArn = viewWithoutTags(); + given() + .header("Authorization", AUTH) + .contentType("application/json") + .body("{\"QueryString\": \"tag:env=test\", \"ViewArn\": \"" + viewArn + "\"}") + .when() + .post("/Search") + .then() + .statusCode(400) + .body("__type", containsString("ValidationException")); + } + + @Test + void aNonTagFilterAgainstTheSameViewStillWorks() { + String viewArn = viewWithoutTags(); + given() + .header("Authorization", AUTH) + .contentType("application/json") + .body("{\"Filters\": {\"FilterString\": \"service:s3\"}, \"ViewArn\": \"" + viewArn + "\"}") + .when() + .post("/ListResources") + .then() + .statusCode(200); + } + } + + @Nested + class QuerySemantics { + + @Test + void freeFormKeywordsAreOredNotAnded() { + // "s3" and "dynamodb" share no resource, so an AND reading would return nothing. + given() + .header("Authorization", AUTH) + .contentType("application/json") + .body("{\"QueryString\": \"s3 dynamodb\"}") + .when() + .post("/Search") + .then() + .statusCode(200) + .body("Resources.ResourceType", hasItems("s3:bucket", "dynamodb:table")); + } + + @Test + void supportsTagsFilterMatchesTaggableTypes() { + given() + .header("Authorization", AUTH) + .contentType("application/json") + .body("{\"Filters\": {\"FilterString\": \"resourcetype.supports:tags service:s3\"}}") + .when() + .post("/ListResources") + .then() + .statusCode(200) + .body("Resources.size()", greaterThan(0)); + } + } + + @Nested + class Ec2Resources { + + @Test + void vpcsAreDiscoverable() { + given() + .header("Authorization", "AWS4-HMAC-SHA256 Credential=test/20260528/us-east-1/ec2/aws4_request") + .contentType("application/x-www-form-urlencoded") + .formParam("Action", "CreateVpc") + .formParam("CidrBlock", "10.42.0.0/16") + .formParam("Version", "2016-11-15") + .when() + .post("/") + .then() + .statusCode(200); + + given() + .header("Authorization", AUTH) + .contentType("application/json") + .body("{\"Filters\": {\"FilterString\": \"resourcetype:ec2:vpc\"}}") + .when() + .post("/ListResources") + .then() + .statusCode(200) + .body("Resources.size()", greaterThan(0)) + .body("Resources[0].Service", equalTo("ec2")); + } + } + + @Nested + class AwsOwnedResources { + + @Test + void managedAndServiceViewsAreEmpty() { + given() + .header("Authorization", AUTH) + .contentType("application/json") + .body("{}") + .when() + .post("/ListManagedViews") + .then() + .statusCode(200) + .body("ManagedViews.size()", equalTo(0)); + + given() + .header("Authorization", AUTH) + .contentType("application/json") + .body("{}") + .when() + .post("/ListServiceViews") + .then() + .statusCode(200) + .body("ServiceViews.size()", equalTo(0)); + + given() + .header("Authorization", AUTH) + .contentType("application/json") + .body("{}") + .when() + .post("/ListStreamingAccessForServices") + .then() + .statusCode(200) + .body("StreamingAccessForServices.size()", equalTo(0)); + } + + @Test + void getManagedViewReportsNotFound() { + given() + .header("Authorization", AUTH) + .contentType("application/json") + .body("{\"ManagedViewArn\": \"arn:aws:resource-explorer-2:us-east-1:000000000000:managed-view/x/1\"}") + .when() + .post("/GetManagedView") + .then() + .statusCode(404) + .body("__type", containsString("ResourceNotFoundException")); + } + + @Test + void accountLevelServiceConfigurationReportsNoOrganization() { + given() + .header("Authorization", AUTH) + .contentType("application/json") + .when() + .post("/GetAccountLevelServiceConfiguration") + .then() + .statusCode(200) + .body("OrgConfiguration.AWSServiceAccessStatus", equalTo("DISABLED")); + } + + @Test + void serviceIndexMirrorsTheRegionsIndex() { + String indexArn = given() + .header("Authorization", AUTH) + .contentType("application/json") + .when() + .post("/GetIndex") + .then() + .statusCode(200) + .extract().path("Arn"); + + given() + .header("Authorization", AUTH) + .contentType("application/json") + .when() + .post("/GetServiceIndex") + .then() + .statusCode(200) + .body("Arn", equalTo(indexArn)) + .body("Type", notNullValue()); + + given() + .header("Authorization", AUTH) + .contentType("application/json") + .body("{}") + .when() + .post("/ListServiceIndexes") + .then() + .statusCode(200) + .body("Indexes.Arn", hasItem(indexArn)); + } + + @Test + void memberIndexesAreReturnedOnlyForThisAccount() { + given() + .header("Authorization", AUTH) + .contentType("application/json") + .body("{\"AccountIdList\": [\"000000000000\"]}") + .when() + .post("/ListIndexesForMembers") + .then() + .statusCode(200) + .body("Indexes.size()", greaterThan(0)) + .body("Indexes[0].AccountId", equalTo("000000000000")); + + given() + .header("Authorization", AUTH) + .contentType("application/json") + .body("{\"AccountIdList\": [\"111122223333\"]}") + .when() + .post("/ListIndexesForMembers") + .then() + .statusCode(200) + .body("Indexes.size()", equalTo(0)); + } + } + + @Nested + class MultiRegionSetup { + + @Test + void createThenDeleteSetupInOneRegion() { + String taskId = given() + .header("Authorization", AUTH) + .contentType("application/json") + .body("{\"RegionList\": [\"ap-south-1\"], \"ViewName\": \"setup-view\"}") + .when() + .post("/CreateResourceExplorerSetup") + .then() + .statusCode(200) + .extract().path("TaskId"); + + given() + .header("Authorization", AUTH) + .contentType("application/json") + .body("{\"TaskId\": \"" + taskId + "\"}") + .when() + .post("/GetResourceExplorerSetup") + .then() + .statusCode(200) + .body("Regions[0].Region", equalTo("ap-south-1")) + .body("Regions[0].Index.Status", equalTo("SUCCEEDED")) + .body("Regions[0].Index.Index.Region", equalTo("ap-south-1")) + .body("Regions[0].View.Status", equalTo("SUCCEEDED")) + .body("Regions[0].View.View.ViewArn", containsString("setup-view")); + + String deleteTaskId = given() + .header("Authorization", AUTH) + .contentType("application/json") + .body("{\"RegionList\": [\"ap-south-1\"]}") + .when() + .post("/DeleteResourceExplorerSetup") + .then() + .statusCode(200) + .extract().path("TaskId"); + + given() + .header("Authorization", AUTH) + .contentType("application/json") + .body("{\"TaskId\": \"" + deleteTaskId + "\"}") + .when() + .post("/GetResourceExplorerSetup") + .then() + .statusCode(200) + .body("Regions[0].Index.Status", equalTo("SUCCEEDED")); + + given() + .header("Authorization", authFor("ap-south-1")) + .contentType("application/json") + .when() + .post("/GetIndex") + .then() + .statusCode(404); + } + + @Test + void regionListAndDeleteInAllRegionsAreMutuallyExclusive() { + given() + .header("Authorization", AUTH) + .contentType("application/json") + .body("{\"DeleteInAllRegions\": true, \"RegionList\": [\"us-east-1\"]}") + .when() + .post("/DeleteResourceExplorerSetup") + .then() + .statusCode(400) + .body("__type", containsString("ValidationException")); + } + + @Test + void anAggregatorRegionOutsideTheRegionListIsRejected() { + given() + .header("Authorization", AUTH) + .contentType("application/json") + .body(""" + {"RegionList": ["ap-northeast-1"], "ViewName": "setup-view", + "AggregatorRegions": ["sa-east-1"]} + """) + .when() + .post("/CreateResourceExplorerSetup") + .then() + .statusCode(400) + .body("__type", containsString("ValidationException")); + } + + @Test + void getResourceExplorerSetupReportsAnUnknownTask() { + given() + .header("Authorization", AUTH) + .contentType("application/json") + .body("{\"TaskId\": \"00000000-0000-0000-0000-000000000000\"}") + .when() + .post("/GetResourceExplorerSetup") + .then() + .statusCode(404); + } + } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/resourceexplorer2/ResourceExplorer2ListVsSearchCapTest.java b/src/test/java/io/github/hectorvent/floci/services/resourceexplorer2/ResourceExplorer2ListVsSearchCapTest.java new file mode 100644 index 0000000000..fb17f2b89e --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/resourceexplorer2/ResourceExplorer2ListVsSearchCapTest.java @@ -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 indexStore = new InMemoryStorage<>(); + private final StorageBackend viewStore = new InMemoryStorage<>(); + private final StorageBackend 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 getResources() { + List 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 getSupportedResourceTypes() { + return Set.of(new SupportedResourceType("test:thing", "test", true)); + } + }; + @SuppressWarnings("unchecked") + Instance 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 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 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 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 getSupportedResourceTypes() { + return Set.of(new SupportedResourceType("test:thing", "test", true)); + } + }; + ResourceProvider broken = new ResourceProvider() { + @Override + public List getResources() { + throw new IllegalStateException("provider is broken"); + } + + @Override + public Set getSupportedResourceTypes() { + return Set.of(); + } + }; + @SuppressWarnings("unchecked") + Instance 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()); + } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/resourceexplorer2/ResourceExplorer2PaginationOrderingTest.java b/src/test/java/io/github/hectorvent/floci/services/resourceexplorer2/ResourceExplorer2PaginationOrderingTest.java new file mode 100644 index 0000000000..b48a3c0dbc --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/resourceexplorer2/ResourceExplorer2PaginationOrderingTest.java @@ -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} 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. + * + *

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 indexStore = new InMemoryStorage<>(); + private final StorageBackend viewStore = new InMemoryStorage<>(); + private final StorageBackend 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 arns = new ArrayList<>(); + private final Random random = new Random(42); + + void add(String resourceArn) { + arns.add(resourceArn); + } + + @Override + public List getResources() { + List order = new ArrayList<>(arns); + Collections.shuffle(order, random); + List 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 getSupportedResourceTypes() { + return Set.of(new SupportedResourceType("test:thing", "test", true)); + } + } + + private ResourceExplorer2Service newServiceWith(ResourceProvider provider) { + @SuppressWarnings("unchecked") + Instance 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 arnsOf(ObjectNode response) { + List 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 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 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 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 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 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 getResources() { + return List.of(); + } + + @Override + public Set getSupportedResourceTypes() { + return Set.of(new SupportedResourceType(type, "test", true)); + } + }); + } + List shuffleSource = new ArrayList<>(providers); + Random random = new Random(7); + @SuppressWarnings("unchecked") + Instance 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 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 expected = new ArrayList<>(); + for (int i = 0; i < 12; i++) { + expected.add(String.format("test:type%02d", i)); + } + assertEquals(expected, seen); + } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/resourceexplorer2/ResourceExplorer2PaginationTest.java b/src/test/java/io/github/hectorvent/floci/services/resourceexplorer2/ResourceExplorer2PaginationTest.java new file mode 100644 index 0000000000..d7f93ed9a2 --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/resourceexplorer2/ResourceExplorer2PaginationTest.java @@ -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)); + } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/resourceexplorer2/query/QueryParserTest.java b/src/test/java/io/github/hectorvent/floci/services/resourceexplorer2/query/QueryParserTest.java new file mode 100644 index 0000000000..5574164eb5 --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/resourceexplorer2/query/QueryParserTest.java @@ -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()); + } + } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/resourceexplorer2/query/ResourceFilterTest.java b/src/test/java/io/github/hectorvent/floci/services/resourceexplorer2/query/ResourceFilterTest.java new file mode 100644 index 0000000000..3e3a1935d6 --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/resourceexplorer2/query/ResourceFilterTest.java @@ -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 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 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)); + } + } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/rum/RumResourceProviderTest.java b/src/test/java/io/github/hectorvent/floci/services/rum/RumResourceProviderTest.java new file mode 100644 index 0000000000..97e377f138 --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/rum/RumResourceProviderTest.java @@ -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 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 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 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")); + } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/rum/RumServiceTest.java b/src/test/java/io/github/hectorvent/floci/services/rum/RumServiceTest.java index c83a6808c8..3e4476772f 100644 --- a/src/test/java/io/github/hectorvent/floci/services/rum/RumServiceTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/rum/RumServiceTest.java @@ -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>() { }); 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>() { }); 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()); diff --git a/src/test/resources/application.yml b/src/test/resources/application.yml index e33dd7e230..928c3bf589 100644 --- a/src/test/resources/application.yml +++ b/src/test/resources/application.yml @@ -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: [] diff --git a/tools/docs/service_matrix.yaml b/tools/docs/service_matrix.yaml index ea6c51190b..1b191467e9 100644 --- a/tools/docs/service_matrix.yaml +++ b/tools/docs/service_matrix.yaml @@ -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 diff --git a/tools/docs/services.yaml b/tools/docs/services.yaml index dae9b815b8..19eef28e61 100644 --- a/tools/docs/services.yaml +++ b/tools/docs/services.yaml @@ -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: