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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Wire-level corrections:

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

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

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

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

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

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

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

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

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

* chore: drop the stray local-dev Dockerfile

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

* fix(resourceexplorer2): order paginated results before slicing

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

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

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

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

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

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

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

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

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

---------

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

No files matched your search

@@ -268,6 +268,7 @@ public interface EmulatorConfig {
BackupStorageConfig backup();
FisStorageConfig fis();
CloudFrontStorageConfig cloudfront();
ResourceExplorer2StorageConfig resourceexplorer2();
AppSyncStorageConfig appsync();
BatchStorageConfig batch();
LightsailStorageConfig lightsail();
@@ -417,6 +418,13 @@ public interface EmulatorConfig {
Optional<String> mode();
}
interface ResourceExplorer2StorageConfig {
Optional<String> mode();
@WithDefault("5000")
long flushIntervalMs();
}
interface AppSyncStorageConfig {
Optional<String> mode();
@@ -632,6 +640,7 @@ public interface EmulatorConfig {
ConfigServiceConfig configservice();
CloudTrailServiceConfig cloudtrail();
CloudControlServiceConfig cloudcontrol();
ResourceExplorer2ServiceConfig resourceexplorer2();
CloudFrontServiceConfig cloudfront();
AppSyncServiceConfig appsync();
BatchServiceConfig batch();
@@ -765,6 +774,11 @@ public interface EmulatorConfig {
int flushIntervalSeconds();
}
interface ResourceExplorer2ServiceConfig {
@WithDefault("true")
boolean enabled();
}
interface AutoScalingServiceConfig {
@WithDefault("true")
boolean enabled();
@@ -289,8 +289,8 @@ public class AwsQueryController {
case "sns" -> snsQueryHandler.handle(action, formParams, region);
case "iam" -> iamQueryHandler.handle(action, formParams, authorization);
case "sts" -> stsQueryHandler.handle(action, formParams);
case "elasticache" -> elastiCacheQueryHandler.handle(action, formParams);
case "rds" -> {
case "elasticache" -> elastiCacheQueryHandler.handle(action, formParams, region);
case "rds" -> {
// Neptune signs requests with "rds" credential scope (same wire protocol).
// Route to Neptune when Engine=neptune (create ops) or when the cluster/instance
// already exists in Neptune storage (describe/modify/delete ops).
@@ -118,6 +118,10 @@ public class RegionResolver {
return defaultRegion;
}
public String getDefaultAccountId() {
return defaultAccountId;
}
/**
* Returns the region for the current request when called from a request context,
* or the configured default region otherwise (async workers, startup, tests).
@@ -3,6 +3,7 @@ package io.github.hectorvent.floci.core.common;
import io.github.hectorvent.floci.config.EmulatorConfig;
import io.github.hectorvent.floci.services.appconfig.AppConfigController;
import io.github.hectorvent.floci.services.backup.BackupController;
import io.github.hectorvent.floci.services.resourceexplorer2.ResourceExplorer2Controller;
import io.github.hectorvent.floci.services.appconfig.AppConfigDataController;
import io.github.hectorvent.floci.services.batch.BatchController;
import io.github.hectorvent.floci.services.bedrockruntime.BedrockRuntimeController;
@@ -397,6 +398,15 @@ public class ResolvedServiceCatalog {
config.storage().services().backup().flushIntervalMs(), null, ServiceProtocol.REST_JSON,
protocols(ServiceProtocol.REST_JSON),
Set.of(), Set.of("backup"), Set.of(), Set.of(BackupController.class)),
descriptor("resource-explorer-2", "resourceexplorer2",
config.services().resourceexplorer2().enabled(), true,
"resourceexplorer2",
storageMode(config.storage().services().resourceexplorer2().mode(), config.storage().mode()),
config.storage().services().resourceexplorer2().flushIntervalMs(),
null, ServiceProtocol.REST_JSON,
protocols(ServiceProtocol.REST_JSON),
Set.of(), Set.of("resource-explorer-2"), Set.of(),
Set.of(ResourceExplorer2Controller.class)),
descriptor("fis", "fis", config.services().fis().enabled(), true,
"fis", storageMode(config.storage().services().fis().mode(), config.storage().mode()),
config.storage().services().fis().flushIntervalMs(), null, ServiceProtocol.REST_JSON,
@@ -9,14 +9,14 @@ import java.util.regex.Pattern;
* Extracts the SigV4 signing service name from an Authorization header's
* credential scope ({@code Credential=<key>/<date>/<region>/<service>/aws4_request}).
*/
final class SigV4CredentialScope {
public final class SigV4CredentialScope {
private static final Pattern SERVICE_PATTERN = Pattern.compile("Credential=\\S+/\\d{8}/[^/]+/([^/]+)/");
private SigV4CredentialScope() {
}
static Optional<String> serviceName(String authorization) {
public static Optional<String> serviceName(String authorization) {
if (authorization == null) {
return Optional.empty();
}
@@ -0,0 +1,54 @@
package io.github.hectorvent.floci.core.resource;
import io.quarkus.runtime.annotations.RegisterForReflection;
import java.time.Instant;
import java.util.Map;
/**
* A single resource made visible to Resource Explorer 2.
* <p>
* One instance describes one AWS resource (a certificate, a queue, a cluster, etc.)
*
* <p>The fields are what the query language filters and keywords match against, so they
* must be populated with real, consistent values for search to work. Filterable attributes:
* {@code resourcetype:}, {@code service:}, {@code region:}, {@code accountid:}, {@code id:} (the
* ARN), and the tag attributes ({@code tag:}, {@code tag.key:}, {@code tag.value:},
* {@code application:} — the last reads the {@code awsApplication} tag). A bare keyword matches a
* case-insensitive substring of {@link #arn}, {@link #resourceType}, {@link #service}, or
* {@link #region}. See {@code ResourceFilter} for the exact matching rules.
*
* @param arn full ARN of the resource, e.g.
* {@code arn:aws:acm:us-east-1:123456789012:certificate/abc}. Doubles as the
* resource's unique id ({@code id:} filter) and is matched by keyword search.
* @param resourceType Resource Explorer's type identifier in {@code service:subtype} form, e.g.
* {@code acm:certificate}, {@code kafka:cluster}, {@code iam:user}. Must be
* identical to the {@link SupportedResourceType#resourceType()} the provider
* advertises for this resource, and unique across all providers.
* @param service AWS service namespace — the service segment of the ARN, e.g. {@code acm},
* {@code kafka}, {@code cognito-idp}. This is the prefix of
* {@link #resourceType}, not necessarily the floci module name.
* @param region AWS region the resource lives in, e.g. {@code us-east-1}; usually
* {@code AwsArnUtils.parse(arn).region()}.
* @param owningAccountId 12-digit account id that owns the resource; usually
* {@code AwsArnUtils.parse(arn).accountId()}.
* @param lastReportedAt when Resource Explorer last observed the resource. floci has no scan
* pipeline, so providers pass the resource's creation timestamp (falling back
* to {@code Instant.now()} when unknown).
* @param tags resource tags as key→value; drives the tag filters and is emitted as the
* {@code tags} property. Never {@code null} — pass {@code Map.of()} when the
* resource has no tags.
* @see SupportedResourceType
* @see <a href="https://docs.aws.amazon.com/resource-explorer/latest/apireference/API_Resource.html">AWS API: Resource</a>
* @see <a href="https://docs.aws.amazon.com/resource-explorer/latest/userguide/using-search-query-syntax.html">Resource Explorer search query syntax</a>
*/
@RegisterForReflection
public record ExplorerResource(
String arn,
String resourceType,
String service,
String region,
String owningAccountId,
Instant lastReportedAt,
Map<String, String> tags
) {}
@@ -0,0 +1,63 @@
package io.github.hectorvent.floci.core.resource;
import java.util.List;
import java.util.Set;
/**
* Extension point that lets an individual AWS service emulator expose its resources to the Resource
* Explorer 2 emulator. Implement this on a service that owns resources you want to be discoverable
* via {@code Search}, {@code ListResources}, and {@code ListSupportedResourceTypes}.
* <p>
* Implementations must be CDI beans (usually {@code @ApplicationScoped} service classes).
* {@code ResourceExplorer2Service} iterates {@code ResourceProvider}s:
* <ul>
* <li>{@code Search} / {@code ListResources} concatenate {@link #getResources()} from all
* providers, apply the query filter, then paginate. {@code Search} returns at most the first
* 1000 matches; {@code ListResources} has no such cap and pages through every match, but omits
* its {@code NextToken} when {@code MaxResults} is 1000. floci mirrors both behaviors.</li>
* <li>{@code ListSupportedResourceTypes} concatenates {@link #getSupportedResourceTypes()} from
* all providers and deduplicates by {@link SupportedResourceType#resourceType()}.</li>
* </ul>
*
* <h2>Implementing</h2>
* <ol>
* <li>{@link #getResources()}: scan your storage backend and map each stored entity to an
* {@link ExplorerResource}.</li>
* <li>{@link #getSupportedResourceTypes()}: return one {@link SupportedResourceType} per distinct
* {@code resourceType} string you emit.</li>
* <li>Keep the {@code resourceType} string identical between the two methods — a resource whose
* type is not advertised will still be searchable, but callers listing supported types would
* not see it, which is inconsistent with AWS.</li>
* </ol>
*
* <p>See {@code AcmService}, {@code MskService}, or {@code IamService} (which exposes two types)
* for reference implementations.
*
* @see ExplorerResource
* @see SupportedResourceType
* @see <a href="https://docs.aws.amazon.com/resource-explorer/latest/userguide/getting-started-terms-and-concepts.html">Resource Explorer terms and concepts</a>
* @see <a href="https://docs.aws.amazon.com/resource-explorer/latest/apireference/API_Search.html">AWS API: Search</a>
*/
public interface ResourceProvider {
/**
* All resources this service currently own.
* <p>
* Build the list from live storage rather
* than caching. Return an empty list when the service holds nothing; never return {@code null}.
* Ordering is not significant — Resource Explorer sorts by ARN before paginating, so an
* unordered store scan is safe to return as-is.
*/
List<ExplorerResource> getResources();
/**
* The resource types this provider can produce.
* <p>
* One entry per distinct
* {@link ExplorerResource#resourceType()} value returned by {@link #getResources()}.
* The set is fixed for a given service, so returning a
* literal {@code Set.of(...)} is the norm. Each {@code resourceType} must be globally unique
* across providers.
*/
Set<SupportedResourceType> getSupportedResourceTypes();
}
@@ -0,0 +1,33 @@
package io.github.hectorvent.floci.core.resource;
import io.quarkus.runtime.annotations.RegisterForReflection;
/**
* One resource type a {@link ResourceProvider} can produce.
* <p>
* This is the type-level counterpart to {@link ExplorerResource}
* (which is an instance): a provider returns one of these per distinct
* {@link ExplorerResource#resourceType()} value it emits.
*
* <p>The Resource Explorer 2 service collects these from every provider, deduplicates by {@link #resourceType}.
*
* @param resourceType type identifier in {@code service:subtype} form, e.g. {@code acm:certificate},
* {@code kafka:cluster}, {@code iam:user}. Must exactly match the
* {@link ExplorerResource#resourceType()} used for the corresponding resources,
* and be unique across all providers — the service uses this string as the
* deduplication key.
* @param service AWS service namespace, i.e. the segment before the colon in
* {@link #resourceType} (e.g. {@code acm}, {@code kafka}, {@code cognito-idp}).
* @param supportsTags whether this type carries tags. Advisory metadata describing the type; the
* Resource Explorer emulator currently treats every exposed type as taggable
* regardless (the {@code resourcetype:supports=tags} filter is a pass-through),
* so set it truthfully but do not expect it to gate behavior today.
* @see ExplorerResource
* @see <a href="https://docs.aws.amazon.com/resource-explorer/latest/apireference/API_ListSupportedResourceTypes.html">AWS API: ListSupportedResourceTypes</a>
*/
@RegisterForReflection
public record SupportedResourceType(
String resourceType,
String service,
boolean supportsTags
) {}
@@ -4,6 +4,9 @@ import io.github.hectorvent.floci.config.EmulatorConfig;
import io.github.hectorvent.floci.core.common.AwsArnUtils;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.common.RegionResolver;
import io.github.hectorvent.floci.core.resource.ExplorerResource;
import io.github.hectorvent.floci.core.resource.ResourceProvider;
import io.github.hectorvent.floci.core.resource.SupportedResourceType;
import io.github.hectorvent.floci.core.storage.StorageBackend;
import io.github.hectorvent.floci.core.storage.StorageFactory;
import io.github.hectorvent.floci.services.acm.model.*;
@@ -35,7 +38,7 @@ import java.util.stream.Collectors;
* @see <a href="https://docs.aws.amazon.com/acm/latest/APIReference/Welcome.html">AWS ACM API Reference</a>
*/
@ApplicationScoped
public class AcmService {
public class AcmService implements ResourceProvider {
private static final Logger LOG = Logger.getLogger(AcmService.class);
private static final int MAX_TAGS = 50;
@@ -481,6 +484,29 @@ public class AcmService {
this.accountDaysBeforeExpiry.set(daysBeforeExpiry);
}
@Override
public List<ExplorerResource> getResources() {
List<ExplorerResource> resources = new ArrayList<>();
for (Certificate cert : store.scan(k -> true)) {
String arn = cert.getArn();
if (arn == null) {
continue;
}
AwsArnUtils.Arn parsed = AwsArnUtils.parse(arn);
resources.add(new ExplorerResource(
arn, "acm:certificate", "acm",
parsed.region(), parsed.accountId(),
cert.getCreatedAt() != null ? cert.getCreatedAt() : Instant.now(),
cert.getTags() != null ? cert.getTags() : Map.of()));
}
return resources;
}
@Override
public Set<SupportedResourceType> getSupportedResourceTypes() {
return Set.of(new SupportedResourceType("acm:certificate", "acm", true));
}
// ============ Helper Methods ============
private Certificate getCertificateByArn(String arn, String region) {
@@ -5,6 +5,9 @@ import io.github.hectorvent.floci.config.EmulatorConfig;
import io.github.hectorvent.floci.core.common.AwsArnUtils;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.common.RegionResolver;
import io.github.hectorvent.floci.core.resource.ExplorerResource;
import io.github.hectorvent.floci.core.resource.ResourceProvider;
import io.github.hectorvent.floci.core.resource.SupportedResourceType;
import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend;
import io.github.hectorvent.floci.core.storage.StorageBackend;
import io.github.hectorvent.floci.core.storage.StorageFactory;
@@ -20,17 +23,19 @@ import jakarta.inject.Inject;
import org.jboss.logging.Logger;
import java.security.SecureRandom;
import java.time.Instant;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
@ApplicationScoped
public class AmazonMqService {
public class AmazonMqService implements ResourceProvider {
private static final Logger LOG = Logger.getLogger(AmazonMqService.class);
private static final String ENGINE_RABBITMQ = "RABBITMQ";
@@ -154,6 +159,29 @@ public class AmazonMqService {
return storage.scan(k -> true);
}
@Override
public List<ExplorerResource> getResources() {
List<ExplorerResource> resources = new ArrayList<>();
for (Broker broker : storage.scan(k -> true)) {
String arn = broker.getBrokerArn();
if (arn == null) {
continue;
}
AwsArnUtils.Arn parsed = AwsArnUtils.parse(arn);
resources.add(new ExplorerResource(
arn, "mq:broker", "mq",
parsed.region(), parsed.accountId(),
broker.getCreated() != null ? broker.getCreated() : Instant.now(),
broker.getTags() != null ? broker.getTags() : Map.of()));
}
return resources;
}
@Override
public Set<SupportedResourceType> getSupportedResourceTypes() {
return Set.of(new SupportedResourceType("mq:broker", "mq", true));
}
public void deleteBroker(String brokerId) {
Broker broker = describeBroker(brokerId);
broker.setBrokerState(BrokerState.DELETION_IN_PROGRESS);
@@ -38,12 +38,19 @@ import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import io.github.hectorvent.floci.core.resource.ExplorerResource;
import io.github.hectorvent.floci.core.resource.ResourceProvider;
import io.github.hectorvent.floci.core.resource.SupportedResourceType;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
/**
* CloudFormation stack lifecycle management — Create, Update, Delete stacks via ChangeSets.
*/
@ApplicationScoped
public class CloudFormationService {
public class CloudFormationService implements ResourceProvider {
private static final Logger LOG = Logger.getLogger(CloudFormationService.class);
@@ -2063,4 +2070,29 @@ public class CloudFormationService {
private static String key(String stackName, String region) {
return region + ":" + stackName;
}
// ─── Resource Explorer 2 ───────────────────────────────────────────────────
@Override
public List<ExplorerResource> getResources() {
List<ExplorerResource> resources = new ArrayList<>();
for (Stack stack : stacks.values()) {
String arn = stack.getStackId();
if (arn == null) {
continue;
}
AwsArnUtils.Arn parsed = AwsArnUtils.parse(arn);
resources.add(new ExplorerResource(
arn, "cloudformation:stack", "cloudformation",
parsed.region(), parsed.accountId(),
stack.getCreationTime() != null ? stack.getCreationTime() : Instant.now(),
stack.getTags() != null ? stack.getTags() : Map.of()));
}
return resources;
}
@Override
public Set<SupportedResourceType> getSupportedResourceTypes() {
return Set.of(new SupportedResourceType("cloudformation:stack", "cloudformation", true));
}
}
@@ -29,9 +29,14 @@ import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicLong;
import java.util.function.LongSupplier;
import io.github.hectorvent.floci.core.resource.ExplorerResource;
import io.github.hectorvent.floci.core.resource.ResourceProvider;
import io.github.hectorvent.floci.core.resource.SupportedResourceType;
import java.time.Instant;
import java.util.Set;
@ApplicationScoped
public class CloudWatchLogsService {
public class CloudWatchLogsService implements ResourceProvider {
private static final Logger LOG = Logger.getLogger(CloudWatchLogsService.class);
@@ -967,4 +972,39 @@ public class CloudWatchLogsService {
return defaultValue;
}
}
// ─── Resource Explorer 2 ───────────────────────────────────────────────────
/**
* Log groups carry no Region of their own — the store keys them {@code region::name} — so the
* key is the only place the Region can come from.
*/
@Override
public List<ExplorerResource> getResources() {
List<ExplorerResource> resources = new ArrayList<>();
for (String key : groupStore.keys()) {
int separator = key.indexOf("::");
if (separator < 0) {
continue;
}
LogGroup group = groupStore.get(key).orElse(null);
if (group == null || group.getLogGroupName() == null) {
continue;
}
String region = key.substring(0, separator);
resources.add(new ExplorerResource(
"arn:aws:logs:" + region + ":" + regionResolver.getAccountId()
+ ":log-group:" + group.getLogGroupName() + ":*",
"logs:log-group", "logs",
region, regionResolver.getAccountId(),
group.getCreatedTime() > 0 ? Instant.ofEpochMilli(group.getCreatedTime()) : Instant.now(),
group.getTags() != null ? group.getTags() : Map.of()));
}
return resources;
}
@Override
public Set<SupportedResourceType> getSupportedResourceTypes() {
return Set.of(new SupportedResourceType("logs:log-group", "logs", true));
}
}
@@ -10,6 +10,9 @@ import io.github.hectorvent.floci.core.common.AwsArnUtils;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.common.RegionResolver;
import io.github.hectorvent.floci.core.common.ReservedTags;
import io.github.hectorvent.floci.core.resource.ExplorerResource;
import io.github.hectorvent.floci.core.resource.ResourceProvider;
import io.github.hectorvent.floci.core.resource.SupportedResourceType;
import io.github.hectorvent.floci.core.storage.StorageBackend;
import io.github.hectorvent.floci.core.storage.StorageFactory;
import io.github.hectorvent.floci.services.cognito.model.CognitoGroup;
@@ -48,6 +51,7 @@ import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.time.Clock;
import java.time.Duration;
import java.time.Instant;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Base64;
@@ -66,7 +70,7 @@ import java.util.UUID;
import static io.github.hectorvent.floci.core.common.ReservedTags.rejectUnknownReservedTags;
@ApplicationScoped
public class CognitoService {
public class CognitoService implements ResourceProvider {
private static final int DEFAULT_REFRESH_TOKEN_VALIDITY_DAYS = 30;
private static final Logger LOG = Logger.getLogger(CognitoService.class);
@@ -313,6 +317,29 @@ public class CognitoService {
return poolStore.scan(k -> true);
}
@Override
public List<ExplorerResource> getResources() {
List<ExplorerResource> resources = new ArrayList<>();
for (UserPool pool : poolStore.scan(k -> true)) {
String arn = pool.getArn();
if (arn == null) {
continue;
}
AwsArnUtils.Arn parsed = AwsArnUtils.parse(arn);
resources.add(new ExplorerResource(
arn, "cognito-idp:userpool", "cognito-idp",
parsed.region(), parsed.accountId(),
pool.getCreationDate() > 0 ? Instant.ofEpochSecond(pool.getCreationDate()) : Instant.now(),
pool.getUserPoolTags() != null ? pool.getUserPoolTags() : Map.of()));
}
return resources;
}
@Override
public Set<SupportedResourceType> getSupportedResourceTypes() {
return Set.of(new SupportedResourceType("cognito-idp:userpool", "cognito-idp", true));
}
private UserPool describeUserPoolByArn(String resourceArn) {
String poolId = extractUserPoolIdFromArn(resourceArn);
return describeUserPool(poolId);
@@ -49,9 +49,12 @@ import java.util.concurrent.ConcurrentSkipListMap;
import java.util.concurrent.locks.ReentrantLock;
import java.util.function.Supplier;
import java.util.zip.GZIPOutputStream;
import io.github.hectorvent.floci.core.resource.ExplorerResource;
import io.github.hectorvent.floci.core.resource.ResourceProvider;
import io.github.hectorvent.floci.core.resource.SupportedResourceType;
@ApplicationScoped
public class DynamoDbService {
public class DynamoDbService implements ResourceProvider {
private static final String LOCAL_REPLICA_UPDATE_ERROR =
"Cannot add, delete, or update the local region through ReplicaUpdates. "
@@ -3014,4 +3017,26 @@ public class DynamoDbService {
return new ListExportsResult(summaries, newNextToken);
}
@Override
public List<ExplorerResource> getResources() {
List<ExplorerResource> resources = new ArrayList<>();
for (TableDefinition table : tableStore.scan(k -> true)) {
if (table.getTableArn() == null) {
continue;
}
AwsArnUtils.Arn parsed = AwsArnUtils.parse(table.getTableArn());
resources.add(new ExplorerResource(
table.getTableArn(), "dynamodb:table", "dynamodb",
parsed.region(), parsed.accountId(),
table.getCreationDateTime() != null ? table.getCreationDateTime() : Instant.now(),
table.getTags() != null ? table.getTags() : Map.of()));
}
return resources;
}
@Override
public Set<SupportedResourceType> getSupportedResourceTypes() {
return Set.of(new SupportedResourceType("dynamodb:table", "dynamodb", true));
}
}
@@ -20,6 +20,7 @@ import java.util.Random;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.Function;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
@@ -31,6 +32,9 @@ import io.github.hectorvent.floci.core.common.AwsArnUtils;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.common.AwsRegions;
import io.github.hectorvent.floci.core.common.ContainerTeardown;
import io.github.hectorvent.floci.core.resource.ExplorerResource;
import io.github.hectorvent.floci.core.resource.ResourceProvider;
import io.github.hectorvent.floci.core.resource.SupportedResourceType;
import io.github.hectorvent.floci.core.storage.InMemoryStorage;
import io.github.hectorvent.floci.core.storage.StorageBackend;
import io.github.hectorvent.floci.core.storage.StorageFactory;
@@ -95,7 +99,7 @@ import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
@ApplicationScoped
public class Ec2Service implements ContainerTeardown {
public class Ec2Service implements ContainerTeardown, ResourceProvider {
private static final Logger LOG = Logger.getLogger(Ec2Service.class);
private static final DateTimeFormatter ISO_FMT = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'")
@@ -5527,4 +5531,80 @@ public class Ec2Service implements ContainerTeardown {
return result;
}
// ─── Resource Explorer 2 ───────────────────────────────────────────────────
/**
* The EC2 resources Resource Explorer indexes. Each store is scanned across every Region,
* because a provider answers for the whole emulator rather than for the request's Region.
*
* <p>Types not listed here — images, snapshots, key pairs, transit gateways — are omitted
* deliberately: they are either AWS-owned catalogue entries rather than account resources, or
* carry no tags and no identity worth searching on.
*/
@Override
public List<ExplorerResource> getResources() {
List<ExplorerResource> resources = new ArrayList<>();
collectExplorerResources(resources, instances.scan(k -> true), "instance",
Instance::getInstanceId, Instance::getRegion, Instance::getLaunchTime, Instance::getTags);
collectExplorerResources(resources, vpcs.scan(k -> true), "vpc",
Vpc::getVpcId, Vpc::getRegion, v -> null, Vpc::getTags);
collectExplorerResources(resources, subnets.scan(k -> true), "subnet",
Subnet::getSubnetId, Subnet::getRegion, s -> null, Subnet::getTags);
collectExplorerResources(resources, securityGroups.scan(k -> true), "security-group",
SecurityGroup::getGroupId, SecurityGroup::getRegion, g -> null, SecurityGroup::getTags);
collectExplorerResources(resources, volumes.scan(k -> true), "volume",
Volume::getVolumeId, Volume::getRegion, Volume::getCreateTime, Volume::getTags);
collectExplorerResources(resources, internetGateways.scan(k -> true), "internet-gateway",
InternetGateway::getInternetGatewayId, InternetGateway::getRegion, g -> null, InternetGateway::getTags);
collectExplorerResources(resources, natGateways.scan(k -> true), "natgateway",
NatGateway::getNatGatewayId, NatGateway::getRegion, NatGateway::getCreateTime, NatGateway::getTags);
collectExplorerResources(resources, routeTables.scan(k -> true), "route-table",
RouteTable::getRouteTableId, RouteTable::getRegion, t -> null, RouteTable::getTags);
return resources;
}
@Override
public Set<SupportedResourceType> getSupportedResourceTypes() {
return Set.of(
new SupportedResourceType("ec2:instance", "ec2", true),
new SupportedResourceType("ec2:vpc", "ec2", true),
new SupportedResourceType("ec2:subnet", "ec2", true),
new SupportedResourceType("ec2:security-group", "ec2", true),
new SupportedResourceType("ec2:volume", "ec2", true),
new SupportedResourceType("ec2:internet-gateway", "ec2", true),
new SupportedResourceType("ec2:natgateway", "ec2", true),
new SupportedResourceType("ec2:route-table", "ec2", true));
}
private <T> void collectExplorerResources(List<ExplorerResource> out, List<T> stored, String resourceType,
Function<T, String> id, Function<T, String> region,
Function<T, Instant> createdAt, Function<T, List<Tag>> tags) {
for (T resource : stored) {
String resourceId = id.apply(resource);
String resourceRegion = region.apply(resource);
if (resourceId == null || resourceRegion == null) {
continue;
}
Instant created = createdAt.apply(resource);
out.add(new ExplorerResource(
"arn:aws:ec2:" + resourceRegion + ":" + accountId + ":" + resourceType + "/" + resourceId,
"ec2:" + resourceType, "ec2", resourceRegion, accountId,
created != null ? created : Instant.now(),
explorerTags(tags.apply(resource))));
}
}
private static Map<String, String> explorerTags(List<Tag> tags) {
if (tags == null) {
return Map.of();
}
Map<String, String> converted = new LinkedHashMap<>();
for (Tag tag : tags) {
if (tag.getKey() != null) {
converted.put(tag.getKey(), tag.getValue() != null ? tag.getValue() : "");
}
}
return converted;
}
}
@@ -4,6 +4,9 @@ import io.github.hectorvent.floci.config.EmulatorConfig;
import io.github.hectorvent.floci.core.common.RegionResolver;
import io.github.hectorvent.floci.core.common.AwsArnUtils;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.resource.ExplorerResource;
import io.github.hectorvent.floci.core.resource.ResourceProvider;
import io.github.hectorvent.floci.core.resource.SupportedResourceType;
import io.github.hectorvent.floci.core.storage.StorageBackend;
import io.github.hectorvent.floci.core.storage.StorageFactory;
import io.github.hectorvent.floci.services.ecr.model.AuthorizationData;
@@ -26,10 +29,11 @@ import java.util.ArrayList;
import java.util.Base64;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.regex.Pattern;
@ApplicationScoped
public class EcrService {
public class EcrService implements ResourceProvider {
private static final Logger LOG = Logger.getLogger(EcrService.class);
private static final Pattern REPO_NAME = Pattern.compile(
@@ -485,6 +489,29 @@ public class EcrService {
return repo;
}
@Override
public List<ExplorerResource> getResources() {
List<ExplorerResource> resources = new ArrayList<>();
for (Repository repo : repoStore.scan(k -> true)) {
String arn = repo.getRepositoryArn();
if (arn == null) {
continue;
}
AwsArnUtils.Arn parsed = AwsArnUtils.parse(arn);
resources.add(new ExplorerResource(
arn, "ecr:repository", "ecr",
parsed.region(), parsed.accountId(),
repo.getCreatedAt() != null ? repo.getCreatedAt() : Instant.now(),
repo.getTags() != null ? repo.getTags() : Map.of()));
}
return resources;
}
@Override
public Set<SupportedResourceType> getSupportedResourceTypes() {
return Set.of(new SupportedResourceType("ecr:repository", "ecr", true));
}
// ============================================================
// Result records
// ============================================================
@@ -50,9 +50,14 @@ import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.stream.Stream;
import io.github.hectorvent.floci.core.resource.ExplorerResource;
import io.github.hectorvent.floci.core.resource.ResourceProvider;
import io.github.hectorvent.floci.core.resource.SupportedResourceType;
import io.github.hectorvent.floci.core.common.AwsArnUtils;
import java.util.Set;
@ApplicationScoped
public class EcsService implements ContainerTeardown {
public class EcsService implements ContainerTeardown, ResourceProvider {
private static final Logger LOG = Logger.getLogger(EcsService.class);
private static final String DEFAULT_CLUSTER = "default";
@@ -1776,4 +1781,38 @@ public class EcsService implements ContainerTeardown {
int slash = after.indexOf('/');
return slash >= 0 ? after.substring(0, slash) : after;
}
// ─── Resource Explorer 2 ───────────────────────────────────────────────────
@Override
public List<ExplorerResource> getResources() {
List<ExplorerResource> resources = new ArrayList<>();
for (EcsCluster cluster : clusters.values()) {
addExplorerResource(resources, cluster.getClusterArn(), "ecs:cluster", null, cluster.getTags());
}
for (EcsServiceModel service : services.values()) {
addExplorerResource(resources, service.getServiceArn(), "ecs:service",
service.getCreatedAt(), service.getTags());
}
return resources;
}
@Override
public Set<SupportedResourceType> getSupportedResourceTypes() {
return Set.of(
new SupportedResourceType("ecs:cluster", "ecs", true),
new SupportedResourceType("ecs:service", "ecs", true));
}
private static void addExplorerResource(List<ExplorerResource> out, String arn, String resourceType,
Instant createdAt, Map<String, String> tags) {
if (arn == null) {
return;
}
AwsArnUtils.Arn parsed = AwsArnUtils.parse(arn);
out.add(new ExplorerResource(arn, resourceType, "ecs",
parsed.region(), parsed.accountId(),
createdAt != null ? createdAt : Instant.now(),
tags != null ? tags : Map.of()));
}
}
@@ -42,9 +42,13 @@ import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
import io.github.hectorvent.floci.core.resource.ExplorerResource;
import io.github.hectorvent.floci.core.resource.ResourceProvider;
import io.github.hectorvent.floci.core.resource.SupportedResourceType;
import java.util.Set;
@ApplicationScoped
public class EksService implements TagHandler {
public class EksService implements TagHandler, ResourceProvider {
private static final Logger LOG = Logger.getLogger(EksService.class);
@@ -571,4 +575,29 @@ public class EksService implements TagHandler {
storage.put(cluster.getName(), cluster);
}
}
// ─── Resource Explorer 2 ───────────────────────────────────────────────────
@Override
public List<ExplorerResource> getResources() {
List<ExplorerResource> resources = new ArrayList<>();
for (Cluster cluster : storage.scan(k -> true)) {
String arn = cluster.getArn();
if (arn == null) {
continue;
}
AwsArnUtils.Arn parsed = AwsArnUtils.parse(arn);
resources.add(new ExplorerResource(
arn, "eks:cluster", "eks",
parsed.region(), parsed.accountId(),
cluster.getCreatedAt() != null ? cluster.getCreatedAt() : Instant.now(),
cluster.getTags() != null ? cluster.getTags() : Map.of()));
}
return resources;
}
@Override
public Set<SupportedResourceType> getSupportedResourceTypes() {
return Set.of(new SupportedResourceType("eks:cluster", "eks", true));
}
}
@@ -51,11 +51,11 @@ public class ElastiCacheQueryHandler {
this.regionResolver = regionResolver;
}
public Response handle(String action, MultivaluedMap<String, String> params) {
public Response handle(String action, MultivaluedMap<String, String> params, String region) {
LOG.debugv("ElastiCache action: {0}", action);
return switch (action) {
case "ValidateIamAuthToken" -> handleValidateIamAuthToken(params);
case "CreateReplicationGroup" -> handleCreateReplicationGroup(params);
case "CreateReplicationGroup" -> handleCreateReplicationGroup(params, region);
case "DescribeReplicationGroups" -> handleDescribeReplicationGroups(params);
case "ModifyReplicationGroup" -> handleModifyReplicationGroup(params);
case "DeleteReplicationGroup" -> handleDeleteReplicationGroup(params);
@@ -83,7 +83,7 @@ public class ElastiCacheQueryHandler {
// ── Replication Groups ────────────────────────────────────────────────────
private Response handleCreateReplicationGroup(MultivaluedMap<String, String> params) {
private Response handleCreateReplicationGroup(MultivaluedMap<String, String> params, String region) {
String groupId = params.getFirst("ReplicationGroupId");
String description = params.getFirst("ReplicationGroupDescription");
String authToken = params.getFirst("AuthToken");
@@ -105,7 +105,7 @@ public class ElastiCacheQueryHandler {
try {
ReplicationGroup group = service.createReplicationGroup(
groupId, description != null ? description : "", authMode, authToken);
groupId, description != null ? description : "", authMode, authToken, region);
String result = replicationGroupXml(group);
return Response.ok(AwsQueryResponse.envelope("CreateReplicationGroup", AwsNamespaces.EC, result)).build();
} catch (AwsException e) {
@@ -2,8 +2,12 @@ package io.github.hectorvent.floci.services.elasticache;
import com.fasterxml.jackson.core.type.TypeReference;
import io.github.hectorvent.floci.config.EmulatorConfig;
import io.github.hectorvent.floci.core.common.AwsArnUtils;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.common.RegionResolver;
import io.github.hectorvent.floci.core.resource.ExplorerResource;
import io.github.hectorvent.floci.core.resource.ResourceProvider;
import io.github.hectorvent.floci.core.resource.SupportedResourceType;
import io.github.hectorvent.floci.core.storage.StorageBackend;
import io.github.hectorvent.floci.core.storage.StorageFactory;
import io.github.hectorvent.floci.services.elasticache.container.ElastiCacheContainerHandle;
@@ -38,7 +42,7 @@ import java.util.regex.Pattern;
* Creates Valkey containers and auth proxies on group creation.
*/
@ApplicationScoped
public class ElastiCacheService {
public class ElastiCacheService implements ResourceProvider {
private static final Logger LOG = Logger.getLogger(ElastiCacheService.class);
@@ -78,7 +82,7 @@ public class ElastiCacheService {
}
public ReplicationGroup createReplicationGroup(String groupId, String description,
AuthMode authMode, String authToken) {
AuthMode authMode, String authToken, String region) {
if (groups.get(groupId).isPresent()) {
throw new AwsException("ReplicationGroupAlreadyExistsFault",
"Replication group " + groupId + " already exists.", 400);
@@ -110,6 +114,8 @@ public class ElastiCacheService {
group.setContainerHost(handle.getHost());
group.setContainerPort(handle.getPort());
group.setAuthToken(authToken);
group.setArn(regionResolver.buildArn("elasticache", region, "replicationgroup:" + groupId));
group.setRegion(region);
proxyManager.startProxy(groupId, authMode, proxyPort,
handle.getHost(), handle.getPort(),
@@ -610,4 +616,26 @@ public class ElastiCacheService {
}
LOG.infov("Deleted cache parameter group {0}", name);
}
@Override
public List<ExplorerResource> getResources() {
List<ExplorerResource> resources = new ArrayList<>();
for (ReplicationGroup group : groups.scan(k -> true)) {
if (group.getArn() == null) {
continue;
}
AwsArnUtils.Arn parsed = AwsArnUtils.parse(group.getArn());
resources.add(new ExplorerResource(
group.getArn(), "elasticache:cluster", "elasticache",
parsed.region(), parsed.accountId(),
group.getCreatedAt() != null ? group.getCreatedAt() : Instant.now(),
Map.of()));
}
return resources;
}
@Override
public Set<SupportedResourceType> getSupportedResourceTypes() {
return Set.of(new SupportedResourceType("elasticache:cluster", "elasticache", true));
}
}
@@ -18,6 +18,8 @@ public class ReplicationGroup {
private int proxyPort;
private String authToken; // stored plain-text for PASSWORD auth validation in the proxy
private Set<String> associatedUserIds = new HashSet<>();
private String arn;
private String region;
// Transient fields — not persisted, restored on container restart
private transient String containerId;
@@ -75,4 +77,10 @@ public class ReplicationGroup {
public int getContainerPort() { return containerPort; }
public void setContainerPort(int containerPort) { this.containerPort = containerPort; }
public String getArn() { return arn; }
public void setArn(String arn) { this.arn = arn; }
public String getRegion() { return region; }
public void setRegion(String region) { this.region = region; }
}
@@ -19,9 +19,16 @@ import java.time.Instant;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;
import io.github.hectorvent.floci.core.resource.ExplorerResource;
import io.github.hectorvent.floci.core.resource.ResourceProvider;
import io.github.hectorvent.floci.core.resource.SupportedResourceType;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
@ApplicationScoped
public class ElbV2Service {
public class ElbV2Service implements ResourceProvider {
@Inject
ElbV2DataPlane dataPlane;
@@ -1145,4 +1152,43 @@ public class ElbV2Service {
}
}
}
// ─── Resource Explorer 2 ───────────────────────────────────────────────────
@Override
public List<ExplorerResource> getResources() {
List<ExplorerResource> resources = new ArrayList<>();
for (Map<String, LoadBalancer> regionLoadBalancers : loadBalancers.values()) {
for (LoadBalancer loadBalancer : regionLoadBalancers.values()) {
addExplorerResource(resources, loadBalancer.getLoadBalancerArn(),
"elasticloadbalancing:loadbalancer", loadBalancer.getCreatedTime());
}
}
for (Map<String, TargetGroup> regionTargetGroups : targetGroups.values()) {
for (TargetGroup targetGroup : regionTargetGroups.values()) {
addExplorerResource(resources, targetGroup.getTargetGroupArn(),
"elasticloadbalancing:targetgroup", null);
}
}
return resources;
}
@Override
public Set<SupportedResourceType> getSupportedResourceTypes() {
return Set.of(
new SupportedResourceType("elasticloadbalancing:loadbalancer", "elasticloadbalancing", true),
new SupportedResourceType("elasticloadbalancing:targetgroup", "elasticloadbalancing", true));
}
private void addExplorerResource(List<ExplorerResource> out, String arn, String resourceType,
Instant createdAt) {
if (arn == null) {
return;
}
AwsArnUtils.Arn parsed = AwsArnUtils.parse(arn);
out.add(new ExplorerResource(arn, resourceType, "elasticloadbalancing",
parsed.region(), parsed.accountId(),
createdAt != null ? createdAt : Instant.now(),
tags.getOrDefault(arn, Map.of())));
}
}
@@ -39,9 +39,13 @@ import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.regex.Pattern;
import io.github.hectorvent.floci.core.resource.ExplorerResource;
import io.github.hectorvent.floci.core.resource.ResourceProvider;
import io.github.hectorvent.floci.core.resource.SupportedResourceType;
import java.util.Set;
@ApplicationScoped
public class EventBridgeService {
public class EventBridgeService implements ResourceProvider {
private static final Logger LOG = Logger.getLogger(EventBridgeService.class);
@@ -1579,4 +1583,38 @@ public class EventBridgeService {
}
}
// ─── Resource Explorer 2 ───────────────────────────────────────────────────
@Override
public List<ExplorerResource> getResources() {
List<ExplorerResource> resources = new ArrayList<>();
for (EventBus bus : busStore.scan(k -> true)) {
addExplorerResource(resources, bus.getArn(), "events:event-bus",
bus.getCreatedTime(), bus.getTags());
}
for (Rule rule : ruleStore.scan(k -> true)) {
addExplorerResource(resources, rule.getArn(), "events:rule",
rule.getCreatedAt(), rule.getTags());
}
return resources;
}
@Override
public Set<SupportedResourceType> getSupportedResourceTypes() {
return Set.of(
new SupportedResourceType("events:event-bus", "events", true),
new SupportedResourceType("events:rule", "events", true));
}
private static void addExplorerResource(List<ExplorerResource> out, String arn, String resourceType,
Instant createdAt, Map<String, String> tags) {
if (arn == null) {
return;
}
AwsArnUtils.Arn parsed = AwsArnUtils.parse(arn);
out.add(new ExplorerResource(arn, resourceType, "events",
parsed.region(), parsed.accountId(),
createdAt != null ? createdAt : Instant.now(),
tags != null ? tags : Map.of()));
}
}
@@ -28,9 +28,17 @@ import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import io.github.hectorvent.floci.core.resource.ExplorerResource;
import io.github.hectorvent.floci.core.resource.ResourceProvider;
import io.github.hectorvent.floci.core.resource.SupportedResourceType;
import java.util.LinkedHashMap;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
@ApplicationScoped
public class FirehoseService {
public class FirehoseService implements ResourceProvider {
private static final Logger LOG = Logger.getLogger(FirehoseService.class);
private static final String DEFAULT_BUCKET = "floci-firehose-results";
@@ -416,4 +424,35 @@ public class FirehoseService {
s3Service.createBucket(bucket, regionResolver.getDefaultRegion());
} catch (Exception ignored) {}
}
// ─── Resource Explorer 2 ───────────────────────────────────────────────────
@Override
public List<ExplorerResource> getResources() {
List<ExplorerResource> resources = new ArrayList<>();
for (DeliveryStreamDescription stream : streamStore.scan(k -> true)) {
String arn = stream.getDeliveryStreamARN();
if (arn == null) {
continue;
}
AwsArnUtils.Arn parsed = AwsArnUtils.parse(arn);
Map<String, String> tags = new LinkedHashMap<>();
if (stream.getTags() != null) {
for (DeliveryStreamDescription.Tag tag : stream.getTags()) {
tags.put(tag.getKey(), tag.getValue() != null ? tag.getValue() : "");
}
}
resources.add(new ExplorerResource(
arn, "firehose:deliverystream", "firehose",
parsed.region(), parsed.accountId(),
stream.getCreateTimestamp() != null ? stream.getCreateTimestamp() : Instant.now(),
tags));
}
return resources;
}
@Override
public Set<SupportedResourceType> getSupportedResourceTypes() {
return Set.of(new SupportedResourceType("firehose:deliverystream", "firehose", true));
}
}
@@ -5,6 +5,9 @@ import io.github.hectorvent.floci.core.common.AwsArnUtils;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.common.RegionResolver;
import io.github.hectorvent.floci.core.common.SessionAccountLookup;
import io.github.hectorvent.floci.core.resource.ExplorerResource;
import io.github.hectorvent.floci.core.resource.ResourceProvider;
import io.github.hectorvent.floci.core.resource.SupportedResourceType;
import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend;
import io.github.hectorvent.floci.core.storage.InMemoryStorage;
import io.github.hectorvent.floci.core.storage.StorageBackend;
@@ -28,6 +31,7 @@ import org.jboss.logging.Logger;
import java.time.Instant;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.ThreadLocalRandom;
import java.util.ArrayList;
import java.util.LinkedHashMap;
@@ -48,7 +52,7 @@ import java.util.regex.Pattern;
*/
@Startup
@ApplicationScoped
public class IamService implements SessionAccountLookup {
public class IamService implements SessionAccountLookup, ResourceProvider {
private static final Logger LOG = Logger.getLogger(IamService.class);
private static final String CHARS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
@@ -1269,6 +1273,43 @@ public class IamService implements SessionAccountLookup {
.toList();
}
@Override
public List<ExplorerResource> getResources() {
List<ExplorerResource> resources = new ArrayList<>();
for (IamUser user : users.scan(k -> true)) {
addIamResource(resources, user.getArn(), "iam:user", user.getCreateDate(), user.getTags());
}
for (IamRole role : roles.scan(k -> true)) {
addIamResource(resources, role.getArn(), "iam:role", role.getCreateDate(), role.getTags());
}
return resources;
}
private void addIamResource(List<ExplorerResource> out, String arn, String type,
Instant createDate, Map<String, String> tags) {
if (arn == null) {
return;
}
AwsArnUtils.Arn parsed = AwsArnUtils.parse(arn);
// IAM is a global service: its ARNs carry no region. Resource Explorer reports
// global resources with the region "global" (not an empty string).
String region = parsed.region() == null || parsed.region().isEmpty()
? "global"
: parsed.region();
out.add(new ExplorerResource(
arn, type, "iam",
region, parsed.accountId(),
createDate != null ? createDate : Instant.now(),
tags != null ? tags : Map.of()));
}
@Override
public Set<SupportedResourceType> getSupportedResourceTypes() {
return Set.of(
new SupportedResourceType("iam:user", "iam", true),
new SupportedResourceType("iam:role", "iam", true));
}
// =========================================================================
// Account Aliases
// ==================================================================
@@ -18,9 +18,15 @@ import java.nio.charset.StandardCharsets;
import java.time.Instant;
import java.util.*;
import java.util.concurrent.atomic.AtomicLong;
import io.github.hectorvent.floci.core.resource.ExplorerResource;
import io.github.hectorvent.floci.core.resource.ResourceProvider;
import io.github.hectorvent.floci.core.resource.SupportedResourceType;
import io.github.hectorvent.floci.core.common.AwsArnUtils;
import java.util.ArrayList;
import java.util.Set;
@ApplicationScoped
public class KinesisService {
public class KinesisService implements ResourceProvider {
private static final Logger LOG = Logger.getLogger(KinesisService.class);
private static final Set<String> VALID_SHARD_LEVEL_METRICS = Set.of(
"IncomingBytes", "IncomingRecords", "OutgoingBytes", "OutgoingRecords",
@@ -779,4 +785,30 @@ public class KinesisService {
private String regionKey(String region, String name) {
return region + "::" + name;
}
// ─── Resource Explorer 2 ───────────────────────────────────────────────────
@Override
public List<ExplorerResource> getResources() {
List<ExplorerResource> resources = new ArrayList<>();
for (KinesisStream stream : store.scan(k -> true)) {
String arn = stream.getStreamArn();
if (arn == null) {
continue;
}
AwsArnUtils.Arn parsed = AwsArnUtils.parse(arn);
resources.add(new ExplorerResource(
arn, "kinesis:stream", "kinesis",
parsed.region(), parsed.accountId(),
stream.getStreamCreationTimestamp() != null
? stream.getStreamCreationTimestamp() : Instant.now(),
stream.getTags() != null ? stream.getTags() : Map.of()));
}
return resources;
}
@Override
public Set<SupportedResourceType> getSupportedResourceTypes() {
return Set.of(new SupportedResourceType("kinesis:stream", "kinesis", true));
}
}
@@ -1,9 +1,13 @@
package io.github.hectorvent.floci.services.kms;
import com.fasterxml.jackson.core.type.TypeReference;
import io.github.hectorvent.floci.core.common.AwsArnUtils;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.common.RegionResolver;
import io.github.hectorvent.floci.core.common.ReservedTags;
import io.github.hectorvent.floci.core.resource.ExplorerResource;
import io.github.hectorvent.floci.core.resource.ResourceProvider;
import io.github.hectorvent.floci.core.resource.SupportedResourceType;
import io.github.hectorvent.floci.core.storage.StorageBackend;
import io.github.hectorvent.floci.core.storage.StorageFactory;
import io.github.hectorvent.floci.services.kms.model.KmsAlias;
@@ -58,7 +62,7 @@ import static io.github.hectorvent.floci.services.kms.model.KmsMessageType.DIGES
import static io.github.hectorvent.floci.services.kms.model.KmsMessageType.RAW;
@ApplicationScoped
public class KmsService {
public class KmsService implements ResourceProvider {
private static final Logger LOG = Logger.getLogger(KmsService.class);
@@ -1165,4 +1169,26 @@ public class KmsService {
}
}
@Override
public List<ExplorerResource> getResources() {
List<ExplorerResource> resources = new ArrayList<>();
for (KmsKey key : keyStore.scan(k -> true)) {
String arn = key.getArn();
if (arn == null) {
continue;
}
AwsArnUtils.Arn parsed = AwsArnUtils.parse(arn);
resources.add(new ExplorerResource(
arn, "kms:key", "kms",
parsed.region(), parsed.accountId(),
key.getCreationDate() > 0 ? Instant.ofEpochSecond(key.getCreationDate()) : Instant.now(),
key.getTags() != null ? key.getTags() : Map.of()));
}
return resources;
}
@Override
public Set<SupportedResourceType> getSupportedResourceTypes() {
return Set.of(new SupportedResourceType("kms:key", "kms", true));
}
}
@@ -7,6 +7,9 @@ import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.common.RegionResolver;
import io.github.hectorvent.floci.core.storage.StorageBackedMap;
import io.github.hectorvent.floci.core.storage.StorageFactory;
import io.github.hectorvent.floci.core.resource.ExplorerResource;
import io.github.hectorvent.floci.core.resource.ResourceProvider;
import io.github.hectorvent.floci.core.resource.SupportedResourceType;
import io.github.hectorvent.floci.services.lambda.model.EventSourceMapping;
import io.github.hectorvent.floci.services.lambda.model.FunctionEventInvokeConfig;
import io.github.hectorvent.floci.services.lambda.model.InvocationType;
@@ -39,6 +42,7 @@ import java.util.Base64;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
import java.util.regex.Pattern;
@@ -47,7 +51,7 @@ import java.util.regex.Pattern;
* Business logic for Lambda function management and invocation.
*/
@ApplicationScoped
public class LambdaService {
public class LambdaService implements ResourceProvider {
private static final Logger LOG = Logger.getLogger(LambdaService.class);
private static final Pattern EFS_ACCESS_POINT_ARN = Pattern.compile(
@@ -252,6 +256,32 @@ public class LambdaService {
}
}
@Override
public List<ExplorerResource> getResources() {
List<ExplorerResource> resources = new ArrayList<>();
for (LambdaFunction fn : functionStore.listAll()) {
if (!"$LATEST".equals(fn.getVersion())) {
continue;
}
String arn = fn.getFunctionArn();
if (arn == null) {
continue;
}
AwsArnUtils.Arn parsed = AwsArnUtils.parse(arn);
resources.add(new ExplorerResource(
arn, "lambda:function", "lambda",
parsed.region(), parsed.accountId(),
fn.getLastModified() > 0 ? Instant.ofEpochMilli(fn.getLastModified()) : Instant.now(),
fn.getTags() != null ? fn.getTags() : Map.of()));
}
return resources;
}
@Override
public Set<SupportedResourceType> getSupportedResourceTypes() {
return Set.of(new SupportedResourceType("lambda:function", "lambda", true));
}
public LambdaFunction createFunction(String region, Map<String, Object> request) {
String functionName = (String) request.get("FunctionName");
String role = (String) request.get("Role");
@@ -5,8 +5,12 @@ import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import io.github.hectorvent.floci.core.common.AwsArnUtils;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.common.RegionResolver;
import io.github.hectorvent.floci.core.resource.ExplorerResource;
import io.github.hectorvent.floci.core.resource.ResourceProvider;
import io.github.hectorvent.floci.core.resource.SupportedResourceType;
import io.github.hectorvent.floci.core.storage.StorageBackend;
import io.github.hectorvent.floci.core.storage.StorageFactory;
import jakarta.enterprise.context.ApplicationScoped;
@@ -17,12 +21,14 @@ import java.time.Instant;
import java.util.ArrayList;
import java.util.Base64;
import java.util.Comparator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
@ApplicationScoped
public class LightsailService {
public class LightsailService implements ResourceProvider {
private static final String SERVICE = "lightsail";
private static final String RESOURCE_INSTANCE = "Instance";
@@ -497,6 +503,53 @@ public class LightsailService {
return mapper.createObjectNode().put("isPeered", false);
}
@Override
public List<ExplorerResource> getResources() {
List<ExplorerResource> resources = new ArrayList<>();
for (ObjectNode node : resourceStore.scan(key -> true)) {
String arn = node.path("arn").asText(null);
if (arn == null) {
continue;
}
AwsArnUtils.Arn parsed = AwsArnUtils.parse(arn);
resources.add(new ExplorerResource(
arn,
SERVICE + ":" + node.path("resourceType").asText(),
SERVICE,
parsed.region(),
parsed.accountId(),
reportedAt(node),
tagsOf(node)));
}
return resources;
}
@Override
public Set<SupportedResourceType> getSupportedResourceTypes() {
return Set.of(
new SupportedResourceType(SERVICE + ":" + RESOURCE_INSTANCE, SERVICE, true),
new SupportedResourceType(SERVICE + ":" + RESOURCE_DISK, SERVICE, true),
new SupportedResourceType(SERVICE + ":" + RESOURCE_KEY_PAIR, SERVICE, true),
// Lightsail static IPs are not taggable in AWS.
new SupportedResourceType(SERVICE + ":" + RESOURCE_STATIC_IP, SERVICE, false));
}
private static Instant reportedAt(ObjectNode node) {
double createdAt = node.path("createdAt").asDouble(0);
return createdAt > 0 ? Instant.ofEpochMilli(Math.round(createdAt * 1000)) : Instant.now();
}
private static Map<String, String> tagsOf(ObjectNode node) {
Map<String, String> tags = new LinkedHashMap<>();
for (JsonNode tag : node.path("tags")) {
String key = tag.path("key").asText(null);
if (key != null) {
tags.put(key, tag.path("value").asText(""));
}
}
return tags;
}
private ObjectNode baseResource(String region, String availabilityZone, String resourceType, String name) {
Instant now = Instant.now();
ObjectNode resource = mapper.createObjectNode();
@@ -6,6 +6,9 @@ import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.common.Pagination;
import io.github.hectorvent.floci.core.common.PaginatedResult;
import io.github.hectorvent.floci.core.common.RegionResolver;
import io.github.hectorvent.floci.core.resource.ExplorerResource;
import io.github.hectorvent.floci.core.resource.ResourceProvider;
import io.github.hectorvent.floci.core.resource.SupportedResourceType;
import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend;
import io.github.hectorvent.floci.core.storage.StorageBackend;
import io.github.hectorvent.floci.core.storage.StorageFactory;
@@ -24,15 +27,17 @@ import org.jboss.logging.Logger;
import java.security.SecureRandom;
import java.time.Instant;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
@ApplicationScoped
public class MskService {
public class MskService implements ResourceProvider {
private static final Logger LOG = Logger.getLogger(MskService.class);
private static final String DEFAULT_KAFKA_VERSION = "3.6.0";
@@ -279,4 +284,27 @@ public class MskService {
storage.put(cluster.getClusterArn(), cluster);
}
}
@Override
public List<ExplorerResource> getResources() {
List<ExplorerResource> resources = new ArrayList<>();
for (MskCluster cluster : storage.scan(k -> true)) {
String arn = cluster.getClusterArn();
if (arn == null) {
continue;
}
AwsArnUtils.Arn parsed = AwsArnUtils.parse(arn);
resources.add(new ExplorerResource(
arn, "kafka:cluster", "kafka",
parsed.region(), parsed.accountId(),
cluster.getCreationTime() != null ? cluster.getCreationTime() : Instant.now(),
cluster.getTags() != null ? cluster.getTags() : Map.of()));
}
return resources;
}
@Override
public Set<SupportedResourceType> getSupportedResourceTypes() {
return Set.of(new SupportedResourceType("kafka:cluster", "kafka", true));
}
}
@@ -24,14 +24,19 @@ import org.jboss.logging.Logger;
import java.security.SecureRandom;
import java.time.Instant;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import io.github.hectorvent.floci.core.resource.ExplorerResource;
import io.github.hectorvent.floci.core.resource.ResourceProvider;
import io.github.hectorvent.floci.core.resource.SupportedResourceType;
@ApplicationScoped
public class OpenSearchService {
public class OpenSearchService implements ResourceProvider {
private static final Logger LOG = Logger.getLogger(OpenSearchService.class);
@@ -366,4 +371,26 @@ public class OpenSearchService {
domainStore.put(domain.getDomainName(), domain);
}
}
@Override
public List<ExplorerResource> getResources() {
List<ExplorerResource> resources = new ArrayList<>();
for (Domain domain : listDomainNames(null)) {
if (domain.getArn() == null) {
continue;
}
AwsArnUtils.Arn parsed = AwsArnUtils.parse(domain.getArn());
resources.add(new ExplorerResource(
domain.getArn(), "es:domain", "es",
parsed.region(), parsed.accountId(),
domain.getCreatedAt() != null ? domain.getCreatedAt() : Instant.now(),
domain.getTags() != null ? domain.getTags() : Map.of()));
}
return resources;
}
@Override
public Set<SupportedResourceType> getSupportedResourceTypes() {
return Set.of(new SupportedResourceType("es:domain", "es", true));
}
}
@@ -4,6 +4,9 @@ import io.github.hectorvent.floci.core.common.AwsArnUtils;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.common.RegionResolver;
import io.github.hectorvent.floci.core.common.TagHandler;
import io.github.hectorvent.floci.core.resource.ExplorerResource;
import io.github.hectorvent.floci.core.resource.ResourceProvider;
import io.github.hectorvent.floci.core.resource.SupportedResourceType;
import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend;
import io.github.hectorvent.floci.core.storage.StorageBackend;
import io.github.hectorvent.floci.core.storage.StorageFactory;
@@ -17,13 +20,15 @@ import jakarta.inject.Inject;
import org.jboss.logging.Logger;
import java.time.Instant;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;
@ApplicationScoped
public class PipesService implements TagHandler {
public class PipesService implements TagHandler, ResourceProvider {
private static final Logger LOG = Logger.getLogger(PipesService.class);
@@ -204,6 +209,29 @@ public class PipesService implements TagHandler {
return pipe;
}
@Override
public List<ExplorerResource> getResources() {
List<ExplorerResource> resources = new ArrayList<>();
for (Pipe pipe : storage.scan(k -> true)) {
String arn = pipe.getArn();
if (arn == null) {
continue;
}
AwsArnUtils.Arn parsed = AwsArnUtils.parse(arn);
resources.add(new ExplorerResource(
arn, "pipes:pipe", "pipes",
parsed.region(), parsed.accountId(),
pipe.getCreationTime() != null ? pipe.getCreationTime() : Instant.now(),
pipe.getTags() != null ? pipe.getTags() : Map.of()));
}
return resources;
}
@Override
public Set<SupportedResourceType> getSupportedResourceTypes() {
return Set.of(new SupportedResourceType("pipes:pipe", "pipes", true));
}
@Override
public String serviceKey() {
return "pipes";
@@ -10,6 +10,9 @@ import io.github.hectorvent.floci.core.common.RegionResolver;
import io.github.hectorvent.floci.core.common.docker.ContainerStorageHelper;
import io.github.hectorvent.floci.core.common.docker.CurrentContainerNetworkResolver;
import io.github.hectorvent.floci.core.common.docker.DockerHostResolver;
import io.github.hectorvent.floci.core.resource.ExplorerResource;
import io.github.hectorvent.floci.core.resource.ResourceProvider;
import io.github.hectorvent.floci.core.resource.SupportedResourceType;
import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend;
import io.github.hectorvent.floci.core.storage.InMemoryStorage;
import io.github.hectorvent.floci.core.storage.StorageBackend;
@@ -33,6 +36,7 @@ import io.github.hectorvent.floci.services.rds.model.DbSubnetGroup;
import io.github.hectorvent.floci.services.rds.model.OptionGroup;
import io.github.hectorvent.floci.services.rds.model.OptionGroupOption;
import io.github.hectorvent.floci.services.rds.proxy.RdsProxyManager;
import io.github.hectorvent.floci.services.resourcegroupstagging.ResourceGroupsTaggingService;
import io.github.hectorvent.floci.services.secretsmanager.SecretsManagerService;
import io.github.hectorvent.floci.services.secretsmanager.model.Secret;
import io.github.hectorvent.floci.core.common.Resettable;
@@ -61,7 +65,7 @@ import java.util.regex.Pattern;
* Starts DB containers and auth proxies on creation.
*/
@ApplicationScoped
public class RdsService implements Resettable {
public class RdsService implements Resettable, ResourceProvider {
private static final Logger LOG = Logger.getLogger(RdsService.class);
private static final ObjectMapper JSON = new ObjectMapper();
@@ -132,6 +136,7 @@ public class RdsService implements Resettable {
private final SecretsManagerService secretsManagerService;
private final DockerHostResolver dockerHostResolver;
private final CurrentContainerNetworkResolver currentContainerNetworkResolver;
private final ResourceGroupsTaggingService taggingService;
private final Set<Integer> usedPorts = ConcurrentHashMap.newKeySet();
private static final Pattern IMAGE_TAG_VERSION_PATTERN = Pattern.compile("^(\\d+(?:\\.\\d+)*)(.*)$");
private static final Pattern SAFE_IMAGE_TAG_PATTERN = Pattern.compile("[A-Za-z0-9._-]+");
@@ -163,7 +168,8 @@ public class RdsService implements Resettable {
StorageFactory storageFactory,
SecretsManagerService secretsManagerService,
DockerHostResolver dockerHostResolver,
CurrentContainerNetworkResolver currentContainerNetworkResolver) {
CurrentContainerNetworkResolver currentContainerNetworkResolver,
ResourceGroupsTaggingService taggingService) {
this.containerManager = containerManager;
this.proxyManager = proxyManager;
this.ec2Service = ec2Service;
@@ -172,6 +178,7 @@ public class RdsService implements Resettable {
this.secretsManagerService = secretsManagerService;
this.dockerHostResolver = dockerHostResolver;
this.currentContainerNetworkResolver = currentContainerNetworkResolver;
this.taggingService = taggingService;
this.instances = storageFactory.create("rds", "rds-instances.json",
new TypeReference<Map<String, DbInstance>>() {});
this.clusters = storageFactory.create("rds", "rds-clusters.json",
@@ -280,7 +287,7 @@ public class RdsService implements Resettable {
this(containerManager, proxyManager, ec2Service, regionResolver, config,
instances, clusters, parameterGroups, clusterParameterGroups, subnetGroups,
secretsManagerService, dockerHostResolver, currentContainerNetworkResolver,
proxies, proxyTargetGroups, new InMemoryStorage<>());
proxies, proxyTargetGroups, new InMemoryStorage<>(), null);
}
RdsService(RdsContainerManager containerManager,
@@ -298,7 +305,8 @@ public class RdsService implements Resettable {
CurrentContainerNetworkResolver currentContainerNetworkResolver,
StorageBackend<String, DbProxy> proxies,
StorageBackend<String, DbProxyTargetGroup> proxyTargetGroups,
StorageBackend<String, OptionGroup> optionGroups) {
StorageBackend<String, OptionGroup> optionGroups,
ResourceGroupsTaggingService taggingService) {
this.containerManager = containerManager;
this.proxyManager = proxyManager;
this.ec2Service = ec2Service;
@@ -315,6 +323,7 @@ public class RdsService implements Resettable {
this.subnetGroups = subnetGroups;
this.proxies = proxies;
this.proxyTargetGroups = proxyTargetGroups;
this.taggingService = taggingService;
}
public void restorePersistedRuntime() {
@@ -5039,4 +5048,48 @@ public class RdsService implements Resettable {
cluster.getSubnetAvailabilityZones());
}
}
@Override
public List<ExplorerResource> getResources() {
List<ExplorerResource> resources = new ArrayList<>();
for (DbInstance instance : listDbInstances(null)) {
String arn = instance.getDbInstanceArn();
if (arn == null) {
continue;
}
AwsArnUtils.Arn parsed = AwsArnUtils.parse(arn);
resources.add(new ExplorerResource(arn, "rds:db", "rds",
parsed.region(), parsed.accountId(),
instance.getCreatedAt() != null ? instance.getCreatedAt() : Instant.now(),
tagsFor(parsed.region(), arn)));
}
for (DbCluster cluster : listDbClusters(null)) {
String arn = cluster.getDbClusterArn();
if (arn == null) {
continue;
}
AwsArnUtils.Arn parsed = AwsArnUtils.parse(arn);
resources.add(new ExplorerResource(arn, "rds:cluster", "rds",
parsed.region(), parsed.accountId(),
cluster.getCreatedAt() != null ? cluster.getCreatedAt() : Instant.now(),
tagsFor(parsed.region(), arn)));
}
return resources;
}
/**
* Resolves tags for a resource, tolerating a null taggingService. The CDI constructor always
* supplies one; the storage-backed test constructors pass null, and unit tests that exercise
* getResources() would otherwise NPE.
*/
private Map<String, String> tagsFor(String region, String arn) {
return taggingService != null ? taggingService.getTagsForResource(region, arn) : Map.of();
}
@Override
public Set<SupportedResourceType> getSupportedResourceTypes() {
return Set.of(
new SupportedResourceType("rds:db", "rds", true),
new SupportedResourceType("rds:cluster", "rds", true));
}
}
@@ -0,0 +1,463 @@
package io.github.hectorvent.floci.services.resourceexplorer2;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.common.RegionResolver;
import io.github.hectorvent.floci.services.resourceexplorer2.model.*;
import jakarta.inject.Inject;
import jakarta.ws.rs.*;
import jakarta.ws.rs.core.Context;
import jakarta.ws.rs.core.HttpHeaders;
import jakarta.ws.rs.core.MediaType;
import jakarta.ws.rs.core.Response;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@Path("/")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public class ResourceExplorer2Controller {
/**
* Per-operation MaxResults ceilings. AWS models a different maximum for each of these, and a
* value above it is a ValidationException — so a single shared constant would either reject
* page sizes AWS accepts or accept ones it rejects.
*/
private static final int MAX_RESULTS_RESOURCES = 1000;
private static final int MAX_RESULTS_INDEXES = 100;
private static final int MAX_RESULTS_VIEWS = 50;
private static final int MAX_RESULTS_MEMBER_INDEXES = 10;
private final ResourceExplorer2Service service;
private final RegionResolver regionResolver;
private final ObjectMapper objectMapper;
@Inject
public ResourceExplorer2Controller(ResourceExplorer2Service service,
RegionResolver regionResolver,
ObjectMapper objectMapper) {
this.service = service;
this.regionResolver = regionResolver;
this.objectMapper = objectMapper;
}
@POST
@Path("/ListResources")
public Response listResources(@Context HttpHeaders headers, String body) throws IOException {
JsonNode req = parseBody(body);
String region = regionResolver.resolveRegion(headers);
String filterString = req.has("Filters") && req.get("Filters").has("FilterString")
? req.get("Filters").get("FilterString").asText(null) : null;
Integer maxResults = validatedMaxResults(req, MAX_RESULTS_RESOURCES);
String nextToken = optString(req, "NextToken");
String viewArn = optString(req, "ViewArn");
try {
return Response.ok(service.listResources(filterString, maxResults, nextToken, viewArn, region)).build();
} catch (IllegalArgumentException e) {
throw new AwsException("ValidationException", e.getMessage(), 400);
}
}
@POST
@Path("/Search")
public Response search(@Context HttpHeaders headers, String body) throws IOException {
JsonNode req = parseBody(body);
if (!req.has("QueryString")) {
throw new AwsException("ValidationException", "QueryString is required", 400);
}
String queryString = req.get("QueryString").asText(null);
Integer maxResults = validatedMaxResults(req, MAX_RESULTS_RESOURCES);
String nextToken = optString(req, "NextToken");
String viewArn = optString(req, "ViewArn");
String region = regionResolver.resolveRegion(headers);
return Response.ok(service.search(queryString, maxResults, nextToken, viewArn, region)).build();
}
@POST
@Path("/ListSupportedResourceTypes")
public Response listSupportedResourceTypes(String body) throws IOException {
JsonNode req = parseBody(body);
Integer maxResults = validatedMaxResults(req, MAX_RESULTS_RESOURCES);
String nextToken = optString(req, "NextToken");
return Response.ok(service.listSupportedResourceTypes(maxResults, nextToken)).build();
}
@POST
@Path("/re2/CreateIndex")
public Response createIndex(@Context HttpHeaders headers, String body) throws IOException {
JsonNode req = parseBody(body);
String region = regionResolver.resolveRegion(headers);
Map<String, String> tags = parseTags(req);
Index index = service.createIndex(region, tags);
var result = objectMapper.createObjectNode();
result.put("Arn", index.arn());
result.put("CreatedAt", index.createdAt().toString());
// Real AWS returns CREATING immediately; we store ACTIVE synchronously but the
// caller must see CREATING as the initial state per the AWS API contract.
result.put("State", "CREATING");
return Response.ok(result).build();
}
@POST
@Path("/re2/GetIndex")
public Response getIndex(@Context HttpHeaders headers) {
String region = regionResolver.resolveRegion(headers);
Index index = service.getIndex(region);
var result = objectMapper.createObjectNode();
result.put("Arn", index.arn());
result.put("CreatedAt", index.createdAt().toString());
result.put("LastUpdatedAt", index.lastUpdatedAt().toString());
result.set("ReplicatingFrom", objectMapper.valueToTree(index.replicatingFrom()));
result.set("ReplicatingTo", objectMapper.valueToTree(index.replicatingTo()));
result.put("State", index.state().name());
result.set("Tags", objectMapper.valueToTree(index.tags()));
result.put("Type", index.type().name());
return Response.ok(result).build();
}
@POST
@Path("/re2/DeleteIndex")
public Response deleteIndex(String body) throws IOException {
JsonNode req = parseBody(body);
String indexArn = optString(req, "Arn");
if (indexArn == null) {
throw new AwsException("ValidationException", "Arn is required", 400);
}
Index deleted = service.deleteIndex(indexArn);
var result = objectMapper.createObjectNode();
result.put("Arn", deleted.arn());
result.put("LastUpdatedAt", deleted.lastUpdatedAt().toString());
result.put("State", deleted.state().name());
return Response.ok(result).build();
}
@POST
@Path("/re2/ListIndexes")
public Response listIndexes(String body) throws IOException {
JsonNode req = parseBody(body);
String type = optString(req, "Type");
List<String> regions = stringArray(req, "Regions");
Integer maxResults = validatedMaxResults(req, MAX_RESULTS_INDEXES);
String nextToken = optString(req, "NextToken");
return Response.ok(service.listIndexes(type, regions, maxResults, nextToken)).build();
}
@POST
@Path("/UpdateIndexType")
public Response updateIndexType(String body) throws IOException {
JsonNode req = parseBody(body);
String arn = optString(req, "Arn");
if (arn == null) {
throw new AwsException("ValidationException", "Arn is required", 400);
}
if (!req.has("Type")) {
throw new AwsException("ValidationException", "Type is required", 400);
}
IndexType type;
try {
type = IndexType.valueOf(req.get("Type").asText());
} catch (IllegalArgumentException e) {
throw new AwsException("ValidationException", "Invalid index type: " + req.get("Type").asText(), 400);
}
Index index = service.updateIndexType(arn, type);
var result = objectMapper.createObjectNode();
result.put("Arn", index.arn());
result.put("LastUpdatedAt", index.lastUpdatedAt().toString());
result.put("State", index.state().name());
result.put("Type", index.type().name());
return Response.ok(result).build();
}
@POST
@Path("/CreateView")
public Response createView(@Context HttpHeaders headers, String body) throws IOException {
JsonNode req = parseBody(body);
String region = regionResolver.resolveRegion(headers);
String viewName = optString(req, "ViewName");
String scope = optString(req, "Scope");
SearchFilter filters = parseFilters(req);
List<IncludedProperty> includedProperties = parseIncludedProperties(req);
Map<String, String> tags = parseTags(req);
View view = service.createView(region, viewName, scope, filters, includedProperties, tags);
var result = objectMapper.createObjectNode();
result.set("View", service.buildViewNode(view));
return Response.ok(result).build();
}
@POST
@Path("/GetView")
public Response getView(String body) throws IOException {
JsonNode req = parseBody(body);
String viewArn = optString(req, "ViewArn");
if (viewArn == null) {
throw new AwsException("ValidationException", "ViewArn is required", 400);
}
View view = service.getView(viewArn);
var result = objectMapper.createObjectNode();
result.set("View", service.buildViewNode(view));
result.set("Tags", objectMapper.valueToTree(
view.tags() != null ? view.tags() : Map.of()));
return Response.ok(result).build();
}
@POST
@Path("/DeleteView")
public Response deleteView(String body) throws IOException {
JsonNode req = parseBody(body);
String viewArn = optString(req, "ViewArn");
if (viewArn == null) {
throw new AwsException("ValidationException", "ViewArn is required", 400);
}
service.deleteView(viewArn);
var result = objectMapper.createObjectNode();
result.put("ViewArn", viewArn);
return Response.ok(result).build();
}
@POST
@Path("/UpdateView")
public Response updateView(String body) throws IOException {
JsonNode req = parseBody(body);
String viewArn = optString(req, "ViewArn");
if (viewArn == null) {
throw new AwsException("ValidationException", "ViewArn is required", 400);
}
SearchFilter filters = parseFilters(req);
List<IncludedProperty> includedProperties = parseIncludedProperties(req);
View view = service.updateView(viewArn, filters, includedProperties);
var result = objectMapper.createObjectNode();
result.set("View", service.buildViewNode(view));
return Response.ok(result).build();
}
@POST
@Path("/ListViews")
public Response listViews(@Context HttpHeaders headers, String body) throws IOException {
JsonNode req = parseBody(body);
Integer maxResults = validatedMaxResults(req, MAX_RESULTS_VIEWS);
String nextToken = optString(req, "NextToken");
String region = regionResolver.resolveRegion(headers);
return Response.ok(service.listViews(region, maxResults, nextToken)).build();
}
@POST
@Path("/BatchGetView")
public Response batchGetView(String body) throws IOException {
JsonNode req = parseBody(body);
return Response.ok(service.batchGetView(stringArray(req, "ViewArns"))).build();
}
@POST
@Path("/AssociateDefaultView")
public Response associateDefaultView(@Context HttpHeaders headers, String body) throws IOException {
JsonNode req = parseBody(body);
String viewArn = optString(req, "ViewArn");
if (viewArn == null) {
throw new AwsException("ValidationException", "ViewArn is required", 400);
}
service.associateDefaultView(regionResolver.resolveRegion(headers), viewArn);
var result = objectMapper.createObjectNode();
result.put("ViewArn", viewArn);
return Response.ok(result).build();
}
@POST
@Path("/DisassociateDefaultView")
public Response disassociateDefaultView(@Context HttpHeaders headers) {
service.disassociateDefaultView(regionResolver.resolveRegion(headers));
return Response.ok("{}").build();
}
@POST
@Path("/GetDefaultView")
public Response getDefaultView(@Context HttpHeaders headers) {
String viewArn = service.getDefaultView(regionResolver.resolveRegion(headers));
var result = objectMapper.createObjectNode();
if (viewArn != null) {
result.put("ViewArn", viewArn);
}
return Response.ok(result).build();
}
@POST
@Path("/GetAccountLevelServiceConfiguration")
public Response getAccountLevelServiceConfiguration() {
return Response.ok(service.getAccountLevelServiceConfiguration()).build();
}
@POST
@Path("/ListIndexesForMembers")
public Response listIndexesForMembers(String body) throws IOException {
JsonNode req = parseBody(body);
List<String> accountIds = stringArray(req, "AccountIdList");
if (accountIds.isEmpty()) {
throw new AwsException("ValidationException", "AccountIdList is required", 400);
}
Integer maxResults = validatedMaxResults(req, MAX_RESULTS_MEMBER_INDEXES);
String nextToken = optString(req, "NextToken");
return Response.ok(service.listIndexesForMembers(accountIds, maxResults, nextToken)).build();
}
@POST
@Path("/ListManagedViews")
public Response listManagedViews(String body) throws IOException {
JsonNode req = parseBody(body);
Integer maxResults = validatedMaxResults(req, MAX_RESULTS_VIEWS);
String nextToken = optString(req, "NextToken");
return Response.ok(service.listManagedViews(maxResults, nextToken)).build();
}
@POST
@Path("/GetManagedView")
public Response getManagedView(String body) throws IOException {
JsonNode req = parseBody(body);
String managedViewArn = optString(req, "ManagedViewArn");
if (managedViewArn == null) {
throw new AwsException("ValidationException", "ManagedViewArn is required", 400);
}
return Response.ok(service.getManagedView(managedViewArn)).build();
}
@POST
@Path("/ListServiceViews")
public Response listServiceViews(String body) throws IOException {
JsonNode req = parseBody(body);
Integer maxResults = validatedMaxResults(req, MAX_RESULTS_VIEWS);
String nextToken = optString(req, "NextToken");
return Response.ok(service.listServiceViews(maxResults, nextToken)).build();
}
@POST
@Path("/GetServiceView")
public Response getServiceView(String body) throws IOException {
JsonNode req = parseBody(body);
String serviceViewArn = optString(req, "ServiceViewArn");
if (serviceViewArn == null) {
throw new AwsException("ValidationException", "ServiceViewArn is required", 400);
}
return Response.ok(service.getServiceView(serviceViewArn)).build();
}
@POST
@Path("/ListServiceIndexes")
public Response listServiceIndexes(String body) throws IOException {
JsonNode req = parseBody(body);
List<String> regions = stringArray(req, "Regions");
Integer maxResults = validatedMaxResults(req, MAX_RESULTS_INDEXES);
String nextToken = optString(req, "NextToken");
return Response.ok(service.listServiceIndexes(regions, maxResults, nextToken)).build();
}
@POST
@Path("/GetServiceIndex")
public Response getServiceIndex(@Context HttpHeaders headers) {
return Response.ok(service.getServiceIndex(regionResolver.resolveRegion(headers))).build();
}
@POST
@Path("/ListStreamingAccessForServices")
public Response listStreamingAccessForServices(String body) throws IOException {
JsonNode req = parseBody(body);
Integer maxResults = validatedMaxResults(req, MAX_RESULTS_VIEWS);
String nextToken = optString(req, "NextToken");
return Response.ok(service.listStreamingAccessForServices(maxResults, nextToken)).build();
}
@POST
@Path("/CreateResourceExplorerSetup")
public Response createResourceExplorerSetup(String body) throws IOException {
JsonNode req = parseBody(body);
String taskId = service.createResourceExplorerSetup(
stringArray(req, "RegionList"),
optString(req, "ViewName"),
stringArray(req, "AggregatorRegions"));
var result = objectMapper.createObjectNode();
result.put("TaskId", taskId);
return Response.ok(result).build();
}
@POST
@Path("/DeleteResourceExplorerSetup")
public Response deleteResourceExplorerSetup(String body) throws IOException {
JsonNode req = parseBody(body);
Boolean deleteInAllRegions = req.has("DeleteInAllRegions")
? req.get("DeleteInAllRegions").asBoolean() : null;
String taskId = service.deleteResourceExplorerSetup(
deleteInAllRegions, stringArray(req, "RegionList"));
var result = objectMapper.createObjectNode();
result.put("TaskId", taskId);
return Response.ok(result).build();
}
@POST
@Path("/GetResourceExplorerSetup")
public Response getResourceExplorerSetup(String body) throws IOException {
JsonNode req = parseBody(body);
String taskId = optString(req, "TaskId");
if (taskId == null) {
throw new AwsException("ValidationException", "TaskId is required", 400);
}
Integer maxResults = validatedMaxResults(req, MAX_RESULTS_INDEXES);
String nextToken = optString(req, "NextToken");
return Response.ok(service.getResourceExplorerSetup(taskId, maxResults, nextToken)).build();
}
private static List<String> stringArray(JsonNode req, String field) {
List<String> values = new ArrayList<>();
if (req.has(field) && req.get(field).isArray()) {
for (JsonNode value : req.get(field)) {
values.add(value.asText());
}
}
return values;
}
private static String optString(JsonNode req, String field) {
return req.has(field) ? req.get(field).asText(null) : null;
}
private JsonNode parseBody(String body) throws IOException {
return objectMapper.readTree(body == null || body.isBlank() ? "{}" : body);
}
private Map<String, String> parseTags(JsonNode req) {
Map<String, String> tags = new HashMap<>();
if (req.has("Tags") && req.get("Tags").isObject()) {
req.get("Tags").fields().forEachRemaining(e -> tags.put(e.getKey(), e.getValue().asText()));
}
return tags;
}
private SearchFilter parseFilters(JsonNode req) {
return req.has("Filters") && req.get("Filters").has("FilterString")
? new SearchFilter(req.get("Filters").get("FilterString").asText()) : null;
}
private List<IncludedProperty> parseIncludedProperties(JsonNode req) {
List<IncludedProperty> includedProperties = new ArrayList<>();
if (req.has("IncludedProperties") && req.get("IncludedProperties").isArray()) {
for (var p : req.get("IncludedProperties")) {
includedProperties.add(new IncludedProperty(p.has("Name") ? p.get("Name").asText() : ""));
}
}
return includedProperties;
}
private Integer validatedMaxResults(JsonNode req, int max) {
if (!req.has("MaxResults")) {
return null;
}
int value = req.get("MaxResults").intValue();
if (value < 1 || value > max) {
throw new AwsException("ValidationException", "MaxResults must be between 1 and " + max, 400);
}
return value;
}
}
@@ -0,0 +1,75 @@
package io.github.hectorvent.floci.services.resourceexplorer2;
import io.github.hectorvent.floci.core.common.ResolvedServiceCatalog;
import io.github.hectorvent.floci.core.common.ServiceDescriptor;
import io.github.hectorvent.floci.core.common.SigV4CredentialScope;
import jakarta.inject.Inject;
import jakarta.ws.rs.container.ContainerRequestContext;
import jakarta.ws.rs.container.ContainerRequestFilter;
import jakarta.ws.rs.container.PreMatching;
import jakarta.ws.rs.ext.Provider;
import java.util.Set;
/**
* Pre-matching filter that disambiguates Resource Explorer 2 endpoints from S3 Vectors
* endpoints that share the same JAX-RS path names ({@code /CreateIndex}, {@code /GetIndex},
* {@code /ListIndexes}, {@code /DeleteIndex}).
*
* <p>Both are REST-JSON services rooted at {@code /}, so JAX-RS cannot tell their identically
* named operations apart. Floci resolves this the same way {@code AwsQueryController} resolves
* query-protocol services: by the SigV4 credential scope, looked up in the
* {@link ResolvedServiceCatalog}. When the scope resolves to the Resource Explorer 2 service,
* the conflicting path is rewritten to the {@code /re2/} prefix so it reaches
* {@link ResourceExplorer2Controller}; otherwise it falls through to the S3 Vectors controller.
*
* <p>All other Resource Explorer 2 paths (e.g. {@code /ListResources}, {@code /Search}) are
* unique across controllers and need no rewriting.
*/
@Provider
@PreMatching
public class ResourceExplorer2PathRewriteFilter implements ContainerRequestFilter {
private static final String RESOURCE_EXPLORER_2 = "resource-explorer-2";
// Mirror of the index operation paths declared by S3VectorsController. A colliding path missing
// from this set falls through to S3 Vectors even for Resource Explorer 2 callers.
private static final Set<String> AMBIGUOUS_PATHS = Set.of(
"/CreateIndex",
"/GetIndex",
"/ListIndexes",
"/DeleteIndex"
);
private final ResolvedServiceCatalog catalog;
@Inject
public ResourceExplorer2PathRewriteFilter(ResolvedServiceCatalog catalog) {
this.catalog = catalog;
}
@Override
public void filter(ContainerRequestContext ctx) {
String path = ctx.getUriInfo().getPath();
String normalizedPath = path.startsWith("/") ? path : "/" + path;
if (!AMBIGUOUS_PATHS.contains(normalizedPath)) {
return;
}
boolean targetsResourceExplorer2 =
SigV4CredentialScope.serviceName(ctx.getHeaderString("Authorization"))
.flatMap(catalog::byCredentialScope)
.map(ServiceDescriptor::externalKey)
.filter(RESOURCE_EXPLORER_2::equals)
.isPresent();
if (!targetsResourceExplorer2) {
return;
}
ctx.setRequestUri(ctx.getUriInfo().getRequestUriBuilder()
.replacePath("/re2" + normalizedPath)
.build());
}
}
@@ -0,0 +1,46 @@
package io.github.hectorvent.floci.services.resourceexplorer2;
import io.github.hectorvent.floci.core.common.TagHandler;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import java.util.List;
import java.util.Map;
/**
* Handles tag operations on Resource Explorer 2 indexes and views.
*
* <p>Discovered by {@link io.github.hectorvent.floci.core.common.SharedTagsController}
* via CDI. Routes {@code /tags/{arn}} requests where the ARN service segment is
* {@code "resource-explorer-2"}.
*/
@ApplicationScoped
public class ResourceExplorer2TagHandler implements TagHandler {
private final ResourceExplorer2Service service;
@Inject
public ResourceExplorer2TagHandler(ResourceExplorer2Service service) {
this.service = service;
}
@Override
public String serviceKey() {
return "resource-explorer-2";
}
@Override
public Map<String, String> listTags(String region, String arn) {
return service.listTags(arn);
}
@Override
public void tagResource(String region, String arn, Map<String, String> tags) {
service.tagResource(arn, tags);
}
@Override
public void untagResource(String region, String arn, List<String> tagKeys) {
service.untagResource(arn, tagKeys);
}
}
@@ -0,0 +1,7 @@
package io.github.hectorvent.floci.services.resourceexplorer2.model;
import io.quarkus.runtime.annotations.RegisterForReflection;
/** A property included in search results. Currently only {@code "tags"} is supported. */
@RegisterForReflection
public record IncludedProperty(String name) {}
@@ -0,0 +1,43 @@
package io.github.hectorvent.floci.services.resourceexplorer2.model;
import io.quarkus.runtime.annotations.RegisterForReflection;
import java.time.Instant;
import java.util.List;
import java.util.Map;
@RegisterForReflection
public record Index(
String arn,
String region,
IndexType type,
IndexState state,
Map<String, String> tags,
Instant createdAt,
Instant lastUpdatedAt,
List<String> replicatingFrom,
List<String> replicatingTo) implements Taggable {
/** New index: lastUpdatedAt tracks createdAt, replication lists start empty. */
public Index(String arn, String region, IndexType type, IndexState state,
Map<String, String> tags, Instant createdAt) {
this(arn, region, type, state, tags, createdAt, createdAt, List.of(), List.of());
}
public Index withState(IndexState state) {
return new Index(arn, region, type, state, tags, createdAt, lastUpdatedAt, replicatingFrom, replicatingTo);
}
public Index withType(IndexType type) {
return new Index(arn, region, type, state, tags, createdAt, lastUpdatedAt, replicatingFrom, replicatingTo);
}
public Index withLastUpdatedAt(Instant lastUpdatedAt) {
return new Index(arn, region, type, state, tags, createdAt, lastUpdatedAt, replicatingFrom, replicatingTo);
}
@Override
public Index withTags(Map<String, String> tags) {
return new Index(arn, region, type, state, tags, createdAt, lastUpdatedAt, replicatingFrom, replicatingTo);
}
}
@@ -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
}
@@ -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
}
@@ -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) {}
@@ -0,0 +1,34 @@
package io.github.hectorvent.floci.services.resourceexplorer2.model;
import io.quarkus.runtime.annotations.RegisterForReflection;
/**
* The result of one step (index or view) of a Resource Explorer setup task in one AWS Region.
*
* <p>floci runs a setup task synchronously, so a step is finished the moment
* {@code CreateResourceExplorerSetup} or {@code DeleteResourceExplorerSetup} returns and the
* status is terminal — {@code SUCCEEDED} or {@code FAILED}. On a failure the AWS
* {@code ErrorDetails} fields carry the same code and message the equivalent single-Region call
* would have thrown, which is why one Region failing does not abandon the rest of the task.
*
* @param status {@code SUCCEEDED} or {@code FAILED}
* @param arn the index or view ARN the step produced; null for a delete or a failure
* @param errorCode AWS error code when {@code status} is {@code FAILED}, else null
* @param errorMessage AWS error message when {@code status} is {@code FAILED}, else null
* @see <a href="https://docs.aws.amazon.com/resource-explorer/latest/apireference/API_GetResourceExplorerSetup.html">
* AWS API: GetResourceExplorerSetup</a>
*/
@RegisterForReflection
public record SetupOutcome(String status, String arn, String errorCode, String errorMessage) {
public static final String SUCCEEDED = "SUCCEEDED";
public static final String FAILED = "FAILED";
public static SetupOutcome succeeded(String arn) {
return new SetupOutcome(SUCCEEDED, arn, null, null);
}
public static SetupOutcome failed(String errorCode, String errorMessage) {
return new SetupOutcome(FAILED, null, errorCode, errorMessage);
}
}
@@ -0,0 +1,25 @@
package io.github.hectorvent.floci.services.resourceexplorer2.model;
import io.quarkus.runtime.annotations.RegisterForReflection;
import java.time.Instant;
import java.util.List;
/**
* A completed multi-Region setup task, addressable by {@code TaskId} through
* {@code GetResourceExplorerSetup}.
*
* <p>The per-Region outcomes are recorded when the task runs rather than recomputed on read: a
* delete task removes the very indexes and views its status describes, so there would be nothing
* left to derive them from afterwards.
*
* @see <a href="https://docs.aws.amazon.com/resource-explorer/latest/apireference/API_CreateResourceExplorerSetup.html">
* AWS API: CreateResourceExplorerSetup</a>
*/
@RegisterForReflection
public record SetupTask(String taskId, List<RegionOutcome> regions, Instant createdAt) {
/** One Region's index and view outcome. Either may be null when the task did not touch it. */
@RegisterForReflection
public record RegionOutcome(String region, SetupOutcome index, SetupOutcome view) {}
}
@@ -0,0 +1,9 @@
package io.github.hectorvent.floci.services.resourceexplorer2.model;
import java.util.Map;
/** A resource carrying mutable tags. Implementations are immutable records; {@link #withTags} returns a copy. */
public interface Taggable {
Map<String, String> tags();
Taggable withTags(Map<String, String> tags);
}
@@ -0,0 +1,42 @@
package io.github.hectorvent.floci.services.resourceexplorer2.model;
import io.quarkus.runtime.annotations.RegisterForReflection;
import java.time.Instant;
import java.util.List;
import java.util.Map;
@RegisterForReflection
public record View(
String viewArn,
String viewName,
String owner,
String scope,
SearchFilter filters,
List<IncludedProperty> includedProperties,
Map<String, String> tags,
Instant lastUpdatedAt) implements Taggable {
public View withFilters(SearchFilter filters) {
return new View(viewArn, viewName, owner, scope, filters, includedProperties, tags, lastUpdatedAt);
}
public View withIncludedProperties(List<IncludedProperty> includedProperties) {
return new View(viewArn, viewName, owner, scope, filters, includedProperties, tags, lastUpdatedAt);
}
public View withLastUpdatedAt(Instant lastUpdatedAt) {
return new View(viewArn, viewName, owner, scope, filters, includedProperties, tags, lastUpdatedAt);
}
@Override
public View withTags(Map<String, String> tags) {
return new View(viewArn, viewName, owner, scope, filters, includedProperties, tags, lastUpdatedAt);
}
/** Whether this view includes tag data in results. */
public boolean includesTags() {
return includedProperties != null &&
includedProperties.stream().anyMatch(p -> "tags".equals(p.name()));
}
}
@@ -0,0 +1,43 @@
package io.github.hectorvent.floci.services.resourceexplorer2.query;
import io.quarkus.runtime.annotations.RegisterForReflection;
import java.util.Locale;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.Stream;
/**
* Known filter attributes in Resource Explorer query syntax.
*/
@RegisterForReflection
public enum FilterAttribute {
ACCOUNT_ID("accountid"),
APPLICATION("application"),
ID("id"),
REGION("region"),
RESOURCE_TYPE("resourcetype"),
RESOURCE_TYPE_SUPPORTS("resourcetype.supports"),
SERVICE("service"),
TAG("tag"),
TAG_KEY("tag.key"),
TAG_VALUE("tag.value");
private static final Map<String, FilterAttribute> BY_PREFIX =
Stream.of(values()).collect(Collectors.toMap(
a -> a.prefix.toLowerCase(Locale.ROOT), a -> a));
private final String prefix;
FilterAttribute(String prefix) {
this.prefix = prefix;
}
public String prefix() {
return prefix;
}
public static FilterAttribute fromPrefix(String prefix) {
return BY_PREFIX.get(prefix.toLowerCase(Locale.ROOT));
}
}
@@ -0,0 +1,25 @@
package io.github.hectorvent.floci.services.resourceexplorer2.query;
import io.quarkus.runtime.annotations.RegisterForReflection;
import java.util.List;
@RegisterForReflection
public record ParsedQuery(
List<Keyword> keywords,
List<Filter> filters
) {
@RegisterForReflection
public record Keyword(String value, boolean negated) {}
@RegisterForReflection
public record Filter(
FilterAttribute attribute,
List<FilterValue> values,
boolean negated
) {}
@RegisterForReflection
public record FilterValue(String value, boolean prefixMatch) {}
}
@@ -0,0 +1,211 @@
package io.github.hectorvent.floci.services.resourceexplorer2.query;
import java.util.ArrayList;
import java.util.List;
/**
* Hand-written character-by-character parser for Resource Explorer query syntax.
*
* <p>Supports: filter prefixes ({@code service:}, {@code region:}, etc.),
* comma-OR, negation ({@code -}), wildcards ({@code *}), quoted strings,
* backslash escaping, and free-form text keywords.
*
* <p>Escapes survive tokenization intact and are resolved only where the meaning of the
* character is decided — splitting a filter's comma-separated values, finding the colon that
* separates a filter prefix from its value, and recognising a trailing wildcard. That ordering
* is what makes {@code tag.key:comma\,literal} one value rather than two, and
* {@code "my\-key\-word"} a keyword rather than a negation.
*
* @see <a href="https://docs.aws.amazon.com/resource-explorer/latest/userguide/using-search-query-syntax.html">
* Search query syntax reference</a>
*/
public final class QueryParser {
/**
* Characters that carry meaning to the parser and therefore have to be neutralised when they
* appear inside a quoted phrase, which AWS defines as literal text.
*/
private static final String OPERATOR_CHARACTERS = "*\"-:=\\,";
private QueryParser() {}
public static ParsedQuery parse(String input) {
if (input == null || input.isBlank()) {
return new ParsedQuery(List.of(), List.of());
}
List<String> tokens = tokenize(input);
return classify(tokens);
}
// Rejects free-form text — ListResources only accepts filter prefixes.
public static ParsedQuery parseFilterOnly(String input) {
ParsedQuery query = parse(input);
if (!query.keywords().isEmpty()) {
throw new IllegalArgumentException(
"ListResources FilterString does not support free-form text. " +
"Use only filter prefixes (e.g., service:ec2, region:us-east-1).");
}
return query;
}
static List<String> tokenize(String input) {
List<String> tokens = new ArrayList<>();
StringBuilder current = new StringBuilder();
boolean inQuotes = false;
// Tracks whether the current token has any content, including a quoted empty string.
boolean hadContent = false;
for (int i = 0; i < input.length(); i++) {
char c = input.charAt(i);
if (c == '\\' && i + 1 < input.length()) {
current.append(c).append(input.charAt(i + 1));
i++;
hadContent = true;
continue;
}
if (c == '"') {
inQuotes = !inQuotes;
hadContent = true;
continue;
}
if (!inQuotes && Character.isWhitespace(c)) {
if (hadContent) {
tokens.add(current.toString());
current.setLength(0);
hadContent = false;
}
continue;
}
if (inQuotes && OPERATOR_CHARACTERS.indexOf(c) >= 0) {
current.append('\\');
}
current.append(c);
hadContent = true;
}
if (hadContent) {
tokens.add(current.toString());
}
return tokens;
}
private static ParsedQuery classify(List<String> tokens) {
List<ParsedQuery.Keyword> keywords = new ArrayList<>();
List<ParsedQuery.Filter> filters = new ArrayList<>();
for (String token : tokens) {
boolean negated = false;
String working = token;
if (working.startsWith("-")) {
negated = true;
working = working.substring(1);
}
int colonIndex = indexOfUnescaped(working, ':');
FilterAttribute attribute = colonIndex >= 0
? FilterAttribute.fromPrefix(unescape(working.substring(0, colonIndex)))
: null;
if (attribute != null) {
String valuePortion = working.substring(colonIndex + 1);
List<ParsedQuery.FilterValue> values = parseFilterValues(valuePortion);
filters.add(new ParsedQuery.Filter(attribute, values, negated));
} else {
keywords.add(new ParsedQuery.Keyword(toKeywordValue(working), negated));
}
}
return new ParsedQuery(keywords, filters);
}
/**
* A trailing wildcard is dropped rather than recorded: keyword matching is a substring test,
* so {@code ec2*} and {@code ec2} already select the same resources. Dropping it only where it
* is unescaped keeps a literal {@code \*} searchable.
*/
private static String toKeywordValue(String raw) {
String value = endsWithUnescaped(raw, '*') ? raw.substring(0, raw.length() - 1) : raw;
return unescape(value);
}
private static List<ParsedQuery.FilterValue> parseFilterValues(String valuePortion) {
List<ParsedQuery.FilterValue> values = new ArrayList<>();
for (String raw : splitUnescaped(valuePortion, ',')) {
values.add(toFilterValue(raw));
}
return values;
}
private static ParsedQuery.FilterValue toFilterValue(String raw) {
if (endsWithUnescaped(raw, '*')) {
return new ParsedQuery.FilterValue(unescape(raw.substring(0, raw.length() - 1)), true);
}
return new ParsedQuery.FilterValue(unescape(raw), false);
}
private static int indexOfUnescaped(String value, char target) {
for (int i = 0; i < value.length(); i++) {
char c = value.charAt(i);
if (c == '\\') {
i++;
continue;
}
if (c == target) {
return i;
}
}
return -1;
}
private static List<String> splitUnescaped(String value, char separator) {
List<String> parts = new ArrayList<>();
StringBuilder current = new StringBuilder();
for (int i = 0; i < value.length(); i++) {
char c = value.charAt(i);
if (c == '\\' && i + 1 < value.length()) {
current.append(c).append(value.charAt(i + 1));
i++;
continue;
}
if (c == separator) {
parts.add(current.toString());
current.setLength(0);
continue;
}
current.append(c);
}
parts.add(current.toString());
return parts;
}
private static boolean endsWithUnescaped(String value, char target) {
if (value.isEmpty() || value.charAt(value.length() - 1) != target) {
return false;
}
int backslashes = 0;
for (int i = value.length() - 2; i >= 0 && value.charAt(i) == '\\'; i--) {
backslashes++;
}
return backslashes % 2 == 0;
}
/** Resolves escape sequences. A backslash with nothing after it is literal text, as AWS treats it. */
private static String unescape(String value) {
StringBuilder out = new StringBuilder(value.length());
for (int i = 0; i < value.length(); i++) {
char c = value.charAt(i);
if (c == '\\' && i + 1 < value.length()) {
out.append(value.charAt(i + 1));
i++;
continue;
}
out.append(c);
}
return out.toString();
}
}
@@ -0,0 +1,224 @@
package io.github.hectorvent.floci.services.resourceexplorer2.query;
import io.github.hectorvent.floci.core.resource.ExplorerResource;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
/**
* Evaluates whether a resource matches a parsed query.
*
* <p>Filters are AND'd and values within one filter are OR'd, as AWS documents. Free-form
* keywords are OR'd with each other: {@code ec2 billing} selects a resource matching either.
* A negated keyword or filter excludes.
*
* <p><strong>Deviation.</strong> AWS never excludes a resource for failing to match a free-form
* keyword — it ranks it lower and still returns it, so a keyword-only query in a live account
* returns everything. floci has no relevance model and returns matches only, which is the
* behaviour that makes {@code Search} useful locally. Filter matching, which AWS documents as
* deterministic, is exact.
*
* @see <a href="https://docs.aws.amazon.com/resource-explorer/latest/userguide/using-search-query-syntax.html">
* Search query syntax reference</a>
*/
public final class ResourceFilter {
/** The one value AWS accepts for {@code resourcetype.supports:}. */
private static final String SUPPORTS_TAGS = "tags";
/** Tag key AWS writes on resources that belong to an application (myApplications). */
private static final String APPLICATION_TAG = "awsApplication";
private ResourceFilter() {}
/**
* @param taggableResourceTypes resource types whose provider advertises tag support, used by
* the {@code resourcetype.supports:tags} filter. Pass the set gathered from every
* {@link io.github.hectorvent.floci.core.resource.ResourceProvider}.
*/
public static boolean matches(ExplorerResource resource, ParsedQuery query,
Set<String> taggableResourceTypes) {
for (var filter : query.filters()) {
boolean anyValueMatches = filter.values().stream()
.anyMatch(v -> matchesValue(resource, filter.attribute(), v, taggableResourceTypes));
if (filter.negated()) {
anyValueMatches = !anyValueMatches;
}
if (!anyValueMatches) {
return false;
}
}
return matchesKeywords(resource, query.keywords());
}
/**
* Positive keywords are OR'd, so a resource matching any one of them qualifies; a negated
* keyword excludes regardless of the others. A query of negations alone matches everything
* they do not exclude.
*/
private static boolean matchesKeywords(ExplorerResource resource, List<ParsedQuery.Keyword> keywords) {
boolean sawPositive = false;
boolean anyPositiveMatched = false;
for (var keyword : keywords) {
boolean matched = matchesKeyword(resource, keyword.value());
if (keyword.negated()) {
if (matched) {
return false;
}
continue;
}
sawPositive = true;
anyPositiveMatched = anyPositiveMatched || matched;
}
return !sawPositive || anyPositiveMatched;
}
public static ParsedQuery combine(ParsedQuery viewFilter, ParsedQuery requestFilter) {
List<ParsedQuery.Keyword> keywords = new ArrayList<>(viewFilter.keywords());
keywords.addAll(requestFilter.keywords());
List<ParsedQuery.Filter> filters = new ArrayList<>(viewFilter.filters());
filters.addAll(requestFilter.filters());
return new ParsedQuery(keywords, filters);
}
/** Whether the query names a filter that AWS only honours on a view carrying tag data. */
public static boolean usesTagData(ParsedQuery query) {
return query.filters().stream().anyMatch(f -> switch (f.attribute()) {
case TAG, TAG_KEY, TAG_VALUE, APPLICATION -> true;
default -> false;
});
}
private static boolean matchesValue(ExplorerResource resource, FilterAttribute attr,
ParsedQuery.FilterValue filterValue,
Set<String> taggableResourceTypes) {
return switch (attr) {
case REGION -> compareString(resource.region(), filterValue);
case SERVICE -> compareString(resource.service(), filterValue);
case RESOURCE_TYPE -> compareString(resource.resourceType(), filterValue);
case ACCOUNT_ID -> compareString(resource.owningAccountId(), filterValue);
case ID -> compareString(resource.arn(), filterValue);
case APPLICATION -> matchesApplication(resource, filterValue);
case TAG -> matchesTag(resource, filterValue);
case TAG_KEY -> matchesTagKey(resource, filterValue);
case TAG_VALUE -> matchesTagValue(resource, filterValue);
case RESOURCE_TYPE_SUPPORTS -> SUPPORTS_TAGS.equalsIgnoreCase(filterValue.value())
&& taggableResourceTypes.contains(resource.resourceType());
};
}
private static boolean compareString(String actual, ParsedQuery.FilterValue filter) {
if (actual == null) {
return false;
}
String actualLower = actual.toLowerCase(Locale.ROOT);
String filterLower = filter.value().toLowerCase(Locale.ROOT);
if (filter.prefixMatch()) {
return actualLower.startsWith(filterLower);
}
return actualLower.equals(filterLower);
}
private static boolean matchesTag(ExplorerResource resource, ParsedQuery.FilterValue filterValue) {
String val = filterValue.value();
if ("all".equalsIgnoreCase(val)) {
return resource.tags() != null && !resource.tags().isEmpty();
}
if ("none".equalsIgnoreCase(val)) {
return resource.tags() == null || resource.tags().isEmpty();
}
int eq = val.indexOf('=');
if (eq < 0) {
return false;
}
String tagKey = val.substring(0, eq);
String tagValue = val.substring(eq + 1);
Map<String, String> tags = resource.tags();
if (tags == null) {
return false;
}
return tags.entrySet().stream().anyMatch(e ->
e.getKey().equalsIgnoreCase(tagKey) && e.getValue().equalsIgnoreCase(tagValue));
}
private static boolean matchesTagKey(ExplorerResource resource, ParsedQuery.FilterValue filterValue) {
Map<String, String> tags = resource.tags();
if (tags == null) {
return false;
}
return tags.keySet().stream().anyMatch(k -> compareTagString(k, filterValue));
}
private static boolean matchesTagValue(ExplorerResource resource, ParsedQuery.FilterValue filterValue) {
Map<String, String> tags = resource.tags();
if (tags == null) {
return false;
}
return tags.values().stream().anyMatch(v -> compareTagString(v, filterValue));
}
private static boolean compareTagString(String actual, ParsedQuery.FilterValue filter) {
String actualLower = actual.toLowerCase(Locale.ROOT);
String filterLower = filter.value().toLowerCase(Locale.ROOT);
if (filter.prefixMatch()) {
return actualLower.startsWith(filterLower);
}
return actualLower.equals(filterLower);
}
/**
* AWS accepts either the application's resource-group ARN or its name, so both are compared
* against the {@code awsApplication} tag — which itself always holds the ARN.
*/
private static boolean matchesApplication(ExplorerResource resource, ParsedQuery.FilterValue filterValue) {
Map<String, String> tags = resource.tags();
if (tags == null) {
return false;
}
String appTag = tags.get(APPLICATION_TAG);
if (appTag == null) {
return false;
}
return compareString(appTag, filterValue)
|| compareString(applicationNameOf(appTag), filterValue);
}
/** Extracts {@code MyApp} from {@code arn:aws:resource-groups:…:group/MyApp/0123abc}. */
private static String applicationNameOf(String applicationArn) {
int groupIndex = applicationArn.indexOf("group/");
if (groupIndex < 0) {
return null;
}
String remainder = applicationArn.substring(groupIndex + "group/".length());
int separator = remainder.indexOf('/');
return separator < 0 ? remainder : remainder.substring(0, separator);
}
/**
* A free-form keyword matches any part of the resource's identity or its tags — AWS states it
* can "match things like a tag key name or a piece of an ARN".
*/
private static boolean matchesKeyword(ExplorerResource resource, String keyword) {
String lower = keyword.toLowerCase(Locale.ROOT);
if (containsIgnoreCase(resource.arn(), lower)
|| containsIgnoreCase(resource.resourceType(), lower)
|| containsIgnoreCase(resource.service(), lower)
|| containsIgnoreCase(resource.region(), lower)) {
return true;
}
Map<String, String> tags = resource.tags();
if (tags == null) {
return false;
}
return tags.entrySet().stream().anyMatch(e ->
containsIgnoreCase(e.getKey(), lower) || containsIgnoreCase(e.getValue(), lower));
}
private static boolean containsIgnoreCase(String actual, String lowercaseNeedle) {
return actual != null && actual.toLowerCase(Locale.ROOT).contains(lowercaseNeedle);
}
}
@@ -41,6 +41,14 @@ public class ResourceGroupsTaggingService implements Resettable {
return region + "::" + arn;
}
/**
* Returns the tags for a single resource, or an empty map if no tags have been applied.
*/
public Map<String, String> getTagsForResource(String region, String arn) {
ResourceTagMapping mapping = store.get(key(region, arn));
return mapping != null ? Collections.unmodifiableMap(mapping.getTags()) : Map.of();
}
// ─── TagResources ──────────────────────────────────────────────────────────
// Mutators are synchronized: StorageBackedMap has no atomic computeIfAbsent, so
@@ -4,7 +4,12 @@ import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.JsonNodeFactory;
import com.fasterxml.jackson.databind.node.ObjectNode;
import io.github.hectorvent.floci.core.common.AwsArnUtils;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.common.RegionResolver;
import io.github.hectorvent.floci.core.resource.ExplorerResource;
import io.github.hectorvent.floci.core.resource.ResourceProvider;
import io.github.hectorvent.floci.core.resource.SupportedResourceType;
import io.github.hectorvent.floci.core.storage.StorageBackend;
import io.github.hectorvent.floci.core.storage.StorageFactory;
import io.github.hectorvent.floci.services.rum.model.AppMonitor;
@@ -13,6 +18,7 @@ import jakarta.inject.Inject;
import java.nio.charset.StandardCharsets;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
@@ -27,7 +33,10 @@ import java.util.regex.Pattern;
/** CloudWatch RUM app-monitor lifecycle backed by the configured Floci storage mode. */
@ApplicationScoped
public class RumService {
public class RumService implements ResourceProvider {
private static final String SERVICE = "rum";
private static final String RESOURCE_APP_MONITOR = "appmonitor";
private static final int DEFAULT_MAX_RESULTS = 50;
private static final int MAX_RESULTS = 100;
@@ -49,18 +58,20 @@ public class RumService {
private static final Set<String> PLATFORMS = Set.of("Web", "Android", "iOS");
private final StorageBackend<String, AppMonitor> monitorStore;
private final RegionResolver regionResolver;
@Inject
public RumService(StorageFactory storageFactory) {
public RumService(StorageFactory storageFactory, RegionResolver regionResolver) {
this(storageFactory.create(
"rum",
"rum-app-monitors.json",
new TypeReference<Map<String, AppMonitor>>() {
}));
}), regionResolver);
}
RumService(StorageBackend<String, AppMonitor> monitorStore) {
RumService(StorageBackend<String, AppMonitor> monitorStore, RegionResolver regionResolver) {
this.monitorStore = monitorStore;
this.regionResolver = regionResolver;
}
public synchronized AppMonitor createAppMonitor(String region, JsonNode request) {
@@ -97,6 +108,7 @@ public class RumService {
dataStorage(cwLogEnabled),
customEvents,
deobfuscation);
monitor.setOwnerAccountId(regionResolver.getAccountId());
monitorStore.put(key, monitor);
return monitor;
}
@@ -152,6 +164,7 @@ public class RumService {
storage,
customEvents,
deobfuscation);
updated.setOwnerAccountId(current.getOwnerAccountId());
monitorStore.put(key, updated);
}
@@ -175,6 +188,57 @@ public class RumService {
return new Page(monitors.subList(offset, end), responseToken);
}
@Override
public List<ExplorerResource> getResources() {
// RUM's stored model carries neither an ARN nor a region (its GetAppMonitor response has no
// such fields), so the region is recovered from the storage key and the ARN is rebuilt here.
// The owning account is the one captured when the monitor was created, not the account of the
// caller listing resources. Monitors reloaded from disk carry no owner account (the field is
// transient), but monitorStore.keys() is already scoped to the calling account by the
// account-aware backend, so a monitor reachable here is owned by that caller by construction.
List<ExplorerResource> resources = new ArrayList<>();
for (String key : monitorStore.keys()) {
AppMonitor monitor = monitorStore.get(key).orElse(null);
if (monitor == null) {
continue;
}
String region = regionFromKey(key);
String accountId = monitor.getOwnerAccountId() != null
? monitor.getOwnerAccountId()
: regionResolver.getAccountId();
String arn = AwsArnUtils.Arn.of(SERVICE, region, accountId,
RESOURCE_APP_MONITOR + "/" + monitor.getName()).toString();
resources.add(new ExplorerResource(
arn, SERVICE + ":" + RESOURCE_APP_MONITOR, SERVICE,
region, accountId,
reportedAt(monitor.getCreated()),
monitor.getTags() != null ? monitor.getTags() : Map.of()));
}
return resources;
}
private static String regionFromKey(String key) {
int separator = key.indexOf("::");
return separator > 0 ? key.substring(0, separator) : key;
}
@Override
public Set<SupportedResourceType> getSupportedResourceTypes() {
return Set.of(new SupportedResourceType(
SERVICE + ":" + RESOURCE_APP_MONITOR, SERVICE, true));
}
private static Instant reportedAt(String created) {
if (created == null) {
return Instant.now();
}
try {
return LocalDateTime.parse(created, TIMESTAMP_FORMATTER).toInstant(ZoneOffset.UTC);
} catch (RuntimeException e) {
return Instant.now();
}
}
private static String storageKey(String region, String name) {
return region + "::" + name;
}
@@ -1,5 +1,6 @@
package io.github.hectorvent.floci.services.rum.model;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.PropertyNamingStrategies;
@@ -28,6 +29,14 @@ public class AppMonitor {
private JsonNode customEvents;
private JsonNode deobfuscationConfiguration;
// The account that created this monitor, captured so Resource Explorer 2 can report the true
// owning account in the reconstructed ARN. RUM's GetAppMonitor response has no ARN or account
// field, so this is @JsonIgnore'd to keep it out of the API body; it is likewise not persisted,
// so getResources() recovers the owner from the account-scoped storage key for monitors
// reloaded from disk.
@JsonIgnore
private String ownerAccountId;
public AppMonitor() {
}
@@ -164,6 +173,16 @@ public class AppMonitor {
this.deobfuscationConfiguration = copy(deobfuscationConfiguration);
}
@JsonIgnore
public String getOwnerAccountId() {
return ownerAccountId;
}
@JsonIgnore
public void setOwnerAccountId(String ownerAccountId) {
this.ownerAccountId = ownerAccountId;
}
private static JsonNode copy(JsonNode value) {
return value == null ? null : value.deepCopy();
}
@@ -44,9 +44,12 @@ import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.locks.ReentrantLock;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import io.github.hectorvent.floci.core.resource.ExplorerResource;
import io.github.hectorvent.floci.core.resource.ResourceProvider;
import io.github.hectorvent.floci.core.resource.SupportedResourceType;
@ApplicationScoped
public class S3Service implements Resettable {
public class S3Service implements Resettable, ResourceProvider {
private String ownerId() { return regionResolver != null ? regionResolver.getAccountId() : "000000000000"; }
private static final String DEFAULT_OWNER_DISPLAY_NAME = "floci";
private static final String AUTHENTICATED_USERS_GROUP_URI = "http://acs.amazonaws.com/groups/global/AuthenticatedUsers";
@@ -3423,4 +3426,25 @@ public class S3Service implements Resettable {
fireNotifications(destBucket, destKey, "ObjectCreated:Copy", copy);
return copy;
}
@Override
public List<ExplorerResource> getResources() {
List<ExplorerResource> resources = new ArrayList<>();
for (Bucket bucket : listBuckets()) {
resources.add(new ExplorerResource(
"arn:aws:s3:::" + bucket.getName(),
"s3:bucket",
"s3",
bucket.getRegion() != null ? bucket.getRegion() : regionResolver.getDefaultRegion(),
regionResolver.getAccountId(),
bucket.getCreationDate() != null ? bucket.getCreationDate() : Instant.now(),
bucket.getTags() != null ? bucket.getTags() : Map.of()));
}
return resources;
}
@Override
public Set<SupportedResourceType> getSupportedResourceTypes() {
return Set.of(new SupportedResourceType("s3:bucket", "s3", true));
}
}
@@ -34,9 +34,14 @@ import java.util.Objects;
import java.util.UUID;
import java.util.concurrent.ThreadLocalRandom;
import java.util.function.Predicate;
import io.github.hectorvent.floci.core.resource.ExplorerResource;
import io.github.hectorvent.floci.core.resource.ResourceProvider;
import io.github.hectorvent.floci.core.resource.SupportedResourceType;
import java.util.LinkedHashMap;
import java.util.Set;
@ApplicationScoped
public class SecretsManagerService {
public class SecretsManagerService implements ResourceProvider {
private static final Logger LOG = Logger.getLogger(SecretsManagerService.class);
@@ -995,4 +1000,35 @@ public class SecretsManagerService {
}
return sb.toString();
}
// ─── Resource Explorer 2 ───────────────────────────────────────────────────
@Override
public List<ExplorerResource> getResources() {
List<ExplorerResource> resources = new ArrayList<>();
for (Secret secret : store.scan(k -> true)) {
String arn = secret.getArn();
if (arn == null) {
continue;
}
AwsArnUtils.Arn parsed = AwsArnUtils.parse(arn);
Map<String, String> tags = new LinkedHashMap<>();
if (secret.getTags() != null) {
for (Secret.Tag tag : secret.getTags()) {
tags.put(tag.key(), tag.value() != null ? tag.value() : "");
}
}
resources.add(new ExplorerResource(
arn, "secretsmanager:secret", "secretsmanager",
parsed.region(), parsed.accountId(),
secret.getCreatedDate() != null ? secret.getCreatedDate() : Instant.now(),
tags));
}
return resources;
}
@Override
public Set<SupportedResourceType> getSupportedResourceTypes() {
return Set.of(new SupportedResourceType("secretsmanager:secret", "secretsmanager", true));
}
}
@@ -5,6 +5,9 @@ import io.github.hectorvent.floci.core.common.AwsArnUtils;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.common.RegionResolver;
import io.github.hectorvent.floci.core.common.Resettable;
import io.github.hectorvent.floci.core.resource.ExplorerResource;
import io.github.hectorvent.floci.core.resource.ResourceProvider;
import io.github.hectorvent.floci.core.resource.SupportedResourceType;
import io.github.hectorvent.floci.core.storage.StorageBackend;
import io.github.hectorvent.floci.core.storage.StorageFactory;
import io.github.hectorvent.floci.services.lambda.LambdaService;
@@ -51,7 +54,7 @@ import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentLinkedDeque;
@ApplicationScoped
public class SnsService implements Resettable {
public class SnsService implements Resettable, ResourceProvider {
private static final Logger LOG = Logger.getLogger(SnsService.class);
private static final Duration FIFO_DEDUP_WINDOW = Duration.ofMinutes(5);
@@ -903,6 +906,29 @@ public class SnsService implements Resettable {
return new java.util.LinkedHashMap<>(topic.getTags());
}
@Override
public List<ExplorerResource> getResources() {
List<ExplorerResource> resources = new ArrayList<>();
for (Topic topic : topicStore.scan(k -> true)) {
String arn = topic.getTopicArn();
if (arn == null) {
continue;
}
AwsArnUtils.Arn parsed = AwsArnUtils.parse(arn);
resources.add(new ExplorerResource(
arn, "sns:topic", "sns",
parsed.region(), parsed.accountId(),
topic.getCreatedAt() != null ? topic.getCreatedAt() : Instant.now(),
topic.getTags() != null ? topic.getTags() : Map.of()));
}
return resources;
}
@Override
public Set<SupportedResourceType> getSupportedResourceTypes() {
return Set.of(new SupportedResourceType("sns:topic", "sns", true));
}
/**
* Evaluates whether a message satisfies the subscription's filter policy.
* Returns {@code true} if no filter policy is set.
@@ -5,6 +5,9 @@ import io.github.hectorvent.floci.core.common.AwsArnUtils;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.common.RegionResolver;
import io.github.hectorvent.floci.core.common.Resettable;
import io.github.hectorvent.floci.core.resource.ExplorerResource;
import io.github.hectorvent.floci.core.resource.ResourceProvider;
import io.github.hectorvent.floci.core.resource.SupportedResourceType;
import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend;
import io.github.hectorvent.floci.core.storage.StorageBackend;
import io.github.hectorvent.floci.core.storage.StorageFactory;
@@ -28,7 +31,7 @@ import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicLong;
@ApplicationScoped
public class SqsService implements Resettable {
public class SqsService implements Resettable, ResourceProvider {
private static final Logger LOG = Logger.getLogger(SqsService.class);
private static final int DEDUP_WINDOW_SECONDS = 300; // 5 minutes
@@ -207,6 +210,35 @@ public class SqsService implements Resettable {
}
}
@Override
public List<ExplorerResource> getResources() {
List<ExplorerResource> resources = new ArrayList<>();
for (String key : queueStore.keys()) {
int sep = key.indexOf("::");
if (sep < 0) {
continue;
}
String region = key.substring(0, sep);
Queue queue = queueStore.get(key).orElse(null);
if (queue == null) {
continue;
}
String account = queue.getAccountId() != null ? queue.getAccountId() : regionResolver.getAccountId();
String arn = AwsArnUtils.Arn.of("sqs", region, account, queue.getQueueName()).toString();
resources.add(new ExplorerResource(
arn, "sqs:queue", "sqs",
region, account,
queue.getCreatedTimestamp() != null ? queue.getCreatedTimestamp() : Instant.now(),
queue.getTags() != null ? queue.getTags() : Map.of()));
}
return resources;
}
@Override
public Set<SupportedResourceType> getSupportedResourceTypes() {
return Set.of(new SupportedResourceType("sqs:queue", "sqs", true));
}
public Queue createQueue(String queueName, Map<String, String> attributes, String region) {
return createQueue(queueName, attributes, null, region);
}
@@ -15,9 +15,15 @@ import org.jboss.logging.Logger;
import java.time.Instant;
import java.util.*;
import io.github.hectorvent.floci.core.resource.ExplorerResource;
import io.github.hectorvent.floci.core.resource.ResourceProvider;
import io.github.hectorvent.floci.core.resource.SupportedResourceType;
import io.github.hectorvent.floci.core.common.AwsArnUtils;
import java.util.ArrayList;
import java.util.Set;
@ApplicationScoped
public class SsmService {
public class SsmService implements ResourceProvider {
private static final Logger LOG = Logger.getLogger(SsmService.class);
@@ -335,4 +341,29 @@ public class SsmService {
historyStore.put(storageKey, history);
}
// ─── Resource Explorer 2 ───────────────────────────────────────────────────
@Override
public List<ExplorerResource> getResources() {
List<ExplorerResource> resources = new ArrayList<>();
for (Parameter parameter : parameterStore.scan(k -> true)) {
String arn = parameter.getArn();
if (arn == null) {
continue;
}
AwsArnUtils.Arn parsed = AwsArnUtils.parse(arn);
resources.add(new ExplorerResource(
arn, "ssm:parameter", "ssm",
parsed.region(), parsed.accountId(),
parameter.getLastModifiedDate() != null ? parameter.getLastModifiedDate() : Instant.now(),
parameter.getTags() != null ? parameter.getTags() : Map.of()));
}
return resources;
}
@Override
public Set<SupportedResourceType> getSupportedResourceTypes() {
return Set.of(new SupportedResourceType("ssm:parameter", "ssm", true));
}
}
@@ -1,8 +1,12 @@
package io.github.hectorvent.floci.services.stepfunctions;
import io.github.hectorvent.floci.core.common.AwsArnUtils;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.common.AwsArnUtils;
import io.github.hectorvent.floci.core.common.RegionResolver;
import io.github.hectorvent.floci.core.resource.ExplorerResource;
import io.github.hectorvent.floci.core.resource.ResourceProvider;
import io.github.hectorvent.floci.core.resource.SupportedResourceType;
import io.github.hectorvent.floci.core.storage.StorageBackend;
import io.github.hectorvent.floci.core.storage.StorageFactory;
import com.fasterxml.jackson.core.type.TypeReference;
@@ -33,7 +37,7 @@ import java.util.regex.Matcher;
import java.util.regex.Pattern;
@ApplicationScoped
public class StepFunctionsService implements Resettable {
public class StepFunctionsService implements Resettable, ResourceProvider {
private static final Logger LOG = Logger.getLogger(StepFunctionsService.class);
@@ -85,6 +89,29 @@ public class StepFunctionsService implements Resettable {
pendingTaskTokens.clear();
}
@Override
public List<ExplorerResource> getResources() {
List<ExplorerResource> resources = new ArrayList<>();
for (StateMachine sm : stateMachineStore.scan(k -> true)) {
String arn = sm.getStateMachineArn();
if (arn == null) {
continue;
}
AwsArnUtils.Arn parsed = AwsArnUtils.parse(arn);
resources.add(new ExplorerResource(
arn, "states:stateMachine", "states",
parsed.region(), parsed.accountId(),
sm.getCreationDate() > 0 ? Instant.ofEpochMilli((long) (sm.getCreationDate() * 1000)) : Instant.now(),
sm.getTags() != null ? sm.getTags() : Map.of()));
}
return resources;
}
@Override
public Set<SupportedResourceType> getSupportedResourceTypes() {
return Set.of(new SupportedResourceType("states:stateMachine", "states", true));
}
// ──────────────────────────── State Machines ────────────────────────────
public StateMachine createStateMachine(String name, String definition, String roleArn, String type,