Commit Graph
1205 Commits
Author SHA1 Message Date
Ahmed khaled 91b6a40bc7 fix(elasticache): clean up container by id on readiness-timeout rollback (#2090)
* fix(elasticache): clean up container by id on readiness-timeout rollback

start() registers the container in activeContainers before its
waitForBackendReady() probe, and that probe throws on timeout. When it
does, start() propagates without ever returning a handle, so the
service's rollback saw handle == null, skipped the container stop, and
left it running (only reaped at shutdown). A readiness timeout is the
most likely provisioning failure, not an edge case.

Add an idempotent stopByGroupId(groupId) that looks the container up
in activeContainers, falling back to the deterministic container name
for one that failed before registration. Call it unconditionally from
rollbackReplicationGroup instead of gating containerManager.stop(handle)
on handle != null.

Mirrors the same fix already merged for Neptune in #1742.

* fix(elasticache): stop by handle when known, only fall back to stopByGroupId

Greptile flagged (PR #2090 review): rollbackReplicationGroup called
containerManager.stopByGroupId(groupId) unconditionally, even when the
handle from this request's own start() was already known. If a
concurrent CreateReplicationGroup for the same group id raced ahead
and overwrote the activeContainers entry before this rollback ran,
stopByGroupId's fresh lookup would fetch and stop the other request's
container instead of this one's.

Restore the precise containerManager.stop(handle) path whenever handle
is non-null (the common case — every failure after the container
itself started successfully) and only use stopByGroupId as the
by-id fallback for the one case that actually needs it: a readiness
timeout, where start() never returns a handle at all.

* fix(elasticache): guard against concurrent creates for the same group id

Reviewer follow-up on PR #2090: the handle-less rollback path (a
readiness timeout, where start() never returns a handle) still cleans
up by looking up whatever containerManager currently has registered
for the group id. If a second CreateReplicationGroup for that same id
raced in and started its own container before the first request's
rollback ran, that lookup would fetch and stop the second request's
container instead of the first's — the existing "already exists"
check only guards against a *persisted* group, not one still being
provisioned, so nothing previously prevented two concurrent creates
for the same not-yet-existing id from both proceeding.

Add a provisioningGroupIds guard: claim the id before provisioning
starts and hold it until createReplicationGroup returns or throws
(rollback included), rejecting a concurrent second create for the same
id with the same ReplicationGroupAlreadyExistsFault used for an
already-persisted group. This closes the race at its root rather than
narrowing it — a second request for the same id can never reach
containerManager.start() while the first is still in flight, so the
by-id rollback fallback can never observe a container it doesn't own.

Added a concurrency test using real threads + latches to prove a
second create for an in-flight id is rejected immediately rather than
racing ahead.

* refactor(elasticache): trim comments to one-liners
2026-08-09 15:53:48 -04:00
Ahmed khaled 11d527547a fix(memorydb): clean up container by id on readiness-timeout rollback (#2092)
* fix(memorydb): clean up container by id on readiness-timeout rollback

start() registers the container in activeContainers before its
waitForBackendReady() probe, and that probe throws on timeout. When it
does, start() propagates without ever returning a handle, so the
service's rollback saw handle == null, skipped the container stop, and
left it running (only reaped at shutdown). A readiness timeout is the
most likely provisioning failure, not an edge case.

Add an idempotent stopByClusterName(name) that looks the container up
in activeContainers, falling back to the deterministic container name
for one that failed before registration. rollbackBackend now calls it
unconditionally instead of gating containerManager.stop(handle) on
handle != null.

Fixing this also required splitting the proxy-stop and container-stop
steps into isolated try/catch blocks (previously shared one try, so a
throwing stopProxy skipped the container cleanup entirely) and guarding
the proxy stop with the same handle != null precondition the container
stop already had. Without that isolation, the by-name cleanup could
still be skipped in the exact scenario it exists to handle.

Mirrors the same fix already merged for Neptune in #1742.

* fix(memorydb): stop by handle when known, only fall back to stopByClusterName

Same issue flagged by greptile on the sibling ElastiCache PR (#2090):
rollbackBackend called containerManager.stopByClusterName(name)
unconditionally, even when the handle from this request's own start()
was already known. If a concurrent createCluster for the same name
raced ahead and overwrote the activeContainers entry before this
rollback ran, stopByClusterName's fresh lookup would fetch and stop
the other request's container instead of this one's.

Restore the precise containerManager.stop(handle) path whenever handle
is non-null (the common case — every failure after the container
itself started successfully) and only use stopByClusterName as the
by-name fallback for the one case that actually needs it: a readiness
timeout, where start() never returns a handle at all.

* fix(memorydb): guard against concurrent creates for the same cluster name

Same fix as PR #2090 for ElastiCache: the handle-less rollback path
looks up whatever containerManager currently has registered for the
name, which a concurrent createCluster for the same name could
overwrite first. Claim the name for the whole provisioning attempt so
a second concurrent create is rejected immediately instead.
2026-08-09 15:43:34 -04:00
Jérémie van der Sande 2594705f9c feat(elbv2): honor preserve_host_header parameter (#2109) 2026-08-09 15:34:30 -04:00
soreavis c8403ac6fc feat(iam): add service-linked role create, delete and deletion status (#2179)
* feat(iam): add service-linked role create, delete and deletion status

aws_iam_service_linked_role calls CreateServiceLinkedRole directly, and one
unsupported operation fails a whole account-bootstrap module. Delete and
GetServiceLinkedRoleDeletionStatus come with it, because create alone leaves
terraform destroy broken.

The role lands under /aws-service-role/<principal>/ with a trust policy for
that principal, and is readable by GetRole afterwards, which is what the
issue asks for.

The role NAME is a deterministic stand-in, not AWS's. The prefix is chosen
by the linked service and is not computable from the principal — AWS turns
lex.amazonaws.com into AWSServiceRoleForLexBots — so this derives a name
from the principal's labels instead: es.amazonaws.com becomes
AWSServiceRoleForEs.
Every label contributes, because rds.amazonaws.com and
rds.application-autoscaling.amazonaws.com are separate roles on AWS and a
config declaring both must not collide on one name.

A CustomSuffix is joined with an underscore, which is the separator callers
parse back out; Terraform recovers custom_suffix by splitting the role name
on it, and that attribute forces replacement, so any other join never
converges.

Deletion is synchronous, so the returned task id is already complete and its
status is SUCCEEDED. Task ids use the documented
task/aws-service-role/<principal>/<role>/<uuid> shape and are held in a
StorageFactory-backed store, so they are account-scoped and survive a
restart like every other IAM record.

Closes #2122

* fix(iam): classify service-linked roles by origin, not by path

CreateRole accepts the /aws-service-role/ prefix, so a role sitting at a
well-formed service-linked path is not necessarily one. Path-based
classification let DeleteServiceLinkedRole delete an ordinary role that
merely lived there.

Roles minted by CreateServiceLinkedRole now carry a marker, and the delete
path keys on that instead. The field is additive, so a role persisted
before this change reads as not service-linked, which is correct.

* fix(iam): protect service-linked roles from ordinary role mutations

DeleteServiceLinkedRole could answer 409 DeleteConflict, a code absent from
that action's published error list (LimitExceeded, NoSuchEntity,
ServiceFailure). It got there by routing through deleteRole, which refuses a
role that still has policies attached — and nothing stopped a caller from
attaching one to a service-linked role first.

AWS never reaches that state. It publishes UnmodifiableEntity (400) on twelve
role actions, and the message names the linked service to go through instead.
So refuse the mutation rather than handle the conflict it would otherwise
cause. This guards the eleven the emulator implements — AttachRolePolicy,
DetachRolePolicy, PutRolePolicy, DeleteRolePolicy,
Put/DeleteRolePermissionsBoundary, UpdateRole, UpdateAssumeRolePolicy,
Add/RemoveRoleFromInstanceProfile and DeleteRole; UpdateRoleDescription is the
twelfth and has no handler here. Several were silent: DeleteRole removed a
service-linked role at 200, UpdateAssumeRolePolicy rewrote its trust policy,
and AddRoleToInstanceProfile attached it to an instance profile. TagRole and
UntagRole stay open, matching AWS. DeleteServiceLinkedRole now removes the
role directly, since deleteRole refuses it.

Also validate CreateServiceLinkedRole's own inputs. CustomSuffix must match
[\w+=,.@-]{1,64}, as AWS constrains it — a suffix containing '/' previously
produced a role name outside RoleName's own pattern, leaving an ARN whose name
segment cannot be recovered. And a derived name over 64 characters is
rejected, because AWS caps RoleName at 64 on every action that takes one and
on the Role this action returns.

Document the three deviations that remain: the role name is derived locally
and will not match AWS for most services, deletion is synchronous so the
deletion status is always SUCCEEDED, and CreateRole accepts the
/aws-service-role/ path that AWS reserves.
2026-08-09 15:11:51 -04:00
Priamo Germosen d78520d5cb feat(kinesisanalytics): add Managed Service for Apache Flink (Kinesis Analytics V2) (#1914)
* feat(kinesisanalytics): add Managed Service for Apache Flink (Kinesis Analytics V2)

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

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

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

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

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

Tests updated accordingly and verified live against the packaged jar.

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

* feat(kinesisanalytics): add CreateApplicationPresignedUrl and SnapshotsEnabled

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

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

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

The readiness poller only called putApplication when advanceToRunning reported
RUNNING, not when it merely assigned flinkJobId after submitting the job (which
returns false until the job state catches up). pendingJars — a separate,
in-process-only cache — is already cleared by that point, so an emulator
restart between job submission and reaching RUNNING would leave the
application stuck: no persisted flinkJobId to resume polling, and no cached
JAR left to resubmit.
2026-08-09 15:01:30 -04:00
Feyikemi Ogunsanya 3b760bd8e5 fix(kinesis): resolve LATEST shard iterator position at GetShardIterator time (#1901)
* fix(kinesis): resolve LATEST shard iterator position at GetShardIterator time

A LATEST iterator recomputed its start position as the shard tip on
every GetRecords call, so records written between obtaining the iterator
and the first poll were skipped forever. Snapshot the tip once when the
iterator is created (matching DynamoDbStreamService) and encode it in
the iterator's index slot. GetShardIterator now also fails fast with
ResourceNotFoundException for an unknown shard, as on AWS.

Fixes #1900

* test(kinesis): add regression tests for tailing with a LATEST iterator

Reproduce issue #1900: a record written after the iterator is obtained
must be returned, both on the first GetRecords call and when polling
via NextShardIterator.

* test(kinesis): cover unknown shard validation for LATEST iterators

GetShardIterator must return ResourceNotFoundException when the shard
does not exist instead of deferring the failure to GetRecords.

* docs(kinesis): document shard iterator semantics

Describe the supported iterator types and the LATEST tip-snapshot
behavior; remove a stray empty Examples heading.

* fix(kinesis): validate shard existence for all iterator types in GetShardIterator

AWS rejects an unknown shard at GetShardIterator time for every
iterator type, not just LATEST. Apply the shard lookup unconditionally
instead of deferring the failure to GetRecords.

Addresses review feedback on #1901.

* test(kinesis): cover unknown shard validation across all iterator types
2026-08-09 00:10:16 -05:00
Priamo Germosen c4f4181c3d fix(cognito): HMAC-sign refresh tokens to prevent forgery (#2139)
* fix(cognito): HMAC-sign refresh tokens to prevent forgery

Refresh tokens were plain poolId|username|clientId|issuedAt|familyId
strings, base64-encoded with no signature or encryption. Anyone who
knew a pool id, client id, and a valid username could hand-craft a
token accepted by InitiateAuth REFRESH_TOKEN_AUTH / GetTokensFrom
RefreshToken, unlike real Cognito, which documents refresh tokens as
encrypted and opaque.

buildRefreshToken now appends an HmacSHA256 signature over the
payload, keyed by a random secret generated and persisted per pool
(mirroring the existing lazy RSA JWT signing key pattern). parse
RefreshToken verifies that signature with a constant-time comparison
before returning any decoded field, and rejects the token (same as
today's null-parse contract) on any mismatch, tampering, or unknown
pool.

* fix(cognito): reject invalid refresh tokens in REFRESH_TOKEN_AUTH instead of impersonating "unknown"

handleRefreshToken fell through to minting real, correctly-signed
AccessToken/IdToken JWTs for a hardcoded "unknown" user whenever
parseRefreshToken returned null (or adminGetUser failed). With
refresh tokens now HMAC-verified, every forged/tampered/garbage token
takes that null path, so this fallback would have kept handing out
valid signed tokens for exactly the forgery attempts this fix is
meant to close off.

parseRefreshToken returning null is now treated the same way it
already is in getTokensFromRefreshToken: NotAuthorizedException /
"Invalid Refresh Token".

* fix(cognito): guard non-numeric issued-at and drop unused variable in handleRefreshToken

Static analysis flagged two issues in the handleRefreshToken rewrite:
Long.parseLong(parts[3]) could throw an uncaught NumberFormatException,
and tokenClientId was parsed but never read. Wrap the parse and reject
with the same NotAuthorizedException/"Invalid Refresh Token" used
elsewhere in this method, and drop the dead variable.
2026-08-09 00:00:28 -05:00
lex00 8d2a5bdd46 fix(cloudformation): create AWS::IAM::Role inline Policies instead of silently dropping them (#1969)
* fix(cloudformation): create AWS::IAM::Role inline Policies instead of silently dropping them

CreateStack now applies each entry of an IAM role's Policies array as an
inline role policy (PutRolePolicy semantics), resolving intrinsics inside
the policy document. Failures propagate so a policy that cannot be created
fails the stack instead of reporting CREATE_COMPLETE without it.

Fixes #1952

* refactor(cloudformation): move AWS::IAM::Role into its own provisioner

Continues the per-service decomposition started with SQS (#1825) by taking the
resource type this branch touches out of the CloudFormationResourceProvisioner
switch, carrying the #1952 inline-Policies fix with it.

- IamRoleCfnProvisioner owns provision and delete for AWS::IAM::Role: name
  resolution and same-stack adoption, managed-policy attachment with its
  rollback, the inline Policies of #1952, and the former deleteRoleSafe, whose
  only caller was the role delete arm.
- CfnRollback holds what both halves of the migration need instead of
  duplicating it: the __FlociRollbackOwned attribute that CloudFormationService
  reads to decide rollback deletion, and attemptIamCleanup, still used by the
  AWS::IAM::Policy and AWS::IAM::ManagedPolicy arms.
- ProvisionContext gains resolveStringList next to the resolveOptional and
  generatePhysicalName it already lifts from the monolith.
- IamRoleCfnProvisionerTest covers the inline policies and the delete path with
  one mocked service; the existing role rollback tests keep running through the
  public provision entry point, now with the provisioner registered.

Role provisioning behavior is otherwise unchanged.

* fix(cloudformation): inline role policies fail loudly and unwind on failure

Three review findings on the IAM role provisioner.

A Policies entry with a null or absent PolicyDocument was skipped, so the stack
reached CREATE_COMPLETE without the declared inline policy — the same silent
drop this PR set out to fix, one level in. It is a ValidationError now.

The inline-policy loop sat outside the block that unwinds a failed provision.
When putRolePolicy failed after createRole succeeded, the resource went
CREATE_FAILED, and because rollback only deletes resources that reached
CREATE_COMPLETE, the role, its managed attachments and any inline policies
already written were left behind. The loop now runs inside that block.

A failed update that adopted an existing role kept whatever the half-applied
attempt had granted. Inline writes are recorded with the value they replaced,
so unwinding restores the previous document, or removes the policy when this
attempt introduced the name. A role the stack did not create is not deleted.

* fix(cloudformation): reconcile role policies an update stopped declaring

An inline policy or managed attachment written by a previous execution and
absent from the new template stayed on the role while the stack still reported
UPDATE_COMPLETE. Both sets are now recorded on the resource and reconciled on
the success path, so what the template drops is removed. Only names a previous
execution recorded are touched, which leaves out-of-band policies alone.

PolicyName is required on AWS::IAM::Role Policies. Generating one gave the same
policy a fresh name on every execution, so an update accumulated copies instead
of replacing it. A missing PolicyName is now a ValidationError, matching what
this resource already does for a missing PolicyDocument.

* fix(cloudformation): skip reconciliation of a role policy already removed

deleteRolePolicy and detachRolePolicy both raise NoSuchEntity on an absent
target, so a tracked policy removed out of band between executions failed an
update whose desired end state already held. Reconciliation now skips what the
role no longer carries.
2026-08-08 22:44:49 -05:00
Alex Banna 6d829ff7a4 feat(s3): resolve index documents for static-website directory requests (#1815)
* feat(s3): resolve static website index documents

* fix(s3): drop the query string from the website folder redirect

Verified against a live S3 website endpoint in us-east-1 rather than inferred: a
bucket with photos/index.html answers

  GET /photos?code=abc&state=xyz  ->  302, Location: /photos/

with a bare Location. Same for HEAD and for nested prefixes (/a/b?x=1 -> /a/b/).

An earlier commit added query-string preservation on the strength of a review
comment asserting AWS behaved that way; the probe shows it does not, and LocalStack's
website_hosting.py agrees with the probe. An SPA whose OAuth callback lands on a
slash-less folder loses its parameters on real AWS too, so the emulator matches
rather than improving on it.
2026-08-08 22:42:26 -05:00
Priamo Germosen cb06a73b78 fix(lambda): disable HTTP/2 cleartext on the runtime API server (#2181)
RuntimeApiServerTest.extensionRegister_racedAgainstStop_eventuallyDeliversShutdown
flaked intermittently with an EOFException from the JDK HTTP/2 client,
surviving #2156's fix for the write-vs-close ordering bug. stop() already
waits for each parked write's flush to complete before closing the
httpServer, but that only confirms the bytes were locally flushed, not
that the peer received them before the connection is torn down -
multiplexed HTTP/2 stream-completion bookkeeping on the same connection
can still race that close.

Real AWS's Runtime/Extensions API is plain HTTP/1.1; nothing here needs
HTTP/2. Disabling h2c removes the class of multiplexed-connection races
entirely and the JDK HttpClient falls back to HTTP/1.1 automatically, no
client-side change required.

Fixes #2180.
2026-08-08 22:15:29 -05:00
leepokai fa8f8d78a4 fix(sqs): delayed FIFO message no longer blocks its message group (#2112)
Only in-flight messages (claimed, within their visibility timeout) lock
a FIFO message group. claimFifo() used !isVisible() as the lock
predicate, which also matches messages still waiting out DelaySeconds,
so a newly sent delayed message made already-visible messages in its
group unreceivable. Require a receipt handle as well, the same
delayed-vs-in-flight discriminator messageCounts() already uses.

Fixes #2104
2026-08-08 23:01:05 -04:00
Nikola GenčićandNikola Gencic cd3c6b54b2 fix(dynamodb): order Query by full composite sort key (#2114)
* fix(dynamodb): order Query by full composite sort key

Query ordered results using only the first RANGE attribute returned by
getSortKeyName(). For an index with a composite sort key (more than one
RANGE attribute, e.g. "state RANGE, createdAt RANGE"), the remaining
components were ignored: when the first component tied across rows, the
stable sort left items in base-table storage order and ScanIndexForward
=false merely reversed that order, so the secondary component (e.g.
createdAt) never drove ordering.

Sort by the full sort key instead, comparing each RANGE attribute in
key-schema order and short-circuiting on the first non-equal component,
then reverse for ScanIndexForward=false. Single-sort-key indexes are
unaffected (one-element list preserves previous behavior).

Adds getSortKeyNames() to GlobalSecondaryIndex, LocalSecondaryIndex and
TableDefinition, and a regression test whose base-key order deliberately
disagrees with the secondary sort component.

Fixes #1675

* fix(dynamodb): paginate composite sort-key Query by full key

The composite-sort-key ordering fix sorted by every RANGE attribute, but
pagination still used only the first RANGE component (getSortKeyName()).
LastEvaluatedKey construction and ExclusiveStartKey matching therefore
dropped the later components, so a cursor no longer uniquely identified the
row a page stopped on — rows sharing the first RANGE value could be skipped
or duplicated across pages.

Thread the full sort-key list (getSortKeyNames()) through buildKeyNode() and
buildItemKeyFromNode(): the emitted cursor now carries every sort-key
component, and cursor matching compares the full composite key. Single
sort-key indexes and the scan/table-key paths keep the previous behavior via
the retained single-key overloads.

Addresses PR review comment r3710297799 ("Composite pagination loses key
identity"). Adds paginated regression tests over the composite index that
fail without this change. Refs #1675.

---------

Co-authored-by: Nikola Gencic <nikola.gencic@centiglobe.com>
2026-08-08 21:50:33 -05:00
Oliver Andrews 02288abc11 fix(rds): fault with DBInstanceNotFound/DBClusterNotFoundFault for missing identifiers in Describe* (#1740)
* fix(rds): fault with DBInstanceNotFound/DBClusterNotFoundFault for missing identifiers in Describe*

DescribeDBInstances/DescribeDBClusters returned an empty 200 when the
identifier parameter matched nothing; real AWS faults for the parameter
form and returns an empty list only for the Filters form. Track whether
the identifier came from the parameter and fault when it matched nothing,
with error codes, messages, and 404 status matching live AWS.

* fix(rds,docdb,neptune): ARN identifiers and Filters-form parity for Describe*

Review follow-ups:

- RDS, DocDB, and Neptune list methods accept an ARN (the identifier
  parameter and the db-instance-id/db-cluster-id filters both allow ARNs
  per the AWS model). The ARN is matched against each resource's stored
  ARN, so a cross-account or cross-region ARN does not resolve a
  same-named local resource.
- DocDbQueryHandler and NeptuneQueryHandler fault only for the identifier
  parameter, not the Filters form, which returns an empty list (mirror of
  the RDS fix).

* test(rds): expect NotFound faults after delete in SDK compat tests

The Go and Java compat suites asserted the old emulator behavior — an
empty 200 when describing a deleted instance/cluster by identifier. Real
AWS faults DBInstanceNotFound/DBClusterNotFoundFault there, which is what
the deletion waiters key on, and the emulator now does the same.
2026-08-08 21:48:17 -05:00
soreavis d943e09a73 feat(ec2): add ReplaceRoute (#2178)
Terraform calls ReplaceRoute whenever an existing route changes target, so
route tables could be created but never updated; the only workaround was
to destroy and recreate the table.

The action replaces the target of the route matching DestinationCidrBlock.
AWS takes exactly one target per call, so the target a request does not name
is cleared rather than carried over; a merge would leave a route holding two
targets at once, which AWS cannot produce.

Only GatewayId and NatGatewayId are modelled by Route, plus LocalTarget,
which needs no new field because `local` is the gateway id a route table's
built-in route already carries. The other ten AWS targets keep the
UnsupportedOperation they returned before this action existed rather than
being accepted and silently clearing the route they were meant to repoint.

Errors follow the EC2 reference: InvalidRoute.NotFound when no route matches
the destination, MissingParameter when DestinationCidrBlock is absent (an
IPv6 or prefix-list request), and InvalidParameterCombination for two
targets or none.

Closes #2087
2026-08-08 22:47:28 -04:00
Hector Ventura 8b8f837728 fix(ecs): report service deployments and MISSING failures on DescribeServices (#2176)
* fix(ecs): report service deployments and MISSING failures on DescribeServices

DescribeServices omitted services[].deployments entirely and always returned an
empty failures list. Both are read by AWS's own ServicesStable waiter, which
accepts on

  length(services[?!(length(deployments) == `1` && runningCount == desiredCount)]) == `0`

and fails fast on failures[].reason == "MISSING" (botocore
ecs/2014-11-13/waiters-2.json). Because that file is codegen'd into every SDK,
`aws ecs wait services-stable` and every SDK waiter polled for the full
40 x 15s before giving up, and Terraform's aws_ecs_service never converged
(terraform-provider-aws internal/service/ecs/service.go:2206 applies the same
len(Deployments) == 1 test). Evaluating the acceptor against the old payload
raises JMESPathTypeError, so it could not even be evaluated.

An ACTIVE service now reports exactly one PRIMARY deployment derived from its
current state, with rolloutState COMPLETED once runningCount reaches
desiredCount. The deployment id is derived from the service ARN and task
definition rather than generated per request, so it is stable across calls and
restarts and rolls over when the task definition changes. An unresolvable
service reference is returned as a MISSING failure carrying the ARN it would
have had, instead of being dropped.

Known deviations are documented in docs/services/ecs.md: a single deployment
with no draining ACTIVE alongside it, no deploymentController gating, and
pendingCount always 0.

Closes #2174

* fix(ecs): stamp a deployment with its own start time, not the service's

A task-definition change mints a new deployment id, but both deployment
timestamps were still taken from the service's creation time, so the payload
contradicted itself: a new deployment claiming to have been created when the
service was. botocore documents Deployment.createdAt as "the time when the
service deployment was created", and moto stamps it at deployment construction
(moto/ecs/models.py:540) rather than reusing the service's.

Track when the current deployment began on the service model, set at creation
and on every task-definition change, and report that. Services persisted before
this field existed fall back to the service creation time.

Raised in review on #2176.
2026-08-08 21:37:59 -05:00
Kenshin Okinaka aed50cc2b2 feat(ses): implement custom verification email templates for v1 and v2 (#1840)
* feat(ses): implement custom verification email templates for v1 and v2

Add the SES custom-verification-email-template CRUD APIs across both protocols,
backed by one shared StorageFactory store (key cvet::<region>::<name>):

- v1 Query: Create/Get/List/Update/DeleteCustomVerificationEmailTemplate.
- v2 REST JSON: the same five operations under
  /v2/email/custom-verification-email-templates.

Behaviour and error shapes were verified against real AWS: duplicate create is
AlreadyExistsException, missing is NotFoundException, the FromEmailAddress must
be a verified identity (NotFoundException otherwise), an invalid redirection URL
is BadRequestException, the template body is not content-validated, List omits
TemplateContent, and the store is shared between v1 and v2. SendCustomVerification-
Email is left as a follow-up.

* fix(ses): serialize custom-verification-template mutations under one lock

Guard the check-then-write of updateCustomVerificationEmailTemplate and
deleteCustomVerificationEmailTemplate on the same lock as create (renamed
cvetCreateLock -> cvetMutationLock) so a concurrent delete can't slip between
an update's existence check and its put and resurrect the just-deleted
template. Also clean up the shared template left by the v1 integration test.

* fix(ses): validate custom-verification-template fields before the existence check on update

UpdateCustomVerificationEmailTemplate ran the existence check before validating
required fields, so omitting TemplateName (possible on the v1 Query API) returned
NotFoundException instead of the required-field InvalidParameterValue (v2
BadRequestException). Validate first, matching CreateCustomVerificationEmailTemplate.
Also drop an unused Hamcrest import in the v2 integration test.

* test(ses): give the custom-verification-template cleanup a unique last order

update_missingTemplateName and cleanup_deleteSharedTemplate both used @Order(8);
with OrderAnnotation equal values have no guaranteed order and the suite is stateful.
Move the cleanup to @Order(9) so it runs last deterministically.

* fix(ses): throw v1 error codes for custom-verification-template not-found/duplicate

The CVET service methods threw the v2 codes (NotFoundException/404, AlreadyExistsException/400)
directly, so remapV1Exception was a no-op and the v1 Query path returned the wrong codes: the
v1 SDK's typed CustomVerificationEmailTemplate* exceptions never fired, and not-found used 404
instead of AWS's 400. Throw the v1-native codes (CustomVerificationEmailTemplateDoesNotExist /
CustomVerificationEmailTemplateAlreadyExists, both 400, verified against AWS) and map them in
remapV1Exception, so v1 is correct while v2 still returns NotFoundException/404 and
AlreadyExistsException/400. Also wrap the get/delete CVET endpoints in remapV1Exception (the
only two that lacked it) and pin the v1 codes with integration assertions.

* fix(ses): throw the v1 code for an unverified custom-verification-template sender

An unverified FromEmailAddress threw NotFoundException/404 from the shared CVET validator, so
the v1 Query wire carried a v2 code. AWS classic SES returns FromEmailAddressNotVerified/400
(verified); throw that v1-native code and map it in remapV1Exception, so v1 is correct while
v2 still returns NotFoundException/404. Pin the v1 code with an integration assertion.
2026-08-08 21:36:21 -05:00
David d039780e3a fix(s3): validate FULL_OBJECT checksum on CompleteMultipartUpload (#1980)
* fix(s3): validate FULL_OBJECT checksum on CompleteMultipartUpload

* fix(s3): align FULL_OBJECT checksum validation with AWS's CRC-only support

- Reject SHA1/SHA256 combined with ChecksumType=FULL_OBJECT on multipart
  completion with InvalidRequest, since AWS only supports full-object
  checksums for CRC32/CRC32C/CRC64NVME (SHA is composite-only).
- Report ChecksumType=FULL_OBJECT instead of COMPOSITE once a requested
  full-object checksum has been validated.
- Abort the multipart upload left dangling by the mismatched-checksum
  test, and add regression coverage for both fixes above.
2026-08-08 21:34:48 -05:00
Kenshin Okinaka fa9ed9100e feat(ses): implement SendEmail ListManagementOptions suppression and unsubscribe (v2) (#1875)
* feat(ses): implement SendEmail ListManagementOptions suppression and unsubscribe (v2)

SendEmail now honors ListManagementOptions (ContactListName / TopicName):

Opt-out suppression — recipients opted out of the named contact list are
suppressed as a Bounce, reusing the existing relay-exclusion and Bounce-event
path. A contact is opted out when UnsubscribeAll is set; with a TopicName, an
explicit OPT_OUT preference (or the topic's OPT_OUT DefaultSubscriptionStatus
when no explicit preference) suppresses; without a TopicName, only
UnsubscribeAll contacts are suppressed. A recipient that is not yet a contact
is created on the list automatically; an unknown contact list fails the send.

Unsubscribe handling — a single-recipient list-managed send gets a functional
unsubscribe link: the {{amazonSESUnsubscribeUrl}} body placeholder is replaced
and List-Unsubscribe / List-Unsubscribe-Post headers are added. The link points
at Floci's own /_aws/ses/unsubscribe endpoint (GET/POST), which applies the
opt-out (topic -> OPT_OUT, no topic -> UnsubscribeAll), auto-creating the
contact if needed. The link uses readable query parameters rather than AWS's
opaque token, and its scheme follows Floci's base URL. Raw sends do not get
link injection yet.

* fix(ses): apply list-management unsubscribe headers to relay + inspection, override duplicates, preserve placeholder in templates

Addresses three review findings on the unsubscribe handling:

- The List-Unsubscribe / List-Unsubscribe-Post headers now reach the SMTP relay
  message (relay() takes the additional headers and applies them) and are stored
  on SentEmail so GET /_aws/ses surfaces them under Headers — previously they
  only appeared in published events.
- withUnsubscribeHeaders now overrides a caller-supplied List-Unsubscribe /
  List-Unsubscribe-Post rather than appending a duplicate, matching AWS.
- applyTemplateData leaves the reserved {{amazonSESUnsubscribeUrl}} placeholder
  intact instead of failing with MissingRenderingAttribute, so a templated body
  can carry it (replacement still happens post-render in the send path).

* fix(ses): sanitize relayed headers against SMTP injection and avoid double-slash unsubscribe URLs

User-supplied SendEmail Headers reach the SMTP relay, where a name or value containing
CR/LF could inject extra headers (e.g. Bcc) into the delivered message. Skip any header
with a blank name or CR/LF in its name/value before adding it to the relay message, and
log the drop. Also trim a trailing slash from the configured base URL when building the
List-Unsubscribe URL so a base-url ending in "/" no longer yields "//_aws/...".

* fix(ses): make the unsubscribe GET a no-mutation confirmation page

The unsubscribe endpoint applied the opt-out on both GET and POST. A GET is a browser
click that AWS answers with a landing page, and treating it as a mutation is the RFC 8058
prefetch hazard: mail clients, scanners and link-preview bots that fetch the URL would
silently unsubscribe the contact. GET now renders a confirmation form that POSTs back;
only the POST (the RFC 8058 one-click request) applies the opt-out. Adds GET test
coverage and updates the docs.

* test(ses): add an SDK compat test for SendEmail with ListManagementOptions

Send with ListManagementOptions through the SES v2 SDK client to prove the nested structure
(ContactListName + optional TopicName) marshals as a real client sends it, and that Floci
actually applies it — an absent recipient is auto-created as a contact on the list. Also note
in the docs that {{amazonSESUnsubscribeUrl}} is left verbatim on a send without
ListManagementOptions (Floci behavior, not verified against real SES).

* fix(ses): harden the unsubscribe confirmation page and document its trust model

Escape '&' as '&amp;' in the confirmation form's action attribute (valid HTML), and add the
RFC 8058 one-click hidden field so the form's POST body matches the advertised
List-Unsubscribe-Post header. Also document — in the controller Javadoc and the SES docs — that
the endpoint carries the target in readable query parameters and, like the rest of Floci, is
unauthenticated, so it is only safe on a trusted dev/test network.

* fix(ses): filter unsafe headers once so all send surfaces stay consistent

The SMTP relay dropped user-supplied headers with a blank name or CR/LF, but the stored
SentEmail (GET /_aws/ses) and published events kept the raw list — so inspection and events
could show headers the relay dropped and retain CR/LF injection payloads. Move the safety
check to MessageHeader.isSafe(), filter the headers once in the send path, and use that
sanitized list for storage, relay, and event publishing alike.

* fix(ses): reject SES v2 message headers that omit a required Name or Value

Content.Simple.Headers / Content.Template.Headers entries declare Name and
Value as required members. A header object missing either member was parsed
leniently and later silently dropped, which is surprising when the request is
otherwise accepted. Reject it at parse time the way AWS does — BadRequestException
with the Smithy "Member must not be null" constraint message anchored at the
offending header path and 1-based index.
2026-08-08 21:33:35 -05:00
Sumedh 66fd109ad6 fix(eks): validate subnet IDs exist before creating a cluster (#1943)
* fix(eks): validate subnet IDs exist before creating a cluster

CreateCluster previously accepted any subnet ID, including ones that
don't exist, and returned a successful cluster with an empty vpcId.
Real EKS validates resourcesVpcConfig.subnetIds against EC2 and
rejects the request with InvalidParameterException if a subnet is
not found.

EksService now delegates to Ec2Service.requireSubnet for each subnet
ID given at cluster creation, mirroring the pattern RdsService already
uses for DB subnet groups.

* fix(eks): resolve subnet validation against the request's region

Subnet validation in createCluster used config.defaultRegion() instead
of the region the request actually targeted, so a cluster created in a
non-default region with real, existing subnets would be wrongly
rejected as InvalidParameterException.

RegionResolver gains getRegion(), mirroring the existing getAccountId()
pattern (reads the per-request region set by AccountContextFilter,
falling back to the configured default outside request scope).
EksService.createCluster now uses regionResolver.getRegion() instead of
config.defaultRegion(), which also fixes the cluster ARN's region to
match the actual request.

Found via review feedback on #1943.

* fix(eks): pin the region test properly and resolve vpcId from the subnets

Addresses both blocking points from review.

1. The region regression test could not fail.

   It used subnet-default-a, and requireSubnet() calls ensureDefaultResources()
   on whatever region it is handed, which seeds subnet-default-a/b/c there on
   the spot. The subnet therefore resolves in every region, so validation passed
   with or without the fix and only the ARN assertion discriminated — exactly as
   pointed out.

   Verified by reverting `regionResolver.getRegion()` back to
   `config.defaultRegion()` and re-running: the old test failed at the ARN
   assertion on line 276, which means createCluster had already returned without
   throwing. Validation was never being exercised.

   Split into two honestly named tests:

     createClusterBuildsArnFromRequestRegionNotDefaultRegion
         what the old test actually pinned

     createClusterValidatesSubnetsInRequestRegionNotDefaultRegion
         creates a subnet explicitly in us-east-1 and requests a cluster in
         eu-west-2 with that id. An explicitly created subnet is not seeded
         elsewhere, so this is the only shape that discriminates.

   With the fix reverted it now fails with "Expected AwsException to be thrown,
   but nothing was thrown" — the cluster is created from a subnet in the wrong
   region, which is the bug. With the fix it passes.

2. resourcesVpcConfig.vpcId was still blank (the other half of #1942).

   CreateCluster carries no vpcId; real EKS derives it from the subnets.
   requireSubnet already returns the resolved Subnet, and validateSubnets threw
   it away. It now carries the vpcId through to buildVpcConfigResponse, with a
   caller-supplied value still taking precedence.

   New test createClusterResolvesVpcIdFromTheSubnets fails before the change
   with "expected: <vpc-default> but was: <>".

EksServiceTest 28 pass, Ec2ServiceTest 17 pass. Other failures in a full run are
pre-existing on this machine and unrelated — confirmed by stashing these changes
and reproducing ZipExtractorTest's backslash-path failure on the untouched tree.

Leaving the `catch (AwsException e)` narrowing for the separate PR as suggested.
2026-08-08 21:32:28 -05:00
Ravi Arnan Irianto 42363886d5 fix(apigateway): preserve trailing slash in proxy event path (#1863)
* fix(apigateway): preserve trailing slash in proxy event path

The REST proxy event path was built from the JAX-RS {proxy} path param, which strips a trailing slash, so a request to /thing/ produced event.path "/thing" instead of "/thing/". A trailing slash is significant to backends that treat /thing and /thing/ as distinct routes. Recover it from the raw request URI for the event path, requestContext.path and the proxy path parameter, while resource matching and path-parameter extraction keep using the normalized path (AWS routes /thing/ to the /thing resource but preserves the slash in the delivered event).

Fixes #1557

* fix(apigateway): preserve trailing slash in the authorizer event path

buildProxyEvent recovers the trailing slash the JAX-RS {proxy} binding
strips, but toAuthorizerEvent still used the normalized path. A CUSTOM
authorizer therefore gated /admin/special while the Lambda received
/admin/special/, so path-based access control in the authorizer and the
handler operated on different strings. Real API Gateway gives both the
raw path.

Use preserveTrailingSlash for the authorizer event's path, methodArn and
requestContext.path; path-parameter extraction still uses the normalized
path, matching buildProxyEvent. Adds an end-to-end regression asserting
the authorizer event path keeps the slash while pathParameters do not.

* fix(apigateway): keep proxy path param and methodArn normalized

Review feedback: pathParameters come from the matcher, which runs on the
normalized path, so the greedy {proxy+} value carries no trailing slash on
real AWS even when event.path keeps one. Independent reports of the AWS
behaviour agree that event.path preserves the slash while
pathParameters.proxy does not.

methodArn is matched against IAM-style policy resources, where a stray
trailing slash would silently fail wildcards an authorizer returns. No AWS
behaviour was found pinning it either way, so it keeps the normalized path.

event.path and requestContext.path still preserve the slash, which is the
part of the original fix the evidence supports.
2026-08-08 21:29:44 -05:00
sheldon-nadarajah-sft 1150cfc657 fix(iam): include policy description in GetPolicy/ListPolicies/CreatePolicy responses (#2155)
* fix(iam): include policy description in GetPolicy/ListPolicies/CreatePolicy responses

policyXml() built the response for CreatePolicy, GetPolicy, and ListPolicies but never
emitted the Description element, even though IamPolicy stores it correctly and the
sibling roleXml() includes it for roles. Callers (e.g. Terraform's AWS provider) that
set a policy description see it as permanently missing on every read, which forces
destroy+recreate since IAM policy descriptions are immutable.

Fixes #2154

* fix(iam): stop ListPolicies from returning Description

policyXml() is shared by CreatePolicy, GetPolicy, and ListPolicies — the
previous fix added Description to all three, but AWS's own Policy model
documents that Description "is included in the response to the GetPolicy
operation. It is not included in the response to the ListPolicies
operation." CreatePolicy documents neither inclusion nor exclusion, so it's
treated the same as GetPolicy.

policyXml() now takes an explicit includeDescription flag: true at the
CreatePolicy/GetPolicy call sites, false in ListPolicies' member loop. Adds
a ListPolicies test asserting no member response ever carries a Description
element, so folding it back into the shared helper unconditionally — the
exact way this would regress — fails loudly.

Addresses review feedback from @pgermosen.

* fix(iam): make listPoliciesOmitsDescription assert the element, not the word

Match "<Description>" rather than the bare word "Description" to avoid a
false failure if a future policy's name/path happens to contain that
substring, and assert the created policy is actually present in the
response first, so the absence check can't pass vacuously against an
empty (or wrongly-filtered) member list.
2026-08-08 22:12:35 -04:00
Aniket Shukla c0f36ea604 fix(lambda): drain parked extensions before closing the runtime API server (#2156)
RuntimeApiServer.stop() called httpServer.close() before the
vertx.runOnContext(...) loops that write the 204 wake-ups and SHUTDOWN events
to parked extensions. Because close() begins tearing down connections
immediately — and is not guaranteed to run on the same event-loop context as
those writes — a parked extension's SHUTDOWN response could be lost when close
won the race, orphaning the extension. That surfaced as the intermittent
EOFException failing RuntimeApiServerTest in CI across unrelated PRs.

Close the HTTP server only after every parked 204/SHUTDOWN response has been
fully flushed: each write is scheduled on the event loop and its end() future
is awaited, decrementing a shared counter that fires the close once the last
response has actually reached the wire. Chaining on the end() future — rather
than on the scheduled handler merely returning — matters because
response.end() is asynchronous, so the bytes are not yet flushed when the
handler returns (the connection could still be torn down mid-write).

Fixes #2142.
2026-08-08 00:33:24 -05:00
Kenshin Okinaka ff8d6efdf3 feat(ses): implement v1 receipt rule set actions (stored-but-inert) (#2128)
* feat(ses): implement v1 receipt rule set actions (stored-but-inert)

Add the SES v1 receipt-rule-set management actions: CreateReceiptRuleSet,
DescribeReceiptRuleSet, ListReceiptRuleSets, DeleteReceiptRuleSet,
SetActiveReceiptRuleSet, and DescribeActiveReceiptRuleSet. Floci has no inbound-mail
endpoint, so rule sets are stored inertly — a set never holds any receipt rules and
routes no mail — but the management API round-trips so tools like Terraform can declare
a rule set during bootstrap without hitting UnsupportedOperation.

Behavior matches AWS (verified): RuleSetDoesNotExist for a missing set, AlreadyExists
for a duplicate name, idempotent DeleteReceiptRuleSet, and an empty
DescribeActiveReceiptRuleSet when no rule set is active. Individual receipt rules and
receipt filters are out of scope.

* fix(ses): reject deleting the active receipt rule set and read active state under lock

DeleteReceiptRuleSet removed the active rule set unconditionally; AWS rejects it with
CannotDelete/400 (verified), so reject it and preserve the set. DescribeActiveReceiptRuleSet
read without the lock, so a concurrent set-active replacement (clear-then-set) could expose
its intermediate no-active state; read under receiptRuleSetLock so the reader sees the old or
new active set, never the gap.

* fix(ses): validate the receipt rule set name against AWS's constraints

RuleSetName was only checked for non-blank, so Floci accepted names AWS rejects. Validate
it as AWS does (verified): a character outside ^[a-zA-Z0-9_.-]+$ is a ValidationError, and a
name over 64 characters or that does not start and end with an alphanumeric is an
InvalidParameterValue ("Not a valid ruleSetName"). Applied on create/describe/delete and on
set-active when a name is given.

* chore(ses): tidy receipt rule set import order and record the RuleSetName probe provenance

Address review nits: move the ReceiptRuleSet import into alphabetical position in
SesQueryHandler, and expand the RuleSetName validation comment to record that the
constraints come from probing live SES (the botocore model has no pattern), so the
next reader can re-verify rather than treat them as settled.
2026-08-07 23:23:01 -04:00
Alex Banna b31cbb9231 fix(rds): resolve AWS-managed default DB cluster parameter groups on reference (#1805)
* fix(rds): resolve AWS-managed default DB cluster parameter groups on reference

AWS ships a managed default DB cluster parameter group per engine family
(e.g. default.aurora-postgresql16) that always exists. A cluster that uses
the engine default — as the CDK emits when no cluster parameter group is
specified — referenced default.<family>, which getDbClusterParameterGroup
rejected with DBClusterParameterGroupNotFound, so CreateDBCluster failed.

Materialize a default.<family> cluster parameter group on first reference
(family = the segment after "default."), reproducing AWS's always-present
managed defaults. Non-default unknown names still raise
DBClusterParameterGroupNotFound.

* fix(rds): materialize named default cluster groups

* fix(rds): catalog managed cluster parameter groups

* fix(rds): validate managed cluster parameter families

* fix(rds): protect managed cluster parameter groups

* test(rds): lock cluster listing error message

* 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.
2026-08-07 20:36:02 -04:00
Jay 10048adced fix(apigateway): match Content-Type case-insensitively in Lambda proxy responses (#2150)
* fix(apigateway): match Content-Type case-insensitively in Lambda proxy responses

buildProxyResponse re-derives the response Content-Type with an exact-case
JSON field lookup (node.path("headers").path("Content-Type")), even though
the header-copy loop just above it already handles arbitrary casing
correctly by iterating every field. Lambda proxy integrations commonly
return lowercased header names - e.g. the AWS Lambda Web Adapter sidecar
returns "content-type", not "Content-Type" - which the exact-case lookup
misses, silently falling back to "application/json" regardless of what the
Lambda actually set. HTTP header names are case-insensitive on the wire
(RFC 7230 §3.2), so this affected every response whose handler didn't
happen to use the exact AWS-console casing, most visibly every RFC 9457
application/problem+json error response.

Confirmed via debug logging of the raw Lambda payload before fixing:
{"statusCode":404,"headers":{"content-type":"application/problem+json",...

Replaces the exact-case lookup with a case-insensitive scan
(findHeaderIgnoreCase) reusing the already-fetched headers node.

* test(apigateway): cover case-insensitive Content-Type matching in proxy responses

Widens buildProxyResponse to package-private (matching dispatch()'s existing
visibility, which exists for the same reason: direct unit testing from
ApiGatewayExecuteControllerTest without standing up a full Lambda invoke).

Covers lowercase, exact-case, and mixed-case Content-Type header names, plus
the pre-existing default-to-application/json behavior when no Content-Type
header is present at all.

Verified by reverting findHeaderIgnoreCase to the old exact-case lookup:
the lowercase and mixed-case tests fail (2 of 13) while the exact-case and
no-header tests keep passing, confirming none of the four are vacuous.

* fix(apigateway): preserve JSON-null Content-Type fallback in findHeaderIgnoreCase

findHeaderIgnoreCase called JsonNode#asText() unconditionally on a matched
header, so a Lambda proxy response with an explicit "Content-Type": null
produced the literal string "null" instead of falling through to the
application/json default the old exact-case lookup preserved (it checked
!ctNode.isNull() before using the value). Response.Builder#type("null")
throws, turning what used to be a 200 with the JSON default into a 502 with
the raw Lambda payload.

Also adds braces to the two new conditionals in findHeaderIgnoreCase per the
project's Java style (AGENTS.md).

Both caught by Greptile review on #2150. Verified the regression test fails
against the un-braced, null-unguarded version before this fix.

* chore: trigger CI

* fix(apigateway): scan multiValueHeaders for Content-Type, preferring it over headers

* chore: retrigger CI (previous run hit 20m job timeout)
2026-08-07 17:36:42 -05:00
soreavis 9b451ccc82 fix(iot): match topic rules outside the default region (#2169)
* fix(iot): match topic rules outside the default region

Topic rules are stored per region — topicRuleKey(region, ruleName) — but
handlePublish looked them up with a hardcoded config.defaultRegion(). A
rule created in any other region was stored, gettable and listable yet
never evaluated: republish/SQS/SNS/Kinesis/DynamoDB/Lambda actions were
silently dropped while Publish still returned 200.

IotDataController.publish now resolves the region from the request's
SigV4 credential, as the shadow endpoints in that controller already do,
and threads it through IotService.publish into handlePublish. A publish
that carries no region — MQTT, or an unsigned data-plane request —
evaluates every region's rules, mirroring the fallback
ApiGatewayService.resolveRestApiRegion applies to unsigned REST API
invocations.

executeTopicRule derives the rule's own region from its ARN and targets
the action sinks with it instead of the default region, so a rule created
in eu-west-1 delivers to eu-west-1 resources.

Closes #2065

* fix(iot): treat a non-SigV4 publish header as an unresolved region

IotDataController.publish skipped region resolution only for a missing
or blank Authorization header. Any other non-SigV4 value — a bearer JWT,
say — fell through to resolveRegionFromAuth, whose miss path returns the
configured default region. So a publish carrying such a header evaluated
only the default region's rules, while one carrying no header at all
evaluated every region's: the same absence of region information, two
different outcomes.

RegionResolver.resolveRegionFromAuthOrNull returns the credential's
region, or null when there is nothing to parse, and publish threads
that through — so every publish that names no region is treated the
same way.
2026-08-07 17:33:01 -05:00
soreavis 0203bc7f7e feat(cognito): add AdminLinkProviderForUser (#2166)
* feat(cognito): add AdminLinkProviderForUser

Linking a federated identity to an existing user pool user returned
400 UnsupportedOperation, because the action had no arm in the
CognitoJsonHandler switch and fell through to the default case.

Add the action to the handler and service. The link is recorded as an
entry in the destination user's `identities` attribute, matching the
JSON array AWS documents: userId, providerName, providerType, issuer,
primary and dateCreated. CognitoUser.attributes is already a free-form
map and AdminGetUser emits every attribute as a UserAttribute, so the
linked identity surfaces without a model change.

dateCreated is stored in epoch milliseconds. That differs from the
seconds this service uses for its own user timestamps, but it is what
AWS emits in the identities attribute and the ID token claim.

providerType is only set when the source provider name is one of the
provider types AWS also uses as a name (Facebook, Google,
LoginWithAmazon, SignInWithApple). SAML and OIDC types, and issuer, are
properties of a registered IdP, which the emulator does not model, so
they stay null rather than being guessed.

A source identity may be linked to at most one user per pool; a
conflicting link throws AliasExistsException, a documented error of
this operation.

Source provider names are not validated against a configured IdP, and
the five-identity cap is not enforced. Both are noted as deliberate
divergences in the pull request.

Closes #1563

* fix(cognito): validate link fields and serialize the uniqueness check

AdminLinkProviderForUser accepted requests with a missing SourceUser
ProviderName or ProviderAttributeValue: path().asText() turns absent
fields into empty strings, so a bad request returned 200 and persisted
an identity with an empty providerName or userId. Require the three
fields up front and answer InvalidParameterException, matching how
this service already reports missing required input.

The uniqueness check and the write could also interleave: two
concurrent links of the same source identity to different users could
both pass the scan before either wrote. Wrap the check and the write
in synchronized (pool), the pattern the tag operations already use.

* fix(cognito): serialize identity links on a stable monitor

The uniqueness check locked the UserPool object, but updateUserPool
replaces the stored instance (convertValue copy + poolStore.put), so
two links racing an update could hold different monitors and both pass
the scan. Serialize on a dedicated lock instead, declared beside the
one method it guards.

Dropping the describeUserPool lookup also changes the unknown-pool
error source: adminGetUser reports it as ResourceNotFoundException 400,
which is how every sibling admin user mutator already reports it.

Verified with an 8-thread probe linking the same source identity to
eight users: one winner and seven AliasExistsException with the lock,
eight winners without it.
2026-08-07 17:30:11 -05:00
soreavis 7d9b9aedd2 feat(cloudformation): honor resource-level DeletionPolicy (#2167)
A resource's DeletionPolicy attribute was never read off the template,
so every managed resource was deleted regardless of what it declared:
deleteStackResources and rollbackCreatedResources both called
provisioner.delete unconditionally.

Read DeletionPolicy alongside Type in executeTemplate and apply it at
both delete sites. Retain keeps the resource on every stack operation.
RetainExceptOnCreate keeps it too, except when the create that made it
is rolled back — deleting it there is the entire meaning of that value,
and rollbackCreatedResources runs only for a failed create.

A retained resource is reported as DELETE_SKIPPED, on the resource and
as a stack event, and is not counted as a failed delete, so the stack
still reaches DELETE_COMPLETE. That also lets a stack owning a
non-empty S3 bucket be deleted, which otherwise fails on the objects.

Any other value falls through to the existing delete. That includes
Snapshot: floci cannot take the snapshots AWS supports for those types,
and AWS does delete the resource under Snapshot, so Delete is the
faithful half. The docs record that and the other divergences.

The policy is set on the resource after the provisioner returns,
because provision() and executeNestedStack() both return a fresh
StackResource that replaces the map entry.

Closes #1555
2026-08-07 17:29:48 -05:00
Priamo Germosen 1795e131a2 feat(applicationautoscaling): add Application Auto Scaling control plane (#2159)
* feat(applicationautoscaling): add Application Auto Scaling control plane

Adds a services/applicationautoscaling package emulating the Application
Auto Scaling API (JSON 1.1, AnyScaleFrontendService. target prefix,
application-autoscaling signing name). This is a distinct service from the
existing EC2 Auto Scaling package, which speaks Query under the
autoscaling signing name.

Implements the nine actions Terraform exercises: RegisterScalableTarget,
DescribeScalableTargets, DeregisterScalableTarget, PutScalingPolicy,
DescribeScalingPolicies, DeleteScalingPolicy, and the ListTagsForResource
/ TagResource / UntagResource trio.

Notable behaviours:

- Identity is the (ServiceNamespace, ResourceId, ScalableDimension)
  triple; RegisterScalableTarget upserts on it and leaves unsupplied
  parameters unchanged, matching AWS.
- ScalableTargetARN uses the application-autoscaling service name while
  PolicyARN uses plain autoscaling and embeds the resource path and policy
  name — the two ARN families genuinely differ.
- Tagging resolves by ScalableTargetARN because the Terraform provider's
  transparent-tagging interceptor calls ListTagsForResource on every read,
  keyed on the ARN it reads from DescribeScalableTargets.
- Target-tracking policies create the real pair of CloudWatch alarms AWS
  creates on the caller's behalf; deregistering a scalable target deletes
  its policies and their alarms.
- Optional configuration fields are only echoed back when supplied, so
  Terraform never sees a value it did not configure.

Scaling policies are stored and described but inert: nothing evaluates
them and no capacity is adjusted, mirroring EC2 Auto Scaling's existing
PutScalingPolicy. This is documented in docs/services/applicationautoscaling.md.

Closes #2157

* refactor(applicationautoscaling): stop exposing the scalable target's tag map

getTags() handed out the live internal map, and the service mutated it in
place at three call sites. listTagsForResource also returned that same
live reference out to the handler layer, so a caller could alter stored
state without going through the service.

getTags() now returns an unmodifiable view, with putTags/removeTags for
the mutations the service actually needs, and a test pins the read-only
contract.

Reported by github-code-quality on #2159.
2026-08-07 17:27:36 -05:00
Feyikemi Ogunsanya b1f953efb1 fix(iam): seed AmazonAPIGatewayPushToCloudWatchLogs managed policy (#2147)
* fix(iam): seed AmazonAPIGatewayPushToCloudWatchLogs managed policy

Floci seeded 52 AWS-managed policies at boot but none matched
API Gateway, so AttachRolePolicy for this standard service-role
policy returned NoSuchEntity. It's the policy attached to the API
Gateway CloudWatch-logs role that aws_api_gateway_account depends
on, so this blocked the first apply of any Terraform config that
enables API Gateway access logging.

Fixes #2121

* test(iam): add regression test for AmazonAPIGatewayPushToCloudWatchLogs seeding

Reproduces #2121: GetPolicy for the API Gateway CloudWatch-logs
managed policy returned 404 NoSuchEntity before the fix.
2026-08-07 17:20:39 -05:00
Olamide Kosile 76b264f667 fix(cloudformation): reconcile AWS::Logs::LogGroup in place on UpdateStack (#2152)
* fix(cloudformation): reconcile AWS::Logs::LogGroup in place on UpdateStack

Fixes #1965

Root cause: provisionLogGroup called CreateLogGroup unconditionally on
every provision, including updates to a stack whose log group already
existed and was untouched. CloudWatchLogsService.createLogGroup throws
ResourceAlreadyExistsException in that case, so any UpdateStack on a
stack with a log group resource rolled back with "The specified log
group already exists", even when nothing about the resource changed.

Fix: on update, reconcile retention and tags in place instead of
recreating, matching the pattern already used for Lambda functions.
LogGroupName isn't updatable in place on real AWS, so a name change
still deletes the old group and creates a new one (replacement).

Also fixed a related gap: auto-generated LogGroupName (no explicit
name in the template) called generatePhysicalName, which mints a new
random name on every call, so an auto-named log group was replaced on
every single update even when unchanged. It now reuses the existing
physical name across updates, matching how auto-generated Lambda
function names are handled.

* fix(cloudformation): fix LogGroup replacement ordering and name-mode tracking

Addresses two review findings on the reconciliation fix:

- A LogGroupName rename deleted the old log group before confirming
  the new name could actually be created. If the new name collided
  with an existing group, CreateLogGroup failed and the update rolled
  back, but the old group was already gone and rollback does not
  restore it - permanent data loss. Now creates the new group first,
  matching the existing create-before-delete pattern already used for
  Lambda function replacement, and only deletes the old group once the
  new one exists.
- Removing an explicit LogGroupName from the template fell through to
  the "no explicit name" branch, which reused the prior physical id -
  the old explicit name - instead of generating a fresh name for the
  new auto-generated mode. Now tracks whether the current name is
  explicit or generated (mirroring FlociLambdaFunctionNameMode) and
  forces a fresh generated name when an explicit name is removed.

* fix(cloudformation): infer LogGroup name mode for pre-fix persisted stacks

A log group persisted by a floci version before FlociLogGroupNameMode
was tracked has no recorded mode, so explicitNameRemoved could never
be detected for it even when it should be.

Fixes it by backfilling the mode from the physical id's shape:
generatePhysicalName always produces <stackName>-<logicalId>-<12 hex
chars>, so anything else must have been an explicit LogGroupName.
Doesn't attempt to un-truncate the (practically unreachable at a
512-character limit) truncation path, conservatively treating that
edge case as explicit.

Added a dedicated unit test exercising both legacy cases directly
against the provisioner, since simulating "created by an older floci
version" isn't reachable through the black-box HTTP integration tests.

* refactor(cloudformation): rename shared name-mode constants off the Lambda prefix

NAME_MODE_EXPLICIT/NAME_MODE_GENERATED are generic mode-value labels
shared by both the Lambda and LogGroup name-mode tracking, not
Lambda-specific, so the LAMBDA_ prefix was misleading now that a
second resource type uses them. LAMBDA_NAME_MODE_ATTR is unchanged,
since that one is a genuinely Lambda-specific attribute key.
2026-08-07 16:10:54 -04:00
floverfelt f6faf0ffe5 fix(s3): Ensure tags are added on multipart s3 uploads. (#2151) 2026-08-07 16:09:18 -04:00
Hector Ventura e3c180b952 fix(ecs): resolve Secrets Manager JSON-key selectors in task definition secrets (#2133)
* fix(ecs): resolve Secrets Manager JSON-key selectors in task definition secrets

containerDefinitions[].secrets[].valueFrom now supports the ECS selector suffix
(:json-key:version-stage:version-id) that CDK emits for Secret.fromSecretsManager
with a field. Parsing mirrors the real ECS agent: the ARN resource is split on
colons and disambiguated by segment count (2 = plain reference passed through
verbatim, 5 = selector with empty segments meaning unset, anything else is the
agent's invalid-ARN error surfaced in stoppedReason). The base ARN is rebuilt
before lookup so partial-ARN resolution keeps working, JSON keys are extracted
top-level-only after the fetch, and SecretsManagerService now validates that a
supplied VersionId and VersionStage name the same version.

Closes #1912

* fix(ecs): document and pin JSON serialization of object selector values

Review follow-up: object/array json-key values serializing as JSON (rather than
Go's map[a:1 b:2] rendering from the agent's %v) is now recorded as the third
deliberate divergence in the javadoc and pinned by a test.
2026-08-06 00:15:18 -05:00
Hector VenturaandMarcel Herhold 760115db14 feat(kms): implement ListKeyPolicies (#2046)
* feat(kms): implement ListKeyPolicies

ListKeyPolicies failed with UnsupportedOperation, so clients enumerating
policy names before a GetKeyPolicy call could not proceed. GetKeyPolicy
and PutKeyPolicy were already supported, so this was a hole in an
otherwise complete area.

Returns the single `default` policy name, which is what the model
prescribes ("The only valid value is default"), with Truncated false and
NextMarker omitted rather than serialized as null, since AWS only emits
NextMarker when Truncated is true.

Limit and Marker are accepted and ignored. One policy name cannot be
paginated, and ListKeyPolicies is the one KMS list operation that does
not declare InvalidMarkerException, unlike ListKeys, ListAliases,
ListGrants, ListKeyRotations, ListResourceTags, ListRetirableGrants and
DescribeCustomKeyStores. There is therefore no marker it could
legitimately reject, and no undeclared error code is invented for one.

Closes #1528

Co-authored-by: Marcel Herhold <herhold.marcel@gmail.com>

* chore: drop hand-written ListKeyPolicies changelog entry (semantic-release owns CHANGELOG.md)

* fix(kms): drop unused ListKeyPolicies pagination params and fix test claims

Review follow-up, validated against the local AWS references: Limit/Marker are
accepted at the wire by never being read (matching moto's list_key_policies), so
the service signature drops the dead parameters and the structurally vacuous
paging unit test goes with them; the integration test remains the real coverage.
The javadoc justification now states the leniency honestly: SDKs do not fully
enforce LimitType [1..1000] client-side (botocore validates only the minimum),
so out-of-range values can arrive and are deliberately tolerated. The ARN
resolution test no longer claims alias coverage the operation does not have.

---------

Signed-off-by: Hector Ventura <hectorvent@gmail.com>
Co-authored-by: Marcel Herhold <herhold.marcel@gmail.com>
2026-08-05 23:36:07 -05:00
Jay 7f51c746cd fix(cloudformation): provision AWS::ApiGatewayV2::Authorizer and wire Route.AuthorizerId (#1760)
* fix(cloudformation): provision AWS::ApiGatewayV2::Authorizer and wire Route.AuthorizerId

CloudFormationResourceProvisioner had no case for AWS::ApiGatewayV2::Authorizer,
so the resource fell through the default stub branch and never reached
ApiGatewayV2Service — the same failure mode #788/#796 fixed for the v1
AWS::ApiGateway::Authorizer type. Stacks reported CREATE_COMPLETE, but
apigatewayv2 get-authorizers came back empty and routes referencing the
authorizer carried no authorizerId, so a JWT-authorized route silently
served every request unauthenticated.

Adds provisionApiGatewayV2Authorizer, modeled on the neighboring v2
Route/Integration/Stage provisioners, mapping the CFN PascalCase properties
(Name, AuthorizerType, IdentitySource, JwtConfiguration, AuthorizerUri,
AuthorizerPayloadFormatVersion, AuthorizerResultTtlInSeconds,
EnableSimpleResponses) onto the existing ApiGatewayV2Service.createAuthorizer
camelCase request shape. Also fixes provisionApiGatewayV2Route, which built
its request map without reading AuthorizerId at all even though
ApiGatewayV2Service.createRoute/updateRoute already handle it.

Fixes #1758.

* fix(cloudformation): accept scalar IdentitySource on ApiGatewayV2 Authorizer

resolveStringListOrEmpty silently returned an empty list when a template
supplied IdentitySource as a bare scalar string rather than the documented
array form, dropping the identity source instead of persisting it.
ApiGatewayV2Service.createAuthorizer/updateAuthorizer already accept a
scalar string for identitySource (identitySourceRaw instanceof String), so
the CFN provisioner was stricter than the service it calls.

Adds resolveIdentitySource, a local resolver that accepts both a scalar
string and an array. Adds a regression test asserting the scalar form is
persisted, alongside strengthening the existing test to assert
IdentitySource itself (previously unchecked).

Addresses review feedback on #1760.

* fix(cloudformation): populate AuthorizerId attribute, add scoped delete for AWS::ApiGatewayV2::Authorizer

- Fn::GetAtt Authorizer.AuthorizerId now resolves: provisionApiGatewayV2Authorizer
  only set the physical id, never the resource's attributes map, so GetAtt (which
  reads a separate map from Ref) fell back to a literal placeholder string.

- Stack deletion now actually removes the authorizer: the generic type/physicalId
  delete switch had no case for AWS::ApiGatewayV2::Authorizer at all and silently
  no-op'd. Added a scoped case in delete(StackResource, region) following the same
  shape already used for AWS::EKS::Nodegroup (a resource needing extra context
  beyond type+physicalId, stored as an attribute during provisioning).

Both fixes store ApiId as a resource attribute during provisioning, since it's
needed by the new delete path and wasn't previously retained anywhere.

* fix(apigateway): support $request.querystring.* identity sources for JWT authorizers

extractToken only checked HttpHeaders — it had no query-parameter access at all, so
any IdentitySource entry like $request.querystring.token was silently unusable, and
a request using a valid token there always 401'd. Threads UriInfo through
enforceJwtAuthorizer/extractToken and adds a $request.querystring. branch mirroring
the one enforceRequestAuthorizerV2 already has for Lambda REQUEST authorizers.

* chore: retrigger CI

The Build and Test job failed on a single flaky error in
RuntimeApiServerTest.extensionRegister_racedAgainstStop_eventuallyDeliversShutdown
(EOFException on an HTTP/2 read while racing extension registration against
server stop) — 1 of 8325 tests. This branch changes no Lambda code; that test
is from #1773 and lives on main independently. Passes locally on repeat runs.
2026-08-05 22:23:47 -05:00
lex00 f71903379c fix(cloudformation): AWS::IAM::ManagedPolicy exposes PolicyArn for Fn::GetAtt (#2056)
CloudFormation documents PolicyArn as the attribute for this type, so a
template written against AWS reads it back with
Fn::GetAtt [<policy>, PolicyArn]. The provisioner only recorded the value under
"Arn", so that GetAtt did not resolve and the unresolved literal propagated into
whatever consumed it — typically a role's ManagedPolicyArns, which then failed
with "Policy <logicalId>.PolicyArn does not exist" and rolled the stack back,
several resources away from the cause.

Both keys are now recorded; "Arn" stays for anything already reading it.
2026-08-05 22:16:48 -05:00
Oleh Melnyk 875e0f2d3b feat(bedrock): add proxy backend for real LLM responses via OpenAI-compatible API (#1789)
* feat(bedrock): add proxy backend for real LLM responses via OpenAI-compatible API

* fix(bedrock): preserve leading text when a tool call response also has content

OpenAI-compatible backends can return assistant text alongside tool_calls in
the same response (e.g. a preamble before invoking a tool). The Converse
translation only emitted the toolUse block in that case, silently dropping
the text.

* fix(bedrock): use InternalServerException for proxy serialization failures

InternalFailure isn't a bedrock-runtime error shape in botocore/the Java
SDK, so clients couldn't map it; InternalServerException is the declared
500 for this API.

* fix(bedrock): map proxy backend timeouts to ModelTimeoutException (408)

HttpTimeoutException (connect or request timeout) was falling into the
generic catch and surfacing as ModelErrorException/424, which the AWS
SDKs treat as terminal. Bedrock's dedicated 408 shape is retryable under
the default SDK retry strategy, so this distinction is load-bearing, not
cosmetic.

Also makes the request timeout configurable
(proxy.request-timeout-seconds, default 60s) since larger models on
CPU-backed backends may need more headroom than the default.

* fix(bedrock): fail fast on InvokeModel under the proxy backend

Falling back to StubBackend's canned response meant a caller who
configured a real proxy backend and called InvokeModel got a
plausible-looking, entirely fabricated completion with no signal beyond
a server-side log line. That's inconsistent with Converse, which already
fails loudly on misconfiguration, and worse: InvokeModel is still the
default entry point for many SDK wrappers, so this could silently mask
a broken integration.

Also fixes the streaming-endpoint error messages, which blamed "the
Floci stub" for a limitation that's actually unconditional (streaming
isn't implemented for any backend).
2026-08-05 17:17:02 -05:00
Jay e048e52ce0 test(lambda): wait for the parked poll instead of sleeping in extension stop race (#2131)
extensionRegister_racedAgainstStop_eventuallyDeliversShutdown slept 5ms to let
the extension's /event/next poll connect and park before racing stop() against
it, then asserted SHUTDOWN came back on that request. The sleep asserts the
poll has parked without checking. On a loaded machine it expires first, so
stop() closes the listening socket while the request is still in flight: the
poll never reaches the handler, stop()'s SHUTDOWN fan-out finds no waiting
context to hand the event to, and the client sees the connection die instead of
the SHUTDOWN the test is about.

That surfaces as an EOFException (connection accepted, then torn down) or a
ConnectException (lost the race before the connect even landed) out of
asyncNext.get(), and it failed CI this way once in 8325 tests.

Replace the sleep with awaitExtensionParked(), polling a new package-private
RuntimeApiServer.isExtensionParked() until the poll has provably parked, so the
race the test sets up is the one it means to test. isExtensionParked reads
under the same lock as the rest of the extension state, per the class's
documented locking discipline; RegisteredExtension.hasWaitingContext() peeks
without consuming, unlike takeWaitingContext().

The test still fails if the "poll pendingEvents before checking stopped" fix in
the /event/next handler is reverted, so this removes the flake without
weakening the regression it covers. Verified by breaking that fix and watching
this test go red, and by reproducing the original failure under CPU saturation
before and after the change.
2026-08-05 17:12:55 -05:00
Alex Bannaandabanna 62a576c8d4 feat(cloudformation): provision AWS::SecretsManager::SecretTargetAttachment (#1804)
* feat(cloudformation): provision AWS::SecretsManager::SecretTargetAttachment

AWS::SecretsManager::SecretTargetAttachment previously fell through the
default branch, so its Ref yielded a generated placeholder rather than the
secret ARN. Per the CloudFormation resource reference, this resource's Ref
returns the ARN of the secret named in SecretId, and consumers such as
Secret.fromSecretCompleteArn(...) require the complete ARN (with the
trailing -6char suffix).

Resolve SecretId (a Ref to the Secret, a friendly name, or a raw ARN) to
the canonical complete ARN via describeSecret and expose it as the
resource's physical id / Arn attribute, falling back to SecretId as-given
if the lookup fails. Deleting the attachment is a detach no-op — it must
not delete the underlying secret.

* fix(cloudformation): require SecretId on SecretTargetAttachment

SecretId is a required property of AWS::SecretsManager::SecretTargetAttachment.
Resolving it as optional let a template omit it and still create (falling back to
the logical id); reject a missing SecretId instead. Adds a regression test.

* fix(cloudformation): complete secret target attachment lifecycle

* fix(cloudformation): require attachment metadata on delete

* fix(cloudformation): tolerate detached secret overwrites

* fix(cloudformation): align secret target attachment behavior

* docs(cloudformation): document secret target attachments

---------

Co-authored-by: abanna <abanna@users.noreply.github.com>
2026-08-05 17:11:25 -05:00
lex00 bdad066694 fix(cloudformation): resolve Fn::GetAtt [Vpc, DefaultSecurityGroup] (#1977)
* fix(cloudformation): resolve Fn::GetAtt [Vpc, DefaultSecurityGroup]

provisionVpc now records the VPC's default security group id as the
DefaultSecurityGroup attribute, so GetAtt resolves to the real sg-* id
instead of passing the literal 'LogicalId.DefaultSecurityGroup' string to
downstream resources (breaks CDK's Custom::VpcRestrictDefaultSG handler).

Fixes #1976

* refactor(cloudformation): extract AWS::EC2::VPC into a per-service provisioner
2026-08-04 22:26:03 -05:00
lex00 4e0a815f20 feat(cloudformation): provision AWS::EC2::LaunchTemplate (#1973)
* feat(cloudformation): provision AWS::EC2::LaunchTemplate

Create the launch template in Ec2Service from LaunchTemplateData
(ImageId, InstanceType, KeyName, SecurityGroupIds, UserData,
IamInstanceProfile). Ref resolves to the launch template id and
Fn::GetAtt exposes LatestVersionNumber/DefaultVersionNumber, which CDK
ASGs and instances reference. DeleteStack removes the template.

Fixes #1971

* feat(cloudformation): resolve EC2 instance config from its LaunchTemplate reference

An AWS::EC2::Instance that sets LaunchTemplate instead of direct
properties now fills ImageId/InstanceType/KeyName from the referenced
template's data (AWS resolution order), so instances launched from a
launch template no longer fail with 'The request must contain the
parameter ImageId'.

* refactor(cloudformation): move AWS::EC2::LaunchTemplate into a per-service provisioner

Follows the CfnResourceProvisioner pattern instead of growing the monolithic
switch: Ec2LaunchTemplateCfnProvisioner injects only Ec2Service and is picked
up by CloudFormationResourceRegistry via CDI. Provision and delete arms for
AWS::EC2::LaunchTemplate are removed from CloudFormationResourceProvisioner
along with the now-unused private provisionLaunchTemplate method. EC2 instance
resolution against a referenced launch template stays put, since
AWS::EC2::Instance is not extracted yet.

An IamInstanceProfile given only by Name is now normalized to its
instance-profile ARN, matching the EC2 query API path; previously the bare
name was stored as if it were an ARN.

Adds unit coverage for the new provisioner (attributes, generated name,
profile ARN normalization, security groups, delete).

* test(cloudformation): delete the launch-template instance stack so EC2 state stays clean

The instance case left its stack standing, so a running instance (and its
network interface) leaked into the shared emulator state for the rest of the
suite. That pushed the total interface count past the MaxResults=5 boundary
Ec2IntegrationTest's DescribeNetworkInterfaces pagination cases assert on, and
they failed in full-suite runs while passing in isolation. Deleting the stack
terminates the instance, which describeNetworkInterfaces skips.

* fix(cloudformation): update a launch template in place instead of recreating it

UpdateStack re-provisions every resource, and the provisioner called
createLaunchTemplate unconditionally. An explicit LaunchTemplateName therefore
hit InvalidLaunchTemplateName.AlreadyExistsException on every update, and an
omitted one generated a fresh random name, creating a second template and
orphaning the first.

A template whose name has not changed is now updated by publishing a new
version and keeping its physical id, which is how AWS::EC2::LaunchTemplate
behaves when only its LaunchTemplateData changes. An unnamed template keeps the
name generated at create time rather than minting a new one. A changed name is
a replacement: the new template is created first and the previous one deleted
only after that succeeds.
2026-08-04 22:25:29 -05:00
lex00 1a99721ae0 feat(cloudformation): provision AWS::EC2::VPCGatewayAttachment (#1972)
* feat(cloudformation): provision AWS::EC2::VPCGatewayAttachment

Attach the internet gateway to the VPC via Ec2Service so route tables
pointing at the IGW behave like AWS. The physical id encodes vpc|igw so
stack deletion can detach. The VpnGatewayId variant records the
attachment without an attach call (no VPN gateway model).

Fixes #1970

* refactor(cloudformation): move VPCGatewayAttachment into a per-service provisioner

The monolithic switch in CloudFormationResourceProvisioner is being split into
per-service CfnResourceProvisioner implementations, so AWS::EC2::VPCGatewayAttachment
lands in the new structure instead of growing the switch.

Ec2VpcGatewayAttachmentCfnProvisioner injects only Ec2Service and is picked up by
CloudFormationResourceRegistry through CDI, no registration needed. The provision
logic and the physical-id encoding (vpcId|gatewayId) carry over unchanged, and
delete() detaches the internet gateway so stack deletion no longer leaves the
attachment orphaned.

Removes the AWS::EC2::VPCGatewayAttachment arms from the provision and delete
switches along with provisionVpcGatewayAttachment and
detachVpcGatewayAttachmentSafe, leaving CloudFormationResourceProvisioner
identical to main.

* fix(cloudformation): validate VPCGatewayAttachment and make its delete type-safe

Four review findings on the attachment provisioner.

A template that omitted VpcId still reported CREATE_COMPLETE: the null went
into attachInternetGateway, so DescribeInternetGateways exposed an attachment
with no VPC and every later detach on that gateway threw on the null compare.
VpcId is now required, as is exactly one of InternetGatewayId or VpnGatewayId.

The VpnGatewayId form recorded a physical id and did nothing else, so
CloudFormation reported CREATE_COMPLETE for an attachment that does not exist
and cannot be observed — there is no VPN gateway model behind it. It now fails
the resource with an explicit message instead of claiming success.

Updates orphaned the previous pair. The new pair is attached first and the old
one detached only after that succeeds, so a failed update leaves the previous
attachment intact; an unchanged update no longer re-attaches and duplicates.

Deletion classified the gateway by the id's igw- prefix, so an igw-* value
supplied as VpnGatewayId could detach a gateway the stack never attached. The
physical id now carries a kind tag (igw|<vpcId>|<gatewayId>) and delete acts
only on ids this provisioner wrote.
2026-08-04 22:24:36 -05:00
Alex Banna 5cb26ff117 fix(cloudformation): treat delete of an already-removed DynamoDB table or Lambda function as idempotent (#1803)
* fix(cloudformation): treat delete of an already-removed DynamoDB table or Lambda function as idempotent

When a stack is torn down after a rollback has already deleted some of its
resources, CloudFormation re-issues the delete against resources that no
longer exist. DynamoDB DeleteTable and Lambda DeleteFunction both raise
ResourceNotFoundException in that case, which flipped the stack to
DELETE_FAILED and wedged the stack name against a later create.

Route the AWS::DynamoDB::Table and AWS::Lambda::Function delete cases
through deleteDynamoTableSafe / deleteLambdaFunctionSafe, which swallow
ResourceNotFoundException (treating an absent resource as already deleted,
as AWS does) while still re-throwing any other AwsException so genuine
conflicts continue to surface as DELETE_FAILED.

* test(cloudformation): cover idempotent delete boundaries

* chore(ci): retrigger flaky checks
2026-08-04 22:22:13 -05:00
Alex Banna 48b2139b4f fix(cloudformation): keep uniqueness suffix when truncating generated resource names (#1802)
* fix(cloudformation): keep uniqueness suffix when truncating generated resource names

CloudFormation auto-generates a physical name as
`{stackName}-{logicalId}-{random}` for resources declared without an
explicit name. When that string exceeded the resource type's name-length
cap, generatePhysicalName truncated the whole string with
`substring(0, maxLength)`, which dropped the trailing random token. Every
auto-named resource in a long-named stack then collapsed onto the same
truncated name, breaking Ref/GetAtt lookups — most visibly a
`Custom::LogRetention` whose `ServiceToken` (a GetAtt of its provider
Lambda's Arn) resolved to a different, colliding function.

Truncate only the descriptive prefix and always keep the random suffix,
matching how CloudFormation shortens a generated name while preserving its
uniqueness token, so distinct logical resources keep distinct physical names.

* fix(cloudformation): preserve uniqueness suffix in extracted ProvisionContext name generator

The #1825 registry refactor lifted generatePhysicalName into ProvisionContext
verbatim, so migrated resource types (SQS) once again truncated the trailing
uniqueness token when a stack name neared the length limit. Apply the same
suffix-preserving truncation there so extracted provisioners stay consistent
with the monolith.

* fix(cloudformation): harden generated name regression test
2026-08-04 22:21:23 -05:00
Alex Banna 91e06ebebf fix(apigateway): import authorizers and security requirements from OpenAPI (#1798) 2026-08-04 22:20:26 -05:00
Priamo Germosen 7e4e3e8c50 feat(mwaa): add Amazon MWAA emulation backed by real Airflow (LocalExecutor) (#2086)
* feat(mwaa): add Amazon MWAA emulation backed by real Airflow (LocalExecutor)

Adds a new services/mwaa package following the EKS lifecycle pattern
(Controller/Service/EnvironmentManager, one Docker container-set per
resource, readiness polling) and the Neptune/ElastiCache proxy pattern
(MwaaWebProxy/MwaaProxyManager: Floci owns the host-facing port, the
backing container stays internal-only).

Each environment is backed by two real containers — postgres:16-alpine
for the metadata DB and apache/airflow:<version>-python3.12 running
LocalExecutor — with AirflowVersion genuinely selecting the image tag
(validated against a configured allow-list), unlike EKS's cosmetic-only
version field. MwaaWebProxy fronts the real Airflow webserver and
intercepts POST /aws_mwaa/cli, bridging it to a docker-exec'd `airflow`
CLI call and returning the documented {stdout, stderr} shape.

DAGs and requirements.txt sync from S3 on a poller, reusing the existing
S3Service in-process rather than a new AWS-facing surface. The Airflow
container is pointed back at Floci via LaunchedContainerAwsEnv (the same
mechanism Lambda/ECS containers already use), so a DAG's own boto3 calls
resolve against Floci instead of real AWS.

StartupScriptS3Path is supported end-to-end: fetched from S3 at create
time, injected before the container starts (create -> inject -> start,
mirroring EksClusterManager's config-injection sequencing), sourced
before migrate/scheduler/webserver so exported vars propagate. The
airflow user gets a passwordless sudo grant (verified against the real
image — sudo ships but isn't passwordless by default, and AWS's own
startup-script examples assume sudo just works), and a fixed set of
Floci-critical env vars (Fernet key, DB DSN, executor, AWS-SDK-redirection
vars) are snapshotted before and restored after the script runs, mirroring
real MWAA's reserved-environment-variable protection.

Verified end-to-end against real Docker (not just the mock=true unit
suite): environment reaches AVAILABLE, proxy pass-through and the CLI
bridge both work with real output, a DAG uploaded to S3 syncs and parses,
a second environment on a different AirflowVersion pulls a genuinely
distinct image, and delete tears down both containers/volumes and the
proxy cleanly.

45 new tests (unit + RestAssured integration, all against mock=true in
the default suite so Docker is never required for `mvnw test`); full
suite otherwise unchanged.

* fix(mwaa): hard-fail startup-script injection failures, release proxy ports on delete

Two issues from review:

copyFileIntoContainer swallowed every failure identically, including the
one case where that's wrong: a configured StartupScriptS3Path that fails
to copy into the container. The entrypoint's "if [ -f /startup.sh ]"
guard would silently skip it and the environment would reach AVAILABLE
having never applied the requested setup, contradicting the documented
intent of gating environment creation on startup-script failure (matching
real MWAA). copyFileIntoContainer now reports success/failure; the
startup-script call site checks it and throws, while DAG sync and the
best-effort sudoers grant keep their existing soft-fail behavior.

deleteEnvironment allocated a proxy port via PortAllocator on create but
never released it on delete, unlike every other service that uses
PortAllocator (Lambda, MSK, EC2, ECR) — repeated create/delete cycles
would eventually exhaust the configured proxy port range even with zero
MWAA proxies actually running.

* fix(mwaa): roll back allocated proxy port and containers on create failure

If startEnvironment() succeeded (containers running) but PortAllocator.allocate
or MwaaProxyManager.startProxy failed afterward, createEnvironment's catch
block set CREATE_FAILED without releasing the reserved port or stopping the
containers that had already started — leaking both on every such failure.

Mirrors NeptuneService.createDbCluster/rollbackDbCluster's already-proven
shape for this exact class of problem (container + proxy + port, partial
failure must roll back everything): a provisioned flag set only after every
step succeeds, and a try/finally that runs rollbackFailedCreate whenever it
doesn't — stopping the proxy (a no-op if it never started), stopping any
containers that did start (MwaaEnvironmentManager.stopEnvironment already
null-checks each container id, so it's safe for partial startup too), and
always releasing the port.

* fix(mwaa): correct CreateEnvironment error shape, namespace container names, add docs

Two items from maintainer review:

- Duplicate CreateEnvironment threw ResourceAlreadyExistsException, a shape the
  operation doesn't declare (verified against the real botocore mwaa/2020-07-01
  model: CreateEnvironment's only errors are ServiceUnavailableException,
  ValidationException, InternalServerException) — SDK clients couldn't map it.
  Now throws ValidationException.

- dbContainerName/airflowContainerName built names via raw string concatenation
  instead of routing through ContainerStorageHelper.dockerName like every other
  Docker-backed service (EKS, RDS, ...), so MWAA alone didn't participate in the
  FLOCI_DOCKER_RESOURCE_NAMESPACE convention that keeps multiple Floci instances
  sharing one Docker daemon from colliding. Both static methods now take the
  EmulatorConfig and route through the shared helper; volume names inherit the
  fix automatically since they're built by extending the container name.

Also adds docs/services/mwaa.md (mkdocs nav updated) following eks.md's
structure — operations table, mock/real mode, the web/CLI proxy, startup-script
behavior (sudo grant, reserved-variable protection), config reference, ARN
format, CLI/SDK examples, and an honest "Not Implemented" section covering the
known gaps already discussed on the PR (PluginsS3Path, cross-account container
naming, restart restoration).
2026-08-04 22:16:14 -05:00
Aniket Shukla 5f7d4d2dc8 fix(s3): recognize virtual-hosted-style requests over HTTP/2 (#1954)
* fix(s3): recognize virtual-hosted-style requests over HTTP/2

Browsers negotiate HTTP/2 via ALPN over HTTPS, and HTTP/2 (RFC 9113) has no
Host header — the authority is carried in the :authority pseudo-header.
S3VirtualHostFilter read only getHeaderString("Host"), which is null over
HTTP/2, so virtual-hosted-style requests fell through to path-style handling:
the bucket label in the authority was ignored and the first path segment was
treated as the bucket instead.

Resolve the effective authority from the request URI (populated from
:authority) when the Host header is absent, so bucket routing works on both
HTTP/1.1 and HTTP/2.

Closes #1866

* fix(s3): detect website requests over HTTP/2 via request-URI authority

Over HTTP/2 there is no Host header, so S3Controller.isWebsiteRequest saw a null host and served API XML instead of website HTML for virtual-hosted website buckets. Resolve the effective authority from the request URI (reusing S3VirtualHostFilter.resolveHost) so website index/error-document handling works on HTTP/2 too; the filter's path rewrite preserves the s3-website authority for this.

Tests: isWebsiteRequest detection over HTTP/1.1 and HTTP/2 (S3ControllerWebsiteRequestTest), and that the filter rewrite keeps the s3-website authority downstream (S3VirtualHostFilterTest).
2026-08-04 22:03:38 -05:00
Arindam Choudhury 79031a240a fix(s3): apply CreateBucketConfiguration tags on bucket creation (#2115)
CreateBucket accepted a <Tags> array in the request body but ignored it.
The body was parsed for LocationConstraint only, so tags supplied at
creation were silently dropped: the request returned 200, and a
following GetBucketTagging or S3 Control ListTagsForResource reported an
empty tag set.

AWS applies these tags. The CreateBucket API reference documents Tags
inside CreateBucketConfiguration as "an array of tags that you can apply
to the bucket that you're creating", gated on the s3:TagResource
permission.

The gap is visible through the AWS Terraform provider, which sends
bucket tags this way rather than via a separate PutBucketTagging call.
Against Floci an aws_s3_bucket with a tags map applies cleanly but lands
with tags = {} in state, so every subsequent plan proposes to add them
again -- a diff that never converges.

Parse the same <Tag> key/value pairs handlePutBucketTagging already
parses, and route them through the existing s3Service.putBucketTagging
once the bucket exists.

Verified end to end: with this change a terraform apply of a tagged
aws_s3_bucket records the tag in state, get-bucket-tagging returns it,
and the next plan reports no changes. The unpatched image, same config
and provider version, still reports tags = {} and a pending change.
2026-08-04 22:01:46 -05:00
floverfeltandFlorian Overfelt b543aa4baa feat(lambda): support extra /etc/hosts entries on Lambda launch (#2073)
* feat(lambda): support extra /etc/hosts entries via FLOCI_SERVICES_LAMBDA_EXTRA_HOSTS

* feat(lambda): support ipv6 addresses.

---------

Co-authored-by: Florian Overfelt <joverfelt@meso-scale.com>
2026-08-04 21:50:25 -05:00
Alex Banna fa96b791b4 fix(codebuild): stabilize start and retry responses (#2052) 2026-08-04 21:49:17 -05:00