Commit Graph
1173 Commits
Author SHA1 Message Date
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
Kumar Prabhat fd78ae4f4b fix(secretsmanager): raise InvalidRequestException, not ResourceNotFoundException, for pending-deletion secrets (#2514)
DeleteSecret without ForceDeleteWithoutRecovery keeps the secret in
store with deletedDate set to a future date (recoverable via
RestoreSecret) - it's only removed from store outright on a force
delete, so resolveSecret() already raises ResourceNotFoundException on
its own for a genuinely gone secret. Any getDeletedDate() != null
check reached past resolveSecret() therefore always means "still
present, scheduled for deletion", which real AWS reports as
InvalidRequestException.

getSecretValue, putSecretValue, updateSecret,
claimTargetAttachment, rotateSecret, and updateSecretVersionStage
all threw ResourceNotFoundException here instead, making a
recoverable, still-restorable secret indistinguishable from one
that's genuinely gone. batchGetSecretValue in the same file already
had this right (InvalidRequestException with the correct message) -
extracted that into a shared throwIfPendingDeletion(secret) helper
and applied it consistently at the six other sites.

Strengthened the existing deleteSecretWithRecoveryWindow test (it
only asserted AwsException.class, which passes regardless of error
code) to check the specific error code, and added a test covering
all six affected operations.

Fixes #2513
2026-08-25 10:00:38 -04:00
Anders Wasen a3044e065e feat(rds-data): adding data-api support for lable/name and batch (#2518)
* feat(rds-data): adding data-api support for lable/name and batch

* feat(rds-data): fixing PR robots comments

* feat(rds-data): fixing PR comments; adding tests
2026-08-25 09:40:33 -04:00
Tom Longhurst a57c6c8112 fix(dynamodb): validate query key types (#2469)
* fix(dynamodb): validate query key types

Closes #2467

* fix(dynamodb): harden query validation

* fix(dynamodb): validate query value payloads
2026-08-24 18:11:05 -04:00
Tom Longhurst e3df59ae1f fix(dynamodb): validate cursor key types (#2470)
* fix(dynamodb): validate cursor key types

Closes #2468

* fix(dynamodb): reject malformed cursors
2026-08-24 17:52:17 -04:00
Allen Sanborn 564dbf204f fix(kinesis): apply CreateStream's Tags instead of dropping them (#2494)
* fix(kinesis): apply CreateStream's Tags instead of dropping them

CreateStream parsed StreamName, ShardCount, StreamModeDetails and
MaxRecordSizeInKiB and silently ignored the optional Tags member, so a stream
created with tags came back untagged from ListTagsForStream. AddTagsToStream
already worked, so only the create path was affected.

A hand-written script would not notice. Terraform does: aws_kinesis_stream sets
tags at create time and then reads them back, so every plan after a successful
apply reports "tags will be updated in-place" on an unchanged configuration.
That is what fails terraform-aws-messaging's TestKinesis, whose four subtests all
assert `terraform plan` returns exit code 0 after apply -- every other assertion
in that test (shard count, encryption type, retention period) already passed.

* refactor(kinesis): parse CreateStream and AddTagsToStream tags with one helper

The create-time tag support added in the previous commit duplicated the three
lines AddTagsToStream already used to turn the request's Tags object into a
map. Two copies of the same parse is two things to keep in step, and this
service now has three tag operations, so extract parseTags() the way
CodeBuild's and SecretsManager's JSON handlers already do.

No behaviour change: a missing or non-object Tags member still yields an empty
map rather than an error, and CreateStream still skips the store write when
that map is empty. Greptile flagged that asText() coerces a non-string tag
value ("null", "3", "") instead of rejecting it. That is true, but it is
AddTagsToStream's pre-existing behaviour, not something this PR introduced --
sharing one parser is what keeps the two paths from answering the same
malformed request differently. Rejecting non-string tag values is a separate
input-validation fix that should land on its own, across every tag operation.

Adds handler-level unit tests, which the class had none of for tags: create
with tags, create without, create with an empty Tags object, and AddTagsToStream
applying the same map. Unlike the ordered integration tests these get a fresh
service per test.
2026-08-24 17:39:59 -04:00
kk feb669d58b fix(bedrock-agentcore): support memory tagging and dropped fields (#2501)
* fix(bedrock-agentcore): tag memory resources and honor dropped CreateMemory/UpdateMemory fields

Three divergences from AWS in the Memory control plane (#2316):

- Memory ARNs were not taggable: the shared /tags/{arn} handler dispatched
  only agent/ and gateway/ segments, returning ValidationException for
  memory/ ARNs even though AWS supports TagResource on memories.
- CreateMemory silently dropped tags, encryptionKeyArn, and
  memoryExecutionRoleArn: accepted with 202, never stored.
- UpdateMemory ignored eventExpiryDuration (and memoryExecutionRoleArn),
  applying only description.

Memory now persists all three fields, the tag handler dispatches three
ways (with the foreign-account 404 guard covering memories), and
UpdateMemory applies description, eventExpiryDuration (validated 3-365),
and memoryExecutionRoleArn. Matching AWS, the Memory response shape never
embeds tags; they surface only via ListTagsForResource.

* fix(bedrock-agentcore): validate UpdateMemory input before mutating stored state

A rejected update (out-of-range eventExpiryDuration) could leave the
description already applied, because get() returns the live stored object
and validation ran after the first setter. Validate all inputs up front,
and pin the no-partial-mutation behavior with unit and integration tests.

Also deduplicates the @Order(3) collision in BedrockAgentCoreMemoryIntegrationTest.

Addresses review feedback from pgermosen.
2026-08-24 17:32:28 -04:00
Tedd 72dfa634f7 fix(apigateway): support AWS type Lambda integration and fix duplicate Content-Type header (#2049)
* fix(apigateway): support AWS type Lambda integration and fix duplicate Content-Type header

Integration tests for AWS type lambda integration with apigateway and duplicate content-type headers

Addressing Greptile review the qualifier is now preserved end to end and covered by tests

* fix(apigateway): resolving review feedback, adding in comment to LambdaArnUtils re lastIndexOf fallback, and updating DOCs with Line re v1 execution plane integration type behaviour
2026-08-24 17:24:09 -04:00
Allen Sanborn fcd662fb62 fix(msk): accept an empty serverProperties on Create/UpdateConfiguration (#2491)
* fix(msk): accept an empty serverProperties on Create/UpdateConfiguration

CreateConfiguration and UpdateConfiguration both validated serverProperties
with `== null || isBlank()`, which conflates "member absent" with "member
present but empty". A zero-length blob is a legitimate value in MSK: it means
"no property overrides".

Terraform modules hit this routinely. Gruntwork's msk module builds
serverProperties by joining a map that defaults to {} and creates
aws_msk_configuration unconditionally, so an unconfigured module sends an
empty blob and the emulator answered BadRequestException "serverProperties is
required." Three terraform-aws-messaging roots failed on it.

Both call sites now reject only null. Absent and empty stay distinguishable at
the REST layer: MskController.asString returns null for a missing member and
decodeServerProperties turns the empty base64 string into "".

* test(msk): read back both revisions, and match the class's naming

The round-trip test read back only revision 1, so an update that stored "" and
one that silently carried the previous revision's properties forward would both
have passed. It now checks both revisions.

Renames createConfigurationRejectsAbsentServerProperties to
...RejectsMissingServerProperties, which is what every neighbouring
missing-member test in these two classes is already called.
2026-08-24 15:59:44 -04:00
Abhigya 1ca19c722a fix(cognito): AWS-accurate UsernameAttributes pools — UUID username, alias sign-in, and token/revocation parity (#1849)
* feat: mint UUID username with mutable email alias for UsernameAttributes pools

* fix(cognito): align token claims, alias-exists, read-attributes, and not-found status with AWS

* fix(cognito): align token claims, alias-exists, read-attributes, not-found status, and canonical-username revocation with AWS

* fix(cognito): accept canonical UUID on RESEND, harden migration sub-minting and email validation)

* fix(cognito): AliasExistsException guard check

* test(cloudformation): expect 400 for Cognito ResourceNotFoundException

Align the post-deletion DescribeUserPool/DescribeUserPoolClient assertions
with the AWS-accurate 400 status now returned for Cognito
ResourceNotFoundException.

* fix(cognito): bind CUSTOM_AUTH challenge USERNAME to the session user

RespondToAuthChallenge validated SECRET_HASH against the caller-supplied
USERNAME while resolving the user from the session, so the two were allowed
to disagree. That reduced SECRET_HASH from a per-user binding to a bare
proof-of-client-secret check, and let callers pass locally against requests
real Cognito rejects.

Resolve the supplied USERNAME the same way sign-in does and require it to
match the session user; aliases still work since the caller may legitimately
send the email while the session holds the UUID.

Also compare SECRET_HASH with MessageDigest.isEqual instead of String.equals
so the MAC comparison does not short-circuit on the first differing byte,
matching the SRP path in CognitoSrpHelper.
2026-08-24 14:43:49 -04:00
Davor Santic 5c45c146c7 fix(ecs): round-trip command and entryPoint on container definitions (#2446)
RegisterTaskDefinition already parsed containerDefinitions[].command and
.entryPoint, and EcsContainerManager honoured both when launching the
container — but containerDefinitionNode never rendered them, so
DescribeTaskDefinition silently omitted both keys.

The practical consequence is data loss on the describe -> register
round trip that tooling relies on to cut a new revision: the overrides
disappear from the JSON and the new revision falls back to the image's
default entrypoint. The container still starts, so nothing surfaces until
whatever the entrypoint was meant to do turns out not to have happened.

Serialize both sparsely, matching the surrounding portMappings /
mountPoints style, so definitions that set neither stay byte-identical.

Tests: a parse+serialize unit test in the EcsJsonHandlerVolumesTest style
(round trip plus an absent-stays-absent guard), and an end-to-end
register -> describe case in EcsIntegrationTest.

Refs #2445
2026-08-24 09:25:47 -04:00
Allen Sanborn e18a262261 fix(ec2): store and report a route's IPv6 destination, and stop DeleteRoute NPEing (#2492)
* fix(ec2): store and report a route's IPv6 destination

CreateRoute accepted DestinationIpv6CidrBlock and dropped it. Route had no
member to put it in, so an IPv6 route was stored with no destination at all,
serialized with no destination element, and could never be matched again.
The Terraform provider's create-waiter polls DescribeRouteTables for the
route it just made and never finds it, so every `aws_route` with an IPv6
destination fails the apply at its 5-minute deadline.

A second defect falls out of the same gap. The destination comparison in
deleteRoute and replaceRoute read the stored side —
`r.getDestinationCidrBlock().equals(dest)` — so once any IPv6 route existed
in a table, every DeleteRoute against that table threw InternalFailure,
IPv4 ones included. That breaks `terraform destroy` independently of the
apply failure, which is why the comparison is now made from the request
side through a shared matchesDestination helper.

Per https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_Route.html
the Route type carries destinationCidrBlock, destinationIpv6CidrBlock and
egressOnlyInternetGatewayId as separate members, all optional. This adds
the latter two to the model, reads DestinationIpv6CidrBlock and
EgressOnlyInternetGatewayId in CreateRoute, emits both in the routeSet, and
accepts either destination in ReplaceRoute and DeleteRoute.
DescribeRouteTables also gains the route.destination-ipv6-cidr-block
filter, which previously fell through to the catch-all and so matched every
route table rather than the ones holding that route.

CreateRoute, ReplaceRoute and DeleteRoute now require exactly one
destination: neither is MissingParameter, both is
InvalidParameterCombination. This is a behaviour change for two requests
that used to be accepted — a CreateRoute with no destination (which stored
the unmatchable route this commit is about) and a DeleteRoute with no
destination (which silently removed nothing). A prefix-list destination is
still not modelled and now lands on MissingParameter rather than being
quietly dropped.

The egress-only internet gateway actions themselves
(CreateEgressOnlyInternetGateway and its Describe/Delete) remain
unimplemented; this only keeps the id a caller sends from being discarded,
so the route reports its target instead of appearing targetless. An
egress-only target is still rejected in ReplaceRoute, which is unchanged.

Not verified: that this clears the Terraform failures end to end. It was
developed against the reproduction in the report and the API reference, not
against a Terraform run, and a private-subnet IPv6 configuration will still
need the egress-only gateway actions before it reaches a route at all.
Whether real AWS answers MissingParameter or InvalidParameterCombination
when both destinations are given is inferred from the reference listing
them as separate optional members, not confirmed against AWS.

Tests: Ec2Ipv6RouteTest covers the IPv6 round trip, the IPv4 route beside
it, both coexisting, the IPv6 filter, ReplaceRoute on IPv6, the IPv4-delete
regression, the IPv6 delete, and the rejected destination combinations;
9 of its 11 fail without this change. Ec2ReplaceRouteIntegrationTest's
"no IPv4 destination is rejected" case now uses a prefix list, since an
IPv6 destination is no longer rejected there.

* fix(ec2): treat a prefix list as the third route destination, not as none

The previous commit rejected CreateRoute/DeleteRoute/ReplaceRoute with
DestinationPrefixListId as MissingParameter, and a test asserted that as AWS
behaviour. It is not. The CreateRoute reference says "You must specify either a
destination CIDR block or a prefix list ID", and DestinationPrefixListId is a
declared member of all three inputs and of the Route output shape in
ec2/service-2.json. A prefix-list route is a route with a destination.

So store and report it like the other two. It was hitting exactly the bug this
PR is about: persisted with no destination at all, unmatchable by DeleteRoute
or ReplaceRoute, and its null IPv4 destination made every DeleteRoute against
the same table throw. The removeIf null-safety now covers all three kinds.

Also reject EgressOnlyInternetGatewayId combined with GatewayId or NatGatewayId,
which would persist and report a route with two targets. Scoped to the parameter
this PR newly accepts: CreateRoute has never enforced exclusivity between
GatewayId and NatGatewayId, and starting to would be a behaviour change beyond
this fix. Raised by Greptile.

On the error code for a genuinely destination-less request: AWS declares no
operation-specific error for these three actions — the API reference Errors
section is empty and the service model carries no error shapes — so
MissingParameter is chosen from EC2's common client error codes, not confirmed
against the real service. Now documented as such rather than asserted.

Ec2Ipv6RouteTest: 11 -> 13 tests.
2026-08-24 00:05:34 -04:00
TATSUNO “Taz” Yasuhiro b6418dbfee feat(sfn): support mocked service integrations (SFN_MOCK_CONFIG) (#2452)
* feat(sfn): support mocked service integrations (SFN_MOCK_CONFIG)

StartExecution accepts a state machine ARN with a test case suffix in
the Step Functions Local format. The test case comes from the mock
configuration file named by SFN_MOCK_CONFIG. A mocked Task state
returns the configured Return payload or fails with the configured
Throw error instead of calling the integrated service. The mocked
error and cause reach Retry and Catch unchanged. States not named in
the test case still call their real integration, so mocked and real
calls combine in one execution. Behavior was verified against Step
Functions Local 2.0.0.

Closes #2283

* fix(sfn): never retry or catch States.Runtime even when named explicitly

* fix(sfn): keep a bare trailing '#' unstripped on StartSyncExecution
2026-08-24 00:04:17 -04:00
Allen Sanborn ea2b62fb95 fix(s3): resolve virtual-hosted buckets whose names contain dots (#2493)
* fix(s3): resolve virtual-hosted buckets whose names contain dots

S3VirtualHostFilter.extractBucket split the Host header at the FIRST dot
and required the remainder to equal the endpoint host. S3 bucket names may
legally contain dots -- naming a website/log bucket after a domain is the
conventional pattern -- so for

    Host: r5e817e.floci.example.com-logs.localhost

it read the bucket as "r5e817e" with remainder "floci.example.com-logs.
localhost", which matches no known endpoint host. extractBucket returned
null, the request silently degraded to a path-style request against "/",
and HEAD / answered 200 (the ListBuckets route).

User-visible symptom: the Terraform AWS provider calls HeadBucket before
CreateBucket, read that 200 as "bucket exists", and failed every dotted
bucket with BucketAlreadyExists for a bucket that had never existed.

Match the endpoint host as a SUFFIX instead: the bucket is everything in
front of ".<endpoint-host>", minus an optional trailing S3 qualifier
(s3, s3.<region>, s3.dualstack.<region>, s3-website-<region>). The same
correction is applied to every resolution path -- configured base hostname,
always-on localhost, configured DNS suffixes, and the AWS-domain fallback --
so bucket.<host>, bucket.s3.<host> and bucket.s3.<region>.<host> all keep
working with dotted names. Where several known suffixes match, the longest
wins, so bucket.localhost.floci.io is not read as "bucket.localhost".

Two things must not be swallowed by the wider matching:

* Service endpoints. The existing isS3ServiceEndpointHost guard still runs
  first, and a prefix that IS a qualifier (s3.localhost,
  s3.us-east-1.localhost, s3-website-us-east-1.localhost) resolves to no
  bucket rather than to a bucket named "s3".
* Other services' virtual hosts. execute-api, lambda-url and friends share
  the endpoint host, and <api-id>.execute-api.<host> would otherwise read as
  a dotted bucket and hijack API Gateway requests. Hostnames carrying a
  non-S3 service label are not buckets.

Path-style hosts, IPv4 authorities and port stripping are unchanged.

* fix(s3): stop suffix matching from swallowing other services' regional hosts

Suffix matching reads any multi-label host under a known endpoint host as a
dotted bucket. The label denylist added with it is not a sound guard: it has to
name every service, and the first one it misses is silently served as a bucket.

Measured against the previous commit, with baseHostname=localhost — every one of
these resolved to null on main:

  123456789012.dkr.ecr.us-east-1.localhost -> 123456789012.dkr.ecr.us-east-1
  search-mydomain-abc.us-east-1.es.localhost -> search-mydomain-abc.us-east-1.es
  abc.iot.us-east-1.localhost -> abc.iot.us-east-1
  myapp.appsync-api.us-east-1.localhost -> myapp.appsync-api.us-east-1

The first is the registry URI EcrRegistryManager hands out, so it is not
hypothetical.

Replace the enumeration with a structural rule: a hostname carrying a region
label in a non-leading position and no S3 qualifier is another service's
regional virtual host. A real S3 virtual host always carries s3, s3.<region> or
s3-website-<region>, and when it does the region is read from there instead — so
a bucket whose own name ends in a region stays addressable as
logs.us-east-1.s3.localhost.

Drop "elb" and "mwaa" from the denylist in the other direction. No filter in this
repository routes *.elb.<host> or *.mwaa.<host> by Host, and my.elb.logs is AWS's
own load-balancer access-log naming convention — a perfectly legal bucket the
guard was rejecting for nothing. The four remaining labels each name a filter
that does claim that hostname in a regionless form the region rule cannot catch.

S3VirtualHostFilterTest: 117 -> 131 tests.

* test(s3): pin what the remaining service-label denylist costs

An automated reviewer flagged that a bucket named my.execute-api.archive is
unreachable virtual-hosted. That is true, and it is the intended side of the
trade rather than an oversight, so assert it instead of leaving it implicit.

The remedy suggested — validate each service's hostname grammar and let anything
that does not match through — trades a recoverable failure for an unrecoverable
one. A bucket that must be addressed path-style still works, and worked no
better before this PR. An API Gateway request answered by S3 is a silent
cross-service hijack with no client-side remedy. Each of the four labels names a
filter in this repository that claims that hostname; the two that named nothing
were removed in the previous commit.

S3VirtualHostFilterTest: 131 -> 135 tests.

* fix(s3): treat an S3 qualifier as a complete tail, not any label

bucketFromPrefix scanned the labels in front of the endpoint host one at a
time and split the bucket at the LAST label matching s3 or s3-website*. An
"s3" label anywhere inside a dotted bucket name therefore truncated it:

    Host: my.s3.archive.localhost   ->  bucket "my"

A request for the bucket my.s3.archive silently read and wrote a different,
existing bucket. That is worse in kind than the wrong 200 this branch set out
to fix -- the client gets a plausible success against the wrong data, with no
signal that anything went wrong.

A qualifier is a complete tail, not a label. isS3QualifierTail requires the
labels from index i onwards to account for the WHOLE remainder of the prefix
and to spell one of the endpoint forms the AWS General Reference publishes:

    s3                        s3-fips.<region>            s3-accelerate
    s3.<region>               s3-fips.dualstack.<region>  s3-accelerate.dualstack
    s3.dualstack.<region>     s3-<region>      (legacy dash form)
    s3-website                s3-website.<region>  (newer regions)
                              s3-website-<region>  (older regions)

Nothing legal follows "s3" except a region, dualstack.<region>, or the end of
the name, so "s3.archive" is bucket text and my.s3.archive is the bucket. The
genuine forms still split, including for a bucket that contains an s3 label:
my.s3.archive.s3.us-east-1.localhost resolves to my.s3.archive.

Stating the grammar properly also widens what is recognised. s3-fips.<region>,
s3-accelerate, the legacy s3-<region> dash form and the newer s3-website.<region>
dot form were previously unrecognised; they resolve now. Note the website
endpoint spells its region with a dot in newer regions and a dash in older ones,
and both are in service.

Recognising s3-<region> needs to tell a region id from arbitrary text, so
AwsRegions gains KNOWN_IDS: every published AWS region id across the commercial,
GovCloud and China partitions. It is deliberately distinct from AwsRegions.ALL
and a superset of it -- ALL is what the emulator ADVERTISES through
DescribeRegions, KNOWN_IDS is what it RECOGNISES in a hostname. AwsRegionsTest
pins ALL as a subset of KNOWN_IDS.

The remaining ambiguity is narrower than before and is asserted: a bucket whose
own name IS a complete qualifier tail (foo.s3, foo.s3.us-east-1) is still read
as a qualified reference to foo. A bucket that merely contains s3 is not.

S3VirtualHostFilterTest: 135 -> 155 tests. AwsRegionsTest: new, 14 tests.

* fix(s3): match region IDs by name, not by a region-shaped pattern

The guard that keeps another service's regional virtual host from being served
as a dotted bucket tested each non-leading label against

    [a-z]{2}-[a-z-]+-\d+

That is the shape of an AWS region id. It is also the shape of perfectly
ordinary bucket labels. my-cd-1 matches it, so the legal bucket data.my-cd-1
was rejected, fell back to path-style, and answered HEAD / with 200 -- exactly
the false "bucket exists" this branch was opened to eliminate, reintroduced for
a different class of name. eu-team-2, us-west-9, ap-corp-1 and no-such-region-12
all match it too.

Test against AwsRegions.KNOWN_IDS instead: the finite list of region ids AWS
actually publishes. data.my-cd-1, reports.eu-team-2, assets.us-west-9 and
logs.ap-corp-1.archive now resolve as buckets, while
123456789012.dkr.ecr.us-east-1.localhost and search-x.eu-north-1.es.localhost
are still refused -- including for regions outside the set the emulator
advertises.

Position within the host was considered as an extra discriminator and rejected:
it does not separate the two cases. The region label is last in
<acct>.dkr.ecr.<region> but medial in <domain>.<region>.es, so no positional
rule covers both without also covering bucket names.

Two residual costs, both accepted deliberately and documented at the call site:

* A bucket carrying a REAL region id in a non-leading position (data.us-east-1)
  is still unreachable in the unqualified virtual-hosted form. It stays
  reachable qualified (data.us-east-1.s3.localhost) and path-style, and it was
  equally unreachable before this branch. Recoverable, and asserted.
* A regional service host in a region AWS launches after KNOWN_IDS was last
  updated would be read as a bucket. That is the maintenance cost of a list over
  a pattern, and the direction in which the pattern was safer. It is bounded:
  the failure is a wrong route rather than data loss, and the four
  NON_S3_SERVICE_LABELS entries still cover the services Floci routes by Host.

The list is preferred because the pattern's failure mode is the one this branch
exists to eliminate -- a legal bucket silently answering 200 from the service
root -- while the list's failure mode only appears for a region AWS has not
launched yet.

S3VirtualHostFilterTest: 155 -> 167 tests.
2026-08-23 22:49:06 -04:00
Kenshin Okinaka bd36b02728 fix(ses): report the sending account in send-event payloads (#2499)
The SES send-event payload's mail.sendingAccountId and mail.sourceArn were built
from the fixed default account, so under Floci's per-request multi-account support
they always showed 000000000000 regardless of the caller. Resolve the account per
request via RegionResolver.getAccountId() in publishSendEvents (falling back to the
default account outside a request, e.g. unit tests). Assert the account in the
delivery event payload.
2026-08-23 21:59:42 -04:00
Kenshin Okinaka 622ba0adbd feat(ses): support v2 PutAccountDetails and GetAccount Details (#2498)
* feat(ses): support v2 PutAccountDetails and GetAccount Details

Add the SES v2 PutAccountDetails operation and surface its data under GetAccount's
Details. Details are per-region and present-when-set (like VdmAttributes): GetAccount
omits the block until PutAccountDetails is called for the region. MailType and
WebsiteURL are required, and their null violations are reported together (aggregated),
matching AWS; MailType/ContactLanguage are enum-constrained. Floci has no sandbox and
runs no production-access review, so ReviewDetails.Status is reported as GRANTED.

Add unit and integration tests, and document the operation.

* test(ses): cover ProductionAccessEnabled in account details

ProductionAccessEnabled is a GetAccount top-level member (not an
AccountDetails field), and Floci has no sandbox so it stays true
regardless of the value sent to PutAccountDetails. Add an integration
case asserting the top-level flag stays true and never appears inside
Details, and assert at the service layer that the value is still stored
as given.
2026-08-23 20:48:31 -04:00
Matheus Oliveira 824701481c feat(core): label emulated resource containers with io.floci.* identity (#2497)
* feat(core): add io.floci.* resource-identity labels

Introduces ContainerStorageHelper.resourceIdentityLabels(service,
resourceId, accountId, region), so a container manager can tag its
spawned container with the emulated resource's identity. Additive to
the existing floci/floci_emulator/floci_namespace labels.

Relates to #1818

Signed-off-by: Matheus Oliveira <matheus.6148@gmail.com>

* feat(rds): label RDS containers with resource identity

RDS backing containers now carry io.floci.service=rds,
io.floci.resource-id=<instanceId>, io.floci.account, and io.floci.region
so a spawned container can be mapped back to the DBInstanceIdentifier
it emulates without empirical docker exec probing.

Account/region reuse the same ARN parsing already done for log-stream
routing; extracted into resolveRuntimeIdentity so both call sites share
one source of truth.

Closes #1818

Signed-off-by: Matheus Oliveira <matheus.6148@gmail.com>

* feat(docdb): label DocDB containers with resource identity

DocDB backing containers now carry io.floci.service=docdb and
io.floci.resource-id=<clusterId> alongside account/region.

Relates to #1818

Signed-off-by: Matheus Oliveira <matheus.6148@gmail.com>

* feat(elasticache): label ElastiCache Redis/Valkey containers with resource identity

Backing containers now carry io.floci.service=elasticache and
io.floci.resource-id=<groupId> alongside account/region.

Relates to #1818

Signed-off-by: Matheus Oliveira <matheus.6148@gmail.com>

* feat(elasticache): label ElastiCache Memcached containers with resource identity

Backing containers now carry io.floci.service=elasticache and
io.floci.resource-id=<clusterId> alongside account/region.

Relates to #1818

Signed-off-by: Matheus Oliveira <matheus.6148@gmail.com>

* feat(memorydb): label MemoryDB containers with resource identity

Backing containers now carry io.floci.service=memorydb and
io.floci.resource-id=<clusterName> alongside account/region.

Relates to #1818

Signed-off-by: Matheus Oliveira <matheus.6148@gmail.com>

* feat(neptune): label Neptune containers with resource identity

Backing containers now carry io.floci.service=neptune and
io.floci.resource-id=<clusterId> alongside account/region.

Relates to #1818

Signed-off-by: Matheus Oliveira <matheus.6148@gmail.com>

* feat(msk): label MSK containers with resource identity

Redpanda backing containers now carry io.floci.service=msk and
io.floci.resource-id=<clusterName> alongside account/region.

Relates to #1818

Signed-off-by: Matheus Oliveira <matheus.6148@gmail.com>

* feat(opensearch): label OpenSearch containers with resource identity

Backing containers now carry io.floci.service=opensearch and
io.floci.resource-id=<domainName> alongside account/region.
RegionResolver is now injected into OpenSearchDomainManager.

Relates to #1818

Signed-off-by: Matheus Oliveira <matheus.6148@gmail.com>

* feat(ecs): label ECS task containers with resource identity

Backing containers now carry io.floci.service=ecs and
io.floci.resource-id=<taskId> alongside account/region.

Relates to #1818

Signed-off-by: Matheus Oliveira <matheus.6148@gmail.com>

* feat(eks): label EKS k3s containers with resource identity

Backing containers now carry io.floci.service=eks and
io.floci.resource-id=<clusterName> alongside account/region.
RegionResolver is now injected into EksClusterManager.

Relates to #1818

Signed-off-by: Matheus Oliveira <matheus.6148@gmail.com>

* feat(amazonmq): label AmazonMQ containers with resource identity

RabbitMQ backing containers now carry io.floci.service=amazonmq and
io.floci.resource-id=<brokerId> alongside account/region.

Relates to #1818

Signed-off-by: Matheus Oliveira <matheus.6148@gmail.com>

* feat(mwaa): label MWAA containers with resource identity

Both the Postgres metadata container and the Airflow container now
carry io.floci.service=mwaa and io.floci.resource-id=<environmentName>
alongside account/region. RegionResolver is now injected into
MwaaEnvironmentManager.

Relates to #1818

Signed-off-by: Matheus Oliveira <matheus.6148@gmail.com>

* feat(kinesisanalytics): label Flink containers with resource identity

Both the JobManager and TaskManager containers now carry
io.floci.service=kinesisanalytics and io.floci.resource-id=<applicationName>
alongside account/region.

Relates to #1818

Signed-off-by: Matheus Oliveira <matheus.6148@gmail.com>

* feat(batch): label Batch job containers with resource identity

Job containers now carry io.floci.service=batch and
io.floci.resource-id=<jobId>, using the job's own account/region
(already carried on BatchJob) rather than RegionResolver.

Relates to #1818

Signed-off-by: Matheus Oliveira <matheus.6148@gmail.com>

* feat(codebuild): label CodeBuild job containers with resource identity

Build containers now carry io.floci.service=codebuild and
io.floci.resource-id=<buildId> alongside account/region.

No new unit test: the container-spawn call site lives inside the
private multi-phase runBuild() method, entangled with real filesystem
and source-download side effects with no existing seam for unit
testing in isolation (CodeBuild's only coverage today is the
QuarkusTest-based CodeBuildIntegrationTest, which would need a real
Docker daemon and a full build run to assert container labels).

Relates to #1818

Signed-off-by: Matheus Oliveira <matheus.6148@gmail.com>

* feat(lambda): label function containers with resource identity

Lambda containers now carry io.floci.service=lambda and
io.floci.resource-id=<functionName>, reusing the existing
ARN-based region resolution and adding the equivalent account lookup.

Relates to #1818

Signed-off-by: Matheus Oliveira <matheus.6148@gmail.com>

* feat(ec2): label EC2 instance containers with resource identity

Backing containers now carry io.floci.service=ec2 and
io.floci.resource-id=<instanceId>, using the already-passed region
parameter and a new RegionResolver dependency for the account id.

Relates to #1818

Signed-off-by: Matheus Oliveira <matheus.6148@gmail.com>

* feat(ecr): label the shared registry container with resource identity

The registry:2 container carries io.floci.service=ecr with no
resource-id, since it is a shared singleton, not a per-resource
container.

Relates to #1818

Signed-off-by: Matheus Oliveira <matheus.6148@gmail.com>

* docs(core): document io.floci.* resource-identity labels

Relates to #1818

Signed-off-by: Matheus Oliveira <matheus.6148@gmail.com>

* style(tests): use imports instead of inline FQCN in resource-identity label tests

Cleans up the Batch, EKS, and OpenSearch label tests added earlier in
this branch, which used fully-qualified names inline instead of imports.

Relates to #1818

Signed-off-by: Matheus Oliveira <matheus.6148@gmail.com>

* fix(kinesisanalytics): restore Mockito import and awsEnv param in Flink label test

Silently dropped by the rebase's clean auto-merge; the test no longer compiled
without them.

Signed-off-by: Matheus Oliveira <matheus.6148@gmail.com>

* docs(core): note ECR keeps every identity label except resource-id

EcrRegistryManager still passes account/region for the shared registry
container; only resourceId is omitted. Docs previously said the opposite.

Signed-off-by: Matheus Oliveira <matheus.6148@gmail.com>

* test(elasticache): log swallowed IOException in label test cleanup

Matches the pattern already used in the DocDB/Neptune/MemoryDB label tests.

Signed-off-by: Matheus Oliveira <matheus.6148@gmail.com>

---------

Signed-off-by: Matheus Oliveira <matheus.6148@gmail.com>
2026-08-23 20:47:00 -04:00
Olamide Kosile 6f1ce9b23f fix(ssm): stop re-reading shared mutable state in the command status rollup (#2477)
* fix(ssm): stop re-reading shared mutable state in the command status rollup

Fixes #2264 (flaky SsmCommandServiceDirectExecutionTest.directTimeoutMarksCommandTimedOut
seeing status=TimedOut with statusDetails still In Progress).

commandStore is a plain ConcurrentHashMap-backed InMemoryStorage whose
get() returns the same shared Command object on every call, not a
defensive copy. updateCommandStatus's finalize branch computed a local
status, called command.setStatus(status), then immediately re-read
command.getStatus() to compute statusDetails instead of using that
same local variable. On a shared mutable object that's a real TOCTOU
gap: if another thread's updateCommandStatus call for the same
command (its own instance's completion racing this one) mutated
command's status in the window between those two lines, this call's
statusDetails ended up reflecting the OTHER thread's status instead of
the one it had just written - reproducing the exact reported symptom.

Fix: use the local status variable directly, the same one already
passed to setStatus, instead of reading it back through the shared
object.

Verified: added a test that forces many instances of a multi-instance
command to complete via a CyclicBarrier as close to simultaneously as
Java threads allow, across many trials, asserting status and
statusDetails always agree. Rigor-checked by reverting the fix and
re-running against 1200 such attempts (12 instances x 100 trials) -
it never reproduced the historical race, which the two-line gap being
a few nanoseconds of adjacent bytecode explains: that's far narrower
than a clean, uncontended test JVM's thread-scheduling granularity,
matching the issue's own report that it only flakes under real CI
load, not locally. So this isn't a fails-before/passes-after
reproduction; it's a standing invariant check, and the fix's
correctness is established by construction instead - statusDetails is
now computed from a local variable no other thread can touch, closing
the TOCTOU window regardless of scheduling rather than just making it
statistically less likely to hit. Full ssm package regression is
green (62 tests).

* fix(ssm): synchronize cancelCommand against the status rollup

greptile flagged a real gap in the previous commit: even with
updateCommandStatus no longer racing against itself, cancelCommand's
own status+statusDetails write could still land entirely inside the
rollup's window between ITS two field writes - e.g. status=Cancelled
from cancelCommand landing between the rollup's setStatus("Success")
and its setStatusDetails(...), leaving statusDetails="Success" stored
alongside status="Cancelled".

Both methods now synchronize on the shared Command object itself
before touching its status fields. commandStore's get() always
returns the same instance for a given key (InMemoryStorage is a plain
ConcurrentHashMap, not a defensive-copying store), so locking on that
object correctly serializes every writer of a given command's status,
regardless of which method they're in.

Verified with a deterministic mutual-exclusion test rather than a
timing-based reproduction: commandStore.put() is called from inside
each synchronized block and is a real interception point (unlike the
plain field-setter calls themselves), so a spy forces the rollup to
block mid-finalize while still holding the lock, and the test asserts
a concurrent cancelCommand call blocks too rather than racing past it
- the same style already used for the code-volume lock in
ContainerLauncherTest's cleanupAndAConcurrentRollback... test.
Confirmed the test fails when either method's lock alone is swapped
for an unshared one (checked both independently) and passes with both
restored. Full ssm package regression is green (63 tests).

* fix(ssm): synchronize reads and every remaining invocation writer

pgermosen found the real remaining gap on this PR: SsmJsonHandler's
commandToNode() (the ListCommands/GetCommandInvocation serializer)
read Status and StatusDetails from the same live, shared Command
object the writers now synchronize on, but never took that lock
itself. A ListCommands call whose two field reads straddled a
concurrent writer's update could observe a torn pair that was never
true at any single instant - most likely the actual path #2264 was
originally seen through, since a customer polls status via
ListCommands, not the internal rollup directly.

Fixes that by synchronizing commandToNode's read on the same Command
object, and invocationToNode's read on the same CommandInvocation
object for the identical reason: CommandInvocation is also returned
as a live shared reference from invocationStore, and multiple methods
already write its status pair independently (cancelCommand's per-
instance cancel, applyDirectResult's completion, agent SendReply and
FailMessage, AcknowledgeMessage's Pending to InProgress transition,
and the bulk timeout sweep in failActiveInvocationsForInstances). None
of those writers synchronized against each other or against the read
side, so this closes the same class of bug at the invocation level
too rather than leaving an identical gap sitting right next to the
fix.

Verified with the same style as the previous two commits: a spy forces
a rollup to block mid-finalize while still holding the Command lock,
and a new test asserts a concurrent ListCommands call (going through
SsmJsonHandler, not just SsmCommandService directly) blocks too rather
than observing a torn read. Confirmed it fails with the read-side lock
swapped for an unshared one and passes with it restored. Full ssm
package regression is green (64 tests).
2026-08-23 18:45:31 -04:00
Aniket Shukla 12b8ddd629 fix(cloudformation): tolerate missing stack resources during deletion (#2039)
* fix(cloudformation): tolerate missing stack resources during deletion

* test(cloudformation): align rollback storage fixture

* fix(cloudformation): require precise missing-resource errors
2026-08-23 17:29:53 -04:00
Matheus Oliveira 726c9c7446 fix(dynamodb): stop getSortKeyNames() from corrupting persisted tables (#2463)
`GlobalSecondaryIndex`, `LocalSecondaryIndex`, and `TableDefinition` expose
`getSortKeyNames()` with no setter. Jackson's getter-as-setter fallback
appends into the list it returns, an immutable `Stream.toList()`, throwing
`UnsupportedOperationException` whenever the schema has a RANGE key. On
startup, the storage backends catch that as an unreadable file and reload
with zero tables, taking down the whole store.

Mark `getSortKeyNames()` `@JsonIgnore` on all three classes; it's already
derived from `keySchema`.

Fixes #2415

Signed-off-by: Matheus Oliveira <matheus.6148@gmail.com>
2026-08-23 17:27:34 -04: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
TATSUNO “Taz” Yasuhiro 56e74d64c6 feat(sfn): support Retry policies in Task, Parallel, and Map states (#2455)
* feat(sfn): honor Retry policies in the ASL executor

Task, Parallel, and Map states previously ignored their Retry field, so
any failure went straight to Catch or failed the execution. They now
retry per the ASL spec. ErrorEquals matching reuses the Catch matcher,
including the States.ALL and States.TaskFailed wildcards, and
States.Runtime is never retried. AWS defaults apply when fields are
omitted (MaxAttempts 3, IntervalSeconds 1, BackoffRate 2.0).
MaxDelaySeconds is honored. Each retrier keeps its own attempt counter
and an exhausted retrier falls through to Catch. The context object
field $$.State.RetryCount increments per attempt.

Attempt counts, defaults, backoff timing, retry before catch order,
and per attempt RetryCount resolution were verified against real AWS
Step Functions in us-east-1 using execution histories.

Two deviations are documented. The delay between attempts is capped at
30 seconds, matching the cap Floci applies to Wait states.
JitterStrategy is accepted but ignored.

Refs #2283

* test(sfn): add end-to-end Retry integration tests

Covers the JSON 1.0 wire protocol path. The fail-then-succeed case
works without mocks by resolving the DynamoDB table name from
$$.State.RetryCount, so attempt 0 targets a missing table and the
retry targets one that exists. This also exercises per attempt
Parameters re-resolution, which real AWS does the same way. The other
cases cover retrier exhaustion falling through to Catch and an
unmatched error failing without retry.

* fix(sfn): unwrap branch failures so Parallel Retry and Catch apply

* fix(sfn): isolate the context object per Parallel branch and per branch state

* fix(sfn): fail a missing Lambda function as Lambda.ResourceNotFoundException

* test(sfn): cover Retry and Catch for Parallel and Map states

* feat(sfn): support JitterStrategy FULL in Retry backoff

* fix(sfn): keep branch Error causes wrapped so executions still terminate
2026-08-23 17:13:30 -04:00
Matt Van HornandMatt Van Horn 127e51e71b fix: inject AWS SDK environment into Flink sidecars (#2486)
Fixes #2404

Co-authored-by: Matt Van Horn <455140+mvanhorn@users.noreply.github.com>
2026-08-23 17:05:13 -04:00
Matheus Oliveira 13f68670d7 fix(dynamodb): cap GSI multi-attribute key parts at 4 attributes (#2475)
Closes #2460

Signed-off-by: Matheus Oliveira <matheus.6148@gmail.com>
2026-08-23 16:52:32 -04:00
Aniket Shukla 86e1c016cd fix(appsync): honor configured base URL in API URIs (#2457)
* fix(appsync): honor configured base URL in API URIs

* fix(appsync): repair persisted API URIs
2026-08-23 16:34:47 -04:00
Kenshin Okinaka c969ffc31d feat(ses): support +label subaddressing on mailbox simulator addresses (#2464)
The SES mailbox simulator lets senders add a +label to distinguish test messages,
so bounce+order-123@simulator.amazonses.com triggers a bounce like the bare address.
SimulatorAddresses now strips a +label from the local part (only + separates the
label; bounce-label@... is not a simulator address) before matching the type
case-insensitively. Add unit tests and document the behavior.
2026-08-23 16:26:41 -04:00
hisham-coderandHisham Mohammed f3b22e7964 fix(ecs): roll service tasks onto a changed task definition (#2483)
UpdateService with a new taskDefinition recorded a deployment but left the
running tasks on the old revision forever: a redeploy (new image tag, new
environment) never reached the containers, and the only way to apply it was
to StopTask by hand so the reconciler relaunched.

The reconciler now counts only tasks on the service's current task
definition towards desiredCount, so replacements start first, and when the
service is over desiredCount it drains the stale tasks before anything
else — the shape of AWS's rolling deployment with the ECS deployment
controller. Stopped reason names the replaced task definition.

The service pins the resolved task-definition ARN on CreateService and
UpdateService (AWS stores and reports the ARN), so a family or
family:revision reference compares exactly with each task's
taskDefinitionArn; a service persisted with a raw reference is pinned on
its first reconciler tick.

Co-authored-by: Hisham Mohammed <hisham.ma.mohammed@gmail.com>
2026-08-23 16:19:01 -04:00
Abarnaa Sree N 97921982d7 fix(bedrock-agentcore): allow maxResults up to 1000 (#2487) 2026-08-23 15:51:55 -04:00
Allen Sanborn c9f456ea7a fix(ec2): install packages with yum on Amazon Linux 2 guests (#2448)
Two package-manager probes in Ec2ContainerManager try dnf, apt-get and apk.
public.ecr.aws/amazonlinux/amazonlinux:2 ships **yum** and none of those
three, so both chains fall through on an Amazon Linux 2 guest:

- startSshd(): the trailing "command -v sshd" then fails, the method returns
  early, and the instance is never reachable over SSH -- despite Floci
  allocating a host port for it and injecting authorized_keys.
- metadataProxyInstallCommand(): reaches its else branch and exits 1 with
  "No supported package manager found for IMDS proxy dependencies", leaving
  the instance without a link-local IMDS endpoint.

This affects instances launched explicitly from ami-amazonlinux2 (or its ID
ami-0abcdef1234567890), not every instance: image-catalog.yaml pins
defaultDockerImage to amazonlinux:2023, which has dnf and already works. A
missing ImageId and unrecognised IDs both fall back to that default.

Verified against the image itself:

    $ docker run --rm public.ecr.aws/amazonlinux/amazonlinux:2 sh -c '
        command -v yum; for m in apt-get dnf apk; do command -v $m; done'
    /usr/bin/yum          # and nothing else

    $ yum install -y openssh-server openssh-clients      -> sshd, scp
    $ yum install -y iproute socat curl ca-certificates  -> ip, socat, curl

yum is probed after dnf so that dnf still wins on Amazon Linux 2023 and
modern Fedora/RHEL, where both exist and yum is only a compatibility shim.
The yum branch installs openssh-clients alongside the server, matching what
the dnf and apt-get branches do since #2449 -- an AL2 guest needs scp for
the same reason every other guest does.

Also extracts the probe into sshdInstallProbeCommand() so the tests can
assert against the string production actually issues rather than against a
copy of it declared in the test file.
2026-08-23 15:42:33 -04:00
Aniket Shukla b27b32f044 fix(ec2): retry Docker port collisions (#2029)
* fix(ec2): retry Docker port collisions

* fix(cloudformation): clean failed EC2 launches

* fix(ec2): bound container launch failures

* fix(ec2): cancel timed out container launches

* fix(ec2): track containers during startup

* test(ec2): align launch mocks with public IP option

* test(ec2): cover cancellation during Docker create

* fix(ec2): allow slow container cold starts

* fix(ec2): make launch failure cleanup idempotent
2026-08-23 15:34:56 -04:00
Aniket Shukla 6fa53abd7c feat(cloudformation): expand SAM AWS::Serverless::HttpApi to ApiGatew… (#1956)
* fix(cloudformation): preserve HttpApi routes and avoid stage-id collisions

expandServerlessHttpApi dropped the SAM DefinitionBody, so route-bearing AWS::Serverless::HttpApi templates expanded into an ApiGatewayV2 API with no routes. Carry DefinitionBody over as the ApiGatewayV2::Api Body.

It also synthesized a '<id>Stage' resource with resources.set(...), silently overwriting any resource the user already declared under that logical id. Skip synthesis (and warn) when the id is taken instead of clobbering the user's resource.

Tests cover both: DefinitionBody preserved as Body, and a user-declared <id>Stage left intact.

* fix(cloudformation): provision SAM HttpApi routes

* fix(cloudformation): reconcile SAM HttpApi routes

* fix(cloudformation): stage HttpApi route replacements

* fix(cloudformation): roll back failed HttpApi replacements

* fix(cloudformation): resolve intrinsic HttpApi definitions

* fix(cloudformation): roll back HttpApi definition removal

* fix(cloudformation): retain failed HttpApi route cleanup

* test(cloudformation): align HttpApi fixture with main

* chore(ci): retrigger flaky Neptune test

* fix(apigatewayv2): prevent duplicate routes on rollback

* fix(cloudformation): persist failed cleanup ownership

* fix(cloudformation): preserve OpenAPI route authorization

* fix(cloudformation): reject unsupported auth conjunctions

* fix(apigatewayv2): preserve rollback and auth semantics

* fix(cloudformation): surface incomplete update rollback

* fix(cloudformation): merge overlapping SAM HTTP API routes

* fix(cloudformation): preserve merged route authorization

* test(cloudformation): document SAM auth defaults
2026-08-23 15:20:20 -04:00
Aniket Shukla 0e3391cac2 fix(apigateway): route CORS preflight (OPTIONS) to deployed API integ… (#1955)
* fix(apigateway): route CORS preflight (OPTIONS) to deployed API integrations

Browsers send an OPTIONS preflight before a cross-origin call to a deployed
API. GlobalCorsFilter short-circuited every OPTIONS preflight with Floci's own
CORS response, so the request never reached the API Gateway integration — a
Lambda (or a configured OPTIONS method) that handles CORS itself never ran.
The deployed-API execute controllers also had no OPTIONS handler.

- Skip GlobalCorsFilter for deployed-API paths (execute-api, _aws/execute-api,
  and the _user_request_ form) on both the request and response sides, so the
  integration owns CORS — matching the filter's documented "integrations keep
  precedence" contract.
- Add @OPTIONS handlers to the three execute controllers, dispatching to the
  configured OPTIONS/ANY method like the other verbs.

Adds unit tests for the deployed-API path matcher.

Closes #1928

* test(apigateway): cover CORS preflight (OPTIONS) routing end-to-end

Add ApiGatewayPreflightRoutingIntegrationTest driving a real browser preflight through the full chain: global CORS filter skip on deployed paths, route matching, OPTIONS/ANY method resolution, and integration invocation. A contrasting preflight to a management path (/restapis) asserts the filter still short-circuits non-deployed paths, so the deployed-path cases run with CORS genuinely enabled.

* fix(apigatewayv2): preserve configured CORS preflight
2026-08-23 15:06:20 -04:00
Matheus Oliveira 768e96a33f fix(dynamodb): recognize every HASH attribute of a composite GSI partition key (#2474)
Query only validated/matched the first HASH attribute of a GSI's
partition key, ignoring the rest.

Closes #2461

Signed-off-by: Matheus Oliveira <matheus.6148@gmail.com>
2026-08-22 17:29:20 -05:00
Matheus Oliveira 0397826b90 fix(dynamodb): reject LSI KeySchema with other than one sort key (#2476)
Closes #2459

Signed-off-by: Matheus Oliveira <matheus.6148@gmail.com>
2026-08-22 16:59:03 -05:00
Davor Santic a2389e7733 fix(ecs): round-trip runtimePlatform and logConfiguration on task definitions (#2443)
RegisterTaskDefinition parsed a fixed field list and dropped everything
else, so a task definition registered with a runtimePlatform or a
container logConfiguration came back from DescribeTaskDefinition without
them. A client that verifies its own write — Terraform, or a deploy tool
comparing the registered revision against desired state — saw drift that
was not there.

Both are now parsed, stored on the task definition, and serialized back
with the AWS wire shape. A request that omits them still produces a
response without the keys, so nothing changes for existing callers.

The two fields are set on the task definition returned by
EcsService.registerTaskDefinition, following the pattern already used for
task-level volumes. That mutation happens after the value was stored, so
a backend that serializes on put (persistent, hybrid, WAL) had captured
the pre-mutation value; the definition is now written back, which also
makes the existing volumes round-trip survive a restart.
2026-08-22 00:22:32 -04:00
Tom Longhurst 30f965d056 fix(dynamodb): validate index access paths (#2278)
* fix(dynamodb): validate index access paths

* fix(dynamodb): address review feedback

* test(dynamodb): cover composite sparse index
2026-08-22 00:13:46 -04:00
Allen Sanborn f3029ee251 fix(ec2): install the SSH client package in guests, not just the server (#2449)
* fix(ec2): install the SSH client package in guests, not just the server

Guests get openssh-server but no client package, so the instance has sshd
and sftp-server but no /usr/bin/scp. Real AMIs carry both -- Amazon Linux 2
ships openssh-clients in the base image.

Provisioning tools need scp *on the instance*. Packer's default file
transfer for a shell provisioner uploads the script with scp, so a build
fails immediately after connecting successfully:

    ==> amazon-ebs.floci: Connected to SSH!
    Error uploading script: SCP failed to start. This usually means that
    SCP is not properly installed on the remote system.

Confirmed on a guest: /usr/libexec/openssh/sftp-server is present (it comes
with openssh-server) but /usr/bin/scp and /usr/bin/sftp are not.

Package names verified against the images rather than assumed:

    amazonlinux:2  yum install -y openssh-clients   -> /usr/bin/scp, sftp
    ubuntu:24.04   apt-get install -y openssh-client -> /usr/bin/scp, sftp
    alpine:3       apk add openssh                   -> /usr/bin/scp, sftp

so apk needs no change -- its openssh package already contains both -- and
only the rpm and deb branches gain a package.

The install guard now tests for scp as well. Keying it on sshd alone would
skip the install on an image that already has the server but no client,
leaving provisioning broken with nothing in the logs to explain it.

Without this, builds need ssh_file_transfer_method = "sftp" in the Packer
template as a workaround, which would not appear in a real template.

* fix(ec2): report a failed SSH client install instead of silent success

The install probe's trailing check was still "command -v sshd", so a guest that
already had the server but whose client package failed to install exited 0 and
initialization carried on -- the exact state the widened guard was added to
catch, and the one where Packer's default scp-based file transfer breaks, with
nothing in the logs to explain it.

The two outcomes are not equally fatal, so the script now distinguishes them:
exit 1 for no sshd, where there is nothing to start and startSshd returns as
before, and exit 2 for sshd present but scp missing, which warns and continues.
An instance that can serve SSH but cannot scp is still worth making reachable;
failing the whole setup there would trade a silent gap for an unreachable
instance.

Tests: the launch test that drives a failing probe is parameterized by exit
code, adding launchWhenOnlySshClientInstallFails_stillStartsSshd for the exit-2
path (keygen and sshd are still issued), and the probe-script assertion now
pins the trailing status check itself.

Ec2ContainerManagerTest: 23 tests, 0 failures, 0 errors.
2026-08-21 23:40:24 -04:00
Michal Schreiber 3887a6ca65 fix(docdb): scope cluster and instance identifiers per region (#2440)
* fix(docdb): scope cluster and instance identifiers per region

AWS scopes these identifiers per region: the same name creates in two regions,
each resource with its own ARN and its own tags. Floci keyed its records by the
identifier alone, so the second region's create was refused as already existing,
and a name spent in one region was spent everywhere.

The key is now region::identifier, the shape RdsService already uses for the
same identifiers. Records written under a bare identifier belong to the
configured default region — that is the region they were created under, the
assumption the ARN backfill already makes — and are moved under their regional
key on first read, under the record's monitor so the move cannot undo a delete.

Every read, write, listing and lock is keyed that way, including the cluster
members list an instance create and delete maintain, and an instance can only
attach to a cluster in its own region. Ownership of an identifier is a lookup
rather than a scan filtered by the region read back off each record's ARN.

Closes #2416.

* fix(docdb): make a field filled in on read safe against a concurrent delete

Filling in a missing ARN on read is still a write, and it was not serialised
against anything: a reader that started before a delete put the record back
after it, leaving a cluster no describe created and no delete can remove.

It takes the monitor every other writer of that record takes now — naming one
after the store key rather than the record gave two monitors, and two monitors
are no mutual exclusion at all — and writes only if the record under the key is
still the one it filled in, so a delete, or a delete and a re-create under the
same name, is not written over.

That second check is also what makes retiring a monitor with its record safe. I
had removed the retirement suggested on #2408, believing it was the cause; a
direct test showed it passes cleanly and the fault was the mismatched monitor,
so it stays.

* fix(docdb): take one monitor per record, and list across a move exactly once

Two things review found in the re-key.

deleteDbInstance took the cluster's monitor by its bare identifier while every
other writer of that record takes it by the regional key. Two names are two
monitors, so removing the last instance could write the cluster back — without
its member, but back — after the cluster had been deleted, leaving metadata no
delete could remove and a name that could not be recreated.

And the listing read the regional keys and then the unscoped ones, so a move
running between the two scans lost the record from both: gone from the bare key
by the time that scan ran, not yet under the regional key when that one did.
The unscoped keys are read first, which leaves no interleaving in which neither
scan sees it, and the result is reduced by identifier for the interleaving where
both do.

Both are staged rather than raced. The tests hold one thread at a chosen store
call while the other runs, because a loop hoping for a window a few instructions
wide passes whether or not the fix is there — as the first versions of these two
tests did.

* test(docdb): stage the interleaving the migration's monitor is for

The only cover for that lock was the racing loop, and a loop does not reach a
window a few instructions wide — removing the lock left every test green. The
move is now held at the write it makes under the regional key while a delete
runs, which is the interleaving the monitor exists to prevent: without it the
held write lands after the delete and the record comes back.

The mutation has to compile to prove anything, incidentally. Replacing the
synchronized block with `if (true)` leaves the method without a return and the
build fails, which reads as a passing suite in a filtered log; locking a
throwaway object removes the exclusion and keeps the code valid.
2026-08-21 20:58:54 -04:00
soreavis 353d9c842f feat(kinesis): add PutRecords request caps and a per-stream max record size (#2438)
PutRecords enforced only the per-record limit. AWS also caps a request at
500 records and 10 MiB including partition keys; both are now whole-request
rejections with InvalidArgumentException, since per-record ErrorCode only
carries throughput and internal failures. The count cap is checked upfront
and the byte cap as the loop goes, so neither an over-long batch nor an
oversized one is fully decoded before it is rejected. Undecodable or
non-string Data counts toward the cap at the UTF-8 bytes the caller sent,
so a batch of malformed records cannot slip past it.

The per-record maximum becomes per-stream state defaulting to 1024 KiB, set
by CreateStream's MaxRecordSizeInKiB or UpdateMaxRecordSize (1024-10240) and
reported by DescribeStreamSummary. UpdateMaxRecordSize documents
ValidationException for an out-of-range size. CreateStream doesn't, and
reserves ValidationException for the on-demand case, so it answers
InvalidArgumentException. Streams persisted before the field existed
deserialize to the default.
2026-08-21 16:15:25 -04:00
Anmol Mishraandanmolxlight ba97c084eb fix(lifecycle): run start/ready hooks when FLOCI_PORT is non-default (#2439)
onHttpStart compared the HTTP server port against a hardcoded 4566, but
Quarkus actually listens on floci.port (quarkus.http.port: ${floci.port}).
With any non-default FLOCI_PORT the guard never matched, so start/ready
hooks never ran and /_floci/init stayed stuck at boot:true forever while
/_floci/health returned 200.

Compare against config.port() instead. TLS mode is unchanged: TlsConfigSource
pins the HTTP backend to 4510 regardless of floci.port.

Fixes #2437

Co-authored-by: anmolxlight <anmolxlight@users.noreply.github.com>
2026-08-21 15:53:04 -04:00
sheldon-nadarajah-sft 39ed7712a7 fix(kinesis-cbor): timestamps mis-scaled 1000x on the CBOR path (#2432)
* fix(kinesis-cbor): timestamps mis-scaled 1000x on the CBOR path

AWS's legacy CBOR protocol (application/x-amz-cbor-1.1, which the real AWS
SDK for Java v2 uses by default for Kinesis) encodes tag(1) timestamps as
epoch milliseconds; the plain-JSON protocol uses fractional epoch seconds.
AwsJsonCborController treated both as seconds in both directions:

- Request side: handleGetShardIterator's AT_TIMESTAMP branch multiplied an
  already-millisecond value by 1000 again, landing the iterator around the
  year 58598 - past every real record - so GetRecords returned an empty
  page forever, with no error at all.
- Response side: ApproximateArrivalTimestamp (and every other *Timestamp
  field) was written under tag(1) as the internal epoch-seconds value
  unchanged, so a real client decodes every arrival timestamp 1000x too
  small (1970 instead of the real date).

Fixes both directions in AwsJsonCborController, the one place that knows
which wire protocol is in play, so no service handler needs to change:
writeCborTimestamp now converts seconds -> millis before writing tag(1),
and a new normalizeCborTimestampsFromMillis converts millis -> seconds on
every decoded request/response body, reusing the same schema-less
field-name heuristic (isTimestampField) the writer already relied on.
BigDecimal (not double arithmetic) preserves millisecond precision exactly
in both directions.

AwsJsonCborSerializerTest's existing assertions had locked in the bug as
intended behaviour (an epoch-second value round-tripping unchanged under
tag(1)) - updated to expect the correct millisecond value, plus new
round-trip and non-timestamp-field coverage. Added
AwsJsonCborKinesisAtTimestampIntegrationTest, a genuine end-to-end
reproduction driven through the real HTTP CBOR endpoint: it hand-builds
the GetShardIterator request's Timestamp as a raw tag(1) millisecond value
(independent of this class's own writer, so it can't pass by testing
against itself) and confirms GetRecords actually finds the record -
verified failing (0 records) against the pre-fix code and passing against
the fix.

Closes #2368

* fix(kinesis-cbor): scope millisecond scaling to the legacy CBOR dialect only

CI (native / sdk-test-go, Compatibility Tests) caught a real regression: the
previous commit scaled EVERY CBOR-routed service's tag(1) timestamps to
milliseconds, but there are genuinely two different CBOR dialects sharing
this same code, not one protocol with an inconsistency:

- The legacy application/x-amz-cbor-1.1 dialect (handleCborRequest, X-Amz-
  Target routing) - Kinesis's default transport, confirmed via a real wire
  capture to use epoch MILLISECONDS under tag(1). This is the dialect
  #2368 actually reported.
- The smithy-rpc-v2-cbor protocol (handleSmithyRpcV2Cbor, path-based
  /service/{id}/operation/{op} routing) - CloudWatch Metrics' transport
  (confirmed via the Go SDK compat test's own comment: "GetMetricData
  round-trips through the rpc-v2-cbor protocol"), which uses RFC 8949
  section 3.4.2's own tag(1) convention: plain, UNSCALED epoch seconds.

Scaling both uniformly broke CloudWatch: PutMetricData's Timestamp got
divided by 1000 on decode, landing every datapoint far outside any
GetMetricStatistics/GetMetricData query window - exactly the CI failure
("Should NOT be empty, but was []").

Splits the previously-shared methods into dialect-specific pairs:
nodeToSmithyCbor/plain bodyToJson stay unscaled (smithy-rpc-v2-cbor,
reverted to original behaviour); nodeToLegacyCbor/
normalizeLegacyCborTimestampsFromMillis apply the millisecond scaling,
used only by handleCborRequest. Kinesis's own reproduction test already
posts through handleCborRequest, so it needed no change and still passes.

Updated AwsJsonCborSerializerTest to cover both dialects explicitly
(smithyRpcV2* / legacy* prefixes) instead of one ambiguous set of
assertions, and added AwsJsonCborCloudWatchTimestampIntegrationTest - a
genuine end-to-end regression guard (PutMetricData -> GetMetricStatistics
via the real rpc-v2-cbor route) that fails the same way the CI failure did
if this scaling is ever mistakenly reapplied to that path.

Verified: the Kinesis and CloudWatch end-to-end tests, the full
AwsJsonCborSerializerTest suite, and 10714 tests across the kinesis,
cloudwatch, and core.common packages all pass with zero failures.
2026-08-21 14:11:37 -04:00
Ben Younes 8ac23deb06 fix(cloudfront): include terraform-required distribution fields (#1940)
Real CloudFront always returns DistributionConfig.OriginGroups and
DistributionConfig.Restrictions on Create/Get/ListDistributions. Floci
omitted both, so the Terraform AWS provider dereferenced a nil
OriginGroups.Quantity and panicked while flattening the distribution.

Emit an empty OriginGroups block plus a Restrictions/GeoRestriction block
(defaulting to RestrictionType "none") in the distribution config body and
in distribution summaries, and parse an incoming GeoRestriction so
submitted restriction types and locations are echoed back.

Closes #1930
2026-08-21 10:33:04 -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
mitsukado-shinagawaandmitsukado-shinagawa d0a96d87b1 fix(apigatewayv2): CloudFormation AuthorizationScopes pass-through and scope-ingestion hardening (follow-up to #2011) (#2431)
* fix(apigatewayv2): pass AuthorizationScopes through CloudFormation routes and harden scope ingestion

Follow-ups from PR #2011 review:

- AWS::ApiGatewayV2::Route now passes AuthorizationScopes to route
  create/update, so CFN-provisioned scoped routes enforce the 403 path.
  The property is always sent (empty when absent) so removing it from a
  template clears the scopes on UpdateStack.
- authorizationScopes elements are normalized to strings at ingestion
  instead of unchecked-cast; a non-string JSON element used to throw
  ClassCastException during response serialization.
- Add JSON 1.1 round-trip coverage for AuthorizationScopes on routes
  (the ApiGatewayV2JsonHandler rendering block was previously unguarded).

* fix(apigatewayv2): reject non-array authorizationScopes with 400

A present-but-non-array value was silently normalized to null, which
created the route without scope enforcement or cleared an existing
route's scopes on update. It now fails with BadRequestException, and
an update that 400s leaves the stored scopes untouched.

---------

Co-authored-by: mitsukado-shinagawa <mitsukado-shinagawa@users.noreply.github.com>
2026-08-20 23:44:21 -04:00
Michal Schreiber 760200223a fix(docdb): give a record without an ARN the one it should have had (#2425)
A tag call is answered for the record its ARN names, which needs the record to
have one. A cluster or instance written before ARNs were stored has none, so the
comparison had nothing to compare and the call resolved by identifier alone —
the hole that check closes, left open for exactly the records that predate it.
Reachable on the docdb credential scope, which addresses this service directly.

The ARN is filled in on read, as the RDS side already fills in a parameter
group's missing region and ARN, and from the default region rather than the
caller's: such a record was created when every ARN came from the default, so
that is the region it is in — taking the reader's would let a caller elsewhere
claim it, which is the same bug wearing a fix's clothes.

With every record carrying an ARN by the time it is compared, the null
allowance in requireArnNamesRecord goes away rather than remaining as a standing
exception.

A deleted record's monitor is also dropped now. What stops a tag from reviving a
deleted record is the re-resolve inside the lock rather than the identity of the
monitor, so retiring one with its record is safe.
2026-08-20 23:35:03 -04:00
Alex Banna 470ec77711 feat(signin): support AWS login credentials provider (#2428)
* feat(signin): add AWS login credentials provider

* fix(signin): initialize secure random at runtime

* fix(signin): make refresh exchange idempotent

* fix(signin): match AWS OAuth token contracts

* refactor(signin): add typed token result model

* fix(signin): align errors with AWS exception handling
2026-08-20 23:34:40 -04:00
Matt Van HornandMatt Van Horn 967ea843a0 fix: preserve Route 53 private hosted-zone VPC associations (#2342)
* fix: preserve Route 53 private hosted-zone VPC associations

Fixes #2294

* fix(route53): correct SDK accessor, validate VPC, dedupe test order

Addresses @pgermosen's three review points:

1. sdk-test-java failed to compile: the real SDK accessor for the VPCs list is
   vpCs(), not vpcs(). Confirmed with javap against the pinned
   route53-2.44.14.jar.

2. parseVpcAssociation accepted a <VPC> element carrying only one of VPCId /
   VPCRegion and still marked the zone private with a half-populated
   association. AWS requires both together whenever VPC is present, so an
   incomplete element is now rejected with InvalidInput/400.

3. Route53IntegrationTest had two methods at @Order(3), leaving their relative
   order undefined. Renumbered the trailing cases so every order is unique.

---------

Co-authored-by: Matt Van Horn <455140+mvanhorn@users.noreply.github.com>
2026-08-20 23:28:14 -04:00
Aniket Shukla c4597f2e53 fix(cloudformation): reconcile DynamoDB streams declared by StreamSpecification (#2411)
Provisioning AWS::DynamoDB::Table ignored StreamSpecification, so a stack that
declared a stream produced a streamless table: DescribeTable returned neither
StreamSpecification nor LatestStreamArn, and event source mappings registered
against the expected stream ARN polled "Stream not found" forever. The plain
UpdateTable API enabled streams correctly on the same runtime, which is what
made this look CloudFormation-specific.

The CloudFormation property carries no StreamEnabled flag — unlike the DynamoDB
API, declaring the block IS the request — so the block's presence now turns the
stream on, honouring StreamViewType. A block that omits StreamViewType still
yields a working stream: the schema marks it required and AWS documents no
default, so this is deliberately the same leniency DynamoDbJsonHandler already
applies on CreateTable/UpdateTable, not an AWS behaviour.

Removing the block on an update is the inverse request and switches the stream
back off, so a table updated out of streaming stops emitting records to whatever
still holds its ARN.

Streams are reconciled through new DynamoDbService enableStream/disableStream,
mirroring what the JSON handler already does inline for CreateTable/UpdateTable
and persisting the table so the change survives. Callers that reach DynamoDB
through the service rather than the handler had no entry point for this.

Re-enabling a live stream now retargets its view type. The records a stream
emits are built from the stream description, which was left untouched once the
stream was ENABLED, so a changed StreamViewType was reported by DescribeTable
while records kept the old shape. This also fixes the same inconsistency on the
UpdateTable path.

Make that stream state durable. Both handler paths mutate the table after the
service has stored it, and a persistent backend serializes on write rather than
holding the live object, so the on-disk copy kept the previous settings. Since
startup rebuilds every stream from the persisted table, a restart resurrected
the old view type — and a stream declared on CreateTable was lost outright,
because the persisted copy still had streamEnabled false. Both paths now flush
once after their mutations, which also makes the billing mode, table class, tags
and SSE settings they set survive a restart.

Also reconcile the StreamArn attribute: only a live stream has an ARN worth
handing to Fn::GetAtt. The previous synthetic value resolved to nothing on a
streamless table, and because an update starts from the resource's previous
attributes, a stale ARN is now removed rather than merely left unwritten.

Adds DynamoDbStreamSpecificationCfnProvisionerTest covering the declared
stream, an explicit StreamViewType, a block with no view type, removal and
retention on update, a view-type change on update, and the unchanged no-stream
path; DynamoDbStreamServiceTest coverage that a retarget reaches the emitted
records; and DynamoDbStreamViewTypeDurabilityTest, which drives the handler
against a file-backed store and reloads it to prove both paths survive a restart.
2026-08-20 23:23:19 -04:00
Saatvik Arya 2314c85b62 fix(lambda): serialize resource policy mutations (#2430)
* fix(lambda): serialize resource policy mutations

* fix(lambda): serialize restored policy statements
2026-08-20 23:14:42 -04:00