Commit Graph
1008 Commits
Author SHA1 Message Date
Dixit R Jain 45bb37f1fb feat(apigatewayv2): route execute-api hosts to WebSocket $connect and @connections (#2188)
Consolidates AWS-style execute-api virtual-host support for WebSocket APIs onto the
existing ApiGatewayExecuteApiHostFilter (added in #2054) plus the WebSocket handler,
instead of adding a second host filter.

- @connections (#1846): ApiGatewayExecuteApiHostFilter now also rewrites a WebSocket
  API's @connections management calls (.../{stage}/@connections/{id}) to the canonical
  /execute-api/{apiId}/{stage}/... route, behind the same disableExecuteApiEndpoint->404
  check. It previously bailed for non-HTTP APIs, so @connections on the execute-api host
  was swallowed by the S3 controller.
- $connect (#1871): WebSocketHandler accepts the execute-api host for the WS handshake
  and resolves the API region -- from the host's region label when present, else a
  cross-region apiId lookup (ApiGatewayV2Service.resolveApiRegion) -- fixing the 403 for
  APIs created in a non-default region.
- Widen the filter host regex to accept the region-bearing AWS form
  ({apiId}.execute-api.{region}.localhost|amazonaws.com) alongside Floci's regionless
  built-in suffixes (.execute-api.localhost.floci.io / .localstack.cloud).
- Fix RegionResolver.resolveRegionFromHost to treat only a real region label as the
  region and return null for the built-in suffixes -- the old pattern parsed "localhost"
  as the region and broke the lookup.
- Remove the separate ExecuteApiSubdomainFilter; host parsing is shared via
  ApiGatewayExecuteApiHostFilter.extractApiId.
- Update docs and add Java unit + Node SDK compatibility coverage for both host forms.

Closes #1871
Closes #1846
2026-08-13 14:40:50 -04:00
Mohammad Mehdi RoshaniandMoroshani 9ebf9feb54 fix(lambda): propagate image inspection failures (#2268)
Co-authored-by: Moroshani <208086089+moroshani@users.noreply.github.com>
2026-08-13 09:56:52 -04:00
Guinevere Friedman b911ccd013 fix(lambda): SIGTERM container before closing runtime API socket (#2098)
* fix(lambda): SIGTERM container before closing runtime API socket

Real AWS Lambda tears an execution environment down by sending SIGTERM
to the runtime while the runtime API stays responsive; the runtime
library (awslambdaric, Node.js RIC, ...) sees the signal and exits
cleanly on the OS default handler. Floci closed the runtime API socket
first, causing the parked /invocation/next long-poll to wake with a
network error before SIGTERM could reach the process — the runtime
library treated that as a fault and printed a ~40-line traceback on
every clean invocation.

Split RuntimeApiServer.stop() into quiesce() (settle bookkeeping,
notify extensions, complete pending/in-flight invocations) and close()
(release the httpServer socket). Reorder ContainerLauncher.stop() to
quiesce → docker stop → close, so the runtime process receives SIGTERM
against a still-bound socket and exits cleanly. Parked runtime pollers
now stay parked through quiesce() rather than receiving an
AWS-undocumented 204, matching real Lambda behaviour where a shutting
runtime is expected to exit on SIGTERM without the API side responding.

Docker's stop timeout is now selected from AWS's documented
Shutdown-phase grace tiers: 2s when at least one extension is
registered, 1s (rounding up AWS's 300ms runtime sub-budget) otherwise.

Closes #2091

* fix(lambda): populate inFlight under lock to close teardown race

enqueue() and the /invocation/next handler polled the parked ctx or
pending invocation inside the server lock, then dispatched
sendInvocation() asynchronously on the Vert.x context. inFlight was
populated inside sendInvocation, after the lock had been released — so
a concurrent quiesce() could sweep pendingQueue and inFlight (both
empty at that instant) and miss an invocation that was already in
flight from the caller's perspective. The invocation's future would
then never complete, and the caller would hang until the function's
deadline.

Move inFlight.put(...) into the same synchronized block as the poll,
so quiesce()'s sweep and enqueue's dispatch are ordered by the lock.
sendInvocation still does its inFlight.put — now a same-value overwrite
in the fast path, and the source of truth for the slow path where
inFlight.put runs earlier than the ctx write does.

Add two property tests exercising the race window: one where enqueue()
hands the invocation to a parked poller, one where NEXT_PATH polls
from pendingQueue, both followed by an immediate stop().

* fix(lambda): drop deferred dispatch if quiesce completed the invocation

After enqueue() records an invocation in inFlight and hands it to a
parked poller, the actual sendInvocation() runs on a deferred Vert.x
context. If quiesce() lands between the two, it sweeps inFlight and
completes the caller's future with ContainerStopped — but the deferred
callback would still deliver the invocation to the runtime, which
would execute the handler (side effects) and POST /response into a
future that's already completed. CompletableFuture silently discards
the second complete(), so the caller sees an error even though the
function ran and succeeded.

Re-check `stopped && inFlight.get(requestId) == null` inside the lock
before dispatching, and skip the dispatch if so. Applies to both entry
points: enqueue()'s deferred sendInvocation and NEXT_PATH's
synchronous-but-post-lock-release sendInvocation.

Add a property test that parks a poller, enqueues, immediately stops,
and asserts the poller does NOT receive a 200 with the invocation
payload — only a socket close from close() is acceptable.

* fix(lambda): make quiesce's inFlight sweep atomic under lock

The dispatch guards in enqueue()'s deferred callback and NEXT_PATH read
`stopped` under the server lock. Their correctness relies on the
invariant: once quiesce() releases its lock, stopped=true implies
inFlight is empty. The prior code cleared inFlight *outside* the lock,
which left a window where a dispatch could observe stopped=true while
an inFlight entry it's about to deliver was still present — the guard
would let the delivery through, quiesce would then complete the future
with ContainerStopped, and the runtime's /response would be silently
discarded.

Snapshot inFlight inside the lock (symmetric with pendingQueue two
lines above), complete futures outside. Dispatch guards simplified to
just `stopped` since the atomicity now holds by construction. Drop
sendInvocation's redundant inFlight.put — both entry points pre-insert
under the lock.

Also:
- Narrow ContainerLauncher.stop()'s timeout comment: docker's --time is
  a max wait for PID 1, not a grace floor. Extensions run as sibling
  `docker exec`s and are killed with the container; the 2s ceiling
  doesn't back the deadlineMs advertised to extensions.
- Fix javadoc placement: hasRegisteredExtensions() had accidentally
  inherited isFaulted()'s comment. Give each its own doc.

Add quiesceAtomicallyClearsInFlightWithStopped test: multiple in-flight
invocations → quiesce → all futures must complete with ContainerStopped.

* fix(lambda): reconcile with #2156 write-flush + trim comments

#2156 landed the "await parked writes before httpServer.close" pattern
for extension SHUTDOWN dispatches. Reconcile our teardown split with
that: quiesce() schedules extension SHUTDOWN dispatches and records
their aggregate flush completion in a new field extensionWritesFlushed;
close() awaits that field before dropping the httpServer.

Preserves both behaviours: SIGTERM-before-socket-close ordering (this
PR's core value) and the write-flush guarantee (#2156's contribution).

Runtime pollers still stay parked — no 204 — matching real AWS Lambda's
teardown. Trim design-doc-shaped comments to reviewer-friendly length
in the same file.

* test(lambda): add deterministic race tests via test-specific subclass

The three sleep-based race tests (removed here) don't distinguish the
fix from the pre-fix code — they exercise the interleaving with
Thread.sleep and pass either way. Replace them with two latch-gated
tests that reproduce the exact interleaving hampsterx flagged
(enqueue's deferred dispatch, and NEXT_PATH's synchronous dispatch,
each racing against a partially-swept quiesce) and prove the guards
plus atomic inFlight sweep close the silent-discard bug.

The tests use the "test-specific subclass" pattern (Meszaros, xUnit
Test Patterns) rather than a settable-field hook on the production
class: quiesce() and the two dispatch sites call three empty
`protected void` methods that a test subclass overrides to gate on
CountDownLatches. Production has no mutable state, no volatile reads,
and matches Floci's existing `Test-only:` javadoc convention
(ContainerLauncher, LambdaService, LambdaConcurrencyLimiter, ...).

Verified: reverting the atomic-sweep-in-lock fix AND the guard
simplification causes both new tests to fail with the expected
"parked poller received the invocation" assertion. Restoring either
fix alone is enough for the tests to pass, confirming they gate on
the invariant that matters (stopped=true ⇒ inFlight empty).

* fix(lambda): commit enqueue dispatch/requeue decision atomically

Per @abanna's review of #2098. enqueue()'s deferred callback read
waitingCtx.response().ended() twice — once inside `synchronized(lock)`
deciding requeue, once outside deciding send. A client disconnect
between the two reads left neither branch firing and the invocation
stranded in inFlight until the function deadline.

Read ended() exactly once inside the lock and commit dispatch/requeue
before releasing. Adds a deterministic latch-gated race test (two new
Test-only protected seams) that fails on the double-read shape and
passes on the fix. 50/50 tests pass.

* fix(lambda): requeue invocation when sendInvocation's write fails

Per Greptile's P1 review of a1a659b4. Even with the atomic dispatch
decision, a runtime disconnect between the lock-committed decision and
the .end() flush left the invocation stranded in inFlight until the
function deadline — the fluent chain has no failure handler.

Wrap the fluent chain in try/catch (setStatusCode/putHeader throw
synchronously on an already-ended response) and attach .onFailure to
.end() (which returns a failed Future for socket-level failures). Both
paths funnel into one handler that requeues into pendingQueue and drops
the stale inFlight entry — mirror of the ctx-ended branch in enqueue()'s
deferred callback. No-op if quiesce() beat us (stopped=true).

Adds a deterministic test that ends the parked ctx from
beforeSendInvocationWrite and asserts pendingQueueSize=1 + inFlightSize=0.
Fails on the pre-fix write-and-forget shape, passes on the fix. 51/51.
2026-08-13 09:30:44 -04:00
Olamide Kosile a235b76835 feat(cloudformation): implement GetTemplateSummary (#2148)
* feat(cloudformation): implement GetTemplateSummary (#1964)

Adds the missing action to the CloudFormation Query allowlist and
computes Parameters, ResourceTypes, Version, DeclaredTransforms and an
informational Capabilities/CapabilitiesReason (derived from AWS::IAM::
resource types) from a stack's existing template, an inline
TemplateBody, or a TemplateURL. Without this, tools like sam deploy
that call GetTemplateSummary before UpdateStack failed with
UnsupportedOperation.

* fix(cloudformation): correct GetTemplateSummary for SAM stacks and named IAM resources

Addresses two review findings:

- StackName lookups summarized the persisted post-transform template,
  so an existing SAM stack lost its Transform declaration and reported
  expanded resource types (AWS::Lambda::Function) instead of the
  original submitted ones (AWS::Serverless::Function). Stack now keeps
  the pre-transform template body alongside the existing post-transform
  one, and GetTemplateSummary prefers it.
- Capabilities always reported CAPABILITY_IAM for any IAM resource,
  even ones with an explicit name (e.g. RoleName). CloudFormation
  requires CAPABILITY_NAMED_IAM for those; GetTemplateSummary now
  checks the relevant name property per IAM resource type.

* fix(cloudformation): detect named IAM resources set via intrinsic functions

The CAPABILITY_NAMED_IAM check only looked for a literal string value
on the name property, so a real-world RoleName/UserName/etc. set via
Ref, Fn::Sub, Fn::Join or another intrinsic (the common shape in SAM
and CDK output) was missed entirely, misclassifying the template as
only needing CAPABILITY_IAM. CloudFormation requires NAMED_IAM whenever
the property is present at all, regardless of how its value resolves,
so the check now looks for presence instead of a textual value.

* docs(cloudformation): clarify GetTemplateSummary's originalTemplateBody fallback

Spells out why the fallback to the post-transform templateBody exists
(originalTemplateBody has no data for stacks persisted before this
field was added) and that it self-heals on the stack's next
CreateChangeSet/UpdateStack call, in response to review feedback.
2026-08-13 00:29:11 -05:00
Hector Ventura 4ba854ab8c fix(stepfunctions): publish execution status after its terminal fields (#2234)
* fix(stepfunctions): publish execution status after its terminal fields

DescribeExecution returns the live Execution instance from the store, and the
executor mutated it in place with the status set before the fields that describe
it. A client polling for a terminal status could therefore observe SUCCEEDED with
a null output, which real Step Functions never returns.

This is what reddened main in run 31457665686: the poll in
StepFunctionsPassParametersIntegrationTest landed inside the window and Jackson
rejected the null document with IllegalArgumentException: argument "content" is
null. It is intermittent (one failure in the last fifteen main runs), because the
window is two adjacent field writes wide.

Set the terminal fields first and the status last on every terminal path, so the
status is the publication point: SUCCEEDED, both FAILED paths, failExecution,
TIMED_OUT, and ABORTED in stopExecution.

The outer catch in doExecute was worse than a race. It set only the status, so an
execution failing there reported FAILED with a null error and cause permanently.
It now records both.

No new test. The window is a few instructions wide while an HTTP round trip is
milliseconds, so a black box test cannot land in it, and onUpdate fires after every
setter so there is no seam to observe from. A concurrent polling test was written
and discarded after it passed against the unfixed code. Existing coverage does
guard the fields themselves: StepFunctionsJsonataIntegrationTest asserts error and
cause on failed executions in several places.

* test(stepfunctions): cover terminal error and cause on the outer catch

The outer catch in doExecute previously set only the status, leaving error
and cause null on an execution DescribeExecution reports as FAILED. That
path had no coverage: no test referenced the "State not found" throw, and
the existing States.Runtime assertions all go through the inner catch.

A missing state reaches it deterministically, since the throw sits outside
the per-state try and unwinds the whole execution loop. Verified as a real
guard rather than a green one: against the pre-fix outer catch these fail
with "expected: <States.Runtime> but was: <null>".

Field ordering is deliberately not asserted. The window between two
adjacent setters is a few instructions wide, so a black box test cannot
land in it.
2026-08-13 00:24:07 -05:00
Olamide Kosile c48c062117 fix(docker): fall back to Windows named pipe when docker-host is at its unix-socket default (#2030)
Floci defaults docker-host to unix:///var/run/docker.sock, which has
no equivalent on native Windows. Since this hardcoded default always
overrides docker-java's own OS-aware detection, every Docker-backed
operation failed at container-start time on Windows with a low-level
socket error — including Lambda-invoked CloudFormation custom
resources such as CDK's Custom::S3BucketNotifications.

When docker-host is still unmodified and DOCKER_HOST isn't set, fall
back to Docker Desktop's named pipe (npipe:////./pipe/docker_engine)
on Windows, mirroring what docker-java already does correctly on its
own. Linux/macOS behavior is unchanged. An explicit docker-host or
DOCKER_HOST always takes priority over the fallback.

Verified end-to-end: a CDK-shaped stack (S3 bucket + Lambda +
Custom::S3BucketNotifications) went from CREATE_FAILED to
CREATE_COMPLETE after this fix.

Fixes #2006.
2026-08-13 00:02:28 -05:00
Maciej cfbae88fca feat(apigateway): derive SQS QueueUrl from path-style integration URI when absent from template (#1903)
* feat(apigateway): derive SQS QueueUrl from path-style integration URI when absent from template

* fix(apigateway): derive SQS QueueUrl from the queue name
2026-08-12 23:57:53 -05:00
lex00 907a2dfbf3 feat(cloudformation): provision AWS::ECS::CapacityProvider and ClusterCapacityProviderAssociations (#1999)
* feat(cloudformation): provision AWS::ECS::CapacityProvider and ClusterCapacityProviderAssociations

Maps both onto the existing EcsService.createCapacityProvider /
putClusterCapacityProviders — provider name generation follows the other
provisioners, associations carry the provider list and default strategy
(weight/base).

Fixes #1998

* refactor(cloudformation): move ECS capacity provisioning into a per-service provisioner

The new resource types from #1998 landed as two more arms of
CloudFormationResourceProvisioner's switch. Move them into the per-service
structure introduced in #1825 so the monolith stops growing:

- EcsCapacityCfnProvisioner owns AWS::ECS::CapacityProvider and
  AWS::ECS::ClusterCapacityProviderAssociations and injects only EcsService.
  It is picked up by CloudFormationResourceRegistry through CDI, so both switch
  arms and their provisionEcsCapacity* methods are gone.

Two review findings are fixed along the way:

- Delete is implemented. Previously stack deletion and create rollback hit the
  default arm of the delete dispatch, so a stack could report DELETE_COMPLETE
  while the capacity provider stayed registered and the cluster kept its
  associations. Deleting the associations resource now detaches the providers
  from the cluster, and deleting a capacity provider deregisters it. Both are
  idempotent for the already-gone case (rollback, a persistent restore that
  dropped the record) and propagate every other AwsException so a genuine
  failure still settles the stack into DELETE_FAILED.

- Capacity provider properties are no longer discarded. Only
  AutoScalingGroupArn was forwarded and tags were replaced with an empty map,
  so ManagedScaling, ManagedTerminationProtection and ManagedDraining silently
  vanished. The whole AutoScalingGroupProvider sub-tree is now carried across
  with intrinsics resolved and keys decapitalized, which is the shape
  CreateCapacityProvider stores, so a provider created by a stack holds the same
  state as one created through the ECS API. Tags are parsed from the standard
  Key/Value list.

EcsCapacityCfnProvisionerTest covers both types against a single mocked
EcsService, including the full ASG configuration, tags and every delete path.
CloudFormationEcsCapacityIntegrationTest additionally asserts the tags reach
DescribeCapacityProviders and that deleting the stack deregisters the provider.

* fix(cloudformation): update an existing ECS capacity provider instead of recreating it

UpdateStack re-executes every resource with the physical id it got at create
time, and createCapacityProvider rejects a name that already exists, so an
unchanged provider failed the whole update. With no Name declared the
provisioner also minted a fresh generated name on every pass and left the
previous provider behind.

An existing provider is now reused through updateCapacityProvider, an unnamed
one keeps the name its first execution generated, and a provider removed out of
band is recreated rather than reported as a failure. Name and
AutoScalingGroupArn are createOnly, so a change to either is reported as an
unsupported replacement, matching how AWS::IAM::Role handles RoleName.

updateCapacityProvider carries only the Auto Scaling settings, so Tags are
applied separately and a tag the template dropped is removed.
2026-08-12 23:47:20 -05:00
lex00 43f47a3c96 feat(cloudcontrol): implement CreateResource / DeleteResource / GetResource (#2037)
* feat(cloudcontrol): implement CreateResource / DeleteResource / GetResource

Floci's Cloud Control handler implemented only ListResources; CreateResource and
the rest returned "unsupported". Tools that drive AWS through the Cloud Control
API (rather than the individual service APIs) therefore could not provision
against Floci at all.

Wire the write operations to the existing CloudFormationResourceProvisioner —
the same 114-type provisioning that CloudFormation stacks already use — via two
standalone helpers (no enclosing stack; Cloud Control DesiredState carries
resolved values, so a minimal template engine suffices). Cloud Control is async,
so CreateResource/DeleteResource return a terminal ProgressEvent and the request
token resolves via GetResourceRequestStatus. GetResource reads a single resource
by identifier off the existing read side.

Any resource type a CloudFormation stack can create, Cloud Control can now create
too. Integration test covers CreateResource(AWS::EC2::VPC) → listable → token
round-trip.

* fix(cloudcontrol): read back every created type and stop reporting SUCCESS for no-op deletes

CreateResource provisions the whole CloudFormation type set while the read side
lists six types, so GetResource threw ResourceNotFoundException for anything
outside that list — a successful create was unreadable. CreateResource now
records what it provisioned, and GetResource falls back to that record when the
read side does not carry the type.

DeleteResource went through deleteStandalone with empty attributes. Custom
resources, EKS nodegroups and IAM inline policies cannot be deleted from type
and physical id alone, so their delete silently no-opped while DeleteResource
still returned SUCCESS. The create-time attributes are now passed through, and
when they are absent for one of those types the operation reports FAILED with
the reason rather than claiming to have deleted something that is still there.

Also the two lifecycle gaps: the executor gets a @PreDestroy shutdown so its
threads do not outlive the bean, and the request-token map is bounded, evicting
the oldest finished tokens while never dropping one a client is still polling.

* feat(cloudcontrol): read EC2 instances, launch templates and instance profiles

ListResources covered six types. AWS::EC2::Instance, AWS::EC2::LaunchTemplate
and AWS::IAM::InstanceProfile were not among them, so a caller that provisions
one through Cloud Control could not read it back — and a tool whose AWS provider
reaches these types only through its Cloud Control proxy could not see its own
estate at all.

Cloud Control reports a resource's current model rather than an echo of the
desired state, so an instance carries what only the running resource knows: its
private and public addresses, its state, its availability zone, and the subnet
and security groups it actually landed in. A property with no value is omitted
rather than reported as null, as Cloud Control does.

This is also what GetResource needs to resolve these types, since it reads
through the same list.

* fix(cloudcontrol): report InvalidRequestException and require DesiredState

Cloud Control declares InvalidRequestException for a malformed request.
ValidationException and InvalidRequest are not in the service model, so an SDK
could not map either onto a typed exception. Both now report the declared code.

DesiredState is a required member of CreateResourceInput. An absent or blank one
became an empty object and provisioned a resource the caller never described, so
it is now rejected.

* fix(cloudcontrol): GetResourceRequestStatus reports RequestTokenNotFoundException

GetResourceRequestStatus does not declare InvalidRequestException. Its only
declared error is RequestTokenNotFoundException, so an absent RequestToken now
reports that instead of the code the other operations share.
2026-08-12 23:36:37 -05:00
soreavis 45811768b2 fix(stepfunctions): wrap optimized lambda:invoke result in the Invoke envelope (#2165)
A Task using the arn:aws:states:::lambda:invoke integration returned the
Lambda function's return value directly as the task result, with no
ExecutedVersion, Payload or StatusCode key. Real Step Functions nests the
function output inside the Invoke response metadata for this integration,
which is why $.Payload and the JSONata $states.result.Payload are the
documented ways to read a Lambda result.

Against the unwrapped result those references resolved to nothing, the
state still succeeded, and the execution finished SUCCEEDED carrying
silently-empty data — a pipeline accumulating results across stages looked
healthy while producing an empty result.

Both the direct-ARN branch and the optimized branch shared one block in
invokeResource(), so the parsed function output was returned raw for both.
Gate the wrap to the optimized branch: it now returns ExecutedVersion (from
the resolved function's version, matching what LambdaService.invoke already
reports), Payload (the parsed function output) and StatusCode (from the
invoke result). A directly specified function ARN keeps returning only the
function output, which is the documented behavior for that form.

SdkHttpMetadata and SdkResponseMetadata are deliberately not emitted. Their
contents are artifacts of a real HTTPS call to the Lambda service — Date,
X-Amzn-Trace-Id, RequestId, Content-Length — and floci invokes in process,
so any value it put there would be invented.

The .waitForTaskToken flow is unaffected: executeTaskState overwrites the
task result with the callback payload, so the envelope is discarded for
that pattern, as it should be.

Closes #2110
2026-08-13 00:34:57 -04:00
Aniket Shukla 988696b057 fix(firehose): return Kinesis source in stream description (#2025) 2026-08-12 23:26:59 -05:00
themark007 486be8f5b0 feat(kinesis): add local inspection endpoints for UI (#1880)
* feat(kinesis): add local inspection endpoints for UI

* fix(kinesis): limit local record inspection

* fix(kinesis): include shard id in inspected records

* fix(kinesis): address reviewer comments on inspection endpoint

- Comment 1 (fix): sort order for Limit — already using a min-heap
  PriorityQueue (oldestFirst comparator) that evicts the oldest record
  when size > resolvedLimit, so the queue retains the newest N records.
  Records are then re-sorted ascending before return. Limit=2 on
  [oldest, middle, newest] now returns [middle, newest], not
  [oldest, middle]. The previous ascending-sort+limit path was replaced
  in the prior commit; this commit pins the behaviour in the test.

- Comment 2 (minor): unify error shapes on the /records endpoint.
  Moved the Limit <= 0 guard from KinesisService into
  KinesisInspectionController next to the StreamName guard so both
  query-parameter validations use the same plain {"message": ...} shape
  instead of the AwsException {"__type": ...} shape.

- Comment 3 (minor): consistent clamping policy. Removed the throw for
  limit <= 0 from resolveInspectionRecordLimit; both bounds are now
  clamped silently via Math.max/min, matching the behaviour of the
  sibling getRecords / getRecordsForAccount methods. Added Javadoc
  noting the 1000-record hard ceiling with no pagination cursor.

- Test: strengthened recordsEndpointHonorsLimit to assert which two
  records are returned (pk-2 and pk-3, the newest), not just hasSize(2).
  Added recordsEndpointRejectsNonPositiveLimit to cover the controller-
  level Limit=0 validation.
2026-08-13 00:24:37 -04:00
MAN$I VERMA 93b6f5e2b0 fix(s3): preserve literal '+' in object keys and support encoding-type=url in list-objects (#1736)
* fix(s3): preserve literal '+' in object keys and support encoding-type=url in list-objects

Object keys containing a literal '+' (for example Airflow task-log keys such as
run_id=2026-06-26T00:00:00+00:00/f.log) came back from ListObjectsV2 with the '+'
turned into a space, so a list-then-get round trip failed with NoSuchKey. '+' only
means space in form-encoded query strings, never in URL paths, so every
URLDecoder.decode call site on a path or copy source now escapes it first.

Also adds encoding-type=url support to ListObjects, ListObjectsV2 and
ListObjectVersions: Key, Prefix, Delimiter, StartAfter, Marker/NextMarker and
KeyMarker/NextKeyMarker are percent-encoded through a new maybeEncode helper, while
the opaque ContinuationToken/NextContinuationToken stay verbatim per the S3 spec.
Query parameters the JAX-RS layer has already decoded are not decoded a second
time, so keys holding literal percent escapes survive a list round trip.
ListObjectVersions honours delimiter, returning CommonPrefixes and the encoded
Delimiter, and pages the combined version/prefix result set.

Closes #1589

* fix(s3): page ListObjectVersions by entry and honour version-id-marker

max-keys grouped every version of a key into a single slot, so a bucket holding
two versions of log.txt answered ?versions&max-keys=1 with both Version entries
and IsTruncated=false. AWS counts each Version, each DeleteMarker and each
CommonPrefixes group as one entry, so a page can stop part-way through a key.

Version entries are now emitted one slot at a time, merged with common prefixes in
key order. A truncated response carries NextVersionIdMarker beside NextKeyMarker,
ListObjectVersions accepts version-id-marker to resume inside a key, and the echoed
VersionIdMarker stays verbatim because version ids are opaque. A version-id-marker
sent without a key-marker is rejected with InvalidArgument, as on AWS.
2026-08-12 22:18:23 -05:00
David fc74987bd3 fix(ec2): delete key pairs by name through the storage backend (#2187)
DeleteKeyPair with KeyName mutated the detached list returned by
StorageBackend.scan, which is documented not to affect the store — so the
call reported success while leaving the key pair in place. Resolve matching
key pairs to their store key and delete through the backend instead.

The only existing DeleteKeyPair test passed KeyPairId, the branch that
already worked, and asserted just a 200; DeleteKeyPair always returns true,
so the no-op was invisible. Cover the by-name path and assert removal rather
than status.

Closes #2185
2026-08-12 22:50:17 -04:00
Saatvik Arya 4215006fe2 feat(logs): support log group deletion protection (#2256)
* fix(logs): accept log group deletion protection lifecycle

* feat(logs): support log group deletion protection
2026-08-12 22:39:39 -04:00
Alex BannaandAlexander Banna a29464abc7 feat(dynamodb): global-table v2 replicas (UpdateTable ReplicaUpdates + Custom::DynamoDBReplica) (#1811)
* feat(dynamodb): support global table replicas

* fix(dynamodb): validate replica updates before mutation

* fix(dynamodb): align replica compatibility behavior

* chore: rerun CI after download outage

* fix(dynamodb): document replica update semantics

---------

Co-authored-by: Alexander Banna <abanna@users.noreply.github.com>
2026-08-12 20:18:42 -04:00
Alex BannaandAlexander Banna d9e4447aeb feat(cloudformation): resolve dynamic references in RDS credentials (#1809)
* feat(cloudformation): resolve dynamic references in RDS credentials

* test(cloudformation): pin secret resolution failures

---------

Co-authored-by: Alexander Banna <abanna@users.noreply.github.com>
2026-08-12 19:38:51 -04:00
Alex Banna 82f80165fb feat(cloudfront): serve distribution requests from S3 and custom origins (#1820)
* feat(cloudfront): serve distribution requests from S3 and custom origins

* chore: re-run CI

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

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

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

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

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

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

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

* test(dynamodb): retain Quarkus port for cleanup

* fix(cloudfront): isolate mocked storage backends
2026-08-12 19:34:18 -04:00
Priamo Germosen 527615bdf0 fix(iam): seed the full AWS managed policy catalog (#2194)
* fix(iam): seed the full AWS managed policy catalog

AttachRolePolicy and GetPolicy resolved arn:aws:iam::aws:policy/* against a
hand-maintained list of 59 entries, so any policy outside it returned
NoSuchEntity even though AWS publishes it. Real Terraform and CloudFormation
configurations failed for a reason unrelated to the user's setup — attaching
AmazonEC2ReadOnlyAccess or service-role/AmazonElasticMapReduceRole was enough
to break a stack — and the list could only be extended one policy per PR.

The catalog now carries the full published list (1566 entries), loaded from
iam/managed-policies.yaml following the existing ec2/image-catalog.yaml
pattern. AwsManagedPolicies keeps its POLICIES and ManagedPolicyDef surface,
so callers and tests are unaffected.

Unknown ARNs still return NoSuchEntity/404. That matters as much as the
additions: resolving every well-formed ARN would accept typos that real AWS
rejects and would stop CloudFormation rolling a stack back on a bad
attachment. Seeding the real catalog is what makes the check faithful in both
directions rather than trading one wrong answer for another.

The catalog is a union with the previously seeded entries, so a policy AWS has
since retired but which Floci already resolved — AWSLambdaFullAccess — keeps
working. Curated descriptions are preserved.

seedAwsManagedPolicies no longer mirrors the catalog into the account store.
That copy was never read back, since listPolicies filters AWS-managed ARNs out
of the local scan and serves them from the catalog, and writing 1566 entries on
every start cost ~1.4 MB of persisted state and ~3.7s of persistent-mode
startup.

Policy names and paths derive from the public AWS managed policy list via
https://github.com/iann0036/iam-dataset (MIT); only names and paths are used.
Regenerate against a real account with `aws iam list-policies --scope AWS`.

* fix(iam): register the managed-policy catalog for native image builds

AwsManagedPolicies reads iam/managed-policies.yaml through
ClassLoader#getResourceAsStream, which Quarkus's static resource analysis
cannot see. Without an explicit registration the file is absent from the
native image, the stream comes back null and IAM aborts startup — taking the
whole application with it.

Registered in both places the EC2 image catalog already uses:
quarkus.native.resources.includes in application.yml, and the resources
pattern in META-INF/native-image/resource-config.json.

Verified against the native binary rather than the build alone, since a
successful build does not prove the resource is embedded: the native image
starts, ListPolicies(Scope=AWS) reports all 1566 entries, previously missing
policies attach, and a misspelled ARN still returns NoSuchEntity.

Reported by Greptile on #2194.
2026-08-12 17:49:57 -05:00
Dmitriy Polomoshnov cdb2c36dfe fix(s3): isolate object byte storage between accounts (#2241)
* fix(s3): isolate object byte storage between accounts

Object bytes (S3Service.memoryDataStore in memory mode, or files
under dataRoot on disk) were keyed only by "bucketName/key", with no
account component — unlike bucketStore/objectStore, which get
automatic account prefixing from AccountAwareStorageBackend.
bucketStore only enforces name uniqueness within an account, so two
accounts can each own a bucket with the same name (real S3 disallows
this globally, which is a separate, pre-existing behavior difference
not addressed here); when they did, their object bytes collided:

  - PutObject in one account's bucket could overwrite the bytes read
    back by GetObject in another account's identically-named bucket.
  - DeleteBucket in one account deleted the *shared* memoryDataStore
    entries / on-disk directory, corrupting another account's
    same-named bucket (surfaced as a 500 "S3 object data is missing").

Scope the physical key/path by the resolved account ID at the four
byte-storage entry points (writeFile/readFile/deleteFile and their
versioned counterparts) plus deleteBucket's cleanup and
openObjectStream's direct memoryDataStore lookups, which bypassed
those helpers. objectKey()/versionedKey() themselves are unchanged,
since they're also used as objectStore's own storage keys, which are
already correctly account-scoped via AccountAwareStorageBackend.

Added S3AccountIsolationIntegrationTest, reproducing both leaks
end-to-end (fails without this fix). Updated S3ServiceTest /
S3VersioningServiceTest disk-path assertions for the new
<accountId>/ path segment (these unit tests construct S3Service
directly with no RegionResolver, so paths fall back to the default
account "000000000000").

* fix(s3): migrate pre-existing objects from the legacy unscoped disk layout

Before this fix, every disk-mode S3 object lived at
dataRoot/bucketName/key.s3data, with no account segment — object
metadata (objectStore) was already account-scoped and unaffected by
an upgrade, but the physical bytes were not. Resolving only the new
account-scoped path meant an existing Floci installation upgrading
past the account-isolation fix would 404 on every object already on
disk.

resolveObjectPath()/resolveVersionedPath() now transparently relocate
a legacy-layout file to its new, account-scoped location on first
access, mirroring how AccountAwareStorageBackend.get() already
migrates a pre-multi-account storage key on read. Memory-mode storage
needs no equivalent fix: memoryDataStore is never persisted across a
restart, so there's no pre-existing state to migrate. Found by review.

* fix(s3): confine legacy-layout migration to reads, guarded and bounded correctly

The previous commit's naive migrateLegacyFileIfPresent() ran on every
path resolution — including writes and deletes — and MOVED the legacy
file into place. Review (Greptile + @pgermosen) surfaced several real
correctness gaps in that design, all addressed here in the final form:

- A legacy object predates any account concept, so it isn't actually
  known to belong to whichever account happens to touch it first —
  and two different accounts can legitimately own a same-named bucket
  in Floci (bucket-name uniqueness is only enforced per account here).
  Migrating on a write/delete let one account's operation destroy
  another account's still-unmigrated data: the same cross-account
  corruption this whole fix exists to prevent, introduced a different
  way. Legacy fallback is now confined to resolveObjectPathForRead/
  resolveVersionedPathForRead, used only by the read call sites
  (readFile, readVersionedFile, openObjectStream); writeFile/
  deleteFile/writeVersionedFile/deleteVersionedFile use the plain
  scoped-path resolvers with no legacy involvement at all. The legacy
  source is copied, never moved, so every account that reads it
  independently gets its own copy instead of racing to claim it.

- Migration and a write/delete of the same path could still race each
  other: a read could copy legacy bytes in, a concurrent write could
  land its real content, and the read's install step could clobber
  that write with the stale legacy content — a completed PutObject's
  data silently reverting. A per-path ReentrantLock, striped across a
  fixed-size (256) array rather than one lock per Path in an
  unboundedly growing map, now guards copyLegacyFileIfPresent and
  every write/delete of the same resolved path, making "does the
  destination already exist" and "install it" one atomic step with
  respect to every other disk operation on that path. This also made
  an earlier temp-file + ATOMIC_MOVE approach unnecessary — with the
  lock guaranteeing no concurrent writer, a plain, portable Files.copy
  is sufficient, sidestepping both ATOMIC_MOVE's lack of universal
  filesystem support and a temp filename that could exceed filesystem
  component limits.

- Files.copy can still throw partway through (disk full, transient
  I/O error) after already creating the destination with truncated
  content. Left in place, that file would satisfy the exists-check on
  every later attempt, permanently shadowing the still-intact legacy
  source. The catch block now deletes the destination (best-effort,
  logged per AGENTS.md) before rethrowing, still holding the lock.

Tests added: anotherAccountsWriteMustNotDestroyThisAccountsUnmigratedLegacyObject
(the cross-account corruption scenario), concurrentOverwriteNeverLosesToARacingLegacyMigration
(a completed write must never be clobbered by a racing migration),
concurrentFirstReadsOfTheSameLegacyObjectBothSucceed (concurrent reads
of a never-yet-migrated file), and migrationFailureIsNotPermanentAndDoesNotLeaveAFileBehind
(a retry after a transient failure recovers the intact legacy content —
note this last test's specific fault, permission denied on the source,
happens to fail before Files.copy ever creates a destination on this
JVM, so it doesn't reproduce a genuinely partial/truncated write; that
scenario isn't reliably forceable through portable java.nio.file APIs
for a file this small, so the cleanup's correctness there rests on the
delete being unconditional on any IOException, not on this test).

* fix(s3): reserve a namespace for account-scoped storage disjoint from bucket names

A 12-digit bucket name is valid on S3, so dataRoot/<accountId>/
<bucket>/<key>.s3data was not disjoint from the legacy
dataRoot/<bucket>/<key>.s3data layout: a legacy bucket literally named
e.g. "000000000000" with key "orders/report.csv" resolved to the exact
same path as account "000000000000"'s own, unrelated "orders" bucket,
key "report.csv". After upgrading, reading one could silently return
the other's bytes, and a write or DeleteBucket("orders") could
overwrite or delete the legacy object entirely — the same class of
cross-account corruption this whole fix exists to prevent, reintroduced
by the specific path-scoping scheme it chose. Found by review.

Account-scoped storage now lives under a reserved ACCOUNT_STORAGE_ROOT
(".accounts") segment: dataRoot/.accounts/<accountId>/<bucket>/...
A leading "." makes this namespace unreachable by any bucket name real
S3 accepts (bucket names must begin with a letter or number); since
Floci doesn't otherwise validate bucket name format at all,
createBucket() additionally rejects the one bucket name that would
collide with the root of this namespace itself (".accounts" exactly).

Added bucketNamedLikeTheDefaultAccountIdDoesNotCollideWithAccountScopedStorage
(the exact scenario above; confirmed it reproduces the corruption
without this fix by temporarily reverting it) and
bucketNamedLikeTheReservedAccountStorageRootIsRejected. Updated
existing S3ServiceTest/S3VersioningServiceTest/S3LegacyDiskLayoutIntegrationTest
path assertions for the new segment.

* style(s3): tighten comments to be concise and scoped to their code

No behavior change. Several comments introduced across this fix had grown into
paragraph-length essays restating context better left to the commit history;
trimmed them down to the non-obvious 'why' at the point they're placed.
2026-08-12 17:05:55 -04:00
Alex BannaandAlexander Banna bc21367cc4 feat(cloudformation): provision AWS::Events::EventBus as a real custom bus (#1807)
* feat(cloudformation): provision EventBridge event buses

* fix(cloudformation): restore main's provisioner changes lost in the EventBus merge

The previous conflict resolution took this branch's whole
CloudFormationResourceProvisioner, which silently reverted five commits main had
landed on that file since the merge base — including the DynamoDB/Lambda delete
idempotency from #1803 and AWS::EC2::LaunchTemplate from #1973.

Re-resolve from main's file and apply only this branch's EventBus additions on
top: the ownership-tracking provisioner, its validation helpers, and the typed
rethrow in deleteEventBridgeRuleSafe. main's provisionEventBusPolicy and inline
Policy support are kept, with Policy added to EVENT_BUS_SUPPORTED_PROPERTIES so
the inline form is no longer rejected.

* fix(cloudformation): delete EventBus resources created before ownership tracking

deleteEventBusSafe(StackResource) refused to delete whenever the
FlociEventBusCreatedTime attribute was absent, treating "ownership not tracked"
the same as "ownership changed". Stacks provisioned by an earlier Floci build are
restored from cloudformation-stacks.json without that attribute, so the first
DeleteStack after upgrading left them permanently in DELETE_FAILED.

Only refuse when a recorded created-time actually disagrees with the live bus.
A missing attribute falls back to the pre-tracking behaviour of deleting what the
stack recorded it created.

* fix(cloudformation): adopt untracked EventBus on update and record identity before the policy call

Two provision-side defects, both surfaced in review:

UpdateStack broke for stacks provisioned before FlociEventBusCreatedTime existed.
Those resources are restored without the attribute, so the adoption guard's
'existingCreatedTime == null' arm re-threw ResourceAlreadyExists on every update,
including no-ops. Same inverted guard the delete path already uses: only a recorded
time that actually disagrees means the bus was recreated out of band.

The bus also leaked when Policy application failed. r.setPhysicalId ran after
putPermission, and rollbackCreatedResources skips resources whose physicalId is
null, so a malformed policy left a live bus rollback could not find. Identity and
ROLLBACK_OWNED_ATTR are now recorded before the policy call, matching how
provisionIamRole marks a freshly created role. The attribute is cleared on the
adoption path so rollback never deletes a bus this stack did not create.

* chore: re-run CI

Build and Test failed on RuntimeApiServerTest's extension/stop race, a pre-existing
flake unrelated to this change (no CloudFormation test failed). Root-caused separately:
test-timing half in #2141, server-side shutdown-ordering half filed as an issue.

* fix(cloudformation): adopt tagged pre-tracking event buses

* test(dynamodb): retain Quarkus port for cleanup

* chore: rerun CI after download outage

* fix(cloudformation): reject unsafe EventBus policy updates

---------

Co-authored-by: Alexander Banna <abanna@users.noreply.github.com>
2026-08-12 16:38:17 -04:00
Alex BannaandAlexander Banna 33ba5ac59c feat(apigateway): route execute-api hostnames for HTTP APIs (#2054)
* feat(apigateway): route execute-api hostnames for HTTP APIs

* fix(apigateway): disambiguate execute-api routing

* fix(apigateway): make the execute-api host filter idempotent

Host matching alone cannot tell whether a request has already been rewritten,
because the Host header still names the execute-api subdomain afterwards. If any
other filter rewrites first, this one rewrites again and produces
/execute-api/{apiId}/execute-api/{apiId}/... which routes to nothing.

Bail out when the path is already under /execute-api/. This keeps the filter
correct regardless of where it sits in the provider chain.

* fix(apigateway): enforce disableExecuteApiEndpoint on the direct execute-api path

The setting was only checked in ApiGatewayExecuteApiHostFilter, which sees the
host-based route (*.execute-api.localhost.*). A request to the direct
/execute-api/{apiId}/{stageName}/... form reaches dispatchV2 without passing the
filter, so the same disabled HTTP API answered 403 by host and 200 by path.

Move the check into dispatchV2, the single choke point both entry points funnel
through, so they cannot disagree. A missing API is left to findMatchingRoute's 404
rather than reported from here.

* test(dynamodb): retain Quarkus port for cleanup

* fix(apigateway): match disabled HTTP API response

---------

Co-authored-by: Alexander Banna <abanna@users.noreply.github.com>
2026-08-12 16:26:24 -04:00
Alex BannaandAlexander Banna e1f389f61b feat(lambda): support EFS file system configs (#2053)
* feat(lambda): support EFS file system configs

* fix(lambda): prevent stale and shared EFS mounts

* fix(lambda): isolate warm pools by version

* test(dynamodb): retain Quarkus port for cleanup

* fix(lambda): scope warm pool invalidation by environment

---------

Co-authored-by: Alexander Banna <abanna@users.noreply.github.com>
2026-08-12 16:12:39 -04:00
Aniket Shukla ea74b979ae fix(lambda): scope resource-policy statements to the request Qualifier (#2129)
* fix(lambda): scope resource-policy statements to the request Qualifier

AddPermission, GetPolicy and RemovePermission ignored the Qualifier query
parameter. Every statement was stored against the unqualified function ARN, so
an alias-scoped permission could never be read back under its alias: GetPolicy
returned identical payloads with and without ?Qualifier, and the statement's
Resource had no qualifier suffix.

This is what stops Terraform's aws_lambda_permission with qualifier set from
converging — it creates the permission, polls GetPolicy?Qualifier=<alias>
forever, and a later apply then hits ResourceConflictException against a
statement its read could never confirm.

AWS keeps a separate resource policy per qualifier, so the qualifier is part of
a statement's identity. Declare @QueryParam("Qualifier") on the three policy
endpoints and thread it through the service, reusing the existing
resolveWithRegion() helper so a qualifier embedded in the function name
(arn:...:function:fn:ALIAS) is reconciled with the query-string value exactly as
the function-URL endpoints already do.

The scope is derived from the statement's own Resource rather than a new stored
field, so statements persisted before this change stay readable as the
function's unqualified policy. Consequently:

- AddPermission?Qualifier=X writes Resource <functionArn>:X
- GetPolicy?Qualifier=X returns only that qualifier's statements (404 if none)
- RemovePermission?Qualifier=X removes only within that qualifier
- the same StatementId may exist on the function and on each alias, and a
  duplicate within one qualifier still conflicts

Qualifier existence is deliberately not validated — that is a separate behaviour
change, and the endpoints did not validate it before either.

Adds LambdaPermissionQualifierIntegrationTest (12 cases); 7 of them fail against
the unfixed code with the exact symptom from the report (Resource missing the
alias suffix). The existing LambdaPermissionTagLayerIntegrationTest (19) and
LambdaVersionIntegrationTest (6) stay green, covering the unqualified path.

* fix(lambda): clarify missing scoped policy error
2026-08-12 14:07:20 -04:00
Aniket Shukla 2f5bc39680 fix(s3vectors): return cosine distance from queries (#2175)
* fix(s3vectors): return cosine distance from queries

Convert cosine similarity to the AWS-compatible distance value and sort query results nearest-first.

* fix(s3vectors): honor query distance response flag

* test(s3vectors): request query distances explicitly
2026-08-12 13:51:45 -04:00
Aniket Shukla 34c9c6c0f5 fix(cloudformation): honor stack status filters (#2244) 2026-08-12 11:04:10 -04:00
soreavis f1c81977ec fix(cloudwatch): warn on unsupported Logs Insights filter operators (#2170)
parseFilter scans for the leftmost '!=', '==' or '=' outside a quoted
value, so the '=' inside '>=', '<=' and '=~' won. For '>=' and '<=' the
comparison character was absorbed into the field name ("@message >"),
which resolves to null for every row, and passesFilters treats null as
non-matching; for '=~' the value became the literal "~ /ERROR/". Either
way the query came back with no rows and no warning, because as far as
parseFilter was concerned it had found a valid operator.

Stop the scan when a position starts one of those three operators, so
control reaches the "Ignoring unsupported Logs Insights filter" warning
that '<', '>', 'like', 'not like' and 'in' already hit, and the stage is
dropped instead. Quote tracking is untouched, so a '>=' inside a quoted
value is still just part of the value.

The docs table describing how unsupported syntax degrades had the same
two cases inverted: '=~' listed as warn-and-drop when it mis-parsed, and
bare '<' / '>' as silent-zero-rows when they already warned. Folded into
the one row that now matches the code, and the compound and/or mis-parse
this change does not fix got its own row instead of staying implied.

Refs #2042
2026-08-12 10:52:24 -04:00
AgustinBertagna 819bfedc6c feat(appsync): Phase 6 — Query Execution + HTTP Endpoint (#1884)
* feat(appsync): Phase 6 GraphQL HTTP execute endpoint

Expose POST /v1/apis/{apiId}/graphql with AppSync-compatible error
mapping, dual Content-Type, schema rehydrate on boot, and smoke
execution without Phase 8 DataFetchers.

* fix(appsync): initialize graphql IdGenerator at native runtime

Query execution pulls graphql.util.IdGenerator into the native image
reachability graph; its static Random must not be frozen in the heap.

* fix(appsync): cache GraphQL engines and always set x-amzn-errortype

Cache graphql-java GraphQL wrappers per apiId in SchemaRegistry (invalidate
on register/remove/rehydrate), and emit x-amzn-errortype on all data-plane
non-2xx responses for AWS parity with AppSync transport errors.

* fix(appsync): hide unexpected exception details on GraphQL 500

AppSync returns a fixed InternalFailure message for unexpected
errors; keep the real cause in server logs only.

* chore(appsync): drop redundant native-init comment

* fix(appsync): rehydrate schemas across all accounts on boot

Startup has no request context, so keys()/get() only saw the default
account. Mirror recoverOrphans with scanAllAccountsAsMap, persist SDL via
putForAccount in the worker, and drop the shared .atl/ gitignore entry.

* fix(appsync): keep non-404 AwsException on data-plane envelope

Avoid rethrowing AwsException from the GraphQL execute endpoint into
AwsExceptionMapper (__type). Map unexpected lookup failures to
InternalFailure with the AppSync errors[] shape instead.

* docs(appsync): point error formatter @see at $util.error docs

security-authz.html covers authorization types, not errorType/errorInfo.
Cite built-in-util-js.html where $util.error documents those fields.

* refactor(storage): type StorageFactory.create as AccountAwareStorageBackend

The factory always wraps every mode in AccountAwareStorageBackend; declaring
that return type removes unsafe casts at AppSync/CodePipeline/CloudFormation
call sites and updates test overrides/mocks to match production.

* fix(test): stub StorageFactory.create with AccountAware backends

thenAnswer stubs that returned bare InMemoryStorage ClassCast after
create() was typed as AccountAwareStorageBackend; align the remaining
service unit tests with the production return type.
2026-08-12 09:32:03 -04:00
Dmitriy Polomoshnov a803626c17 fix(dynamodb): isolate item storage and locks between accounts (#2240)
* fix(dynamodb): isolate item storage and locks between accounts

DynamoDbService kept item data (itemsByTable), per-item locks
(itemLocks), and TransactWriteItems idempotency tokens in raw maps
keyed only by "region::tableName" / "region::token", with no account
component — unlike tableStore/itemStore, which get automatic account
prefixing from AccountAwareStorageBackend. Two AWS accounts creating a
same-named table in the same region therefore shared one underlying
item map: PutItem in one account's table was visible via GetItem/Scan
in another account's identically-named table.

Scope every itemsByTable/itemLocks access by the resolved account ID.
Also fixes two related gaps surfaced by the same code path:
loadPersistedItems() only reloaded the default account's items after a
restart (AccountAwareStorageBackend.keys() is request-scoped, and
startup has no request), and the TTL sweeper's use of
scanAllAccountsAsMap() collapsed same-named tables from different
accounts into one map entry, silently skipping one account's expired
items. Both are fixed via a new AccountAwareStorageBackend
.scanAllAccountsRaw(), which preserves the account segment instead of
stripping it.

Added DynamoDbAccountIsolationIntegrationTest, reproducing the leak
end-to-end (fails without this fix).

* fix(dynamodb): scope item keys in non-account-aware fallback branches too

loadPersistedItems() and deleteExpiredItems() call scopedItemsKey()
for every access except their fallback branch (used when tableStore/
itemStore isn't an AccountAwareStorageBackend, e.g. some test-only
constructors) — that branch stored/looked up itemsByTable entries
under the bare, unscoped key, inconsistent with every other accessor
in the class. Not reachable in production (StorageFactory always
wraps backends in AccountAwareStorageBackend), but would silently
orphan reloaded items / disable TTL sweeping for any future test using
the plain-backend constructors. Caught in review.

* fix(dynamodb): recover pre-multi-account data in scanAllAccountsRaw

scanAllAccountsRaw() silently dropped any key with no account segment
— data persisted before multi-account support existed. Unlike a
per-key AccountAwareStorageBackend.get() call, which falls back to the
bare unprefixed key and migrates it on read, a bulk startup reload via
scanAllAccountsRaw() has no per-key caller to trigger that path, so
loadPersistedItems() would silently lose such items on upgrade instead
of surfacing them under the default account.

Attribute slash-less keys to defaultAccountId instead of skipping
them, consistent with how get() already treats them. Found by review.

* fix(dynamodb): migrate legacy keys in scanAllAccountsRaw instead of leaving them stale

scanAllAccountsRaw() attributed a bare legacy key to defaultAccountId
but never migrated it in the underlying storage the way get()'s
per-key migrate-on-read does. Concretely: after a restart, a legacy
item loads and gets attributed to defaultAccountId in memory; a
subsequent write to that table then persists under the properly
prefixed key, but the original bare key is left untouched in storage.
On a second restart, both the stale bare key and the fresh prefixed
key map to the same effective key, and whichever the scan's iteration
happens to visit last silently wins — reviving stale data with no
deterministic outcome.

Already-prefixed keys are now loaded first, so a legacy key can never
win a collision against one that's since been written under its proper
prefix; a superseded bare key is deleted outright instead of lingering
to collide again later, and a genuinely-still-legacy key is migrated
(written under its prefix, bare key deleted) rather than left in place.
Found by review (Greptile + @pgermosen).

* style(dynamodb): tighten comments to be concise and scoped to their code

No behavior change. Trimmed comments introduced across this fix down to the
non-obvious 'why' at the point they're placed.
2026-08-12 09:22:17 -04:00
Anders Wasen 19a32ab51d feat(rds-data): adding data-api preparedstatement() support (#1887)
* feat(rds-data): adding data-api preparedstatement() support

* feat(rds-data): addressing greptile comments

* feat(rds-data): addressing PR review comments, fixing timestamp
2026-08-12 07:03:06 -04:00
Usman Zaheer 517094adc1 fix(eventbridge): boolean/numeric pattern values are matched correctly (#1889)
* fix(eventbridge): boolean/numeric pattern values are matched correctly

* fix(eventbridge): fix scientific notation claim. Update styling.

* fix(eventbridge): make null checks tighter.

* fix(eventbridge): add check for if anything-but is a value, not object or array
2026-08-12 06:48:26 -04:00
Olamide Kosile c21337c3b1 feat(iam): add GetAccountSummary support (#1986)
Adds all 34 documented SummaryMap fields: live entity counts (Users,
Groups, Roles, customer-managed Policies, InstanceProfiles,
PolicyVersionsInUse) plus IAM quota values, cross-checked against
AWS's published service quotas and independently verified against
moto's AccountSummary implementation. Resources Floci does not track
(MFA devices, SAML/OIDC providers, server certificates, account
password) report 0 rather than being omitted, so callers indexing
into the full AWS field set don't hit a missing-key error.

Part of #1938.
2026-08-12 00:23:51 -04:00
Alex BannaandAlexander Banna 59cb643d6e feat(stepfunctions): emulate distributed Map ResultWriter (S3 export + manifest) (#1823)
* feat(stepfunctions): export distributed map results to S3

* chore: re-run CI

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

---------

Co-authored-by: Alexander Banna <abanna@users.noreply.github.com>
2026-08-12 00:22:17 -04:00
Kenshin Okinaka cd3588b517 feat(ses): honor ConfigurationSetName on CreateEmailIdentity (v2) (#1812)
* feat(ses): honor ConfigurationSetName on CreateEmailIdentity (v2)

CreateEmailIdentity now reads the optional ConfigurationSetName and sets it as
the identity's default configuration set, surfaced by GetEmailIdentity. Verified
against AWS: a non-existent configuration set fails with NotFoundException before
the identity is created (atomic), matching the deleted-default send behavior.

* fix(ses): treat only an empty ConfigurationSetName as absent on CreateEmailIdentity

A whitespace-only ConfigurationSetName was silently ignored (isBlank),
diverging from the PutEmailIdentityConfigurationSetAttributes path, which
routes such a name through name validation. Switch to isEmpty so both paths
reject a whitespace-only name as invalid input (400), and add coverage for
the empty (no default) and whitespace (400) cases.

* test(ses): clarify that empty-string ConfigurationSetName handling deviates from AWS

The comment on the empty-string CreateEmailIdentity test mentioned that AWS stores ""
verbatim without stating that Floci deliberately diverges (treating "" as "no default"),
which could read as if the assertion matched AWS. Reword to make the deviation and its
rationale explicit.

* docs(ses): correct the non-string ConfigurationSetName comment to match the actual response

The comment claimed AWS returns a 400 with an empty body, but the code throws a
SerializationException that AwsExceptionMapper renders as a JSON error body. Reword the
comment to describe the actual response shape.

* fix(ses): reject a non-string EmailIdentity on CreateEmailIdentity

CreateEmailIdentity read EmailIdentity via asText, which coerces a non-string JSON value
(e.g. 123 -> "123") and would silently create an identity named "123". Reject a non-string
EmailIdentity with a 400 SerializationException, matching the ConfigurationSetName handling
in the same method.

* fix(ses): validate Tags before creating the identity on CreateEmailIdentity

parseTagsArray ran after verifyEmailIdentity/verifyDomainIdentity, so a non-array Tags
value (e.g. "Tags":"oops") returned 400 but left the identity created — a half-created
state. parseTagsArray is pure, so hoist it above the create; the identity is now
persisted only after both the ConfigurationSetName and the Tags shape have been
validated, matching AWS.
2026-08-12 00:12:16 -04:00
Dennis O'Connor b6765b3056 feat(apigateway): API key management — UpdateApiKey, DeleteApiKey, UsagePlan custom-id, generateDistinctId (#1883)
* feat(apigateway): implement UpdateApiKey and DeleteApiKey

Adds the two missing API key lifecycle operations for API Gateway v1:

- UpdateApiKey (PATCH /apikeys/{apiKeyId}): applies replace patch
  operations for /name, /description and /enabled, 404 when absent
- DeleteApiKey (DELETE /apikeys/{apiKeyId}): 202 on success, 404 when
  absent

Also adds a description field to the ApiKey model so it can be set on
create, returned in responses and patched via UpdateApiKey.

Integration tests cover each patch path, the 404 cases and a repeated
delete. Service docs updated to move both operations out of the Not
Implemented list.

* feat(apigateway): persist and return UsagePlan tags

CreateUsagePlan accepted a tags map but discarded it, so tags never
appeared in CreateUsagePlan, GetUsagePlan or GetUsagePlans responses.
Tags are now stored on the UsagePlan model and emitted by the
controller.

A _custom_id_ tag sets a deterministic plan ID, mirroring the existing
createRestApi behaviour. Tag values are coerced through String.valueOf
rather than an unchecked cast so a non-string value in the request body
cannot produce a ClassCastException on later reads.

The tags field defaults to an empty map, so usage plans already
persisted without it deserialize unchanged.

* fix(apigateway): treat an absent generateDistinctId as id == value

CreateApiKey generated a distinct short-token id whenever
generateDistinctId was absent, so the emulator's default disagreed with
AWS. Only an explicit generateDistinctId: true produces an id that
differs from the key value; absent and false both yield id == value.

A blank supplied value now falls back to a generated UUID on the
distinct-id path too, matching the guard the shared-value path already
had.

Integration tests cover all three states — absent, explicit false and
explicit true — and the service docs gain a table for the behaviour.

* refactor(apigateway): route UsagePlan custom IDs through ReservedTags

The usage plan override read the raw _custom_id_ key directly, which
diverged from createRestApi after #2045 made floci:override-id the
reserved key. It now calls ReservedTags.extractOverrideApiId, so the
plan gets the same validation (non-blank, no whitespace, no control
characters, no /?#) and the same precedence when both keys are present.

Persisted tags go through stripApiGatewayReservedTags, so neither
override key survives into CreateUsagePlan, GetUsagePlan or
GetUsagePlans responses.

Tests assert the reserved keys are absent from the returned tags and
cover the deprecated key, the precedence rule and both rejection paths.

* fix(apigateway): stop deleted and disabled API keys authenticating

A UsagePlanKey stores its own copy of the API key value, and the data
plane resolves requestContext.identity.apiKey by matching the x-api-key
header against those copies. Neither revocation path reached them:

- DeleteApiKey removed the key from apiKeyStore but left every usage
  plan association behind, so a deleted key stayed listed by
  GetUsagePlanKeys and kept being recognised on the data plane. It now
  detaches the key from every plan in the region first, matching AWS.
- resolveApiKeyForRequest never read enabled, despite its javadoc
  saying it matched enabled keys, so patching /enabled to false changed
  nothing about request handling. It now requires the key to still exist
  and be enabled, via a new non-throwing findApiKey lookup.

Floci has no apiKeyRequired gate, so a revoked key yields a null
identity.apiKey rather than a 403; the docs now say so explicitly. The
new integration test pins both paths and fails on all three assertions
without these changes.
2026-08-12 00:02:32 -04:00
f17dd1ed81 feat(iam): support OIDC identity providers (#2106)
* feat(iam): support OIDC identity providers

Implement CreateOpenIDConnectProvider, GetOpenIDConnectProvider,
DeleteOpenIDConnectProvider, AddClientIDToOpenIDConnectProvider,
RemoveClientIDFromOpenIDConnectProvider, UpdateOpenIDConnectProviderThumbprint
and the provider tag actions, and back ListOpenIDConnectProviders with real
data instead of a fixed empty list.

A provider is identified by its URL, so the ARN is derived from it and the
scheme is stripped: GetOpenIDConnectProvider reports the URL without https://,
matching AWS. Creating the same URL twice returns EntityAlreadyExists.

Thumbprints are stored and echoed back but never validated against the remote
endpoint, since nothing here performs the TLS handshake they describe.

Closes #2102

* test(iam): cover OIDC provider persistence and cap the provider URL

Add IamServicePersistenceTest: IAM state is persisted through StorageFactory,
so a restart must preserve providers along with their client IDs, thumbprints,
tags and creation time. The model carries an Instant and two lists, so a broken
serialization round trip would surface here first.

Also enforce the documented 255-character limit on the provider URL, which was
otherwise unchecked and would have produced an oversized ARN.

* fix(iam): match verified AWS behaviour for OIDC providers

Checked the emulated surface against a live AWS account and corrected where it
diverged:

AddClientIDToOpenIDConnectProvider and RemoveClientIDFromOpenIDConnectProvider
are idempotent on AWS. Adding a client ID that is already present, and removing
one that was never added, both succeed and change nothing; they previously
raised EntityAlreadyExists and NoSuchEntity.

Exceeding the thumbprint limit reports InvalidInput, not LimitExceeded. The
client ID quota and duplicate-provider messages now use the AWS wording, and
DeleteOpenIDConnectProvider reports its own not-found phrasing.

Confirmed unchanged: the ARN is derived from the scheme-less URL, Get echoes the
URL without its scheme, the URL is capped at 255 characters, the client ID quota
is 100 with LimitExceeded, and URLs are not normalized, so a trailing slash or a
case difference yields a separate provider.

* fix(iam): reject missing required parameters on OIDC mutators

A null ClientID read as "not in the client ID list", so
RemoveClientIDFromOpenIDConnectProvider reported a no-op success for a request
that never named one. DeleteOpenIDConnectProvider had lost its ARN check when
it stopped routing through getOpenIDConnectProvider to report the not-found
wording AWS uses for that action, so a request with no ARN came back as
NoSuchEntity rather than a required-parameter error.

Route every OIDC mutator through shared ARN and client ID checks so a malformed
request fails as ValidationError before any lookup.

* fix(iam): unbreak the reflective test fixture for the new constructor arity

IamServiceTestHelper resolves the package-private IamService constructor
reflectively against a hardcoded parameter list, so the extra storage backend
broke it at run time with nothing failing at compile time. Every test using the
fixture errored, and one of them blocks on a socket read rather than failing,
which exhausted the CI job before it could report. Extend both lookups and both
newInstance calls to the new arity.

* fix(iam): reject empty tag collections on OIDC providers

TagOpenIDConnectProvider with no Tags and UntagOpenIDConnectProvider with no
TagKeys performed a no-op mutation and returned 200. AWS rejects both, as
InvalidInput rather than ValidationError, with distinct messages for the map and
the key list; checked against a live account. Validate the ARN on the tag path
too, so a missing one fails before the lookup like the other mutators.

---------

Co-authored-by: Michal Schreiber <michal.p.schreiber@gmail.com>
Co-authored-by: Michal Schreiber <michal.schreiber@benefitsystems.pl>
2026-08-11 23:07:37 -04:00
Mihai BlidaruandMihai Blidaru a79e04e4ec fix(firehose): build S3 object keys with AWS prefix expressions and name suffix (#1858)
* fix(firehose): build S3 object keys with AWS prefix expressions and name suffix

Delivered objects now follow the AWS key format
<evaluated prefix><stream>-<version>-<yyyy-MM-dd-HH-mm-ss>-<uuid> observed on
real AWS: default prefix yyyy/MM/dd/HH/ when no Prefix is set, literal
concatenation of the time prefix for expression-free prefixes,
!{timestamp:<pattern>} and !{firehose:random-string} evaluation, no .json
extension, and CustomTimeZone support. The non-AWS {year}/{month}/{day}/{hour}
placeholders are gone.

See floci-io/floci#1857 for the behavior captured against a real AWS account.

* refactor(firehose): cache the default time-prefix DateTimeFormatter

---------

Co-authored-by: Mihai Blidaru <mihai.blidaru@lynxfctech.com>
2026-08-11 21:40:24 -04:00
Tony Nguyen ea1231b8b4 fix(rds): restore Terraform RDS and RabbitMQ compatibility (#1951)
* fix(rds): support dbi resource id filter

* fix(mq): omit RabbitMQ users from broker response
2026-08-11 12:26:51 -04:00
Olamide Kosile a5daab6fb7 fix(lambda): reconcile code volumes against real Docker state and clean up superseded ones (#2208)
* fix(lambda): reconcile code volumes against real Docker state and clean up superseded ones

Fixes #2164

Three problems in ContainerLauncher's per-function-version code volume
management, all stemming from the same root cause: the "populated"
bookkeeping was purely in-memory, never checked against or reconciled
with Docker's actual state.

- Stale volumes were never cleaned up on redeploy, only ever reclaimed
  by a user manually running docker volume prune. Now tracks each
  function's current volume and queues the superseded one for cleanup.
- The in-memory "already populated" flag was trusted without ever
  re-checking Docker, so a volume removed out of band (manual docker
  volume rm, or an out-of-band prune) would silently mount an empty
  /var/task into the next container. ensureCodeVolume now also checks
  lifecycleManager.volumeExists() before trusting the flag.
- Both of the above are really the same problem: no reconciliation
  against real Docker state. Fixed together by the same change.

Cleanup is deferred rather than immediate: Docker auto-creates an
empty named volume for a container mount that doesn't reference an
existing one rather than failing, so a launch that resolved the old
volume name just before a redeploy, but hasn't created its container
yet, could be handed an empty /var/task by an immediate delete. A
60-second grace period, swept by a scheduled background task, crosses
that window safely; removeVolume() also no-ops if the volume is still
genuinely in use by then.

* fix(lambda): rescue rolled-back code volumes and retry failed cleanup

Addresses two review findings on the volume reconciliation fix:

- The fast-path early return in ensureCodeVolume skipped the
  bookkeeping update entirely, so rolling back to a previous code
  version (v1 -> v2 -> v1) resolved v1's already-populated volume
  without pulling it back out of the pending-cleanup queue or marking
  it current again. The next sweep would delete the volume the
  function was actively using again. The bookkeeping reconciliation
  now always runs, whether or not the volume needed repopulating.
- cleanupSupersededVolumes discarded a pending-cleanup entry
  unconditionally before attempting deletion, so a volume that
  Docker refused to remove (still in use by a slow-draining
  container that outlived the grace period) was silently dropped
  with no later sweep ever retrying it, permanently orphaning it.
  Now re-checks volumeExists after the delete attempt and re-queues
  with a fresh timestamp if the volume is still there.

* fix(lambda): close the cleanup-vs-rollback race on code volumes

Addresses a review finding: ensureCodeVolume's bookkeeping
reconciliation and cleanupSupersededVolumes' claim-and-delete both
touched volumesPendingCleanup with no mutual exclusion between them.
If cleanup atomically claimed a superseded volume's entry a moment
before a concurrent rollback resolved that same volume, the rollback
would mark it current and hand it to a new container while cleanup
proceeded to delete the real Docker volume out from under that launch
- the exact empty /var/task failure mode the grace period exists to
prevent, reached through the rescue path instead.

Both methods now synchronize on the same per-volume-name lock
(codeVolumeLocks) for their full resolve-or-claim-and-reconcile
section, not just the expensive populate step. Whichever side wins the
race, the other reliably observes the result under the lock rather
than acting on stale state.

Added a deterministic concurrency test using latches to force cleanup
to block mid-deletion while still holding the lock, and assert a
concurrent rollback blocks too rather than racing past it. Confirmed
it fails against the previous commit (rollback completes immediately,
racing past cleanup) and passes with this fix.

* fix(lambda): stop pruning code-volume locks, closing a lock-identity race

Addresses a review finding on the mutual-exclusion fix: pruning a
volume's entry from codeVolumeLocks while a waiter elsewhere still
held a reference to the removed entry's lock object let a third
caller's computeIfAbsent create a replacement lock object for the
same volume name. The original waiter (once granted the old lock)
and that third caller (holding the new one) could then run their
supposedly mutually-exclusive sections concurrently, reintroducing
the exact cleanup-vs-rescue race the previous commit closed.

The map is now never pruned. Each entry is a single Object keyed by
volume name, bounded by the number of distinct function+code-version
combinations ever launched, and negligible next to the disk space the
rest of this fix reclaims - not worth the correctness risk of trying
to bound it.

Added a direct test verifying the actual invariant this depends on:
a volume's lock entry survives a full populate-then-cleanup-delete
cycle unchanged. The real interleaving that triggers this race needs
precise JVM thread-scheduling control that isn't reliably forceable
in a test, so this proves the fix by construction instead - confirmed
it fails (both by compile error, since the accessor is new, and by a
genuine runtime assertion failure when the removal is surgically
reintroduced) without the fix and passes with it.

* fix(lambda): give removeVolume a definitive success signal for cleanup retry

Addresses a review finding: cleanupSupersededVolumes decided whether a
deletion actually succeeded by making a second, separate call to
volumeExists() afterward. That call's own exception handling treats a
transient Docker API failure (a network blip, the daemon momentarily
busy) the same as "confirmed does not exist", so a transient failure
during that specific verification call, following an in-use no-op from
removeVolume, would make cleanup wrongly conclude the volume was gone
and drop it from the retry queue for good - the same permanent-loss
bug fixed two commits ago, reachable through a different trigger.

ContainerLifecycleManager.removeVolume now returns whether the volume
is confirmed gone (removed, or already absent) rather than void.
cleanupSupersededVolumes uses that return value directly instead of a
second ambiguous check, so the failure mode described above can no
longer happen: any removal attempt that isn't positively confirmed
successful, for any reason, correctly retries on the next sweep.

The other three real callers (EksClusterManager, MwaaEnvironmentManager,
ContainerStorageHelper) all treat the call as fire-and-forget and don't
need any changes; a void-to-boolean change doesn't break callers that
ignore the return value. Verified with the full lambda and
core.common.docker packages (550 tests, only the same pre-existing
unrelated failures) plus the eks/mwaa/rds packages that call the other
real usages of this method (one pre-existing, unrelated failure in
RdsContainerManagerTest, confirmed identical against an unmodified
upstream/main baseline in a throwaway worktree).

* fix(lambda): protect in-flight code volumes from premature cleanup

A launch that resolves its code volume name (ensureCodeVolume returns
and releases the volume's lock) but hasn't yet called
lifecycleManager.create() has no real Docker container-to-volume
reference for removeVolume()'s own in-use check to protect. The fixed
grace period isn't a safe upper bound on that gap either: create()
itself has no proven bound on its duration (this file's own history
notes it observed taking ~80s under daemon load, longer than the
default 60s grace period). If a redeploy supersedes that volume and
the grace period elapses while the original launch is still stuck
before create(), a sweep can delete the volume out from under it,
handing the container an empty /var/task once create() finally runs
(Docker auto-creates an empty volume for a mount referencing a name
that no longer exists rather than failing).

Adds true in-flight reference counting instead of relying on elapsed
time: ensureCodeVolume increments a per-volume counter before
returning (still under the volume's lock, so a concurrent sweep that
acquires the same lock next is guaranteed to observe it), and the
caller releases it in launch() once create() succeeds - or in the
existing catch-all failure handler if it never gets that far.
cleanupSupersededVolumes re-queues rather than deletes any volume
whose count is still nonzero, regardless of how long it's been queued.

Verified: new test forces a second launch of an already-populated
volume to block right before create() while a redeploy supersedes it
and the grace period is made to elapse instantly; cleanup must skip
it while the count is nonzero and only remove it once the delayed
launch completes and releases its reference. Confirmed the test fails
(cleanup deletes the volume mid-flight) with the guard temporarily
disabled, and passes with it restored. Full lambda.launcher and
core.common.docker package regression (174 tests) is green.

* fix(lambda): serialize the current-volume transition per function

pgermosen's review on this PR pointed out that functionCurrentVolume
and volumesPendingCleanup are reconciled under the per-volume lock
only. Two code versions of the same function resolve to two different
volume names, so they acquire two different codeVolumeLocks entries
and can run that reconciliation concurrently - which is fine for the
populate work each guards, but not for this transition.

Without a shared lock, a rapid back-to-back redeploy (v2 then v3) can
have the two functionCurrentVolume.put() calls land out of order:
whichever one happens to execute last wins as "current" regardless of
which redeploy was actually latest, and the volume it displaces gets
queued for cleanup using a "previous" value each thread captured
locally right before its own put() - so if v2's full transition runs
after v3's, v3 (briefly and correctly current) ends up queued for
deletion while stale v2 is left recorded as current.

Adds a per-function lock (functionVolumeTransitionLocks, keyed by
function name rather than volume name) around just this transition.
It doesn't and can't guarantee which redeploy "wins" when two race
genuinely concurrently - that would need ordering information this
method isn't given - but it does guarantee the bookkeeping itself
stays self-consistent: whichever volume ends up current is never also
left in the pending-cleanup set, and whatever it displaced is queued
exactly once.

Verified: the transition's three statements are plain map operations
with no interception point inside them, so forcing the exact bad
interleaving isn't reliably doable in a test. Instead added a test
proving the fix's actual mechanism - a concurrent launch for a second
code version of the same function blocks on the same per-function
lock object while another launch holds it - the same style already
used for the per-volume lock in
cleanupAndAConcurrentRollback_areMutuallyExclusiveForTheSameVolume.
Confirmed the test fails when the lock is swapped for an unshared one
and passes with the real lock restored. Full lambda.launcher and
core.common.docker package regression (175 tests) is green.
2026-08-11 06:56:00 -04:00
Aniket Shukla 6344852540 fix(lambda): reassemble container log lines split across Docker frames (#1953)
* fix(lambda): reassemble Docker log frames into complete lines

Buffer stdout and stderr independently, emit complete UTF-8 lines, and finalize trailing tails only after Docker has stopped or its reader reaches a terminal state.

* fix(codebuild): retain buildspec overrides when retrying builds

Keep request-scoped buildspec overrides alongside transient build state so RetryBuild executes the same source-less build definition as the original request.

* fix(ecs): finalize logs after force-removing tasks

Keep Docker force removal available after stop failures and release task log handles once removal has terminated their transports.

* fix(ecs): retain logs for containers that survive teardown

Track ECS log handles by Docker ID so teardown finalizes only containers that have stopped, disappeared, or been force-removed.

* fix(ecs): retry unresolved log stream teardown
2026-08-11 06:50:07 -04:00
lex00 40e8aad55a feat(lambdamicrovms): AWS Lambda MicroVMs service module and its CloudFormation types (#2079)
* feat(lambdamicrovms): AWS Lambda MicroVMs service module

Adds the Lambda MicroVMs control plane, a service AWS took GA on 2026-06-22:
MicroVM images with a version and build lifecycle, the managed base-image
catalog, MicroVM CRUD, and VPC egress network connectors.

Two service models rather than one. Lambda Microvms (apiVersion 2025-09-09)
carries images and MicroVMs under /2025-09-09; Lambda Core (2026-04-30)
carries network connectors under /2026-04-04. Both sign as lambda, so their
requests arrive under the existing lambda claim in ResolvedServiceCatalog and
route by path. Neither prefix collides with anything LambdaController serves,
and both are enabled by the lambda service rather than adding a toggle.
Tagging rides the classic /2017-03-31/tags/ routes, so LambdaTagController
learns the MicroVM ARN forms.

Resources are stored per account and region. Floci resolves a per-request
account in AccountContextFilter and these ARNs carry it, so region-only
storage would let two accounts sharing a region read and mutate each other's
images, MicroVMs and connectors.

Wire shapes come from the vendored service models and, where the models are
silent or disagree with the service, from responses recorded against live
AWS. Several members the models mark optional are enforced in practice — a
connector needs ClientToken, OperatorRole, NetworkProtocol and
AssociatedComputeResourceTypes despite all four being optional in Smithy — and
several resources are returned in a different projection per operation: an
image in four shapes, a connector in four, with only the list summaries
carrying Type.

Builds converge instantly rather than on a timer, the usual emulator trade.
Where that would otherwise produce an inconsistent body it is handled
explicitly: a create or update reports the transitional state and does not
name the version it is minting as active, because a client reading otherwise
would launch a MicroVM off a version that does not exist yet.

Auth tokens, the per-VM endpoint, and the idle and suspend timers are
deliberately out of scope here; they belong to a full-fidelity MicroVMs
emulator rather than to CloudFormation provisioning.

Verified against a suite of responses recorded from live AWS
(https://github.com/INTENTIUS/m80): 26 checks over the image, MicroVM and
connector lifecycles, 0 failures.

* feat(cloudformation): provision AWS::Lambda::MicrovmImage and AWS::Lambda::NetworkConnector

Registers a CfnResourceProvisioner for the two MicroVM CloudFormation types
against the LambdaMicrovmsService added alongside, so a template declaring
either provisions and deletes rather than being skipped.

Uses the CloudFormationResourceRegistry interface rather than the switch in
CloudFormationResourceProvisioner, following SqsCfnProvisioner.

* test(lambdamicrovms): AWS CLI compatibility coverage for images, MicroVMs and connectors

* fix(lambdamicrovms): wire service state through StorageFactory

Images, MicroVMs and connectors were held in plain in-memory maps, so in
persistent mode a restarted Floci lost them while the CloudFormation stacks that
created them survived. Those stacks then referenced resources that no longer
existed and DeleteStack failed on the 404.

The three stores are now StorageBackedMap over StorageFactory backends, keyed
region/id. MicroVMs are delivered as part of the lambda service, so they share
its storage key and therefore its configured mode and flush interval rather than
declaring their own. The account half of the key is dropped from the service and
left to the backend, which prefixes and strips the same account the
RegionResolver returns, so region and account isolation are unchanged.

StorageBackedMap only marks the backend dirty on put and remove, so every path
that mutated a stored object in place now writes it back: image update, version
status, version delete, rebuild, MicroVM settle and terminate, connector settle
and update, and both tag paths.

* style(core): import the lambda microvms controllers in the service catalog

* fix(lambdamicrovms): register the persisted types for reflection

Moving images, microvms and connectors into StorageBackedMap made their model
classes persisted types, and PersistedModelReflectionTest fails on any that lack
@RegisterForReflection because native-image persistence cannot rebuild them on
restart.
2026-08-10 23:10:48 -05:00
Maciej 0cfffbea00 fix(kms): reject mismatched keys in decryption requests (#1893)
* fix(kms): reject mismatched keys in decryption requests

* fix(kms): reject mismatched keys in reencryption requests

* fix(kms): verify if key is usable for cryptographic operations
2026-08-10 23:49:31 -04:00
Krishnan MahadevanandKrishnan Mahadevan 15d6ce8429 fix(s3): DeleteObjects honours empty key list (#2201)
Fixes : #2198

Co-authored-by: Krishnan Mahadevan <kmahadevan-bidgely@users.noreply.github.com>
2026-08-10 23:11:59 -04:00
Jan Waś f417164d42 fix(rds): advertise reachable endpoints (#2074)
RDS endpoints currently expose the proxy's container port even when
Docker publishes it on a random host port. That works when the host can
route to the container network, but fails with VM-backed Docker
runtimes.

Resolve the current container's published port when an external
endpoint host is configured while preserving the internal proxy port
used by the listener.
2026-08-10 22:03:52 -04:00
Langning Zhang 28e9f6ed63 fix(apigatewayv2): encode binary Lambda request bodies (#2203)
* test(apigatewayv2): cover binary Lambda request payload

Change-Id: Iae344954b576b49826164e0f5e68964f86198cd4

* fix(apigatewayv2): encode binary Lambda request bodies

Change-Id: I5e32fe304c932878afdbf5be0c3c773595364ff0

* test(apigatewayv2): cover request body encoding matrix

Change-Id: Id16e0cc81f6806afa50d8db8c6ac1cb7897af6f6

* fix(apigatewayv2): accept UTF-8 text media parameters

Change-Id: Ibf82062b9345ebd80d722b497a15e60d62dce86d

* test(apigatewayv2): make binary payload cleanup best effort

Change-Id: Ib62dc80c73eb1836007b4492ccfda965da03f6ac

* revert(apigatewayv2): keep measured AWS media matrix

Change-Id: Ibbf8d8bca8d9967bf84628773cc08a991ffea6a1
2026-08-10 19:44:07 -05:00
Kenshin Okinaka bd01c1a70b feat(ses): implement SendCustomVerificationEmail for v1 and v2 (#2191)
* feat(ses): implement SendCustomVerificationEmail for v1 and v2

Add the SendCustomVerificationEmail action on both the v1 Query API and the v2 REST
JSON API (POST /v2/email/outbound-custom-verification-emails). The service renders the
stored custom-verification-email template into the inspection mailbox and the SMTP
relay, returns a MessageId, and registers the recipient as a pending-verification
identity, matching AWS. A missing template is the v1-native
CustomVerificationEmailTemplateDoesNotExist (remapped to NotFoundException on v2), with
the v1 send message ("Template <name> does not exist") verified against AWS.

* test(ses): log custom-verification compat cleanup failures instead of swallowing them

The @AfterAll cleanup deleted templates and identities in best-effort try/catch
blocks that swallowed every exception, so a real deletion failure would leave
state behind with no diagnostic. Log the affected template/identity and the
exception message, per AGENTS.md's rule against silently discarding exceptions.
2026-08-10 20:34:09 -04:00
Michal SchreiberandMichal Schreiber ac4b865a34 feat(ec2): support managed prefix lists (#2105)
* feat(ec2): support managed prefix lists

Implement CreateManagedPrefixList, DescribeManagedPrefixLists,
GetManagedPrefixListEntries, ModifyManagedPrefixList and
DeleteManagedPrefixList.

Entries are versioned: a list starts at version 1 and every modification that
changes entries stores a new version, so GetManagedPrefixListEntries can serve
an earlier TargetVersion. Renaming or raising MaxEntries does not create a
version, CurrentVersion makes a modification conditional, and removals apply
before additions so one call can replace an entry's description.

The AWS-managed gateway-endpoint lists are now built once and served by both
DescribeManagedPrefixLists and the existing DescribePrefixLists, so the two
surfaces cannot report different CIDRs for the same list. They are read-only.

Closes #2100

* fix(ec2): validate prefix list input and keep tag copies in sync

Three defects in the managed prefix list surface:

ModifyManagedPrefixList only checked the resulting entry count against
MaxEntries, so a zero or negative MaxEntries on an empty list passed the check
and persisted an impossible capacity.

CreateTags and DeleteTags update the generic tag store and then mirror the
result onto the resource, but updateResourceTags had no arm for prefix lists,
leaving the copy on the model stale for describe responses and tag filters.

MaxEntries and TargetVersion were converted with Integer/Long.valueOf, so
malformed input escaped as an unchecked NumberFormatException and became a 500
rather than a structured EC2 client error.

* fix(ec2): reject a missing PrefixListId and infer the prefix-list tag type

A null PrefixListId reached List.of() inside describeManagedPrefixLists and
threw NullPointerException, so DeleteManagedPrefixList,
GetManagedPrefixListEntries and ModifyManagedPrefixList answered a request that
never named a list with a 500 rather than a client error. Guard the lookup and
raise MissingParameter.

inferResourceType had no pl- arm, so tags on a prefix list were stored but
reported as resourceType "unknown" and were invisible to a DescribeTags filter
on resource-type. The existing test only covered describe and tag: filters,
which is why this went unnoticed.

Also cover the accepting branch of the address-family check, which until now was
only reached by the rejecting case.

* fix(ec2): treat a blank numeric parameter as malformed rather than absent

intOrNull and longOrNull returned null for a present but blank value, which the
callers read as "parameter not supplied". For CurrentVersion that silently
downgraded a conditional ModifyManagedPrefixList to an unconditional one, so a
request that asked to be gated on a version was applied anyway. Only an absent
parameter is null now; a blank one reaches the parse and surfaces as
InvalidParameterValue.

* fix(ec2): report PrefixListVersionMismatch for a stale CurrentVersion

A conditional ModifyManagedPrefixList that loses the version check returns
PrefixListVersionMismatch on AWS, not IncorrectState; verified against a live
account, which also supplies the message. The Terraform provider keys its retry
handling on that code, so the previous one would have left a caller unable to
recognise a losing conditional update.

---------

Co-authored-by: Michal Schreiber <michal.p.schreiber@gmail.com>
2026-08-10 19:03:26 -05:00
Feyikemi Ogunsanya 3ce5041c71 fix(cognito): reject invalid refresh tokens in InitiateAuth REFRESH_TOKEN_AUTH (#2132)
* fix(cognito): reject invalid refresh tokens in InitiateAuth REFRESH_TOKEN_AUTH

InitiateAuth with AuthFlow=REFRESH_TOKEN_AUTH silently fell back to
minting fresh tokens for a fake "unknown" user whenever the supplied
REFRESH_TOKEN failed to parse or didn't resolve to a real user,
instead of failing like GetTokensFromRefreshToken already does.

Fixes #2113

* test(cognito): add regression tests for invalid refresh token rejection

Cover InitiateAuth REFRESH_TOKEN_AUTH with a garbage token and with a
well-formed token encoding a nonexistent user; both must fail with
NotAuthorizedException rather than returning an AuthenticationResult.

* test(cognito): add regression test for non-numeric refresh token issued-at

Covers a well-formed refresh token whose issued-at field is not a
number; must fail with 400 NotAuthorizedException rather than the
500 NumberFormatException that surfaced before the parse was guarded.

* fix(ec2): make network interface pagination tests order-independent

describeNetworkInterfacesWithMaxResultsNoNextToken and
describeNetworkInterfacesMultipagePagination assumed a fixed/low ENI
count, but other tests in this class are not isolated and can leave
ENIs behind depending on JUnit's tie-breaking order among tests
sharing @Order(92). Use MaxResults=1000 for the single-page case and
measure the actual ENI baseline before asserting page counts for the
multipage case.
2026-08-10 19:01:47 -05:00
Tim Gibson 50fe67dde6 feat(eventbridge): deliver events to event-bus targets (#1814)
* feat(eventbridge): deliver events to event-bus targets

* fix(eventbridge): skip null resources when republishing to event-bus targets

* fix(eventbridge): validate Detail and resolve account for bus targets

readTree accepts any well-formed JSON value, so an input override producing
"hello" or [1,2] passed the guard and reached the target bus as a scalar
detail, with putEvents reporting success — a silent malformation rather than
the intended warn-and-drop. The pass-through arm had the same hole. Both arms
now share one isObject() check.

Bus targets also went through the two-arg putEvents overload, which passes a
null accountId, so a cross-account bus ARN resolved in the caller's account and
surfaced only as a warning. Thread the ARN's account through, as SQS targets
already do via the queue URL. Same-account and account-less ARNs still forward
null: only that path carries the legacy-key fallback in
AccountAwareStorageBackend.get().

* docs(eventbridge): document event-bus target behavior and limits

* fix(eventbridge): cap bus-to-bus forwarding at one hop, matching AWS
2026-08-10 17:46:13 -04:00
Aniket Shukla f34e0b5655 fix(apigateway): create the stage when CreateDeployment carries a stageName (#2130)
CreateDeployment ignored the stageName parameter: the deployment was created but no stage was, so GetStages stayed empty and invoking the deployed API returned {"message":"Stage not found"}. Calling CreateStage explicitly afterwards was the only way to make the API reachable.

CreateDeployment creates the named stage pointing at the new deployment. When the stage already exists, repoint it while preserving its other settings so repeated Terraform applies remain usable. The API does not document this collision behavior. Stage variables from the request are applied either way, and omitting stageName still creates no stage.

Adds ApiGatewayDeploymentStageNameIntegrationTest (7 cases) following the reproduction from the report: the stage appears in GetStages, the deployed route answers 200 instead of "Stage not found", a redeploy moves the same single stage to the new deployment id, and no-stageName is unchanged.
2026-08-10 13:41:43 -04:00