Commit Graph
51 Commits
Author SHA1 Message Date
Matan Baruch 277809fb41 feat(aps): add Amazon Managed Service for Prometheus workspaces (#2604)
* feat(aps): add Amazon Managed Service for Prometheus workspaces

Implements the AMP workspace lifecycle (CreateWorkspace,
DescribeWorkspace, ListWorkspaces, UpdateWorkspaceAlias,
DeleteWorkspace) plus tagging through the shared /tags/{resourceArn}
dispatcher via a TagHandler with service key aps. Previously the aps
service did not exist, so aws_prometheus_workspace could not be created
through Terraform or Pulumi at all.

Workspaces are ACTIVE from birth so the provider's create waiter
(CREATING to ACTIVE) completes on its first DescribeWorkspace poll, and
a deleted workspace answers DescribeWorkspace with the typed
ResourceNotFoundException its delete waiter matches. createdAt is
serialized as restJson1 epoch-seconds; the ListWorkspaces alias
parameter is a prefix filter, matching the provider's alias_prefix.

clientToken is accepted and ignored, kmsKeyArn is stored and echoed,
and no alertmanager/rulegroups/scraper/logging operations are included.

* refactor(aps): build ARNs via RegionResolver and parse tag ARNs with AwsArnUtils

Replaces the inlined AwsArnUtils.Arn.of + config.defaultRegion pair with
regionResolver.getRegion()/buildArn so a request signed for another
region gets an ARN and endpoint in that region, and drops the
EmulatorConfig dependency that existed only for that getter. The tag
dispatcher path now parses ARNs with AwsArnUtils.parse plus an explicit
workspace/ prefix check (the SchedulerTagHandler idiom), so a
non-workspace aps ARN fails with ValidationException instead of a
misleading workspace ResourceNotFoundException. Also makes the delete
and alias mutators void (their returns were unused) and removes a dead
DELETING status mutation.

* docs(aps): map the aps service key to managed-prometheus.md in the service matrix

The docs-check gate matches ResolvedServiceCatalog external keys against
docs/services/index.md rows by filename; aps is documented at
managed-prometheus.md, so it needs the same alias treatment as
kafka -> msk.

* fix(aps): partition workspaces by request region and align minor wire details

Review follow-ups from #2604:

- Key the workspace store by region (region::workspaceId, like
  CloudWatchLogsService's groupKey), and thread the SigV4-resolved request
  region through every lifecycle and TagHandler operation, so workspaces
  created in one region are invisible to describe/list/delete/tag calls
  served in another. Covered by unit and HTTP region-isolation tests.
- Default ListWorkspaces to pages of 100 (AWS's documented default) while
  keeping the 1000 ceiling, via Pagination's seven-argument overload.
- Strip leading/trailing blanks from aliases at create, alias update, and
  the list prefix filter, per the documented normalisation.
- Return DeleteWorkspace's 202 with an empty body instead of {}.
- Reject tag keys beginning with the reserved aws: prefix in TagResource
  with a ValidationException.

* refactor(aps): align the reserved tag-key check with sibling services

- Match the aws: prefix case-insensitively as a plain loop, the same idiom
  as FisService and BatchService, instead of a case-sensitive stream chain.
- Derive key() from keyPrefix() so the :: separator lives in one place, and
  hoist the region prefix out of the scan predicate.
- Replace the two near-identical SigV4 Authorization literals in the
  integration test with an auth(region) helper.
2026-08-28 10:05:42 -04:00
Alex Banna 399bf20387 fix(signin): preserve AWS token error modes (#2554) 2026-08-25 23:38:18 -05:00
d3871e1f25 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>
2026-08-25 21:05:52 -05:00
NAMAN JAIN 943b4c1b45 feat(efs): add Elastic File System (file systems, mount targets, access points) (#2371)
* chore(efs): initialize service structure

* feat: implement EFS service models for file system and mount target management

* feat(efs): implement EFS metadata service emulator

This introduces support for the AWS Elastic File System (EFS) service, handling the control plane operations across the 2015-02-01 REST API.

- Scaffolded and generated EFS DTO models with Jackson PascalCase mapping

Created EfsService with StorageBackend capabilities for File Systems, Mount Targets, Access Points, and Policies
Created EfsController for all mapped REST-JSON routes under /2015-02-01
Registered EFS in the global EmulatorConfig and ResolvedServiceCatalog
Added comprehensive EfsIntegrationTest verifying end-to-end API lifecycle
Created EFS service documentation in docs/services/efs.md

* feat(efs): implement EFS metadata service emulator

This introduces support for the AWS Elastic File System (EFS) service, handling the control plane operations across the 2015-02-01 REST API.

- Scaffolded and generated EFS DTO models with Jackson PascalCase mapping
- Created EfsService with StorageBackend capabilities for File Systems, Mount Targets, Access Points, and Policies
- Created EfsController for all mapped REST-JSON routes under /2015-02-01
- Registered EFS in the global EmulatorConfig and ResolvedServiceCatalog
- Added comprehensive EfsIntegrationTest verifying end-to-end API lifecycle
- Created EFS service documentation in docs/services/efs.md

* fix(efs): address code review comments

- Fixed describe listings to be appropriately region-scoped
- Ensured idempotency token caching for AccessPoint and FileSystem creations
- Altered creation timestamps to use standard epoch seconds

* fix(efs): register models for reflection to satisfy native-image requirements

* fix(efs): resolve remaining review comments and add documentation

- Prevented file system deletion when mount targets exist
- Cleaned up policies and access points upon file system deletion
- Validated parent file system exists during Access Point creation
- Added proper logging for tolerated exceptions during mount target deletion
- Created missing documentation page docs/services/efs.md

* fix(efs): prevent deletion races by locking on file system ID

Wraps all state-mutating operations on file systems and their dependent resources in synchronized blocks keyed by the file system ID. This guarantees that CreateMountTarget, CreateAccessPoint, and similar operations cannot race with DeleteFileSystem, satisfying the Greptile review for P1 Deletion races dependent creation.

* fix(efs): resolve additional concurrency bugs identified by Greptile

- Prevents duplicate access point creation when concurrent requests reuse the same ClientToken across different file systems by adding a dedicated token lock.
- Prevents resurrection of deleted mount targets by wrapping modifyMountTargetSecurityGroups and deleteMountTarget in target-specific locks.

* fix(efs): enforce idempotent parameter matching for access points

* fix(efs): enforce parameter matching for idempotent creation requests

- Compares all parameters in CreateFileSystem (PerformanceMode, ThroughputMode, Encrypted, KmsKeyId, ProvisionedThroughputInMibps) when CreationToken matches
- Compares all parameters in CreateAccessPoint (FileSystemId, PosixUser, RootDirectory) when ClientToken matches
- Throws IdempotentParameterMismatch if parameters differ on a retried token, satisfying Greptile bot review

* fix(efs): enforce idempotent parameter matching for nested access point fields

- Compares PosixUser.SecondaryGids
- Compares RootDirectory.CreationInfo (OwnerUid, OwnerGid, Permissions)
- Throws IdempotentParameterMismatch if nested parameters differ on a retried token, satisfying Greptile bot review

* fix(efs): enforce idempotent parameter matching for default field omission and tags

- Treats null PerformanceMode as 'generalPurpose' for equality checks
- Treats null ThroughputMode as 'bursting' for equality checks
- Treats null Encrypted as false for equality checks
- Strictly compares tag lists in both CreateFileSystem and CreateAccessPoint
- Throws IdempotentParameterMismatch if these differ on a retried token, satisfying Greptile bot review

* fix(efs): override equals and hashCode on Tag model to enable correct idempotency comparison

- Resolves issue where identical tag values on retries were evaluated as mismatched due to object identity comparison
- Satisfies Greptile bot review for Tag idempotency checks

* fix(efs): enforce idempotent parameter matching for AvailabilityZoneName and Backup settings

- Persists AvailabilityZoneName (and derived ID) on the FileSystem during creation if supplied
- Implicitly creates an ENABLED/DISABLED BackupPolicy during CreateFileSystem to match AWS default behavior
- Compares AvailabilityZoneName on retry
- Evaluates Backup request flag against stored BackupPolicy status
- Satisfies final Greptile bot review for missing idempotency parameters

* fix(efs): evaluate creation-time backup configuration rather than current mutable policy during retries

- Adds originalBackupParameter to FileSystem model to immutably capture the configuration at creation time
- Refactors idempotency check to evaluate this stored value rather than querying the potentially modified live BackupPolicy
- Addresses Greptile P1 defect where PutBackupPolicy broke CreateFileSystem retries

* fix(efs): resolve backup retry snapshot persistence across emulator restarts

- Replaces @JsonIgnore FileSystem property with a dedicated originalBackupStore
- Ensures the original backup parameter is properly persisted and reloaded from disk
- Maintains AWS API contract fidelity while preventing IdempotentParameterMismatch on restarts

* fix(config): resolve EmrServerless and EFS configuration syntax

* fix(efs): prevent stale mount targets by deleting them inside the file system lock

* fix(efs): correct file-system policy endpoint path to singular /policy

* fix(efs): apply query string filters correctly for describe operations

* fix: align EFS emulator with AWS specifications

- Fix idempotency matching logic for CreateFileSystem and CreateAccessPoint
- Implement modern TagResource, UntagResource, and ListTagsForResource APIs
- Dynamically resolve regions and ARNs via RegionResolver
- Detect mount target subnet conflicts and dynamically resolve AZs
- Remove unused obsolete EFS model classes
- Ensure UpdateFileSystem returns 202 Accepted status code

* docs: generate EFS action table from controller

Resolves 'make docs-check' failure by injecting the floci:actions sentinel markers so the automated docs tool can maintain the supported actions list.

* fix: align EFS emulator with AWS specifications

- Fix idempotency matching logic for CreateFileSystem and CreateAccessPoint
- Implement modern TagResource, UntagResource, and ListTagsForResource APIs
- Dynamically resolve regions and ARNs via RegionResolver
- Detect mount target subnet conflicts and dynamically resolve AZs
- Remove unused obsolete EFS model classes
- Ensure UpdateFileSystem returns 202 Accepted status code

* docs: generate EFS action table from controller

Resolves 'make docs-check' failure by injecting the floci:actions sentinel markers so the automated docs tool can maintain the supported actions list.

* fix: prevent stale count on mount target deletion failure

Removes the generic catch block in deleteMountTarget so that an unexpected exception during the file system update causes the entire operation to fail, leaving the mount target intact instead of silently deleting it and causing an inconsistent parent count.

* fix: store original creation requests to prevent false idempotency conflicts

When a file system or access point is updated or retagged, its mutable state changes. Retries using the original creation token were incorrectly compared against this mutated state, causing IdempotentParameterMismatch conflicts. This commit introduces dedicated storage backends to retain the original CreateFileSystemRequest and CreateAccessPointRequest, ensuring that idempotent retries correctly compare their parameters against the original request rather than the current mutated state.

* fix: store original creation requests to prevent false idempotency conflicts

When a file system or access point is updated or retagged, its mutable state changes. Retries using the original creation token were incorrectly compared against this mutated state, causing IdempotentParameterMismatch conflicts. This commit introduces dedicated storage backends to retain the original CreateFileSystemRequest and CreateAccessPointRequest, ensuring that idempotent retries correctly compare their parameters against the original request rather than the current mutated state.

* refactor: remove unused idempotent parameter stores in EFS

Dropping originalFileSystemRequestStore, originalAccessPointRequestStore, and originalBackupStore, as parameter matching is no longer performed by the EFS emulator. These stores were persistent and written to on every create but never read, unnecessarily keeping state files around.

* fix(efs): resolve compliance issues and reviewer feedback

- Populate AccessPointDescription.Name from tags during create and describe
- Return 404 FileSystemNotFound for unknown IDs or CreationTokens in DescribeFileSystems
- Implement Marker/MaxItems pagination for DescribeTags
- Refactor AZ-ID generation to match exact AWS shapes (e.g. usw2-az1)
- Clear ProvisionedThroughputInMibps on transition to elastic/bursting mode
- Reject update requests setting ProvisionedThroughputInMibps on non-provisioned filesystems
- Add trailing newline to ThroughputMode.java
- Expand integration tests for ThroughputMode transitions

---------

Signed-off-by: NAMAN JAIN <naman.049259@tmu.ac.in>
2026-08-25 19:48:38 -05:00
William St John Bacon 87e804492a feat(organizations): add AWS Organizations service (#2489)
* feat(organizations): add AWS Organizations service

Implements the AWS Organizations control plane over JSON 1.1
(AWSOrganizationsV20161128.*): organizations and roots, the OU tree,
member accounts, all policy types, tags, trusted service access,
delegated administrators, the organization resource policy, and the
invitation/handshake flow.

Organizations is global and cross-account, so records are addressed
through the explicit *ForAccount methods on AccountAwareStorageBackend
rather than the request-context-derived get/put: a member account
calling DescribeOrganization has a different request account than the
one owning the data. The caller account is used for authorization
instead — mutations are management-account only, members get read
access to their own organization, and outsiders get
AWSOrganizationsNotInUseException.

Because Floci already resolves a 12-digit access key id to an account,
an account created by CreateAccount is immediately usable as a caller
identity against every other service.

* fix(organizations): emit only AWS's handshake resource types

Review feedback on #2489.

The ORGANIZATION resource on an INVITE handshake was carrying a
MASTER_ACCOUNT_ID child. HandshakeResourceType is a closed enum and that
value is not in it, so the AWS SDK deserializes it as
UNKNOWN_TO_SDK_VERSION rather than failing loudly. AWS's documented
children are MASTER_EMAIL and MASTER_NAME; emit those instead. The
javadoc already described the correct pair, so it was the code that
deviated. Adds an integration test pinning the resource types against
the enum so this cannot regress.

Also from review:

- POLICY_TYPES and EFFECTIVE_POLICY_TYPES are rendered into validation
  messages, but Set.of's iteration order is unspecified and salted per
  JVM run, so the same rejection could read differently between runs.
  Declare them as ordered Lists with companion Sets for O(1) membership.
- listHandshakesForAccount called organizationById — itself a full scan —
  once per handshake. Build the orgId to management-account map once.
2026-08-23 17:18:42 -04:00
Alex Banna 04d120fdd5 feat(fis): add AWS FIS support (#2435)
* feat(fis): add AWS FIS support

* refactor: add typed FIS persistence models

* ci(fis): retrigger timed-out build

* fix(fis): reject trailing JSON request bodies
2026-08-21 00:09:04 -04:00
Mihai BlidaruandMihai Blidaru bba5ffb644 feat(firehose): honor CompressionFormat and FileExtension on S3 delivery (#2410)
Firehose accepted CompressionFormat on the control plane and echoed it back on
DescribeDeliveryStream, but the delivery path never read it: every delivered
object held the raw record bytes, with no compression extension in the key and
no Content-Encoding. The divergence was silent, since only a consumer reading
the delivered objects (Athena over .gz, Spark reading Snappy, anything that
decompresses by extension or encoding) ever saw the wrong bytes.

Deliveries are now compressed the way real AWS compresses them:

  UNCOMPRESSED   (no extension)  (no Content-Encoding)
  GZIP           .gz             gzip
  ZIP            .zip            zip            single deflated entry, UUID name
  Snappy         .snappy         snappy-java    xerial stream format
  HADOOP_SNAPPY  .snappy         hadoop-snappy  Hadoop block framing

Snappy is the xerial snappy-java stream format, not the official Snappy framing
format, so a consumer must use snappy-java's own reader; HADOOP_SNAPPY is the
block framing Hadoop and Spark consumers read. Both are reproduced byte for
byte against real AWS. HADOOP_SNAPPY deliberately carries .snappy rather than
the .hsnappy the S3 object name documentation tables: the service delivers
.snappy, reproduced on two separate dates, and only Content-Encoding tells the
two variants apart.

Content-Type is now application/octet-stream for every format, including
UNCOMPRESSED, matching AWS instead of the previous application/x-ndjson.

Buffered records are concatenated as bytes rather than through a String.
Record payloads are arbitrary bytes, and compression makes the corruption of
anything that is not valid UTF-8 observable.

FileExtension is implemented alongside it, since it governs the same part of
the key: it replaces the extension the compression format contributes instead
of being appended to it, the empty string means "not specified", and it changes
only the key, never the body or its Content-Encoding. Building the extension
into the key belongs to S3ObjectKeyResolver, which already owns the key format,
so the resolver now takes the destination and resolves prefix, time zone and
extension together.

Both members are validated, with the code and message shape captured from real
AWS's raw HTTP responses rather than from an SDK's rendering of them.
Unsupported values answer ValidationException naming the shape that carried
them, so the same bad value reports
extendedS3DestinationConfiguration.compressionFormat,
s3DestinationConfiguration.compressionFormat or
extendedS3DestinationUpdate.compressionFormat, which is why the wire-shape
check runs from the handler.

snappy-java becomes a direct dependency: it is the only Java library that
writes the xerial stream format, it already shipped as a runtime-scope
transitive of kafka-clients, and its version comes from the Quarkus BOM.

For the GraalVM native image the loader needs run-time initialization; left to
build-time initialization the image still builds and then dies with
UnsatisfiedLinkError on the first compression. Snappy and SnappyLoader are the
only classes on the compression path with a static initializer, which jdeps and
a set of Mandrel 25.0.4 builds confirm is the whole requirement.

Two deviations from AWS are documented rather than changed, both newly verified
while testing this: Floci appends a newline after records that lack one where
AWS inserts no separator at all, and Floci accepts streams with no destination
configuration where AWS requires exactly one complete destination.

Closes #2328

Co-authored-by: Mihai Blidaru <mihai.blidaru@lynxfctech.com>
2026-08-19 16:44:01 -04:00
Tucker 6779aa8270 feat(guardduty): add GuardDuty detector and organization configuration emulation (#2346) 2026-08-17 00:40:12 -05:00
1cc97d57c1 feat(cloudhsmv2): implement CloudHSM v2 service (#1776)
* feat(cloudhsmv2): implement CloudHSM v2 service

* refactor(cloudhsmv2): delete HSM parameters and docs

* feat(cloudhsmv2): implement AWS CloudHSM v2 service (phased)

* fix: greptile bot reviews

* refactor(cloudhsmv2): delete HSM parameters and docs

* feat(cloudhsmv2): implement AWS CloudHSM v2 service (phased)

* fix: greptile bot reviews

* fix(cloudhsmv2): fix backup retention policy parsing and SDK test cert usage

* fix(cloudhsmv2): fix CreateHsm IP generation, ModifyCluster validation, and duplicate test Order

* docs(cloudhsmv2): add service to mkdocs, readme, and index matrices

* fix(rds): preserve configured database images (#2035)

* fix(cloudhsmv2): resolve remaining AWS-compatibility edge cases

* feat(stepfunctions): run Map iterations concurrently honoring MaxConcurrency (#1810)

* feat(stepfunctions): run Map iterations concurrently honoring MaxConcurrency

A Map state ran its iterations one after another. AWS runs them
concurrently up to MaxConcurrency (default 0 = unlimited), which is a
correctness requirement, not just a speed-up: a Map whose iterations
coordinate — e.g. a dependency-ordered fan-out where one child blocks
until a sibling completes — deadlocks when the iterations are serialised.

Run each iteration on the shared executor under the execution's account,
gated by a Semaphore sized to MaxConcurrency (unlimited when 0). Results
are written into per-index slots so the output array preserves input order
regardless of completion order, MaxConcurrency=1 stays strictly sequential,
and a failed iteration cancels the rest and fails the Map (fail-fast,
matching the default ToleratedFailureCount of 0).

* fix(stepfunctions): cap Map worker threads with a bounded pool + handle interruption

Address review: submitting every iteration to the shared cached pool behind
a Semaphore spawned one thread per item (a 1000-item Map with
MaxConcurrency=5 created ~1000 threads, ~995 parked). Run iterations on a
fixed-size per-Map ThreadPoolExecutor sized to MaxConcurrency so live
threads are capped and the rest queue. shutdownNow() in finally stops the
iterations on any exit, and an InterruptedException from the driver now
preserves the interrupt status.

* fix(stepfunctions): make Map concurrency bounded and fail-fast

* docs(stepfunctions): document map concurrency

* test(dynamodb): retain Quarkus port for cleanup

* chore: rerun CI after OpenTofu registry flake

* test(stepfunctions): pin Map item selection order

* perf(lambda): reuse a populated code volume across restarts via a completion marker (#1827)

* perf(lambda): reuse populated code volumes across restarts

* test(dynamodb): retain Quarkus port for cleanup

* chore: rerun CI after download outage

* ci: retry transient gosu downloads

---------

Co-authored-by: Alexander Banna <abanna@users.noreply.github.com>

* fix(apigateway): apply MOCK integration response headers (#1822)

* fix(apigateway): apply mock response headers for OPTIONS

* refactor(apigateway): drop the OPTIONS route in favour of #1955

Both this PR and #1955 added an @OPTIONS method on the same @Path in
ApiGatewayExecuteController and ApiGatewayUserRequestController, so whichever
merged second would not have compiled.

#1955's version is the more complete one: it covers ApiGatewayAwsExecuteController
(the /_aws/execute-api path) as well, forwards the request body, and skips
GlobalCorsFilter for deployed-API paths -- without which a real browser preflight
is short-circuited before it ever reaches the route.

This PR keeps only its own contribution: invokeMock returned early on the
empty-response-template path and dropped static method.response.header.* mappings.
ApiGatewayMockCorsHeadersTest now exercises that over GET, since the dropped-header
bug is verb-agnostic, leaving the two PRs independently mergeable in either order.

* test(dynamodb): retain Quarkus port for cleanup

* chore: rerun CI after autoscaling test flake

---------

Co-authored-by: abanna <abanna@users.noreply.github.com>

* fix(cloudwatch): return logStreamName on FilterLogEvents results (#2259)

FilterLogEvents is the cross-stream search API, so a match is only
attributable if the response names the stream that emitted it. Floci
served FilterLogEvents and GetLogEvents from one serializer emitting
eventId, timestamp, message and ingestionTime, so a caller searching a
whole log group could tell which group a hit came from but not which
stream, and tooling written against real AWS lost that attribution
without any error.

Derive the stream from the event's storage key rather than persisting it
on the event. Keys are already
<region>::<group>::<stream>::<timestamp>::<uuid>, so the key is an
authoritative record of the emitter for every event in the store,
including ones written before this change. Storing the name on LogEvent
instead would leave every already-persisted event with a null
logStreamName and need a backfill pass to repair it. The stream is read
back between the group prefix and the trailing timestamp and uuid, both
generated here, so a stream name is recovered whole even though nothing
stops a caller from creating one that holds a ':'.

filterLogEvents walks the keyset once and pairs each event with its
stream, which also collapses the stream-restricted branch: it previously
ran one full keyset scan per requested stream, since a scan walks every
key regardless of the prefix it filters on.

GetLogEvents keeps its existing shape. Real AWS returns OutputLogEvent
there, which carries no logStreamName, because the caller named the
stream in the request.

Closes #2210

* fix(ec2): start sshd even when run-instances omits a key pair (#2245)

* fix(ec2): start sshd even when run-instances omits a key pair

Reported in #2184: run-instances without --key-name left every
container with no SSH daemon listening at all, "connection refused"
regardless of image (alpine, Amazon Linux 2023, Ubuntu all affected).

The cause: startSshd() only ran inside the same conditional as
injectSshKey(), so no key pair meant sshd never started. Real AWS AMIs
run sshd as part of normal boot regardless of whether a key pair is
attached - the daemon is always there, it just has nothing to
authenticate an unattached client with. Floci's behavior diverged by
not running the daemon at all in that case, rather than running it and
correctly having no way in.

Splits the two: injectSshKey still only runs when a key was actually
provided (nothing to inject otherwise), but startSshd now always runs.
It's fully self-contained already (installs openssh-server if absent,
generates host keys, starts the daemon) and never depended on anything
injectSshKey sets up, so making it unconditional needed no other
changes.

Verified: new test launches an instance with no public key and asserts
sshd still starts (and confirms nothing gets written to
authorized_keys, since there's no key to inject). Confirmed it fails
with the fix reverted (no /usr/sbin/sshd invocation happens without a
key) and passes with it restored. Full ec2 package regression is green
(268 tests) - including the several existing tests that already
launched with no key pair and needed no changes to keep passing.

* fix(ec2): stop silently claiming sshd started when it never actually did

Follow-up on a comment from duytanisme on #2245: sshd not starting even
when an SSH key IS provided, requiring a manual exec-in or a custom
user-data script to work around it.

Root cause: startSshd() ran every step through execInContainer(),
which discards the exec's exit code entirely and only throws if the
Docker API call itself fails. The install step's shell script is an
if/elif chain with no matching branch, or whose install command itself
failed (no network yet, apt lock held, etc.) - and a bash if/elif with
no matching branch and no else clause exits 0 by convention. So a
container without a package manager, or one where the install call
failed for any reason, still reported success, ssh-keygen and sshd
then both ran anyway against a daemon that was never installed, and
"Started sshd in EC2 instance" got logged regardless.

Switches every step to execInContainerForResult and checks its exit
code explicitly, following the exact pattern already used by
configureLinkLocalMetadataEndpoint for the same class of problem:
bail out and log a specific warning with the actual command output at
whichever step actually failed, instead of silently proceeding.

Also adds an explicit "command -v sshd" as the last statement of the
install script, so its own exit code is the real source of truth for
whether sshd is actually available afterward, and switches the start
command from a hardcoded /usr/sbin/sshd to a bare "sshd" resolved via
PATH (matching how ssh-keygen is already invoked two lines above),
since not every image installs it to that exact path.

Verified: new test forces the install probe to fail and asserts
ssh-keygen and the start command are never even attempted. Confirmed
it fails (proceeds anyway) with the exit-code check disabled and
passes with it restored. Updated the existing no-key-pair test for the
new bare "sshd" command. Full ec2 package regression is green (269
tests).

* feat(stepfunctions): add UpdateStateMachine and update in place on stack updates (#1867)

* feat(stepfunctions): add UpdateStateMachine and update in place on stack updates

* test(dynamodb): retain Quarkus port for cleanup

* chore: rerun CI after download outage

* fix(cloudformation): preserve log group on failed rename

* fix(cloudformation): scope update rollback to attempted resources

* fix(cloudformation): delete resources after stack updates

* test(cloudformation): wire cloudfront fixture dependency

* fix: include Step Functions update date in describe response

* fix: preserve Step Functions describe response shape

* fix: preserve generated Step Functions names

* fix(s3): derive S3 host suffix matching from DNS config (#1843)

* fix(s3): derive S3 host suffix matching from DNS config

S3VirtualHostFilter hardcoded the wildcard-DNS suffixes (localhost.floci.io,
localhost.localstack.cloud) in two places: the bare service-host check
(isS3ServiceEndpointHost) and the virtual-hosted bucket fallback (isAwsS3Domain).
Both now derive their suffix set from the embedded DNS source of truth plus any
configured floci.dns.extra-suffixes, so a custom DNS suffix is recognised the same
way the builtins are.

Why: the two literal lists duplicated what the DNS server already knows and could
drift from it silently. Deriving from EmbeddedDnsServer.BUILTIN_SUFFIXES keeps them
in lockstep, and folding in extra-suffixes means a user migrating from LocalStack
via a custom suffix gets consistent S3 host handling (bucket routing and service
endpoint detection), not just the DNS resolution they get today.

How:
- buildServiceHostSuffixes() computes {localhost} + BUILTIN_SUFFIXES + extra-suffixes
  once per instance; isS3ServiceEndpointHost() checks membership instead of literals.
- matchesConfiguredSuffixHost() routes the virtual-hosted forms bucket.<suffix>,
  bucket.s3.<suffix> and bucket.s3.<region>.<suffix> for every configured suffix,
  replacing the hardcoded localstack/floci branches in isAwsS3Domain.
- EmbeddedDnsServer.BUILTIN_SUFFIXES widened to public so the filter reuses the list.

The virtual-host match now requires the full builtin suffix (.localhost.localstack.cloud)
rather than the bare parent domain (.localstack.cloud), matching LocalStack's actual
wildcard DNS (*.localhost.localstack.cloud).

* test(s3): derive DEFAULT_SUFFIXES from the production factory

The test constant hardcoded a copy of the builtin suffix set, which would
silently drift if a new builtin were added to EmbeddedDnsServer.BUILTIN_SUFFIXES.
Widen buildServiceHostSuffixes() to package-private and reuse it in the test so
the two stay in sync automatically.

* fix(s3): include the configured hostname in the derived suffix set

EmbeddedDnsServer resolves builtins + floci.hostname + floci.dns.extra-suffixes,
but the derived service-host set carried only two of the three. The configured
hostname reaches the filter as baseHostname, and matchesEndpointHost excludes the
bare s3.<host> remainder by design, so the bucket form one level down
(bucket.s3.<hostname>) matched nothing. DNS still resolves that host, so the
request reached Floci and was then handled path-style, binding the first path
segment as the bucket, rather than being refused.

Carry the hostname into buildServiceHostSuffixes so all three DNS inputs are
mirrored and a host that resolves by wildcard DNS routes under the same rules.

* fix(ec2): assign a public IP only when the subnet opts in via MapPublicIpOnLaunch (#2023)

* fix(ec2): assign a public IP only when the subnet opts in via MapPublicIpOnLaunch (#1984)

Every instance was given PublicIpAddress 127.0.0.1 unconditionally in
Ec2ContainerManager, so a private-subnet instance wrongly reported an
internet-facing address (breaks the ssh-reachability / public-vs-private
distinction). runInstances now flags the instance (associatePublicIp) from its
subnet's MapPublicIpOnLaunch, and the container manager exposes a public
address only when that flag is set. Private-subnet instances get no
PublicIpAddress — DescribeInstances omits the element (XmlBuilder skips nulls),
matching real EC2. The value for public instances stays the host-reachable
127.0.0.1 (unchanged). Unit test covers the public-vs-private flag.

Supports the aws-bench project: un-excludes the ssh-reachability scenario.

* fix(ec2): honor the launch-time AssociatePublicIpAddress override

* fix(ec2): honor the top-level AssociatePublicIpAddress and an explicit-false launch configuration

Two gaps left by the previous commit, both flagged in review.

RunInstances only read the override off the primary network-interface spec
(NetworkInterface.1.AssociatePublicIpAddress), so the legacy top-level
AssociatePublicIpAddress parameter — what the CLI and older SDKs send — was
silently dropped and the subnet default decided instead. It is now read as a
fallback; AWS rejects both shapes at once, so the interface spec wins when
present.

The launch-configuration path was worse than before. LaunchConfiguration
stored a primitive boolean, so an absent flag and an explicit false were
indistinguishable, and the reconciler could only forward an explicit true.
An LC that set AssociatePublicIpAddress=false in a MapPublicIpOnLaunch subnet
still got a public address. The field is now a nullable Boolean the whole way
through (service, query handler, CFN provisioner), so false overrides the
subnet and only null falls back to it. DescribeLaunchConfigurations omits the
element when it was never set, as AWS does.

Tests: a handler-level test pins all four parse cases (top-level, interface
spec, both present, absent), and the reconciler test pins true/false/null
reaching runInstances unchanged.

* feat(cloudfront): enforce signed private content (#1831)

* feat(cloudfront): serve distribution requests from S3 and custom origins

* feat(cloudfront): enforce signed private content

* chore: re-run CI

The Build and Test failure on the previous head was RuntimeApiServerTest's
extension/stop race, a pre-existing flake unrelated to this change — it also failed
on #1820, #1823 and on #2131's own branch (the PR that tried to de-flake it).
Reproduced locally under `--cpus=1` and fixed separately.

* fix(cloudfront): wildcard aliases match exactly one subdomain level

wildcardAliasMatches did a plain suffix check, so "*.example.com" also matched
a.b.example.com. AWS is explicit that a wildcard alternate domain name replaces the
wildcard at that level only:

  "you can't add alternate domain names that are at levels higher or lower than the
   wildcard. For example, you can't add the alternate domain names example.com or
   marketing.product.example.com."

  https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/CNAMEs.html

Practical effect: a distribution owning "*.example.com" would answer for
a.b.example.com, which on AWS belongs to whoever owns "*.b.example.com" — or to
nobody. Require the label standing in for the wildcard to contain no dot.

wildcardAliasesMatchSubdomainsAndPreferMoreSpecificNames asserted the old behaviour
(a.b.example.test resolving to the *.example.test distribution); it now asserts no
match, plus the same for a deeper wildcard.

* test(dynamodb): retain Quarkus port for cleanup

* fix(cloudfront): isolate mocked storage backends

* fix(cloudfront): match wildcards in signed policy queries

* feat(cloudhsmv2): implement AWS CloudHSM v2 service (phased)

- Fix malformed dummy certificate in sdk-test-java by generating a self-signed X.509 cert programmatically using BouncyCastle
- Apply fixes for tag operations targeting backups
- Escape backslashes in regex
- Resolve compilation issues

* fix(test): Add CloudFrontClient to TestFixtures to resolve merge conflict

* revert(test): revert CloudFrontClient addition to TestFixtures

* fix(cloudhsmv2): fix CSR public key mismatch in SDK tests by signing properly extracted CSR

* test(ec2): fix Ec2PublicIpOnLaunchTest compilation after StorageBackend changes

* fix(cloudhsmv2): remove explicit BouncyCastle JCA provider to fix native image certificate validation

* fix(cloudhsmv2): add null check for DestinationRegion in copy backup

* fix(test): correct storage imports in Ec2PublicIpOnLaunchTest after rebase

* fix(cloudhsmv2): resolve code review comments including AZ lookup and validation

* style(cloudhsmv2): remove trailing whitespace in CloudHsmV2Test

---------

Signed-off-by: NAMAN JAIN <naman.049259@tmu.ac.in>
Co-authored-by: Aniket Shukla <aniketshukla619@gmail.com>
Co-authored-by: Alex Banna <alexanderbanna@gmail.com>
Co-authored-by: Alexander Banna <abanna@users.noreply.github.com>
Co-authored-by: TiM <tim@nuimarkets.com>
Co-authored-by: Olamide Kosile <64154023+Mide69@users.noreply.github.com>
Co-authored-by: lex00 <121451605+lex00@users.noreply.github.com>
2026-08-17 00:00:49 -05:00
Kenshin Okinaka ba843013ec chore(compat): align pinned SDK versions across the Python, Java, and CDK suites (#2253)
* chore(compat): align pinned SDK versions across the Python, Java, and CDK suites

Bump the exact-pinned SDK versions to a common recent baseline so the suites no longer
span a wide release window:

- sdk-test-python: boto3 / botocore 1.37.1 -> 1.43.69
- sdk-test-java: AWS SDK for Java v2 2.44.14 -> 2.52.0
- compat-cdk: aws-cdk-lib 2.171.1 -> 2.264.0, aws-cdk 2.171.1 -> 2.1135.1,
  aws-cdk-local ^2.0.0 -> ^3.0.4

Bumping boto3/botocore also restores the current SES v2 model (97 -> 112 operations,
including the Tenant and ReputationEntity families).

The aws-cdk 2.1000+ CLI (decoupled from the library version line) publishes template
assets to S3 using virtual-hosted-style URLs and needs aws-cdk-local v3. Pointing
AWS_ENDPOINT_URL_S3 at Floci's virtual-hosted domain (http://s3.localhost.floci.io:4566)
makes the SDK build <bucket>.s3.localhost.floci.io, which resolves via public DNS locally
and via Floci's embedded DNS (already injected with --dns in the compat workflow) inside
the Docker network, instead of the unresolvable <bucket>.floci.

The Go, Node, AWS CLI, Terraform, and OpenTofu suites float to the latest by design and
are left unchanged.

* chore(compat): let AWS_ENDPOINT_URL_S3 be overridden in the compat-cdk helper

Use a ${:-default} fallback like the other endpoint/region variables in
common-setup.bash so a caller or CI can point the CDK S3 virtual-host endpoint
elsewhere (e.g. a non-4566 port), instead of hard-coding it.
2026-08-16 22:40:20 -05:00
lex00 4e6e6df06d feat(bedrockagentcore): emulate the AgentCore control plane and InvokeAgentRuntime stub (#2316)
* docs(bedrockagentcore): add AgentCore emulation design + upgrade path

* feat(bedrockagentcore): add agent runtime CRUD control plane

Implements the bedrock-agentcore-control runtime registry (Phase 1):
Create/Get/List/Update/Delete AgentRuntime plus ListAgentRuntimeVersions,
with immutable version snapshots, cursor pagination, and ISO-8601 timestamps.

- REST-JSON controller + service + reflection-safe models
- ServiceRegistry descriptor + EmulatorConfig toggle
- Unit + RestAssured integration tests
- AWS SDK v2 compatibility test (sdk-test-java)
- Service docs page

Refs lex00/floci#2

* feat(bedrockagentcore): add agent runtime endpoints

Phase 2: Create/Get/Update/Delete/List AgentRuntimeEndpoint under
/runtimes/{id}/runtime-endpoints/, with a DEFAULT endpoint auto-created per
runtime and agentEndpoint/<uuid> ARNs. RestAssured + SDK v2 compat tests.

Refs lex00/floci#3

* feat(bedrockagentcore): add InvokeAgentRuntime data-plane stub

Phase 3: POST /runtimes/{agentRuntimeArn}/invocations returns a fixed,
configurable canned response ({"output":"yes"}) and echoes the runtime
session id. Opaque payload is never parsed; streaming is not emulated.
Separate stateless bedrock-agentcore service. RestAssured + SDK v2 compat tests.

Refs lex00/floci#4

* feat(bedrockagentcore): add tagging and workload identity

Phase 4:
- TagResource/UntagResource/ListTagsForResource for runtime ARNs via a
  TagHandler on the shared /tags/{arn} route
- Workload identity RPC CRUD (POST /identities/<Op>); each runtime auto-creates
  a resolvable workload identity
- Workload-identity timestamps are epoch-seconds (unixTimestamp), distinct from
  the runtime ISO-8601 timestamps

RestAssured + SDK v2 compat tests.

Refs lex00/floci#5

* feat(bedrockagentcore): add gateway and memory primitives

Phase 5 (optional): metadata-only CRUD registries.
- Gateways (POST /gateways/) + gateway targets, standard REST
- Memory (POST /memories/create, GET /memories/{id}/details, ...), action-suffix
- Gateway timestamps are ISO-8601; memory timestamps are epoch seconds
RestAssured + SDK v2 compat tests.

Refs lex00/floci#6

* fix(bedrockagentcore): correctness fixes from adversarial audit

- Fix ListAgentRuntimeVersions pagination cycling for >=10 versions: sort by
  the pagination cursor and zero-pad the version cursor (closes #7)
- Capture authorizerConfiguration/protocolConfiguration in version snapshots so
  GetAgentRuntime?version returns the requested version's config (closes #8)
- Support tagging AgentCore gateways (AWS-taggable): add tags to Gateway,
  dispatch the TagHandler by ARN resource type, store tags on CreateGateway;
  non-taggable AgentCore ARNs now 400 (closes #9)
- Validate maxResults range (1..N) across all list operations (closes #12)

Adds regression tests: version-pagination multi-page, version-config snapshot,
gateway tag round-trip (REST + SDK), unsupported-ARN 400, maxResults + malformed
nextToken validation, and an HTTP-level multi-page pagination test.

Refs lex00/floci#14

* feat(bedrockagentcore): clientToken idempotency, invoke existence flag, config docs

- clientToken idempotency for Runtime/Endpoint/Memory create+delete (lenient:
  same token returns the existing resource; completed-delete tokens tracked
  in-memory so a replayed delete returns 202 not 404) (closes #10)
- InvokeAgentRuntime existence check behind floci.services.bedrock-agent-core
  .validate-runtime-exists (default false, preserving permissive behavior);
  when on, unknown runtime ARNs return ResourceNotFoundException (closes #11)
- Document that YAML config keys are hyphenated (bedrock-agent-core-control),
  distinct from the reported service name (closes #13)

Adds unit tests (create/delete idempotency), a TestProfile integration test for
the existence flag, and an SDK v2 idempotency compat test.

Refs lex00/floci#10 lex00/floci#11 lex00/floci#13

* ci: trigger fork pipeline dry-run

* test(bedrockagentcore): add persistence, region-isolation, concurrency and boundary coverage

Closes the structural test gaps from the audit (issue #14):
- Persistence-across-restart: full AgentRuntime (JsonNode config, Instants,
  version snapshots, endpoints, tags, env vars) round-trips through
  PersistentStorage to disk and reloads intact
- Region isolation: a runtime is invisible/ungettable from another region
- Concurrency: concurrent creates all persist (no dropped inserts)
- Endpoint version retargeting, gateway + target update, duplicate-name 409,
  and memory eventExpiryDuration boundaries (2/3/365/366)

Refs lex00/floci#14

* fix(bedrockagentcore): validate endpoint versions and the identity in a tagging ARN

createEndpoint and updateEndpoint stored agentRuntimeVersion without resolving
it against the runtime, so a version that was never published produced a READY
endpoint whose generated runtime ARN resolves to nothing. Both now reject one
the runtime has not published.

Tag operations resolved a resource from the ARN's id suffix alone, so an ARN
naming another account or region but a local id reached the local runtime or
gateway and could read or change its tags. The shared tag dispatch now checks
both fields against the request, which covers runtimes and gateways in one
place, and reports not found rather than a validation error so the response
does not confirm what sits behind the foreign identity.
2026-08-15 16:24:46 -04:00
Dixit R Jain b45de1bb7d feat(s3tables): emulate metadata service (#2322)
* feat(s3tables): emulate metadata service

* fix(s3tables): serialize metadata updates
2026-08-15 12:48:27 -04:00
Andre Kurait ecad6acf58 feat(swf): add Simple Workflow Service emulation (#2257)
* feat(swf): add Simple Workflow Service emulation

Implements all 39 SWF operations over the JSON 1.0 protocol
(X-Amz-Target: SimpleWorkflowService.*): domain and type registration,
the workflow execution state machine, and the decider/worker task
lifecycle.

Behaviour was derived from botocore's swf-2012-01-25 model and verified
against the live service, which drove several details that are easy to
get wrong from the model alone:

- Faults carry a namespaced __type (com.amazonaws.swf.base.model#Fault)
  in the body but the bare fault name in x-amzn-query-error. botocore
  prefers the header, so a namespaced value there makes the CLI print
  "com.amazonaws.swf.base.model#UnknownResourceFault" where SWF prints
  "UnknownResourceFault". SwfException keeps the two spellings apart.
- Timestamps are epoch-second numbers, not ISO strings.
- Void operations answer 200 with an empty body rather than {}.
- An idle poll returns taskToken "" rather than omitting the member;
  the SDKs read the empty token as "no task".
- ActivityTaskTimedOut reports startedEventId 0 for a task that never
  started, and WorkflowExecutionStarted reports parentInitiatedEventId 0
  on root executions, rather than omitting either member.

State machine:

- One decision task outstanding per execution. Events arriving while one
  is outstanding set a pending flag that is satisfied when it completes,
  so a signal cannot produce two concurrent decision tasks.
- Decisions apply in order; a decision after a closing decision is
  dropped. A decision that cannot be applied appends its *Failed event
  with the AWS cause and gives the decider a fresh task instead of
  failing the request.
- Closing with open activities, timers, or children appends
  UNHANDLED_DECISION and leaves the execution open.
- Timeouts (activity schedule-to-start, start-to-close,
  schedule-to-close, heartbeat; decision start-to-close; execution
  start-to-close; timers) expire from one background sweep rather than a
  timer per task, so a restart leaves nothing to reconcile.
- Child executions link to their parent and report their outcome back;
  the closing parent's childPolicy is applied to open children.

Tests: 29 unit tests drive timeout expiry through a controllable clock,
32 integration tests assert the wire shapes and fault strings captured
from the live service, and a compatibility suite exercises the same
flows through the AWS SDK v2 client so responses must deserialize into
the generated model and faults into typed exceptions.

Long polling, ScheduleLambdaFunction invocation, and retention-based
pruning are not implemented; docs/services/swf.md records each.

Signed-off-by: Andre Kurait <akurait@amazon.com>

* fix(swf): report the child-started event id on ChildWorkflowExecution* events

A ChildWorkflowExecution* event carries two correlation ids, and they point at
different events in the parent's history: initiatedEventId is the
StartChildWorkflowExecutionInitiated id, startedEventId is the
ChildWorkflowExecutionStarted id. Both were reported as the initiated id, so a
decider correlating a child's outcome on startedEventId matched the wrong event.

Verified against the live service, where a parent that starts one child and sees
it complete produces:

  5 StartChildWorkflowExecutionInitiated
  6 ChildWorkflowExecutionStarted        {initiatedEventId: 5}
  8 ChildWorkflowExecutionCompleted      {initiatedEventId: 5, startedEventId: 6}

The child now records the parent's ChildWorkflowExecutionStarted id at start
time and reports it back on every ChildWorkflowExecution* event.

The integration test asserts both ids against the events they name rather than
against a "greater than zero" placeholder, and fails on the previous behaviour
with "startedEventId Expected: <6> Actual: <5>".

Signed-off-by: Andre Kurait <akurait@amazon.com>

* fix(swf): reject a decision batch whose closing decision is not last

RespondDecisionTaskCompleted accepted a batch with decisions after a closing
decision and silently dropped the remainder. The live service rejects the whole
batch instead:

  HTTP 400
  {"__type":"com.amazon.coral.validate#ValidationException",
   "message":"Close must be last decision in list"}

Silently accepting it hides a decider bug and diverges on both the status code
and the response body, so a decider that ships a malformed batch sees success
locally and a 400 against AWS.

The batch is now validated before any state is mutated, matching the live
service's behaviour of leaving the decision task outstanding so the decider can
retry with a corrected batch. Note this fault is namespaced
com.amazon.coral.validate rather than com.amazonaws.swf.base.model.

Tests assert the status code, both fault spellings, the message, that no
DecisionTaskCompleted event is appended, and that the same task token still
works afterwards. They fail on the previous behaviour with "Expected status code
<400> but was <200>".

Signed-off-by: Andre Kurait <akurait@amazon.com>

* fix(swf): name the scheduled event when an activity task has already closed

An activity task token that resolves to a task which is no longer open reported
"Unknown or expired task token". The live service distinguishes the two cases: a
genuine token whose task has closed names the scheduled event instead, because
the token itself was valid.

Captured from the live service, heartbeating a task that a cancel had already
closed:

  HTTP 400
  {"__type":"com.amazonaws.swf.base.model#UnknownResourceFault",
   "message":"Unknown activity, scheduledEventId = 5"}

Both cases are UnknownResourceFault, so SDK error typing was already correct and
only the message diverged — but a worker that logs or matches on the message sees
a different string locally than against AWS.

A token that never existed still reports the bad token; only a resolved token on
a closed task reports the scheduled event. This required keeping the token's map
entry when an activity closes, since removing it made both cases indistinguishable;
reuse is still refused by the existing open-state check.

Test asserts both branches and fails on the previous behaviour with "expected:
<Unknown activity, scheduledEventId = 5> but was: <Unknown or expired task token>".

Signed-off-by: Andre Kurait <akurait@amazon.com>

* fix(swf): serialize execution mutation per domain and guard the sweep interval

Addresses three review findings.

Concurrent StartWorkflowExecution calls for one workflowId all scanned for an
open run before any of them inserted, so each persisted its own run key. Eight
concurrent starts produced eight open runs where SWF admits one, and later
operations without a runId then selected an arbitrary run. The open-run check
and the insert are now one atomic step.

A closing execution mutates its parent (ChildWorkflowExecution* events) and its
children (childPolicy), but held only its own lock, so event-id allocation and
the history list raced. Six children closing against one parent reproduced
ConcurrentModificationException.

Both come from the same mismatch: the lock was per execution while the
invariants span an execution family. The lock is now per domain. A parent and a
child always share a domain, so one lock covers the family and never has to be
nested — nesting would deadlock, since a closing child takes its parent while a
closing parent takes its children. Per-domain granularity is sufficient here:
the emulator serves a single developer's workload, not production concurrency.

A zero or negative timeout-sweep interval reached scheduleWithFixedDelay, which
threw IllegalArgumentException out of the StartupEvent observer and stopped the
whole emulator becoming ready — one bad SWF setting taking down every other
service. A non-positive interval now falls back to 1s with a warning.

Tests fail on the previous behaviour with "expected: <1> but was: <8>",
ConcurrentModificationException, and IllegalArgumentException respectively.
Verified over the wire too: eight concurrent starts yield one success, seven
WorkflowExecutionAlreadyStartedFault, and one open run.

Signed-off-by: Andre Kurait <akurait@amazon.com>

* fix(swf): report the live service's TypeNotDeprecatedFault message

DeleteWorkflowType/DeleteActivityType against a still-registered type
reported the type descriptor, e.g. "WorkflowType=[name=W, version=1]". The
live service answers with prose instead, and uses the same wording for both
type kinds:

  {"__type":"com.amazonaws.swf.base.model#TypeNotDeprecatedFault",
   "message":"The type is currently registered and cannot be deleted in its
              current state"}

Since both variants are identical, the two fault factories collapse into one.
The descriptor form is still correct for the other type faults
(TypeDeprecatedFault, TypeAlreadyExistsFault, UnknownResourceFault), which were
verified unchanged in the same probe.

Also adds integration coverage for the five actions that had none at either
test layer: DeprecateActivityType, UndeprecateActivityType, DeleteActivityType,
ListWorkflowTypes, and RespondActivityTaskFailed. Every assertion is taken from
a live-service capture, including that scheduling a deprecated activity type
appends ScheduleActivityTaskFailed with cause ACTIVITY_TYPE_DEPRECATED and
leaves the execution open, that ListWorkflowTypes filters by registration
status and name, and that a second RespondActivityTaskFailed on the same token
reports "Unknown activity, scheduledEventId = 5".

The message tests fail on the previous behaviour with "Expected: The type is
currently registered ... Actual: WorkflowType=[name=TestWf, version=1.0]".

Signed-off-by: Andre Kurait <akurait@amazon.com>

* feat(swf): invoke real Lambda functions for ScheduleLambdaFunction

The decision was recorded as ScheduleLambdaFunctionFailed with cause
LAMBDA_SERVICE_NOT_AVAILABLE_IN_REGION rather than invoking anything. SWF is
otherwise a pure coordination service — deciders and activity workers are the
user's own processes, so there is no user code for the emulator to run — but
ScheduleLambdaFunction is the one decision where SWF itself executes something,
and Floci already runs Lambda functions in containers. A decider that fans work
out to Lambda could not be exercised locally at all.

Floci now invokes the function through its own Lambda service, the same way the
EventBridge and Scheduler invokers do, and records the outcome. Verified against
the live service:

  5 LambdaFunctionScheduled  {control, id, input, name, startToCloseTimeout}
  6 LambdaFunctionStarted    {scheduledEventId: 5}
  7 LambdaFunctionCompleted  {result, scheduledEventId: 5, startedEventId: 6}
  8 DecisionTaskScheduled

Four behaviours came from that capture and are easy to get wrong:

- A function that cannot be resolved is LambdaFunctionFailed with Lambda's own
  error code as reason (ResourceNotFoundException) — not
  ScheduleLambdaFunctionFailed — and it still reports Started first.
- An execution with no lambdaRole never starts the function at all: Scheduled is
  followed by StartLambdaFunctionFailed with cause ASSUME_ROLE_FAILED and the
  message "No IAM role is attached to the current workflow execution."
- lambdaRole resolves from StartWorkflowExecution's lambdaRole, falling back to
  the workflow type's defaultLambdaRole, and is echoed in the started event.
- An absent input reaches the handler as {}, and reusing an id is accepted —
  there is no ID_ALREADY_IN_USE for Lambda the way there is for activity ids.

SwfService takes a LambdaInvoker seam rather than LambdaService directly, so the
unit tests keep running without a Docker daemon while SwfLambdaInvoker wires the
real thing at runtime. The invocation is RequestResponse because the response
body is what gets recorded as result; the fire-and-forget invokers use Event for
the opposite reason.

The Lambda region comes from the execution's domain ARN, so a workflow in one
region does not invoke a function in another.

Tests: SwfServiceTest covers all four paths against a recording invoker and
fails on the previous behaviour with "the function must actually be invoked
==> expected: <1> but was: <0>". SwfLambdaIntegrationTest and the SDK
compatibility SwfLambdaTest deploy a real function and assert the recorded
result is what the container returned, so neither passes against a synthesised
event. Docker-backed cases live in their own class so a Docker-less run loses
only them rather than the whole SWF wire suite.

Signed-off-by: Andre Kurait <akurait@amazon.com>

* fix(swf): scope state by region and paginate the registration lists

Addresses two AWS compatibility gaps from review.

SWF names are unique per region, but storage keys were the bare name, so
registering a domain in us-east-1 made the same name in eu-west-1 fail as a
duplicate, and describe/list could return the first region's domain and ARN.
Verified against the live service: the same name registers in both regions with
independent descriptions and retention periods, each ARN naming its own region;
a type registered in one region answers UnknownResourceFault in the other; and
executions, including their runIds, do not cross.

Keys are now region-qualified — `<region>:<domain>` for domains,
`<region>:<domain>/<name>/<version>` for types, and
`<region>:<domain>/<workflowId>/<runId>` for executions — and every store scan
is prefixed by region. The region reaches the service on each call and is stored
on the execution, which is also what task tokens resolve through, so a token
issued in one region cannot address another's execution. The per-domain
mutation lock is region-qualified too; leaving it bare would have let two
regions serialize against each other, and would have disagreed with the
sweeper's own lock derived from the storage key.

ListDomains, ListWorkflowTypes and ListActivityTypes ignored maximumPageSize and
nextPageToken and returned everything. They now share one paging helper with the
history and execution listings. Details taken from live captures rather than the
docs: nextPageToken is absent on the final page even when that page is exactly
full, a maximumPageSize of 0 or absent means "no caller limit", above 1000 is
rejected rather than clamped, and a corrupt token answers
`ValidationException: Invalid token` instead of silently restarting at the first
page — which would make a paging loop repeat forever.

Adds AWS SDK regression tests (SwfRegionPaginationTest) driving two clients at
different regions against the same emulator, plus wire-level integration
coverage. Against the previous implementation those SDK tests fail with
DomainAlreadyExists on the second region, "maximumPageSize must cap the page: 5",
and nothing thrown for an oversized page size.

Signed-off-by: Andre Kurait <akurait@amazon.com>

* test(swf): pin reverseOrder as applying before pagination

The registration lists reverse the whole result set and then page it, so with
maximumPageSize=3 and reverseOrder=true the first page is the tail of the
ascending order. That was already the behaviour but nothing asserted it, and the
shared paging helper makes "page first, then reverse the page" an easy
regression to introduce.

Measured against the live service: 5 types at page size 3 reversed returns
Paged4, Paged3, Paged2 and then Paged1, Paged0. Injecting the page-then-reverse
ordering fails the new test with
"Expected: <[Paged4, Paged3, Paged2]>".

Signed-off-by: Andre Kurait <akurait@amazon.com>

* test(swf): cover region scoping at the wire level

The region-scoping tests went in at the service and SDK layers, but every
SwfIntegrationTest request omitted an Authorization header, so nothing asserted
that the region is read from the SigV4 credential scope — the step that decides
which region's state a call addresses.

Adds a wire test that sends a credential scope naming the region, covering the
same name registering in two regions with independent descriptions, retentions
and ARNs, a type being unknown in the other region, and a same-region
re-registration still faulting.

Against 7cc6c0f2 the test fails with
DomainAlreadyExistsFault / "Expected status code <200> but was <400>".

Signed-off-by: Andre Kurait <akurait@amazon.com>

* fix(swf): correct four decision, polling and locking cases from review

An invalid decision anywhere in a batch could still mutate the execution.
respondDecisionTaskCompleted appended DecisionTaskCompleted, dropped the token
and applied earlier decisions before applyDecision's default arm rejected an
unknown decisionType mid-loop, so [RecordMarker, NotARealDecision] grew the
history from 3 to 5 events and burned the token. A try/catch cannot undo that —
decisionTokens is a separate map and the history lands on the in-memory
execution — so the whole batch is now validated up front, extending the shape
requireCloseIsLastDecision already used. Both rules live in one requireValidBatch,
and the accepted types come from SwfConstants.DECISION_TYPES so the check and the
message quoting the enum set cannot drift.

PollForDecisionTask with a nextPageToken claimed a new task instead of paging the
original. AWS states that "calling PollForDecisionTask with a nextPageToken
doesn't return a new decision task", and the live service answers a continuation
with the same startedEventId, previousStartedEventId and workflowExecution, plus
the next contiguous history page. The continuation token now names the task it
belongs to, so a continuation resolves that task rather than polling again.
startAtPreviousStartedEvent was modeled but read nowhere; it now trims the window
to events from previousStartedEventId onward, which the live service treats as
inclusive.

A child that continued as new lost its parent. The successor was built from a
StartWorkflowExecutionRequest, which carries no parent fields, so its parent was
null and the parent kept tracking the closed run — never learning the successor's
outcome and never applying child policy to it. carryParentTo moves the parent
identifiers and repoints the parent's childExecutions entry before the successor's
WorkflowExecutionStarted is appended, so that event names the parent as it does
on the live service.

The Lambda invocation held the domain lock. That lock deliberately covers a whole
domain family, so a cold start stalled every unrelated execution in the domain.
A decision now queues the invocation, records LambdaFunctionScheduled and
LambdaFunctionStarted under the lock, and the invocation runs after the lock is
released; the outcome is recorded under the lock again, so the state transition
around the result stays atomic.

Guards, each failing on the code before it: the batch case with
"a rejected batch must not grow the history ==> expected: <3> but was: <5>", the
continue-as-new case with "the successor of a child must keep its parent ==>
expected: <wf-cn-parent> but was: <null>", the two polling cases on an empty
continuation response, and the liveness case by blocking inside the invoker and
signalling an unrelated execution in the same domain.

Signed-off-by: Andre Kurait <akurait@amazon.com>

* refactor(swf): collapse the paging helpers into one, and cap every operation

Three page-token codecs and three copies of the same offset/limit/token block had
accumulated across the history, execution and registration listings, plus a
fourth for the PollForDecisionTask continuation. There is now one Page record
with one encode/decode pair — the task token is an optional field, which is the
only thing the poll needed — and one pagedList helper the history and execution
listings reuse. Net 62 fewer lines in the service and handler.

Collapsing the two page-size methods surfaced a real divergence rather than just
shortening code: historyPageSize clamped an oversized maximumPageSize while the
registration lists rejected it. The live service rejects it everywhere, measured
on GetWorkflowExecutionHistory, ListOpenWorkflowExecutions and
PollForDecisionTask, and rejects a negative value with its own message
("greater than or equal to 0"). One pageSize method now serves all of them.

Signed-off-by: Andre Kurait <akurait@amazon.com>

* docs(swf): document batch atomicity, poll continuation and the page-size cap

The three behaviours the last two commits changed were only visible in the code: a decision batch is all-or-nothing, a PollForDecisionTask continuation pages the same task rather than claiming a new one (and startAtPreviousStartedEvent is inclusive), and the 1000 page-size cap applies to every paginated operation rather than only the registration lists.

Signed-off-by: Andre Kurait <akurait@amazon.com>

* fix(swf): render the decisionType enum set in the service's own order

The rejection message for an unknown decisionType listed the enum members in the
API model's order. The live service uses a different order, stable across
repeated calls, so a client comparing the message byte-for-byte saw a mismatch:

  service: [CompleteWorkflowExecution, StartTimer, RequestCancelExternal...
  model:   [ScheduleActivityTask, RequestCancelActivityTask, CompleteWork...

Taken from four live responses rather than from the model. The guard now asserts
the whole message instead of a substring, and fails on the previous order with
the two strings diffed in full.

Signed-off-by: Andre Kurait <akurait@amazon.com>

* fix(swf): scope queued Lambda work to the request, not the thread

The queue of deferred invocations was a ThreadLocal drained after the domain lock
was released. On a pooled request thread that outlives the request: if anything
threw between queueing an invocation and draining, the work stayed on the thread
and the next decision response ran it — invoking a real function for a request
that had already failed, and recording the outcome against whatever state that
later execution was in.

The queue is now a local list created per call and threaded through
applyDecisions, so the drain is reachable only after the batch has been applied
and stored. A request that throws leaves the list unreferenced; there is no
cross-request carrier left to leak through.

Signed-off-by: Andre Kurait <akurait@amazon.com>

* test(swf): guard that a failed batch leaves no queued Lambda work

Reaches the leak window by failing the execution store after a Lambda has been queued and the history mutated, then issuing a second request on the same thread.

Signed-off-by: Andre Kurait <akurait@amazon.com>

---------

Signed-off-by: Andre Kurait <akurait@amazon.com>
2026-08-14 11:16:21 -04:00
Alex Banna 5657e35007 feat(cloudfront): enforce signed private content (#1831)
* feat(cloudfront): serve distribution requests from S3 and custom origins

* feat(cloudfront): enforce signed private content

* chore: re-run CI

The Build and Test failure on the previous head was RuntimeApiServerTest's
extension/stop race, a pre-existing flake unrelated to this change — it also failed
on #1820, #1823 and on #2131's own branch (the PR that tried to de-flake it).
Reproduced locally under `--cpus=1` and fixed separately.

* fix(cloudfront): wildcard aliases match exactly one subdomain level

wildcardAliasMatches did a plain suffix check, so "*.example.com" also matched
a.b.example.com. AWS is explicit that a wildcard alternate domain name replaces the
wildcard at that level only:

  "you can't add alternate domain names that are at levels higher or lower than the
   wildcard. For example, you can't add the alternate domain names example.com or
   marketing.product.example.com."

  https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/CNAMEs.html

Practical effect: a distribution owning "*.example.com" would answer for
a.b.example.com, which on AWS belongs to whoever owns "*.b.example.com" — or to
nobody. Require the label standing in for the wildcard to contain no dot.

wildcardAliasesMatchSubdomainsAndPreferMoreSpecificNames asserted the old behaviour
(a.b.example.test resolving to the *.example.test distribution); it now asserts no
match, plus the same for a deeper wildcard.

* test(dynamodb): retain Quarkus port for cleanup

* fix(cloudfront): isolate mocked storage backends

* fix(cloudfront): match wildcards in signed policy queries
2026-08-13 23:32:24 -04:00
Priamo Germosen d78520d5cb feat(kinesisanalytics): add Managed Service for Apache Flink (Kinesis Analytics V2) (#1914)
* feat(kinesisanalytics): add Managed Service for Apache Flink (Kinesis Analytics V2)

Adds the kinesisanalyticsv2 service (X-Amz-Target KinesisAnalytics_20180523.*):
a control-plane state machine plus a real Apache Flink JobManager container spun up
as a sidecar on StartApplication, modeled on the AmazonMQ->RabbitMQ pattern.

- CreateApplication -> READY, StartApplication -> STARTING -> RUNNING via a readiness
  poller, StopApplication -> READY, DeleteApplication -> removed
- Container image chosen from the requested RuntimeEnvironment (FLINK-1_15..1_20 ->
  apache/flink:1.x) via KinesisAnalyticsRuntimes, with an optional operator override;
  unsupported runtimes (SQL / Zeppelin) rejected with InvalidArgumentException
- Container naming via ContainerStorageHelper.resourceName (floci-kinesisanalytics-<name>)
- Registered in ResolvedServiceCatalog, dispatched by AwsJson11Controller; container
  teardown wired into EmulatorLifecycle.onStop
- Tests: service + handler unit tests, @QuarkusTest integration, Java SDK compatibility test
- Docs: service page, services index, README, environment-variable reference

* fix(kinesisanalytics): enforce delete/update state and version/timestamp guards

Addresses review feedback (self-review + Greptile) on the Managed Flink service:

- DeleteApplication rejects a non-READY (RUNNING/STARTING) application with
  ResourceInUseException; the caller must StopApplication first (Greptile P1)
- DeleteApplication validates the required CreateTimestamp against the stored value
- UpdateApplication validates CurrentApplicationVersionId (ConcurrentModificationException
  on mismatch, InvalidArgumentException when absent)
- StopApplication error message reads 'RUNNING or STARTING' to match the guard
- Readiness poller @PreDestroy awaits termination (bounded) before returning so a
  mid-flight write cannot race the shutdown storage flush
- Drop the unused Tags field from FlinkApplication (full tag support tracked as a follow-up)
- Compat test @AfterAll logs tolerated teardown failures (AGENTS.md) and stops before delete

Tests updated accordingly and verified live against the packaged jar.

* feat(kinesisanalytics): deploy and run the application JAR on the Flink cluster

Implements real job submission for Managed Service for Apache Flink, so the AWS
'deploy a JAR' flow actually runs the job (previously only a bare JobManager reached RUNNING):

- CreateApplication parses and stores ApplicationConfiguration (ApplicationCodeConfiguration
  S3ContentLocation + ParallelismConfiguration); DescribeApplication echoes it back as
  ApplicationConfigurationDescription
- StartApplication reads the JAR from Floci's local S3 (via S3Service), starts a JobManager plus a
  TaskManager (sharing the JobManager network namespace for localhost RPC), then uploads and runs the
  JAR via the Flink REST API (new FlinkRestClient); the app reaches RUNNING when the Flink job is RUNNING
- StopApplication cancels the job and tears down both containers
- Applications created without code still come up as a bare cluster
- Docs + README updated; unit tests for config round-trip; verified live end-to-end against the
  packaged jar (S3 JAR -> RUNNING Flink job -> stop/delete cleanup)

Not yet emulated: EnvironmentProperties injection, snapshots/savepoints, in-place code updates.

* fix(kinesisanalytics): align Flink runtimes with AWS and add the 2.x line

The runtime map now mirrors the runtimes AWS Managed Service for Apache Flink actually offers:

- Add FLINK-2_0 / 2_1 / 2_2 / 2_3 -> apache/flink:2.0/2.1/2.2/2.3 (the Flink 2.x line; FLINK-2_2 is in
  the AWS SDK RuntimeEnvironment enum and the whole 2.x line has published apache/flink images)
- Remove FLINK-1_16 / FLINK-1_17 -> AWS does not offer these runtimes, so Floci should reject them too
  rather than accept versions real AWS refuses

Supported set: FLINK-1_15, 1_18, 1_19, 1_20, 2_0, 2_1, 2_2, 2_3. Tests + docs + README updated.

* test(kinesisanalytics): cover both Flink 1.18 and 2.3 in the SDK compat test

Refactor the single-runtime compat test into an abstract ordered lifecycle run against two
runtimes, so the suite guards both the Flink 1.x and 2.x lines (Flink 2.0 changed the config
system and boots slower):

- AbstractKinesisAnalyticsV2LifecycleTest: PER_CLASS instance state + the create->start->RUNNING->
  list->stop->unsupported->delete lifecycle, parameterized on an abstract runtime()
- KinesisAnalyticsV2Flink118Test (FLINK-1_18) and KinesisAnalyticsV2Flink23Test (FLINK-2_3)
- FLINK-2_3 is passed as a string (newer than the pinned SDK 2.44.14 enum) and asserted via
  runtimeEnvironmentAsString(); RUNNING wait bumped to 300s for Flink 2.x's slower boot

Verified live: both subclasses boot real apache/flink:1.18 and :2.3 clusters and reach RUNNING
(0 skipped). CI now exercises two clusters; both skip gracefully when Docker is unavailable.

* fix(kinesisanalytics): preserve AwsException from a bad application-code S3 location

StartApplication's catch(RuntimeException) wrapped every failure from startCluster into
InternalFailureException (HTTP 500) — including the AwsException that readJar throws when the
application-code S3 object is missing/empty/unreadable. A client's bad S3 code location therefore
surfaced as a 500 server error instead of the intended InvalidArgumentException (400).

Now AwsException propagates as-is (preserving its error code and message); only unexpected
RuntimeExceptions (e.g. Docker unavailable) become InternalFailureException. Addresses Greptile P1.

* feat(kinesisanalytics): add resource tagging (TagResource/UntagResource/ListTagsForResource)

Adds Tags support to CreateApplication plus TagResource, UntagResource, and
ListTagsForResource, dispatched as regular JSON1.1 actions under the same
KinesisAnalytics_20180523 target prefix as every other action — verified
against the real botocore kinesisanalyticsv2 model that this API has no
separate REST tagging endpoint (protocol is pure "json"/1.1 with all
operations on POST /), unlike REST-JSON services (EKS, MWAA) that use the
shared /tags/{arn} controller.

Tags is a list of {Key, Value} objects on the wire (not a map), same shape
MemoryDB's handler already uses for its own tagging actions; mirrored that
parse/build pattern rather than the map-shaped TagHandler interface. Tags
are stored on FlinkApplication but, matching the real API, never echoed in
ApplicationDetail (CreateApplication/DescribeApplication) — only
ListTagsForResource returns them. TagResource enforces AWS's 50
user-defined-tag ceiling (TooManyTagsException) on both CreateApplication
and TagResource.

docs/services/kinesisanalytics.md's action table is auto-generated from the
handler source (tools/docs/regen_action_docs.py) — regenerated it and filled
in the three new rows' hand-written descriptions.

* feat(kinesisanalytics): inject EnvironmentProperties into the Flink cluster

CreateApplication now accepts ApplicationConfiguration.EnvironmentProperties
.PropertyGroups and writes them to /etc/flink/application_properties.json in
both the JobManager and TaskManager containers before the job runs — the
same well-known path and JSON shape (a list of {PropertyGroupId, PropertyMap}
objects, matching the AWS API's own PropertyGroups shape) real Managed
Service for Apache Flink uses, so a JAR written against
KinesisAnalyticsRuntime.getApplicationProperties() picks them up unmodified
against Floci. DescribeApplication echoes them back under
ApplicationConfigurationDescription.EnvironmentPropertyDescriptions
.PropertyGroupDescriptions.

/etc/flink does not exist in the stock apache/flink image, and the
container's non-root "flink" user (uid 9999) can't create it directly under
/etc (confirmed live: mkdir -p /etc/flink fails with permission denied as
that user). The fix, also verified live: name the tar entry
"flink/application_properties.json" and extract into the existing /etc
rather than targeting /etc/flink directly — the daemon-level copy API can
create the missing subdirectory as part of unpacking the archive even
though the in-container user couldn't, landing as root:root 775 (so it's
still world-readable by the flink user). A real apache/flink:1.18 container
was used to verify both the failure mode and the fix before writing the
Java implementation.

* feat(kinesisanalytics): add application snapshot (savepoint) support

Adds CreateApplicationSnapshot/DescribeApplicationSnapshot/ListApplicationSnapshots/
DeleteApplicationSnapshot. Triggers a real Flink savepoint of the running job and
polls it to completion the same way StartApplication polls job readiness. Snapshot
files land on a persistent named Docker volume mounted at /opt/flink/savepoints in
the JobManager container, so they survive a Stop/Start cycle; the volume is only
removed on DeleteApplication.

* feat(kinesisanalytics): support in-place application code updates

UpdateApplication with a new ApplicationCodeConfigurationUpdate (or
ParallelismConfigurationUpdate) now redeploys onto an already-running application
without tearing down its JobManager/TaskManager containers: the current job is
cancelled and the new JAR is uploaded and run on the same cluster, transitioning
RUNNING -> STARTING -> RUNNING the same way StartApplication submits a fresh job.
Updating a READY application just stores the new code location for the next
StartApplication. Attaching code to a running bare cluster for the first time is
not yet supported and is rejected with InvalidRequestException.

* fix(kinesisanalytics): use AWS's documented generic InternalFailure code

startApplication and updateApplication's redeploy-code path threw an invented
"InternalFailureException" for unexpected Docker provisioning failures — not a
shape kinesisanalyticsv2's model declares (no operation in this API declares any
5xx shape at all). AWS documents "InternalFailure" (no "Exception" suffix, HTTP
500) as the generic error common to every service's API; it's also already the
default used elsewhere in this codebase (JsonErrorResponseUtils, KMS, Pricing,
SES, CloudControl, EventBridge, and others).

* feat(kinesisanalytics): add CreateApplicationPresignedUrl and SnapshotsEnabled

CreateApplicationPresignedUrl returns a URL to the running application's Flink
Dashboard (UrlType: FLINK_DASHBOARD_URL only; Zeppelin/Studio isn't supported).
Floci has no real session/proxy layer for this, so it returns the JobManager
container's own REST/dashboard URL directly, while still validating UrlType and
SessionExpirationDurationInSeconds against AWS's documented constraints.

ApplicationSnapshotConfiguration.SnapshotsEnabled (default true, matching real
AWS) is now honored on CreateApplication and toggleable via UpdateApplication's
ApplicationSnapshotConfigurationUpdate; CreateApplicationSnapshot rejects the
request with InvalidRequestException while disabled.

* fix(kinesisanalytics): persist flinkJobId as soon as the job is submitted

The readiness poller only called putApplication when advanceToRunning reported
RUNNING, not when it merely assigned flinkJobId after submitting the job (which
returns false until the job state catches up). pendingJars — a separate,
in-process-only cache — is already cleared by that point, so an emulator
restart between job submission and reaching RUNNING would leave the
application stuck: no persisted flinkJobId to resume polling, and no cached
JAR left to resubmit.
2026-08-09 15:01:30 -04:00
Alex Bannaandabanna aadc93e306 feat(rum): add CloudWatch RUM app-monitor service (#1797)
* feat(rum): add CloudWatch RUM app-monitor service

Adds a minimal CloudWatch RUM service (restJson1) covering the app-monitor
lifecycle — CreateAppMonitor, GetAppMonitor, UpdateAppMonitor, DeleteAppMonitor,
ListAppMonitors — backed by an in-memory store.

Previously restJson1 RUM requests (e.g. POST /appmonitor) fell through to the S3
path-style catch-all (@Path("/{bucket}")) and returned an XML error that
restJson1 SDKs (and the CDK AwsCustomResource used for RUM AppMonitor custom
resources) cannot parse. Literal /appmonitor and /appmonitors paths take JAX-RS
precedence over S3's /{bucket} template (the same mechanism eks/mq use), so the
routes win with no extra routing wiring.

Verified with aws-cli 2.33.18 against a dev-mode emulator: CreateAppMonitor
returns an Id, GetAppMonitor/ListAppMonitors round-trip, DeleteAppMonitor then
GetAppMonitor returns ResourceNotFoundException.

* fix(rum): make monitor updates atomic

* fix(rum): align app monitor lifecycle with AWS

* chore: retry flaky Node compatibility check

* fix(rum): address app-monitor review feedback

---------

Co-authored-by: abanna <abanna@users.noreply.github.com>
2026-08-01 15:28:54 -05:00
kotov228 97b64a1d3b feat: add AWS Lightsail emulation (#1583)
* feat(lightsail): add AWS Lightsail emulation

* fix(lightsail): align error responses with AWS

* fix(lightsail): address review edge cases

* fix(lightsail): reject attached disk reattach

* fix(lightsail): reject static ip reattach

* fix: register lightsail docs handler
2026-07-10 20:43:42 -05:00
Ahmed khaled 188854f2df feat(amazonmq): add Amazon MQ broker control plane backed by RabbitMQ (#1642)
* feat(amazonmq): add Amazon MQ broker control plane for RabbitMQ

* feat(amazonmq): provision RabbitMQ container with rollback

Back a broker with a real rabbitmq:3-management container, following the
MSK/ElastiCache container-manager pattern.

- RabbitMqManager starts the container, publishes AMQP (5672) and
  management (15672) ports, and resolves the broker endpoints
- Service branches on the mock flag; real brokers stay
  CREATION_IN_PROGRESS until a readiness poller observes the management
  API answering, then flip to RUNNING
- Rollback on failed provisioning: the manager removes the half-built
  container and the broker is persisted as CREATION_FAILED
- @PreDestroy stops containers on shutdown; DeleteBroker stops and
  removes the container and its storage

Readiness probes the management UI root (no auth) to avoid RabbitMQ's
loopback-only guest user over Docker port mapping.

* feat(amazonmq): seed broker admin user and reject ActiveMQ-only User API

Amazon MQ's standalone User API (CreateUser/DescribeUser/ListUsers/
DeleteUser) applies only to ActiveMQ brokers; AWS rejects it for RabbitMQ
and directs callers to the RabbitMQ web console. CreateBroker now requires
exactly one broker user (validated against AWS password rules) which is
seeded into the container via RABBITMQ_DEFAULT_USER/PASS, sidestepping
RabbitMQ's loopback-only guest restriction.

* test(amazonmq): SDK compatibility test against live RabbitMQ broker

Adds AmazonMqTest exercising the real container path via the AWS SDK MqClient:
CreateBroker provisions a rabbitmq:3-management container, the broker
transitions to RUNNING once its management API answers, endpoints are
published, the ActiveMQ-only User API is rejected, and DeleteBroker tears the
container down. Uses JUnit Assumptions to skip cleanly when Docker is absent.

* fix(amazonmq): harden error handling, persistence, and shutdown teardown

- Redact the provisioning failure 500: log the cause, return a generic AWS
  error envelope instead of leaking e.getMessage() (which can be null).
- Add @JsonIgnoreProperties(ignoreUnknown = true) to Broker, MqUser, and
  BrokerInstance so old persisted snapshots survive field changes.
- Wire RabbitMQ container teardown into EmulatorLifecycle.onStop() via
  RabbitMqManager.stopAll(), alongside the other container managers; the
  service @PreDestroy now only stops the readiness poller.

* docs(amazonmq): add Amazon MQ service page and bump service count to 66

Adds docs/services/amazonmq.md, lists Amazon MQ in the services overview and
README service tables, and updates the "65 -> 66 AWS services" count across
docs/index.md, docs/services/index.md, and README.md.

* fix(amazonmq): reject RebootBroker unless the broker is RUNNING

RebootBroker unconditionally set the broker to RUNNING, so a non-RUNNING
broker (e.g. CREATION_FAILED, which has no backing container) was silently
promoted to RUNNING and never reconciled by the readiness poller. AWS allows
RebootBroker only on a broker in the RUNNING state; guard it and return a 400
otherwise, matching the Amazon MQ API ("You can reboot only a broker with the
RUNNING status").

* fix(amazonmq): close readiness-probe connection and log tolerated failures

isReady() opened an HttpURLConnection but never disconnected it; since the
probe runs every 2s per pending broker this leaked sockets. Disconnect in a
finally block, and log the tolerated failure at debug with broker/URL context
(AGENTS.md: no empty catch; avoid noise in hot paths) instead of swallowing it.

* fix(amazonmq): tear down broker container by deterministic name after restart

containerId is in-memory bookkeeping (intentionally not persisted, since the
Broker model is serialized straight to DescribeBroker and must not leak it).
After an emulator restart it is null, so stopContainer() previously returned
early and left the container running. It now falls back to the deterministic
container name (floci-amazonmq-{brokerId}) so an explicit DeleteBroker still
removes a container left over from a previous run. Documented the field and
added RabbitMqManagerTest covering both the id and name-fallback paths.

* fix(amazonmq): keep admin password in-memory only and fail loudly if absent

The admin password is a secret used solely to seed the RabbitMQ container at
create time. Persisting it (to make it survive a restart) would write the
credential in cleartext to amazonmq-brokers.json, which the project's security
rule prohibits. It stays in-memory only via @JsonIgnore; startContainer (the
only consumer, called from CreateBroker) now throws if the password is absent
rather than seeding a null credential. Added MqUserTest asserting the password
is never serialized and round-trips to null.

* fix(amazonmq): persist broker volumeId/accountId/containerId without leaking them

These internal fields were @JsonIgnore'd, so they were absent from
amazonmq-brokers.json. After a restart in persistent mode volumeId was null
(removeBrokerStorage could not locate the named volume, leaking it) and
accountId was null (the readiness poller wrote brokers via the non-account-aware
path). Unlike the admin password, these are not secrets, so they should persist.

Remove @JsonIgnore so they round-trip through storage, and build the
DescribeBroker response explicitly in the controller so they are still never
exposed to clients (matches MskCluster, which persists volumeId/containerId).
Adds BrokerTest (round-trip) and asserts the describe response omits them.
2026-07-03 00:01:54 -05:00
shrimptails-f 0ac1a01884 fix(ses): align CreateEmailIdentity DKIM behavior with AWS (#1620)
* fix(ses): align CreateEmailIdentity DKIM behavior with AWS

* test(ses): verify tracking domains via route53 in sdk compatibility tests

* fix(ses): cache pending DKIM Route53 lookups

* test(ses): log cleanup failures in tracking options test
2026-07-02 18:09:36 -05:00
Hector Ventura b87955b630 chore(deps): update maven dependencies and github actions (#1690)
Combines the open dependabot updates with the vulnerable-dependency pins:

- quarkus platform 3.36.0 -> 3.36.3, apicurio 2.6.9.Final -> 2.6.13.Final
- graphql-java 22.0 -> 26.0, neo4j-java-driver 5.28.5 -> 6.1.0 (test)
- import jackson-bom 2.21.4 and pin wire-runtime 6.3.0
- compat tests: aws sdk 2.44.14, netty-bom 4.1.135.Final, postgresql 42.7.11,
  jackson-bom 2.18.8, kafka-clients 3.9.2, commons-lang3 3.18.0
- actions/checkout v7.0.0, configure-aws-credentials v6.2.0, setup-graalvm pin
2026-07-01 23:27:56 -05:00
nblomquistandnathan 326b495496 feat(iot) Feature/issue 1038 iot core (#1359)
* feat: add IoT endpoint and thing registry

* feat: add IoT thing tagging

* feat: add IoT certificates and shadows

* feat: add IoT MQTT broker

* feat: upgrade IoT MQTT broker to Moquette 0.18

* feat: restore IoT reserved MQTT topics

* feat: add IoT topic rules engine

* feat: improve IoT thing registry compatibility

* feat: complete IoT MVP 1 compatibility

* feat: complete IoT MVP 2 compatibility

* feat: finish IoT MVP 2 coverage

* fix: disable IoT MQTT broker persistence

* fix(docker): include vendored Maven artifacts in source builds

* fix(iot): stabilize MQTT integration test sockets

* fix(iot): verify MQTT test connections

* fix(iot): use Paho for MQTT integration tests

* fix(iot): use Vert.x MQTT broker

---------

Co-authored-by: nathan <nathan@debian-dev-small.localdomain>
2026-06-25 22:58:44 -05:00
kotov228 efacb37130 feat: Adds initial Elastic Beanstalk Query API support to Floci. (#1362)
* feat: add Elastic Beanstalk query API support

feat: add Elastic Beanstalk query API support

* fix(elasticbeanstalk): configure native-image runtime initialization

* fix(elasticbeanstalk): align missing parameter errors and add application ARN

* test(elasticbeanstalk): add Java SDK compatibility coverage
2026-06-25 19:16:51 -05:00
Jason van Zyl e8b54e45e9 fix(autoscaling): reject launch templates without image ids (#1451) 2026-06-21 09:40:33 -05:00
kotov228 3f314dcb4e feat(codepipeline): add AWS CodePipeline emulation (#1469)
* feat(codepipeline): add AWS CodePipeline emulation

* fix(codepipeline): align webhook and rollback response shapes
2026-06-21 09:01:44 -05:00
Prakhar Kapoor 93782c0142 feat(s3vectors): add S3 Vectors service support (#1435)
* feat(s3-vector-store): add S3Vectors service support with storage configuration and integration testing

* feat(s3-vector-store): implement S3 Vectors service API with controller, service, and integration tests
2026-06-21 00:55:10 -05:00
Hector Ventura 33cb72e341 feat(wafv2): add AWS WAF v2 management API (Phase 1) (#1327)
Add the wafv2 (AWSWAF_20190729) JSON 1.1 service: Web ACLs, IP sets, regex
pattern sets, and rule groups, plus resource association, logging and permission
policies, and tagging. Uses LockToken optimistic concurrency and isolates the
CLOUDFRONT and REGIONAL scopes.

Covered by an in-repo RestAssured integration test and an AWS SDK v2
compatibility test.
2026-06-13 09:25:55 -05:00
Hector Ventura 8b5adea915 feat(emr): add Amazon EMR management API (Phase 1) (#1321)
Add the elasticmapreduce (ElasticMapReduce) JSON 1.1 service: cluster lifecycle
with a simulated state machine, job-flow steps, instance groups and fleets,
security configurations, and tags. Honours the ActionOnFailure legacy alias and
EMR's distinct error shapes.

Operations: RunJobFlow, DescribeCluster, ListClusters, TerminateJobFlows,
SetTerminationProtection, SetVisibleToAllUsers, SetKeepJobFlowAliveWhenNoSteps,
SetUnhealthyNodeReplacement, ModifyCluster, AddJobFlowSteps, DescribeStep,
ListSteps, CancelSteps, AddInstanceGroups, ListInstanceGroups, AddInstanceFleet,
ListInstanceFleets, ListInstances, CreateSecurityConfiguration,
DescribeSecurityConfiguration, DeleteSecurityConfiguration,
ListSecurityConfigurations, AddTags, RemoveTags.

EmrService holds a static SecureRandom, so it is registered under
quarkus.native.resources additional-build-args --initialize-at-run-time to keep
the GraalVM native build working.

Covered by an in-repo RestAssured integration test and an AWS SDK v2
compatibility test.
2026-06-13 09:01:48 -05:00
Jason van Zyl 9a244a6964 Add CloudTrail trail lifecycle support (#1256)
* feat(cloudtrail): add trail lifecycle operations

* test(cloudtrail): cover provisioning integration

* test(cloudtrail): add SDK compatibility coverage

* fix(cloudtrail): harden trail lifecycle state
2026-06-11 01:57:18 -05:00
nblomquistandnathan 92f4ff1ccf Feature/issue 1130 glue database tags (#1248)
* fix(glue): register database tags with tagging API (#1130)

* test(glue): add database tagging compatibility coverage (#1130)

* test(tagging): allow additional tagged resources (#1130)

---------

Co-authored-by: nathan <nathan@debian-dev-small.localdomain>
2026-06-11 00:47:00 -05:00
Hector Ventura b449ba2c29 feat(cloudmap): add AWS Cloud Map (servicediscovery) management API (#1217)
* feat(cloudmap): add AWS Cloud Map (servicediscovery) management API

Implements the Route53AutoNaming_v20170314 JSON 1.1 service: namespace
management (HTTP/public-DNS/private-DNS), services, instance register/
deregister, async operation tracking, DiscoverInstances/DiscoverInstancesRevision
(honouring the data- host prefix), instance health status, and tags.

Dispatched via AwsJson11Controller; storage through StorageFactory; config in
EmulatorConfig + application.yml. Covered by an in-repo RestAssured integration
test and an AWS SDK v2 ServiceDiscoveryClient compatibility test.

* refactor(cloudmap): drop unused prefix variable in scanInstances
2026-06-07 07:24:30 -05:00
AgustinBertagna d7ddac73fe feat(appsync): AWS AppSync management API (Phase 1) (#1108)
* feat(appsync): add GraphQL API management service

Implement Phase 1 CRUDL management API for AWS AppSync.
Includes controller, service layer, and model classes for:
- GraphQL API lifecycle (create/get/update/delete/list)
- Schema creation and introspection
- Data Sources, Resolvers, Functions, Types, API Keys
- Tagging and Environment Variables

* chore(appsync): register service in config and catalog

Add AppSync service configuration (EmulatorConfig), service
descriptor (ResolvedServiceCatalog), YAML config entries, and
SDK test client fixture.

* test(appsync): add integration and SDK compatibility tests

AppSyncIntegrationTest: 44 tests covering CRUDL for all resources
 GraphQL API, Schema, DataSources, Resolvers, Functions, Types,
 API Keys, Tags, Environment Variables, and cascade delete.

AppSyncTest: AWS SDK v2 compatibility tests for management API
 operations using the real AppSyncClient.

* feat(appsync): add typed enums for AWS API models

Add Java enums matching AWS AppSync API constants:
- AuthenticationType (API_KEY, AWS_IAM, COGNITO, OIDC, LAMBDA)
- DataSourceType (NONE, LAMBDA, DYNAMODB, HTTP, EVENTBRIDGE, ...)
- ResolverKind (UNIT, PIPELINE)
- ResolverRuntimeName (APPSYNC_JS, VTL)
- TypeFormat (SDL, JSON)
- SchemaCreationStatusType (PROCESSING, ACTIVE, FAILED, ...)

* refactor(appsync): align model types with AWS API reference

- DataSource.type: String → DataSourceType enum
- GraphqlApi.authenticationType: String → AuthenticationType enum
- GraphqlApi.logConfig: String → Map<String, Object> (structured)
- GraphqlApi.additionalAuthenticationProviders: Map → List<Map> (array)
- GraphqlApi.xrayEnabled: String → Boolean
- Resolver.kind: String → ResolverKind enum
- Resolver.ResolverRuntime.name: String → ResolverRuntimeName enum
- AppSyncType.format: String → TypeFormat enum
- SchemaCreationStatus.status: String → SchemaCreationStatusType enum
- ApiKey.expires: String → Long (epoch seconds)

* fix(appsync): correct ARN format, add enum validation, fix field types

- Function ARN: add missing region parameter
- Add parseEnum() helper for type-safe enum deserialization
- Reject invalid enum values with BadRequestException (400)
- Handle String/Boolean/Number coercion for xrayEnabled, expires
- Remove extra 'details' from StartSchemaCreation response
- Pass region to createFunction from controller

* fix(appsync): validate required fields on resource creation

Reject requests missing required fields with BadRequestException (400):
- CreateGraphqlApi: name required
- CreateDataSource: name and type required
- CreateResolver: fieldName and dataSourceName required
- CreateFunction: name required
- CreateType: name required

* test(appsync): add error handling, delete standalone, and cascade tests

Add 22 new integration tests (44 → 66 total):
- Error handling: missing name, blank name, invalid enum, missing required
  fields for API/DataSources/Resolvers/Functions/Types (11 tests)
- Non-existent resource 404 tests for API, DataSource, Type (3 tests)
- Delete standalone: verify CRUD delete for Resolver, DataSource,
  Function, Type, ApiKey with post-delete 404 confirmation (5 tests)
- Cascade verification: API delete cascades to DataSources and Functions;
  Function delete does not affect resolvers (3 tests)

* feat(appsync): add pagination support for list endpoints

Add maxResults and nextToken query params to all list endpoints:
- ListGraphqlApis, ListDataSources, ListResolvers, ListResolversByFunction
- ListFunctions, ListTypes, ListApiKeys

Uses offset-based pagination with Base64-encoded tokens, following
the Pricing service pattern. Returns nextToken when more results
are available, null when all results have been returned.

* test(appsync): add pagination integration tests

Add 9 pagination tests (66 → 75 total):
- ListApis with maxResults returns subset and nextToken
- ListApis with nextToken returns second page
- ListApis without pagination returns all items
- ListDataSources, ListTypes, ListFunctions, ListApiKeys,
  ListResolvers with maxResults
- Invalid nextToken returns 400

* fix(appsync): align SDK test with AWS SDK v2 model, extract type name from SDL

- Fix SDK test: use typeAsString() for enum comparison, remove apiKey()
  field assertion, use functions() instead of functionConfigurationList()
- Extract type name from SDL definition when name is not provided
  (matches real AWS CreateType behavior)
- Update integration test for type creation without explicit name

* fix(appsync): use extracted type name when definition-based extraction succeeds

The type name extracted from SDL definition was stored in a local
variable but not set on the AppSyncType object, causing createType
to return a type without name and making subsequent get/delete fail.

* refactor(appsync): inject RegionResolver instead of passing region as string

Follow the established pattern used by BackupService and PipesService.
Replace manual ARN string concatenation with regionResolver.buildArn()
and remove the hardcoded accountId field.

* fix(appsync): add functionId to Resolver model and fix listResolversByFunction filtering

The listResolversByFunction endpoint was incorrectly comparing
function.getName() with resolver.getDataSourceName(), which is not
the correct AWS AppSync relationship. Resolvers reference functions
via a functionId field, not by data source name matching.

- Add functionId field to Resolver model
- Handle functionId in createResolver and updateResolver
- Fix listResolversByFunction to filter by functionId
- Add listResolversByType method for per-type filtering

* feat(appsync): add global listResolvers endpoint

Add GET /v1/apis/{apiId}/resolvers to list all resolvers across all
types, matching the AWS AppSync API. The per-type endpoint
(GET /v1/apis/{apiId}/types/{typeName}/resolvers) is preserved.

- Add global listResolvers to controller
- Rename per-type endpoint to listResolversByType for clarity
- Add integration test for global listResolvers
- Update listResolversByFunction test to verify functionId-based filtering

* test(appsync): complete SDK compatibility tests for Phase 1

Add missing SDK v2 compatibility tests to match all Phase 1 operations:

- API Keys: updateApiKey, deleteApiKey
- Resolvers: updateResolver
- Types: createType, getType, listTypes, updateType
- Error handling: getNonExistentApi, getNonExistentDataSource,
  getNonExistentType throw AppSyncException

Total SDK tests: 24 → 35. All operations in Phase 1 are now covered.
2026-06-02 00:17:01 -05:00
Nitesh K JainandHector Ventura b71cf0f827 feat(neptune): Neptune control plane, Gremlin Docker backend, and SDK compatibility tests (#958)
Signed-off-by: Hector Ventura <hectorvent@gmail.com>
Co-authored-by: Hector Ventura <hectorvent@gmail.com>
2026-05-20 18:02:00 -05:00
Dixit R Jain 3ae5c7b467 feat(apigatewayv2): Add WebSocket data-plane support (#712)
* feat: implement API Gateway v2 WebSocket data-plane support Implement full WebSocket data-plane for API Gateway v2, including: - Real WebSocket connection handling via Vert.x (ws://localhost:4566/ws/{apiId}/{stage}) - $connect/$disconnect/$default route lifecycle with Lambda integration - Custom route selection via routeSelectionExpression ($request.body.{field}) - @connections management API (POST/GET/DELETE) for server-to-client messaging - Lambda REQUEST authorizer support on $connect with identity source validation - Stage variable substitution in integration URIs - Multiple integration types: AWS_PROXY, AWS (VTL), HTTP_PROXY, HTTP (VTL), MOCK - Route response selection expression for bidirectional messaging - Binary frame support (isBase64Encoded: true) - 128 KB payload size limit enforcement (frames and @connections POST) - 10-minute idle timeout and 2-hour max connection duration - GoneException (410) for disconnected connections - $connect response headers propagation - Server-initiated close via @connections DELETE (skips $disconnect Lambda) Also includes: - Refactored LambdaArnUtils.extractFunctionNameFromUri as shared utility - Extended Authorizer/Integration/Stage models with new fields - Comprehensive Java integration tests (WebSocket lifecycle, routing, auth, etc.) - Node.js SDK compatibility tests using ws client and @aws-sdk/client-apigatewaymanagementapi - Updated documentation with full feature matrix

* test(apigatewayv2): support custom WebSocket endpoint via env var

- Update wsUrl helper to read FLOCI_ENDPOINT environment variable
- Convert http/https schemes to ws/wss for WebSocket compatibility
- Strip trailing slashes from endpoint URL for consistent formatting
- Enable testing against non-localhost endpoints for CI/CD flexibility

* fix: use AwsErrorResponse for @connections API error responses

Replace raw JSON string literals in handlePostToConnection,
handleGetConnectionInfo, and handleDeleteConnection with the
project-standard AwsErrorResponse record, which serialises to
the correct {"__type": ..., "message": ...} wire shape.

* fix: simplify extractFunctionNameFromUri using AwsArnUtils.parse

Adopt AwsArnUtils.parse() as the core of the implementation per
reviewer suggestion. One addition beyond the suggested snippet:
the API Gateway v1 integration URI format embeds a Lambda ARN
inside an apigateway ARN (resource starts with 'path/.../functions/'),
so we detect that pattern and recurse on the embedded ARN before
applying the standard function-name extraction. All 43
LambdaArnUtilsTest cases pass, including the API Gateway v1 style URI.
2026-05-08 17:15:35 -05:00
Hector Ventura c2cc053853 feat(backup): AWS Backup management-plane API (#734) 2026-05-07 00:56:34 -05:00
Tristan BurchandHector Ventura b84d205b89 feat: Glue Schema Registry support (#621)
* feat(glue): add Glue Schema Registry support
* Move Glue SDK coverage to compatibility tests
* Align protobuf compatibility expectations
* Resolve services index merge conflict
* Remove unused Lombok compatibility dependency
* Serialize Glue schema registry timestamps as strings
* Tighten Glue schema registry name validation
* Avoid duplicate schema registry index rebuild
* Limit schema registry in-memory constructor visibility
* Clone Glue tables before resolving schema references
* Align Glue schema registry response shapes
* Extract Glue schema version resolver helper

Both validateSchemaReference and withResolvedSchemaReference duplicated
the latest-version computation and the four-argument getSchemaVersion
call. Pull that into a private resolveSchemaVersion(SchemaReference)
helper so the call sites read at one level of abstraction and a future
change to the resolution rule lands in one place.
* Fix Glue schema version list projection

---------

Signed-off-by: Tristan Burch <tburch@users.noreply.github.com>
Signed-off-by: Hector Ventura <hectorvent@gmail.com>
Co-authored-by: Hector Ventura <hectorvent@gmail.com>
2026-05-03 22:41:19 -05:00
Hector Ventura f5ec6fc887 feat(codebuild,codedeploy): add management APIs (#622) 2026-04-28 00:09:12 -05:00
Hector Ventura d39bdf1c22 feat(elbv2): Elastic Load Balancing v2 management API (Phase 1) (#617)
* feat(elbv2): add Elastic Load Balancing v2 management API (Phase 1)
* fix: adding new service to health check test
2026-04-27 22:52:52 -05:00
Hector Ventura c7152cef8a fix(kms): GetKeyRotationStatus returns false for asymmetric and HMAC keys (#618)
* fix(kms): return false for GetKeyRotationStatus on asymmetric/HMAC keys

AWS updated GetKeyRotationStatus behavior so asymmetric and HMAC keys
return { KeyRotationEnabled: false } instead of UnsupportedOperationException.
EnableKeyRotation and DisableKeyRotation still reject these key types.

* fix(kms): return false for GetKeyRotationStatus on asymmetric/HMAC keys

AWS updated GetKeyRotationStatus behavior so asymmetric and HMAC keys
return { KeyRotationEnabled: false } instead of UnsupportedOperationException.
EnableKeyRotation and DisableKeyRotation still reject these key types.
2026-04-27 22:50:49 -05:00
Kenshin OkinakaandKenshin OKINAKA 763ea379d7 feat(ses): implement email template CRUD with stored, inline, and ARN variants (#573)
* feat(ses): implement email template CRUD with stored, inline, and ARN variants

Adds CreateTemplate / GetTemplate / UpdateTemplate /
DeleteTemplate / ListTemplates on both V2 REST JSON
(/v2/email/templates) and V1 Query.

SendEmail / SendTemplatedEmail resolve templates in three forms
with Mustache-style {{var}} substitution against TemplateData:
  - TemplateName references a stored template
  - TemplateArn extracts the name from the template/<name>
    segment of an SES template ARN (region and account segments
    are not validated, mirroring how KMS / Secrets Manager
    handle ARNs in Floci)
  - TemplateContent (V2 only) supplies inline subject / text /
    html without storing the template first

V2 Content.Template requires exactly one of TemplateName,
TemplateArn, or TemplateContent; violations return
BadRequestException (400). V1 SendTemplatedEmail accepts
TemplateArn either alone or alongside Template (name) — the
name is used for resolution when both are present, matching
AWS where boto3 and the Java SDK keep Template as a required
field and treat TemplateArn as supplementary for cross-account
addressing.

Templates persist region-scoped via StorageFactory in
ses-templates.json. Template names reject leading/trailing
whitespace (same rule as identities) and are validated through
a single validateTemplateName helper reachable from every
resolution path. listTemplates is sorted by CreatedTimestamp
with TemplateName as a tiebreaker for deterministic output.

Error codes: the service layer throws V1-style codes
(TemplateDoesNotExist / AlreadyExists / InvalidTemplate /
InvalidParameterValue); SesController remaps them to
NotFoundException (404) / AlreadyExistsException (400) /
BadRequestException (400) for V2 callers.

* test(ses): add Python and Java SDK compatibility tests for templates

Covers boto3 (ses / sesv2) and AWS Java SDK v2 (SesClient /
SesV2Client) against the SES email template CRUD, inline
TemplateContent, and TemplateArn paths. Happy path,
duplicate-create rejection, missing-template lookups,
Mustache-style variable substitution, and 3-way selector
conflicts on V2 Content.Template are exercised on both SDK
surfaces.

Adds:
- Python: ses_client / sesv2_client conftest fixtures and a
  tests/test_ses_templates.py suite covering V1 + V2
- Java: sesv2 Maven dependency, SesV2Client factory in
  TestFixtures, and a SesTemplateTest covering V1 + V2

* docs(ses): document email template CRUD and templated send

Adds the new V1 template actions (CreateTemplate / GetTemplate
/ UpdateTemplate / DeleteTemplate / ListTemplates /
SendTemplatedEmail) and the V2 /v2/email/templates endpoints
to the SES service reference, and extends the README service
matrix to mention template support on the SES / SES v2 rows.

* fix(ses): add template actions to SES_ACTIONS for unsigned request routing

Unsigned clients (curl, aws --no-sign-request) were falling through to
the SQS handler because the six template Query actions were not
registered in SES_ACTIONS.

* fix(ses): narrow exception catch to JsonProcessingException in template endpoints

Broad Exception catch was masking unexpected errors (e.g. NPE) as 400
responses. Narrowed to JsonProcessingException which is the only
checked exception from objectMapper.readTree().

* test(ses): add template variable substitution edge cases and cross-region isolation

Add SesServiceTemplateTest with 14 unit tests for applyTemplateData
covering undefined variables, spaced/hyphenated names, unclosed braces,
non-string JSON values, regex metacharacters, and case sensitivity.

Add cross-region isolation integration test verifying templates created
in one region are not visible in another.

* test(ses): add awscli compatibility tests for template CRUD and templated send

Cover create, get, update, list, delete template and send-templated-email
via the AWS CLI. Uses JSON parameter format to avoid awscli parser issues
with Mustache-style {{variable}} syntax.

---------

Co-authored-by: Kenshin OKINAKA <kenshin_okinaka@realcross.co.jp>
2026-04-24 20:59:49 -05:00
Christine Nguyen 51bf4f8480 feat(pipes): add source polling and target invocation for EventBridge Pipes (#555) 2026-04-22 23:36:48 -05:00
Hector Ventura 63ed81c59d feat(eks): implement EKS service with real k3s data plane support (#493)
* feat(eks): implement EKS service with real k3s data plane support
* fix: adjusting eks volume issues
2026-04-18 01:35:25 -05:00
Dmitriy Polomoshnov 25f360002e fix: DynamoDB expression evaluation, UpdateExpression paths, and ConsumedCapacity (#197)
* fix: replace regex-based DynamoDB expression evaluation with AST parser
* feat: add ConsumedCapacity in DynamoDB responses and GSI throughput in DescribeTable
* test: add DynamoDB expression compatibility tests and fix rebase conflicts
2026-04-15 09:55:58 -05:00
Hector Ventura ea597c67d6 feat: implement local Data Lake stack (Athena, Glue, and Firehose) (#429)
* feat: implement local Data Lake stack (Athena, Glue, and Firehose)
* fix: adding athena, firehose and glue documentation
* fix: updating dataLateTest
2026-04-15 01:22:10 -05:00
Hector Ventura 91071aaae7 feat: implement Amazon MSK service with Redpanda orchestration (#419)
* feat: implement Amazon MSK service with Redpanda orchestration
* fix: adding missing msk service on the test
2026-04-13 20:22:37 -05:00
Hector Ventura e3e8903ffa fix(s3): implement S3 Control ListTagsForResource, TagResource, Untag… (#363)
* fix(s3): implement S3 Control ListTagsForResource, TagResource, UntagResource (#341)
* fix(s3): implement S3 Control ListTagsForResource, TagResource, UntagResource (#341)
2026-04-12 20:24:23 -05:00
Conor Heine a0ed51e9d1 feat: ecr (#337) 2026-04-11 09:59:05 -05:00
Hector Ventura e4d8d44724 feat: adding appconfig service (#324)
* feat: adding appconfig service
* fix: unittest appconfig service
2026-04-10 02:43:08 -05:00
GitMarco 8bac81807e Fix(dynamoDB): handle null for Java AWS SDK v2 DynamoDB EnhancedClient correctly (#309)
* Fixes DynamoDB support for adding values to a list for the SET ... ADD query/command
* Revert "Fixes DynamoDB support for adding values to a list for the SET ... ADD query/command"
* fix(dynamoDB): support Java AWS SDK v2 enhanced client null values
* fix(dynamoDB): added compatibility integration test for DynamoDB EnhancedClient. Including suggestion for default host+port for test fixture, so `mvn test -q` can work even without setting the env variable set.
2026-04-09 17:53:48 -05:00
Conor Heine 13916913e8 fix: handle base64-encoded ACM cert imports (#248) 2026-04-07 13:20:27 -05:00
Kenshin Okinaka 48b6ca3475 feat(scheduler): add EventBridge Scheduler service (#260)
* feat(scheduler): add EventBridge Scheduler ScheduleGroup CRUD

Introduces the scheduler service skeleton with ScheduleGroup CRUD over
the REST JSON protocol at /schedule-groups/{Name}. The default group is
lazily seeded on first access, mirroring the EventBridge default bus
pattern. Covers Create/Get/Delete/List, region scoping, name validation,
and the default-group delete guard.

* feat(scheduler): add Java SDK compatibility tests for ScheduleGroup CRUD
* feat(scheduler): add Schedule CRUD operations
2026-04-07 12:36:59 -05:00