Commit Graph
1546 Commits
Author SHA1 Message Date
hisham-coderandHisham Mohammed f3b22e7964 fix(ecs): roll service tasks onto a changed task definition (#2483)
UpdateService with a new taskDefinition recorded a deployment but left the
running tasks on the old revision forever: a redeploy (new image tag, new
environment) never reached the containers, and the only way to apply it was
to StopTask by hand so the reconciler relaunched.

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

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

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

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

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

Verified against the image itself:

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

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

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

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

* fix(cloudformation): clean failed EC2 launches

* fix(ec2): bound container launch failures

* fix(ec2): cancel timed out container launches

* fix(ec2): track containers during startup

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

* test(ec2): cover cancellation during Docker create

* fix(ec2): allow slow container cold starts

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

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

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

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

* fix(cloudformation): provision SAM HttpApi routes

* fix(cloudformation): reconcile SAM HttpApi routes

* fix(cloudformation): stage HttpApi route replacements

* fix(cloudformation): roll back failed HttpApi replacements

* fix(cloudformation): resolve intrinsic HttpApi definitions

* fix(cloudformation): roll back HttpApi definition removal

* fix(cloudformation): retain failed HttpApi route cleanup

* test(cloudformation): align HttpApi fixture with main

* chore(ci): retrigger flaky Neptune test

* fix(apigatewayv2): prevent duplicate routes on rollback

* fix(cloudformation): persist failed cleanup ownership

* fix(cloudformation): preserve OpenAPI route authorization

* fix(cloudformation): reject unsupported auth conjunctions

* fix(apigatewayv2): preserve rollback and auth semantics

* fix(cloudformation): surface incomplete update rollback

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

* fix(cloudformation): preserve merged route authorization

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

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

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

Adds unit tests for the deployed-API path matcher.

Closes #1928

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

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

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

Closes #2461

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

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

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

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

* fix(dynamodb): address review feedback

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

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

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

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

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

Package names verified against the images rather than assumed:

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

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

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

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

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

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

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

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

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

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

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

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

Closes #2416.

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

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

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

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

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

Two things review found in the re-key.

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

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

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

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

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

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

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

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

Fixes #2437

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

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

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

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

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

Closes #2368

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

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

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

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

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

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

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

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

Closes #1930
2026-08-21 10:33:04 -04:00
Alex Banna 04d120fdd5 feat(fis): add AWS FIS support (#2435)
* feat(fis): add AWS FIS support

* refactor: add typed FIS persistence models

* ci(fis): retrigger timed-out build

* fix(fis): reject trailing JSON request bodies
2026-08-21 00:09:04 -04:00
mitsukado-shinagawaandmitsukado-shinagawa d0a96d87b1 fix(apigatewayv2): CloudFormation AuthorizationScopes pass-through and scope-ingestion hardening (follow-up to #2011) (#2431)
* fix(apigatewayv2): pass AuthorizationScopes through CloudFormation routes and harden scope ingestion

Follow-ups from PR #2011 review:

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

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

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

---------

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

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

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

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

* fix(signin): initialize secure random at runtime

* fix(signin): make refresh exchange idempotent

* fix(signin): match AWS OAuth token contracts

* refactor(signin): add typed token result model

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

Fixes #2294

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

Addresses @pgermosen's three review points:

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

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

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

---------

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

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

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

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

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

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

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

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

* fix(lambda): serialize restored policy statements
2026-08-20 23:14:42 -04:00
Abhigya f45d64a00e feat(sns): deliver topic broadcasts to application-protocol platform endpoints (#1856)
* feat(sns): deliver topic broadcasts to application-protocol platform endpoints

Add an application-protocol case to deliverMessage so publishing to a
topic fans out to subscribed mobile push platform endpoints, matching
real SNS behavior. Thread messageStructure through the delivery boundary
so platform-specific payload keys (GCM/FCM/APNS) resolve per endpoint,
and factor the push-capture tail of publishToEndpoint into a shared
capturePushForEndpoint helper. Disabled endpoints are skipped in the
fan-out rather than failing the publish. Broadcast pushes surface in the
same retrospection API keyed by EndpointArn.

* fix(sns): validate MessageStructure synchronously before topic fan-out

Topic Publish with MessageStructure=json now validates that the message is
a JSON object with a top-level default entry up front, mirroring the real
SNS API. Previously a malformed envelope was only rejected lazily inside
per-subscriber delivery, where deliverMessage's catch swallowed the
InvalidParameter and logged a warning while publish still returned a
success messageId, so application subscribers silently received no push.

* fix(sns): validate MessageStructure per entry in PublishBatch

publish() validates a MessageStructure="json" envelope synchronously before
fan-out, but publishBatch() only threaded MessageStructure into deliverMessage.
A batch entry with a malformed or default-less envelope was therefore added to
Successful while deliverMessage's catch swallowed the resulting InvalidParameter,
dropping the push for every application subscriber.

Run the same validation per entry, reporting a bad envelope as that entry's
BatchResultErrorEntry (InvalidParameter, senderFault=true) instead of throwing,
so the rest of the batch still publishes as real PublishBatch does.

* fix(sns): resolve MessageStructure=json payload per protocol on fan-out

Under MessageStructure="json", only the application protocol consumed the
envelope: sqs, lambda, http/https, email, email-json and sms each delivered
the raw JSON structure. Real SNS resolves per-protocol for every subscriber,
picking the value under the protocol key and falling back to default.

deliverMessage now resolves the payload for each subscription through the
(renamed) resolveProtocolPayload, which already keyed off an arbitrary
string; application keeps resolving against the push platform inside
capturePushForEndpoint. validateTopicMessageStructure guarantees default
exists before fan-out, so the fallback cannot come up empty.

* fix(sns): ignore non-string MessageStructure=json keys, matching AWS

Under MessageStructure=json, real SNS ignores a protocol key whose value
is not a string ("Non-string values will cause the key to be ignored"),
falling back to default rather than stringifying it. resolveProtocolPayload
was calling protocolValue.toString(), so {"default":"hi","sqs":42} delivered
the literal "42" to an SQS subscriber instead of "hi".

Only textual values are now accepted for both the protocol key and the
default fallback; non-textual values fall through. validateTopicMessageStructure
is tightened to require a textual default so a non-string default is rejected
synchronously rather than throwing (and being swallowed) during fan-out.

Adds regression tests for a non-string protocol key falling back to default
and for rejection of a non-string default.

* chore: remove unnecessary file
2026-08-20 23:10:38 -04:00
Abarnaa Sree N ebd4a078d3 fix: preserve Firehose compression format in CloudFormation (#2406)
* fix: preserve Firehose compression format in CloudFormation

* test(cloudformation): assert Firehose compression format

* test(cloudformation): assert Firehose compression format
2026-08-20 22:32:48 -04:00
Alex Banna f2ad05ce22 feat(cloudfront): forward origin custom headers (#1832)
* feat(cloudfront): serve distribution requests from S3 and custom origins

* feat(cloudfront): forward origin custom headers

* fix(cloudfront): omit Allow-Credentials and Vary for wildcard S3 CORS rules

withS3CorsHeaders emitted Access-Control-Allow-Credentials: true for every matched
rule, including one whose AllowedOrigin is "*" (where evaluateCors echoes "*").
The CORS specification forbids that pairing and browsers reject it for credentialed
requests, so the emulator produced a response that fails in a browser while passing
against Floci.

Verified against real S3 rather than inferred. Bucket with AllowedOrigins ["*"]:

  Access-Control-Allow-Origin: *
  Access-Control-Allow-Methods: GET
  Access-Control-Max-Age: 3000

and with a concrete AllowedOrigin it additionally returns

  Access-Control-Allow-Credentials: true
  Vary: Origin, Access-Control-Request-Headers, Access-Control-Request-Method

Both preflight and actual GET behave identically. Vary is now also conditional: the
wildcard response is byte-identical for every origin, so there is nothing to vary on,
and real S3 omits it there too.

* chore: re-run CI

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

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

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

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

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

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

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

* test(dynamodb): retain Quarkus port for cleanup

* fix(cloudfront): isolate mocked storage backends

* fix(ec2): wire managed prefix list storage in public IP test

* fix(cloudfront): allow authorization origin custom headers

* fix(cloudfront): preserve S3 preflight CORS headers
2026-08-20 22:21:51 -04:00
Alex Banna 520c0f4da2 feat(cloudfront): apply response-headers policies when serving (#1833)
* feat(cloudfront): serve distribution requests from S3 and custom origins

* feat(cloudfront): add response headers policy support

* chore: re-run CI

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

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

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

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

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

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

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

* test(dynamodb): retain Quarkus port for cleanup

* fix(cloudfront): isolate mocked storage backends

* fix: validate credentialed CloudFront CORS headers

* fix: log ignored CloudFront policy parse errors

* fix(ec2): wire managed prefix list storage in public IP test

* fix(cloudfront): preserve custom CORS-like headers
2026-08-20 18:06:12 -04:00
Hector Ventura f40d2e34f3 fix(elasticache): return the modeled capacity fault on proxy-port exhaustion (#2423)
Proxy-port exhaustion threw InsufficientReplicationGroupCapacity with HTTP 503.
No such shape exists in the elasticache model, so SDK clients cannot map it to a
typed exception. CreateReplicationGroup declares InsufficientCacheClusterCapacityFault,
whose wire code is InsufficientCacheClusterCapacity at HTTP 400 with senderFault
set, so return that instead.

The exhausted range is a Floci-side limit rather than anything AWS models, so the
response now carries AWS's own capacity wording and the real cause — the configured
proxy-base-port/proxy-max-port range — is logged at WARN.

Note this changes retry semantics: 503 invites a retry, 400 is a sender fault and
should not be retried. That follows the model, and the previous 503 was inviting
retries against a condition that will not clear on its own.
2026-08-20 13:16:59 -04:00
Alex Banna d778a6e393 feat(rds): model Aurora Serverless v2 scaling configuration on DB clusters (#1829)
* feat(rds): model Aurora Serverless v2 scaling configuration

* test(dynamodb): retain Quarkus port for cleanup
2026-08-20 13:06:30 -04:00
TATSUNO “Taz” Yasuhiro bc13801121 feat(lambda): support kubernetes as the lambda runner (#1941)
* feat(lambda): support kubernetes as the lambda runner

* fix(lambda): keep the port reserved when a failed launch cannot confirm pod deletion

* fix(lambda): carry the owning account in the layer Content.Location URL

The URL is fetched unsigned. Without an X-Amz-Credential query the
account filter falls back to the default account, so a layer published
under another account resolves the wrong bucket namespace and 404s.
Mirror the credential query the kubernetes executor already appends to
its download URLs.

* chore(build): raise the surefire heap to 6g

The suite outgrew the 4g default heap of 16g CI runners. At OOM a full
GC reclaims almost nothing, so the live set is real. The heap dump
shows 192 surviving QuarkusClassLoader instances, each pinned test app
keeping its own copy of the Jandex index. This PR widens the classpath
with the kubernetes client, which made each pinned copy heavier and
tipped CI over the edge. Verified locally that the full suite passes
with 6g and fails with 4g. Unpinning the leaked classloaders remains
follow-up work on main.
2026-08-20 12:52:32 -04:00
Saatvik Arya 5744082c5e fix(apigatewayv2): return stage tags across protocols (#2413)
* fix(apigatewayv2): return stage tags across protocols

* test(apigatewayv2): cover reserved stage tag stripping
2026-08-19 23:50:48 -05:00
Priamo Germosen 5ed3a8cad9 fix(rds,firehose,cognito): match AWS's real defaults so a second terraform plan reports no changes (#2420)
* fix(rds,firehose,cognito): match AWS's real defaults so a second terraform plan reports no changes

Three unrelated fields across three services all had the same shape of
bug: a value AWS defaults or fills in was never populated, so a create
(or a later describe) returned something a real AWS response never
would - applying cleanly and then drifting on every subsequent plan.

- RDS: AutoMinorVersionUpgrade was never read from CreateDBInstance or
  echoed back at all. AWS defaults it to true when omitted (confirmed
  against the CreateDBInstance API reference, whose example response
  echoes it explicitly); floci reported false/absent. Threaded the
  request parameter through to the model and the response XML,
  defaulting to true like AWS does.
- Firehose: S3BackupMode was missing from the ExtendedS3Destination
  model entirely, so describeDeliveryStream's existing applyDefaults()
  (which already backfills CompressionFormat/EncryptionConfiguration
  for exactly this reason) never touched it. Added the field and its
  "Disabled" default there.
- Cognito: DeviceConfiguration/UserPoolAddOns/EmailConfiguration all
  returned an empty JSON object when unconfigured. Reproduced against
  a live floci with the actual compat Terraform fixture and confirmed
  via re-plan: an empty object (rather than a real default or a JSON
  null) got Terraform's AWS provider to capture one shape into state
  at apply and read back a different one on refresh.
  - DeviceConfiguration/UserPoolAddOns: AWS's own docs state "a null
    value indicates you have deactivated device remembering" - matched
    that by emitting JSON null instead of {} when unconfigured (an
    earlier version of this fix filled UserPoolAddOns with
    AdvancedSecurityMode: OFF based on a doc example that turned out to
    be echoing an explicitly-set request value, not demonstrating a
    real default - caught by re-running the actual reproduction rather
    than trusting the read).
  - EmailConfiguration: defaults EmailSendingAccount to COGNITO_DEFAULT,
    matching its documented built-in-email-by-default behavior.

Verified end to end against the real compat-terraform fixture (not
just unit tests): a full `terraform apply` followed by
`terraform plan -detailed-exitcode` now exits 0 with "No changes"
across every resource in the fixture, not just these three. Widened
the "re-planning ... reports no changes" bats test from the
Application-Auto-Scaling-only subset it was scoped to (specifically to
dodge this bug) to the full configuration, per the issue's own
suggestion.

Closes #2200.

* fix(rds,firehose): propagate AutoMinorVersionUpgrade/S3BackupMode through update, not just create

Two review findings on the same class of bug this PR already fixes for
create/describe, but for the update path instead:

- ModifyDBInstance silently ignored AutoMinorVersionUpgrade - an
  explicit modify request was accepted (200) but never applied, so a
  subsequent describe kept reporting the old value. Threaded it
  through as a nullable Boolean, matching the existing
  EnableIAMDatabaseAuthentication pattern (null = not specified, so
  ModifyDBInstance's other unrelated fields aren't force-reset).
- FirehoseService#mergeDestination copied every ExtendedS3DestinationUpdate
  field except S3BackupMode, so an UpdateDestination call that changed
  it applied cleanly but the change never took.

A third finding (S3BackupMode also appears in the standard, non-extended
S3DestinationDescription shape) is real but pre-existing: Destination
already serializes the same S3Destination object under both
S3DestinationDescription and ExtendedS3DestinationDescription keys, so
CustomTimeZone and FileExtension - both extended-only fields per AWS's
S3DestinationDescription reference - already leak into the standard
shape today. Not fixing that here; it's a separate, larger change
affecting fields this PR didn't touch.

* fix(firehose): stop leaking extended-only fields into the standard S3 destination shape

S3DestinationDescription and ExtendedS3DestinationDescription shared
the same S3Destination object, so FileExtension/CustomTimeZone/
S3BackupMode - all extended-only per AWS's S3DestinationDescription
reference - leaked into the plain shape on every describe.

Added S3Destination#standardView(), a copy holding only the fields
AWS's plain shape actually has, and serve it from
getS3DestinationDescription(). ExtendedS3DestinationDescription keeps
serializing the live object with every field, as before.

The first attempt at this filtered the wrong call site: s3Destination(),
the internal accessor every FirehoseService business method uses
(object-key file extension/timezone logic, applyDefaults(), merges),
went through the same getter and got the same filtered copy - silently
dropping those three fields from all of it, including applyDefaults()
mutating a throwaway copy instead of the real stream. Repointed it to
getExtendedS3DestinationDescription() instead, which was never touched.

* fix(cognito): omit unset DeviceConfiguration/UserPoolAddOns instead of emitting JSON null

hectorvent's review: AWS's JSON protocol serializes only members with
a value provided - an unconfigured pool omits the key entirely, it
doesn't write a wire-level null. The "a null value indicates..." line
in AWS's own docs describes what a typed SDK getter returns for an
absent member, not the JSON literal.

Verified independently rather than taking either side on faith: the
Smithy awsJson1_1 protocol spec describes serializing "each member
value provided" as a JSON property (nothing for members without one),
and moto's DescribeUserPool never writes either key when unset - its
to_json() only ever adds keys present in extended_config, no
None-producing default. Switched both fields from putNull to omitting
the node.set(...) call entirely, matching how every other genuinely-
optional field in this same method is already handled.
2026-08-19 23:29:58 -05:00
Matt Van Horn bd8d99b757 fix: apply S3 Vectors metadata filters (#2417)
Fixes #2160
2026-08-19 23:17:36 -05:00
NAMAN JAIN 8a673fc580 feat(emrserverless): support EMR Serverless applications (#2403)
* feat(emrserverless): add EMR Serverless application management emulator

This adds a full emulator for the EMR Serverless Application management plane,
allowing tools like Terraform to provision and manage EmrServerless applications.
Includes full CRUD operations, route collision handling, and integration tests.

* fix(emrserverless): disambiguate local endpoint routing using SigV4 auth header

* fix(emrserverless): resolve bot feedback on ARNs, idempotency, updates, and list controls

* fix(emrserverless): resolve bot feedback on idempotency races and dropped update fields

* fix(emrserverless): add jobLevelCostAllocationConfiguration to updates

* fix(emrserverless): retain nested configuration fields using dynamic properties

* fix(emrserverless): add required field validation and correct 404 status code

* docs(emrserverless): document unsupported tagging APIs

* fix(emrserverless): increase ListApplications maxResults limit to 100

* test(emrserverless): fix integration test assertions to align with required field validations and correct 404 status code

* fix(emrserverless): revert ListApplications maxResults limit to 50 to match AWS limits

* test(emrserverless): add validation tests for CreateApplication required fields
2026-08-20 00:08:21 -04:00
ProGamingDkandPriamo 3daab4a1ae fix(ec2): create /run/sshd before starting sshd (#1855)
Modern OpenSSH refuses to start without its privilege-separation
directory, and /run is a fresh tmpfs in most container images, so
/run/sshd genuinely is not there. sshd exited with "Missing privilege
separation directory: /run/sshd" and instances launched via
`aws ec2 run-instances` came up with no SSH, requiring the directory to
be created by hand inside the container.

Add a regression test that drives the launch path with an SSH public
key, records the container execs in order, and asserts /run/sshd is
created before /usr/sbin/sshd is invoked.

Signed-off-by: ProGamingDk <smashyalts@gmail.com>
Co-authored-by: Priamo <pgermosen@gmail.com>
2026-08-19 23:51:10 -04:00
Priamo Germosen 7505110ed9 feat(msk): add configuration revision actions (#2344)
* fix(core): extract shared pagination helper, reject maxResults=0

Closes #2339, #2340.

ListResult<T> and its paginate()/encode()/decode() helpers existed as
five near-identical private copies (BedrockAgentCoreGatewayService,
BedrockAgentCoreIdentityService, BedrockAgentCoreMemoryService,
BedrockAgentCoreControlService's three list methods, and MskService),
not the two originally scoped in #2340 - the ListResult<T> record was
already shared within bedrockagentcorecontrol, which is what earlier
scoping missed. Extracts core.common.Pagination + PaginatedResult<T>
and migrates every one of them, deleting both now-unused per-service
ListResult model classes.

Every duplicate collapsed "maxResults omitted" and "maxResults=0"
onto the same primitive int, defaulting both to the full page instead
of rejecting the explicit zero the way AWS's MaxResults min:1
constraint requires (confirmed against botocore's real kafka and
verified live: botocore itself refuses to send MaxResults=0
client-side). Pagination.paginate/parseMaxResults take a boxed
Integer so the two cases are distinguishable, and every migrated
service now rejects 0 with its own existing error code
(ValidationException for the bedrockagentcorecontrol services,
BadRequestException for MSK) - the fix lands once, not five times.

Also carries over the MskController fix from #2336: an
Integer-typed @QueryParam converts before the resource method runs,
so a non-numeric maxResults was a bare 404 instead of an AWS-shaped
400. Every migrated REST controller now binds maxResults as a String
and calls Pagination.parseMaxResults, closing the same gap in
BedrockAgentCoreGatewayController/ControlController/MemoryController
that MSK already had fixed.

* feat(msk): add configuration revision actions

Closes #2338.

Adds UpdateConfiguration, ListConfigurationRevisions, and
DescribeConfigurationRevision, the three actions #2299 explicitly
scoped out ("a separate follow-up issue"). MskConfiguration now
stores a full revision history (revisions + serverPropertiesByRevision
keyed by revision number) instead of a single latest-revision field -
UpdateConfiguration appends rather than overwrites, and
DescribeConfigurationRevision is the only action that returns
serverProperties (base64), matching AWS's real shapes: Configuration/
DescribeConfigurationResponse/CreateConfigurationResponse never
include it, verified against botocore's kafka service model the same
way as #2336/#2343 rather than trusting the docs page.

ListConfigurationRevisions builds on the shared Pagination.paginate
helper from #2343 (cursor = zero-padded revision number) instead of
introducing a sixth duplicate of that logic.

getLatestRevision() is now derived from the revision list rather than
a separately-stored field, so it can never drift out of sync with it.

* fix(msk): guard configuration schema upgrade and update-race in UpdateConfiguration

Old (pre-revision-history) persisted configurations have latestRevision/
serverProperties keys this class no longer maps, which previously threw and
failed the entire msk-configurations.json load; ignore them instead and
reject updates against such an entry with a 400 rather than NPE-ing.

Also serialize UpdateConfiguration's read-modify-write behind a lock so two
concurrent updates for the same ARN can no longer derive the same revision
number and silently overwrite each other's serverProperties.

* fix(msk): stop leaking mutable revision state through getters

MskConfiguration#getRevisions/getServerPropertiesByRevision returned the
live internal List/Map, which is why MskService#updateConfiguration was
mutating through them directly - and in an order (revision appended,
then its properties inserted) that let an unsynchronized reader observe
a revision with no server properties yet and NPE on Base64-encoding it.

Add MskConfiguration#addRevision to own both writes in the safe order,
and have the getters return copies so callers can no longer bypass it.

* fix(msk): guard revision reads with the same lock updateConfiguration writes under

listConfigurationRevisions/describeConfigurationRevision read revisions
and serverPropertiesByRevision - plain, non-thread-safe collections -
without holding configurationUpdateLock, so a concurrent updateConfiguration
could race the reader's iteration/copy, not just return stale data.

* fix(msk): close remaining unsynchronized-read races on configuration revisions

Two more gaps in the same family as the last fix:

- deleteConfiguration didn't take configurationUpdateLock, so it could
  race updateConfiguration and get resurrected by the update's trailing
  put(arn, ...) after the delete already removed the entry.
- getLatestRevision() is read directly from MskController with no access
  to the service's lock at all, so no per-call-site synchronized block
  can close that gap. Make revisions/serverPropertiesByRevision
  CopyOnWriteArrayList/ConcurrentHashMap instead, so every current and
  future reader is safe by construction rather than by remembering to
  take a lock it may not have access to.

* fix(msk): migrate pre-revision-history configurations onto revision 1

A configuration persisted before this PR's schema change stored a single
"latestRevision" object plus a flat "serverProperties" string. Those keys
were only being swallowed by ignoreUnknown, so the entry loaded with an
empty revision list and getLatestRevision() == null. AWS marks
Configuration's LatestRevision required, and toConfigurationView builds
into a HashMap - which keeps a key with a null value, unlike Map.of - with
no NON_NULL inclusion configured anywhere in the application. So
DescribeConfiguration and ListConfigurations emitted a required member as
an explicit "latestRevision": null for those entries, and
UpdateConfiguration rejected them permanently.

Map both old keys back onto revision 1 at load time instead. The data was
always still there, so this is a migration rather than a degradation, and
it un-breaks UpdateConfiguration for those configurations as well.

- The setters are deserialize-only: @JsonSetter is an explicit marker, so
  it survives the @JsonIgnore split on getLatestRevision() without
  re-enabling the write side. The old shape is read, never written back.
- Jackson calls the two setters in whatever order the keys sit in the
  file, so neither can assemble the revision alone; each buffers its half
  and the pair completes the migration.
- A legacy entry with no serverProperties migrates to an empty string, not
  null: serverPropertiesByRevision is a ConcurrentHashMap, which rejects
  null values, and DescribeConfigurationRevision base64-encodes what it
  finds without a null check.
- The updateConfiguration guard stays, now covering only an entry with no
  revision data at all rather than every pre-schema configuration.

Also corrects the comment in listConfigurationRevisions, which still
justified its lock by calling the collections plain and non-concurrent.
That was true when it was written but stopped being true in 93bc30e7; the
lock is kept, for consistency with describeConfigurationRevision reading
both collections, not to prevent a torn read.

Verified locally: MskServiceTest 34, MskControllerTest 2,
MskControllerIntegrationTest 20 - 0 failures, 0 errors. Reverting only the
MskConfiguration change fails 6 of the new tests, confirming they bite.
2026-08-19 21:53:33 -05:00
Priamo Germosen c54f8ddf02 fix(cloudformation): keep a rolled-back stack's diagnostics until the next redeploy (#2365)
* fix(cloudformation): keep a rolled-back stack's diagnostics until the next redeploy

CreateStack had no name-conflict check at all: createChangeSet's
computeIfAbsent silently reused any existing stack regardless of
status, so a second CreateStack for a live name re-ran the template
against the same stack instead of failing. That left callers no
AWS-faithful way to redeploy over a ROLLBACK_COMPLETE stack except an
explicit DeleteStack first - which destroys the failed attempt's
DescribeStackEvents before an operator gets to read them.

Now a CREATE-type change set against an existing stack throws
AlreadyExistsException unless that stack is ROLLBACK_COMPLETE, in
which case it's replaced with a fresh stack (new StackId, empty
resources/events) at execute time - the moment a redeploy is actually
requested, not eagerly when the rollback itself completes. The failed
attempt stays fully describable for as long as nobody's asked to
retry.

Closes #2207.

* fix(cloudformation): make the CreateStack name-conflict check atomic

The existence check (stacks.get) and the stack-map insert
(computeIfAbsent) were two separate operations, so two CreateStack
requests racing for the same never-before-used name could both
observe "absent", pass the check, and then share whichever Stack
computeIfAbsent settled on - each independently executing the
template against it instead of one request getting
AlreadyExistsException.

Fold both into a single stacks.compute() call: it holds the map's
per-key lock for the whole call, so the second racing request now
finds the first's stack already there and throws.

Verified the race is real and the fix closes it: reverting just the
source change while keeping the new concurrency test, 15 of 16
concurrent requests against an unused name "succeeded" (duplicate
provisioning); with the fix, exactly 1 does.

* fix(cloudformation): drop the unverified ROLLBACK_COMPLETE recreate exemption

The previous commit let a CREATE change set proceed directly over a
ROLLBACK_COMPLETE stack, deleting and recreating it at execute time,
on the claim that AWS added this in 2022. That claim was wrong and
went into the PR without a source - checked now against AWS's own
CreateStack API reference and troubleshooting guide, both of which
document AlreadyExists/AlreadyExistsException unconditionally for an
existing stack name, with no ROLLBACK_COMPLETE carve-out anywhere.

ROLLBACK_COMPLETE is a real conflict like any other status; only an
explicit DeleteStack clears the name for reuse. This is exactly the
simpler option #2207 itself proposed ("let DeleteStack remove it"),
which the diagnostic-preservation fix from the first commit already
supports on its own - the stack stays fully describable for as long
as nobody deletes it, whether that's a rejected retry or a real
DeleteStack call.

* fix(cloudformation): let a CREATE change set attach to a REVIEW_IN_PROGRESS stack

The unconditional AlreadyExistsException broke the deploy retry flow.
`aws cloudformation deploy` (and SAM, which shares the code) treats a
REVIEW_IN_PROGRESS stack as nonexistent - has_stack in the AWS CLI's
deployer.py ends with `return stack["StackStatus"] != "REVIEW_IN_PROGRESS"`
- and sends a second CREATE change set against it, which real
CloudFormation accepts: a CREATE change set leaves the stack in
REVIEW_IN_PROGRESS until somebody executes it, so it is a placeholder
rather than a deployment to conflict with. Retrying a failed deploy
before any execute now works again.

The exemption is scoped to the CreateChangeSet operation rather than to
the status alone, which is the part a one-line status check would have
got wrong. CreateStack funnels through this same method and newStack()
sets REVIEW_IN_PROGRESS immediately, so every brand-new stack carries
that status for the window between newStack() and the execute that
follows it. Keying only on the status therefore hands a racing
CreateStack the first request's stack and reopens the duplicate
provisioning race closed in baf406b5 - confirmed by running the
unscoped version against createStack_concurrentRequestsForUnusedName_
exactlyOneSucceeds, where all 16 concurrent requests then "succeed"
instead of 1.

LocalStack draws the same line: the REVIEW_IN_PROGRESS exemption lives
only in its create_change_set, while create_stack conflicts on any
status but DELETE_COMPLETE.

CreateStack, UpdateStack and StackSet deployment keep the existing
signatures and stay unexempted; only the CreateChangeSet handler moves
to the new entry point.

Tests: two CREATE change sets before execution land on the same stack
and the second executes normally; a CREATE change set after execution
still conflicts; CreateStack against a REVIEW_IN_PROGRESS stack still
conflicts, pinning the implicit path so this cannot later be collapsed
into a status-only check. Full cloudformation package: 603 tests, 0
failures.

* fix(cloudformation): record a change set inside the stack's per-key lock

Stack#changeSets is a plain LinkedHashMap, and the insert ran after
stacks.compute() had already released the per-key lock. Two requests
that legitimately share one stack - two UPDATE change sets on a live
stack, or two CREATE change sets attaching to the same
REVIEW_IN_PROGRESS placeholder - could therefore both write it
unsynchronized, losing an accepted change set or breaking the map's
links.

Build and insert the ChangeSet inside the same remapping function that
resolves the stack, so name reservation, the REVIEW_IN_PROGRESS event
and the change-set insert are one atomic unit per stack key. The
brand-new-stack branch records its event there too: a stack the
remapping function has not returned yet is not in the map, so no other
thread can reach it, and keeping the sequence in one place beats
splitting it either side of the lock. persistStack() stays outside -
it is storage I/O, and compute()'s contract is that the remapping
function does short, non-blocking work.

The unsynchronized write predates this PR - it is byte-identical on
main, where the UPDATE path reaches it the same way - so this is
hardening of an adjacent hazard rather than a fix for a regression.
The rest of Stack's collections (events, resources, outputs) are still
mutated outside any lock; that is filed as #2419 rather than widened
into here.

Adds createChangeSet_concurrentRequestsOnSamePlaceholder_keepEveryChangeSet,
which fires 16 concurrent CREATE change sets at one placeholder and
asserts every one is accepted and still listed afterwards. It is a
behavioural guard, not a reproducer: run against the previous ordering
it passes, because the window between the two puts is nanoseconds
against an HTTP round trip. The correctness here comes from the
structure, not from the test catching the race.

Full cloudformation package: 604 tests, 0 failures.
2026-08-19 21:46:07 -05:00
Michal Schreiber 7b83bd5283 feat(rds,docdb): tag DocumentDB clusters and parameter groups (#2408)
* fix(rds): tag DB and DB cluster parameter groups

The tag resolver handled db, cluster, subgrp, db-proxy and og, so tagging a
parameter group answered that Floci does not implement the type — a live account
tags both, and the terraform provider reads a group's tags as part of its read.
DocumentDB's cluster parameter groups are these records too, so the same read
fails for aws_docdb_cluster_parameter_group.

Neither model carried tags, and neither carried the ARN a caller tags by: the
create response omitted it, leaving nothing to address the group with. Both are
stored and reported now, and tags given at create are kept, as a live account
keeps them.

* feat(docdb): tag clusters and instances

aws_docdb_cluster reads a cluster's tags as part of every read, so a cluster
that created fine failed its apply on DBClusterNotFoundFault — created, but not
readable.

DocumentDB signs with the rds credential scope, and on that scope it is told
apart by Engine or a cluster/instance identifier. The tag actions carry neither,
only the ARN of the resource they address, so they reached the RDS handler,
which does not hold DocumentDB's records. The router reads that ARN now, and an
ARN naming something DocumentDB does not have still goes to RDS.

Clusters and instances store tags, keep the ones given at create, and answer the
three tag actions. Behaviour follows a live account: an existing key is
overwritten, removing a key that is not present is not an error, and an ARN in
another region or account is rejected with the one message AWS gives for both —
storage is keyed by identifier alone, so without that check an ARN naming
another region would be answered with this caller's cluster.

A tag update is a read-modify-write, so it takes the record's monitor and the
other writers take the same one; otherwise tagging a cluster while it is being
deleted stores it again. Paths that hold both take the instance's monitor before
the cluster's.

Filters on ListTagsForResource are accepted without validation: a live account
rejects an unrecognised name, but Floci carries no list of the ones it accepts,
and the tags of one named resource are the same answer either way.

* fix(rds,docdb): store an empty value for a tag given without one

A tag whose Key arrived without a Value was stored with a null, and the read
hands the tags back as an immutable copy, which rejects nulls — so one such tag
made every subsequent read of that resource fail with an internal error, not
just the tag that caused it. A live account stores an empty value and reads it
back.

Both handlers parse tags the same way and both had it.

* fix(rds,docdb): match the whole ARN when routing tags, and give legacy groups one

Two things reported on review.

Routing read the trailing name of the ResourceName ARN and looked it up in
DocumentDB storage, but RDS and DocumentDB share one ARN space: an RDS resource
whose name a DocumentDB record happens to share was answered — and mutated —
out of the wrong store, and an RDS parameter group or option group could be
resolved as a cluster. The whole stored ARN is matched now, which settles
region, account, type and name at once, as the db-cluster-id filter already
does.

And only creation assigned a parameter group's ARN, so a group persisted by an
earlier version read back without one, leaving describe with no ARN to report
and the caller nothing to tag by. The read that backfills a missing region
backfills the ARN too.

The service keeps rejecting an ARN from another region or account: the router
no longer sends it one, but the check guards its own contract, and it is
covered directly rather than through the endpoint.

* fix(rds,docdb): keep one identifier space across the RDS family

Matching the whole ARN still left one ambiguity: an RDS cluster and a
DocumentDB cluster of the same name in the same account and region produce the
same ARN, and a tag call naming it could only reach one of them.

A live account settles it — creating an Aurora cluster named like an existing
DocumentDB one is refused with DBClusterAlreadyExistsFault, because the RDS
family shares one identifier space. Floci already refused that direction, since
a create naming an identifier DocumentDB holds is routed to DocumentDB, which
answers AlreadyExists; the other direction was open, so a docdb create could
take a name RDS already had.

A create naming an identifier RDS holds now goes to RDS whatever engine it
names, so it answers AlreadyExists too and the two stores cannot both hold one
identifier — which is what makes an ARN unambiguous.

* fix(rds,docdb): report a persisted identifier held by both services

Creates can no longer put one identifier in both stores, but state written
before that can, and a restart loads it. For such a record the identifier
checks in the router already send every action to DocumentDB — describe, modify
and delete included — and have long before tags existed, so tags answer from
there too: one identifier keeps one answer, rather than a tag call reaching a
record no describe can show.

The collision is logged once per ARN, since the RDS record behind it cannot be
reached on this scope at all and only deleting one of the two records fixes it.

* fix(docdb): build cluster and instance ARNs from the caller's region

The ARN was built from the configured default region, so a caller signing for
anywhere else got back an ARN naming somewhere they were not — and since a tag
call is checked against the region it is made from, that caller could not tag
the cluster the create had just answered with.

It also reopened the identifier collision from the other side: the create-time
check looked for an RDS record in the request region while the ARN landed in
the default one, so signing the create for another region got past the check and
produced two records under one ARN. DocumentDB keys records by bare identifier,
so the check now covers every region — narrower than AWS, which allows one name
per region, but Floci cannot hold both and answer either correctly.

The check also asked about the wrong identifier for instances: CreateDBInstance
names its parent cluster, and that cluster existing in RDS is the normal case,
not a clash. Only the identifier being created is checked, and the clash is
answered with AlreadyExists directly rather than by handing the create to a
service that rejects the engine first.

* fix(rds): scope the create-time identifier check to the request's region

Widening it to every region broke what RDS actually does: names are scoped by
region, so the same instance name in two regions is two resources, and
RdsControlPlaneTest.sdkScopesTheSameDbInstanceNameBySignedRegion pins exactly
that. The second create answered DBInstanceAlreadyExists.

The cross-region case that widening was meant to cover is closed by the ARNs
instead: each carries the region it was created in, so two records of one name
in different regions never share an ARN and no tag call has to choose between
them. What must not exist is one identifier in both services in one region, and
that is what the check now asks about.

* fix(docdb): decide ownership of an identifier per region

The routing checks asked whether DocumentDB holds an identifier at all, and its
records are keyed by identifier alone, so a name DocumentDB held in one region
was taken away from RDS in every other one: the create was refused as already
existing, and a describe, modify or delete answered from the wrong region's
record.

The region now comes from the one place a record carries it — the ARN — so
DocumentDB claims an identifier only in the region it was created in. Records
written before ARNs carried the caller's region read as the configured default,
which is the region they were in fact created under.

This was true before tags existed; it becomes reachable in a way worth fixing
now that a create in another region records that region rather than the default.

* fix(docdb): check the identifier on every route into DocumentDB

The create-time check lived in the rds credential scope's branch, but
DocumentDB is reachable under its own scope too, and that one dispatches
straight to its handler — which knows only its own store. A create signed that
way could take an identifier RDS already held in the region, which is the state
the ARN matching relies on being impossible.

The check is one method now, called from both routes.

Neptune shares the same identifier space and its scope is not checked either;
that is untouched here, since this PR's invariant is about the ARN a tag call
resolves and Neptune holds no tags.

* fix(docdb): resolve a tag ARN to the record it names, not to the identifier

resolveTagTarget checked the ARN's region against the caller's and then loaded
the record by identifier, and records are keyed by identifier alone — so an ARN
whose region matched the request but named a record stored in another region
resolved to that other record, and tagged it.

Reachable on the docdb credential scope, which dispatches to this service
directly rather than through the routing that matches the whole ARN. The stored
ARN is now compared with the one asked for, and anything else is not found.
2026-08-19 20:23:32 -04:00
mitsukado-shinagawaandmitsukado-shinagawa 498021087f fix(apigateway): match measured JWT claim wire format and enforce route authorizationScopes (#2011)
behaviors still diverge from what real API Gateway delivers to a payload 2.0
AWS_PROXY Lambda (measured against a Cognito-backed HTTP API in ap-northeast-1,
2026-08-05; raw captures in #2011):

- Claim values: array claims rendered as their JSON text and null-valued claims
  as the string "null". Real events use the space-separated bracket form
  (cognito:groups -> "[admin poweruser]"), stringify scalars, omit null-valued
  claims entirely, and fall back to JSON text only for nested objects.
- jwt.scopes: any scope claim was split and surfaced. On real AWS a route
  without authorizationScopes renders "scopes": null even when the token
  carries a scope claim; a route with authorizationScopes surfaces the token's
  FULL scope list (scp array/string first, else scope split on whitespace),
  not the intersection with the route's scopes.
- Route.authorizationScopes did not exist, so scoped routes could not enforce
  anything. Routes now persist and return authorizationScopes on both
  management surfaces (REST and JSON 1.1), and enforcement rejects tokens
  whose scp/scope claim matches none of the route's scopes with
  403 {"message":"Forbidden"} after signature verification.

Co-authored-by: mitsukado-shinagawa <mitsukado-shinagawa@users.noreply.github.com>
2026-08-19 20:03:33 -04:00
Matt Van HornandMatt Van Horn c33508651e fix: serialize Kinesis stream creation timestamps as plain decimals (#2173)
Fixes #2099

Co-authored-by: Matt Van Horn <455140+mvanhorn@users.noreply.github.com>
2026-08-19 19:08:44 -04:00
Saatvik Arya c22652dd15 fix(lambda): resolve ARN and function URL invocations in owning account (#2414)
* fix(lambda): resolve ARN and function URL invocations in owning account

* test(lambda): adapt account routing fixtures to layer service

* fix(lambda): migrate legacy ARN invocation targets
2026-08-19 18:55:21 -04:00
Michal Schreiber 06d58aad36 feat(elasticache): support cache subnet groups (#2401)
* feat(elasticache): support cache subnet groups

CreateCacheSubnetGroup was unsupported, so aws_elasticache_subnet_group could
not be created and no Redis or Valkey module placing a cluster in a VPC could
apply. DescribeCacheSubnetGroups already answered with an empty list, so the
read half existed with nothing behind it.

Adds Create, Modify and Delete, and makes the describe return what was created.

A group's VpcId and each subnet's availability zone come from the subnets rather
than the request, because that is where AWS reads them: resolving the subnets
against EC2 is part of answering, not an optional check. The service follows the
RDS DB subnet group, which faces the same problem.

Taken from a live account: the create response and its ARN, SupportedNetworkTypes
on both the group and each subnet, and the error for each rejection — subnets
that do not exist, subnets spanning two VPCs, a duplicate group, and a name that
breaks the identifier rule. Describe and delete word their not-found differently
from one another, and both are reproduced as AWS words them.

Tags given at create are stored and readable through ListTagsForResource, rather
than accepted and dropped. A modify naming no subnets keeps the stored ones as
they are instead of resolving them again, which would fail a description-only
change if a subnet had since been deleted.

* fix(elasticache): resolve subnet group subnets in the caller's region

CreateCacheSubnetGroup and a subnet-changing ModifyCacheSubnetGroup looked the
subnet ids up in the configured default region. A caller in any other region had
its own subnets rejected as invalid, and the group was reported under an ARN
built from the caller's region while its VPC and availability zones came from
somewhere else.

Resolve against the request's region, which is the region the ARN already uses.

* fix(elasticache): report a subnet group's subnets in the order they were given

describeSubnets answers in the subnet store's own scan order, and the group was
built by iterating that answer, so the order a group reported its subnets in was
arbitrary between calls — the model documents the order the caller gave.

Build the zone map from the requested ids. Adds a CLI case covering the region
the subnets are resolved in, which is what caught this: it read Subnets[0] and
disagreed with itself between runs.

* fix(elasticache): answer a missing cache subnet group with 400, not 404

The service model declares CacheSubnetGroupNotFoundFault a 400, where the
parameter-group fault a few hundred lines up is a 404 — the two really differ,
in the wire code as well as the status, and the status was carried across from
the parameter-group code. All three sites answered 404, and the integration
test pinned it there, so a client reading the status saw the wrong one.

The difference is now stated where the copy would be made, since either fault
looks like a mistake beside the other.
2026-08-19 18:03:54 -04:00
lex00 65b22ff01e fix(memorydb,neptune,docdb): degrade gracefully with no Docker daemon (#2386)
* fix(memorydb,neptune,docdb): degrade gracefully with no Docker daemon

Applies the daemonless degradation pattern (EcrRegistryManager/RdsContainerManager's
tryStart + isDockerReachable seam) to MemoryDB, Neptune and DocumentDB: control-plane
CreateCluster now reaches AWS's documented 'available' steady state with no backing
container when the Docker daemon is unreachable, instead of leaking a raw
SocketException as a 500. Metadata operations (describe, tag, delete) keep working;
only the data-plane connection to the cache/graph/document database stays unavailable
until a daemon appears.

Changed:
- MemoryDbContainerManager, NeptuneContainerManager, DocDbContainerManager: add
  tryStart()/isDockerReachable(), mirroring RdsContainerManager. start() is untouched
  for other callers.
- MemoryDbService.startBackend, NeptuneService.createDbCluster,
  DocDbService.createDbCluster: use tryStart() and proceed with metadata-only state
  (no proxy/container fields, no auth proxy started) when it returns null.

Already done before this change (grepped for tryEnsureStarted|tryStart across
services/ first): ElastiCache (ElastiCacheContainerManager/ElastiCacheMemcachedContainerManager
+ both services) already has this seam — the issue's mention of "elasticache" needing
the fix is stale. EC2 (Ec2ContainerManager) already has an equivalent seam under a
different name (isDockerAvailable()/markContainerlessRunning()); launch, stop, start,
terminate and reboot all already null-check the container id or probe the daemon
before touching Docker, so no EC2 changes were needed.

Left out: dedicated unit tests for EC2's existing daemonless paths (isDockerAvailable,
markContainerlessRunning) — they were already implemented and behaviorally covered by
existing integration tests, and adding manager-level unit tests for the async
executor-based EC2 launch flow is a separable effort from this rollout.

Tests: added tryStart/isDockerReachable unit tests to
{MemoryDb,Neptune,DocDb}ContainerManagerTest (new file for DocDb) covering
daemon-unreachable, genuine-failure and success paths, plus a
createWithoutDockerDaemonStillReachesAvailable service-level test per service
proving control-plane CRUD succeeds and no proxy/container is touched. Existing
tests that stubbed containerManager.start(...) were updated to stub tryStart(...)
to match the new call site.

Refs lex00/floci#44

* test(memorydb,neptune,docdb): log the tolerated teardown IOException

The three new tryStart-reachable tests caught the acceptor socket's
IOException during teardown with only a comment, no log statement,
identically in all three files. Add a debug-level log line per CLAUDE.md's
catch-block rule.
2026-08-19 17:17:56 -04:00
lex00 337dead734 fix(ec2): derive default vpc/subnet/sg ids per region (#2384)
* fix(ec2): derive default vpc/subnet/sg ids per region

The default VPC, subnets, and security group seeded by ensureDefaultResources
used literal ids ("vpc-default", "subnet-default-a/b/c", "sg-default")
regardless of region. Storage was already keyed by region, so nothing
actually collided server-side, but every region echoed identical ids back
to callers, making a region's default resources indistinguishable from any
other region's via the AWS SDK/CLI.

Add Ec2Service.defaultVpcId/defaultSubnetId/defaultSecurityGroupId, which
derive region-scoped ids (e.g. "vpc-default-eu-west-1"), and use them at
every seeding and fallback-resolution call site in Ec2Service. RdsService's
default DB subnet group lookup now calls Ec2Service.defaultVpcId(region) too,
so it keeps resolving against the right region's default VPC.

Updates tests across Ec2Service/Ec2Integration/Eks/ElbV2/AutoScaling/
CloudFormation that asserted on the old literal ids, and adds a regression
test (Ec2ServiceTest#defaultVpcSubnetAndSecurityGroupIdsAreRegionScoped)
asserting two different regions get distinct default vpc/subnet/sg ids.

Fixes lex00/floci#21

* fix(ec2,rds): resolve default vpc/sg ids against persisted storage

ensureDefaultResources skips reseeding a region that already has a VPC on
file, so storage written before default ids were made region-scoped keeps
its old unscoped literal ("vpc-default"/"sg-default") forever. Every lookup
that blindly computed the new scoped id instead of resolving against what
storage actually holds would silently stop finding that region's real
default VPC and security group.

Added Ec2Service.resolveDefaultVpcId/resolveDefaultSecurityGroupId, which
check the scoped id first and fall back to the pre-#21 literal. Used them
at every lookup call site (runInstances' default subnet/SG fallback,
createSecurityGroup's default-VPC fallback, DescribeAccountAttributes,
and RdsService.buildDefaultSubnetGroup's vpc-id filter). Seeding itself is
unchanged, it always assigns the new scoped id for a genuinely fresh
region.

RdsServiceTest mocks Ec2Service, so its shared setup now stubs
resolveDefaultVpcId to match the old static call's behavior.

* test(compat): fetch RDS proxy subnet ids per signed region

sdkScopesTheSameDbProxyNameBySignedRegion reused the shared us-east-1
subnetIds field for both the east and west proxy, which only worked
because default subnet ids collided across regions before #21. Real AWS
scopes subnet ids per region and rejects a cross-region id, which is
exactly what floci now correctly does too.

Added subnetIdsFor(Region) and an ec2Client(Region) fixture, and changed
createIamProxy to take explicit subnet ids instead of the shared field.

* test(cloudformation): use region-scoped subnet ids in the update-reconcile test

dbSubnetGroupTemplate hardcoded the pre-#21 unscoped "subnet-default-a/b"
literals, written before this branch's default-id fix landed. Broke on
rebase since those subnets no longer exist under that name. Matches the
sibling test method in the same file, which already used
Ec2Service.defaultSubnetId(region, az).

* docs(ec2): spell out the #21 comment references

Bare #21 in this repo links to floci-io/floci#21, not the fork issue the
comment means.
2026-08-19 17:14:48 -04:00
yoshinori-aono-om 41ff13e66d fix(dynamodb): return LastEvaluatedKey when Limit stops exactly at the last item (#2389)
* fix(dynamodb): return LastEvaluatedKey when Limit stops exactly at the last item

Query dropped the cursor when the number of evaluated items equaled
Limit, and Scan looked ahead with hasNext() before surfacing it. Real
DynamoDB does not look ahead: any read that stops at the Limit boundary
returns a LastEvaluatedKey, and the client only learns it reached the
end when a follow-up request comes back without one ("the absence of
LastEvaluatedKey is the only way to know that you have reached the end
of the result set"). Verified against amazon/dynamodb-local and
LocalStack 4.12, which both return the cursor at the exact-Limit
boundary for ascending/descending Query, GSI Query, and Scan.

Fixes #2383

* fix(dynamodb): stop reads at the first boundary and skip sparse items in index Scans

Addresses both review findings on #2389:

- Query and Scan now evaluate the 1 MB cap and Limit in a single pass,
  stopping at whichever boundary the read reaches first. Per the Query
  API reference, "if the processed dataset size exceeds 1 MB before
  DynamoDB reaches this limit, it stops the operation", so the size
  check comes first and an item that would cross the cap is not read,
  not counted, and anchors the cursor to the previous scanned item.
  Previously the two caps were independent, order-dependent gates: a
  Limit-truncated page skipped the size check entirely, including the
  exact-Limit case introduced by the previous commit.
- Scan now counts scanned (pre-filter) bytes toward the cap, matching
  the service contract; with a filter, a page can return zero matching
  items and still carry a cursor pointing at an unreturned item.
- Index Scans skip items missing any index key attribute (sparse index
  behavior, same hasNonNullAttribute criterion Query already uses):
  they are never read, never counted, and can never anchor a malformed
  cursor.

Neither amazon/dynamodb-local nor LocalStack implements the 1 MB page
cap (both return a 1.08 MB result set in one page), so the size-cap
expectations follow the documented contract; the sparse-index
expectations were verified against amazon/dynamodb-local.
2026-08-19 16:57:24 -04:00
Mihai BlidaruandMihai Blidaru bba5ffb644 feat(firehose): honor CompressionFormat and FileExtension on S3 delivery (#2410)
Firehose accepted CompressionFormat on the control plane and echoed it back on
DescribeDeliveryStream, but the delivery path never read it: every delivered
object held the raw record bytes, with no compression extension in the key and
no Content-Encoding. The divergence was silent, since only a consumer reading
the delivered objects (Athena over .gz, Spark reading Snappy, anything that
decompresses by extension or encoding) ever saw the wrong bytes.

Deliveries are now compressed the way real AWS compresses them:

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

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

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

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

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

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

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

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

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

Closes #2328

Co-authored-by: Mihai Blidaru <mihai.blidaru@lynxfctech.com>
2026-08-19 16:44:01 -04:00
Michal Schreiber 29b0d600c6 feat(rds,docdb): answer DescribeGlobalClusters (#2402)
* feat(rds,docdb): answer DescribeGlobalClusters

aws_docdb_cluster reads global cluster information as part of every cluster
read, so a cluster that created successfully failed its apply on
UnsupportedOperation — created, but not readable.

DocumentDB's signing name is rds and the action carries no engine or cluster
identifier to route on, so the request reaches RdsQueryHandler whichever service
the caller has in mind; the docdb scope Floci also accepts is answered the same
way. Global clusters are not modelled, so the list is empty, which is what a
live account with none answers.

Behaviour follows a live account: MaxRecords outside 20-100 is rejected before
the identifier is looked up, a named identifier that does not exist is
GlobalClusterNotFoundFault, and a marker is rejected after the identifier. The
response is in the RDS namespace, which is the namespace DocumentDB answers in.

Filters are accepted without validation: every name AWS accepts answers empty
here, and a partial list of accepted names would refuse filters a live account
allows.

* fix(rds): infer rds for DescribeGlobalClusters on unsigned requests

Without a credential scope the service is inferred from the action name, and an
action the RDS handler serves but the inference list does not name is dispatched
to SQS, which answers UnsupportedOperation for it.

* fix(rds): infer rds for every action the RDS handler serves

The inference list that routes unsigned Query requests named 32 of the 43
actions RdsQueryHandler dispatches. The other eleven — the cluster parameter
groups, the option groups, and both snapshot describes — were dispatched to SQS,
which answers UnsupportedOperation for them.

The two sets now match exactly: every dispatched action is inferable, and
nothing inferable is undispatched. None of the added names appear in another
service's inference list, so no existing routing changes.
2026-08-19 15:40:36 -04:00
Michal Schreiber 6b628179f3 feat(elasticache): support cache parameter groups (#2392)
* feat(elasticache): support cache parameter groups

CreateCacheParameterGroup was unsupported, so a Redis module that sets any
parameter could not apply at all — most set at least maxmemory-policy. The
describe was a stub that answered with an empty list whatever was asked of it.

Adds the group surface over the Query protocol:

- CreateCacheParameterGroup, DescribeCacheParameterGroups,
  ModifyCacheParameterGroup, DescribeCacheParameters, DeleteCacheParameterGroup
- ListTagsForResource for a parameter group ARN, without which the tags a create
  carries would be stored and never readable
- the default.* groups AWS publishes for all 13 families, derived rather than
  stored: nothing can modify or delete them, so persisting them would only add
  records to migrate and a writer to race

Taken from a live account: the create response and its ARN, IsGlobal, and the
error each rejection carries — CacheParameterGroupAlreadyExists for a duplicate,
CacheParameterGroupNotFound for an unknown group, and the identifier rule that
rejects a name containing a dot, which is also how AWS refuses to delete a
default group.

Each writer takes one monitor keyed by the group name before it reads. Guarding
the record cannot serve a create, which has no record yet, so two of them would
both pass the existence check; and a modify that resolved its record before
locking would write back a group a concurrent delete had removed.

floci does not carry AWS's per-family catalogue of parameter names, so it stores
what a caller sets and reports it with source "user". Rejecting names missing
from a partial catalogue would refuse configurations AWS accepts, so nothing is
rejected on that basis, and a request for system parameters returns none rather
than reporting user parameters under another source.

* fix(elasticache): answer tags for the ARN that was asked about

ListTagsForResource read the trailing name out of the ARN and ignored the rest,
so an ARN naming another account or region was answered with this caller's
group of the same name — a response describing a different resource than the
request identified.

The ARN is now checked before it is used, with the errors AWS gives for each:
InvalidARN for a string that is not seven components, "Unauthorized call.
Please check the region or customer id" for another region, "The resource ARN
does not belong to the caller's account." for another account, and
"<name> is not present" for a group that does not exist, which is worded
differently from the describe's not-found.

Tightening the tolerated exception in the race test, as review asked, turned up
a second problem: a modify whose group had been deleted reported "is a default
group and cannot be modified", because absence from the store was read as
proof of a published default. The two are now told apart, and both errors are
asserted directly rather than only when the race happens to expose them.

* fix(elasticache): check every component of a tag ARN, not only region and account

An ARN in another service's namespace was accepted as long as its region and
account matched, so arn:aws:rds:<region>:<account>:parametergroup:<name> was
answered with the ElastiCache group of that name — tags for a resource the
caller did not ask about.

The partition and service are checked too, with the errors AWS gives: "partition
field is wrong. Expected value is aws" and "service field is wrong. Expected
value is elasticache".

* fix(elasticache): word each parameter group not-found the way AWS words it

Three actions, three sentences on a live account. Delete omits the space after
the type name — that is verbatim, and the line now says so, because it reads
like a typo and the next person to tidy it would silently stop matching AWS.

Modify was the one that was actually wrong: it answered with describe's
sentence. A live account words it "CacheParameterGroup not found: <name>",
which is neither describe's nor delete's.

Pinned by a test that asserts all three, so the odd one cannot be quietly
aligned with the others.
2026-08-19 15:25:05 -04:00
floverfelt f8b07a78ff feat(lambda): add the ability to name and label lambda containers, code volumes (#2409) 2026-08-19 14:21:47 -04:00
AgustinBertagna 3f12428d97 feat(appsync): Phase 7 — GraphQL execute authentication (#2380)
* feat(appsync): register GraphQL execute controller in the service catalog

Unsigned POST /v1/apis/{apiId}/graphql was not a registered AppSync resource, so the data-plane path could be claimed by other catch-all routes.

* feat(appsync): default API key expiry and reject duplicate auth providers

CreateApiKey now expires in seven days when omitted, caps expiry at 365 days, and looks keys up by value. Create/UpdateGraphqlApi reject duplicate API_KEY, IAM, and Lambda providers.

* feat(appsync): authenticate GraphQL execute requests

Classify credentials by header shape and require a configured provider before GraphQL runs. Request failures return HTTP 401 UnauthorizedException on the data-plane envelope.

* feat(appsync): enforce SDL field authorization on GraphQL execute

Wrap registered fields with AuthorizationDataFetcher so directive mismatch, Cognito groups, IAM field DENY, and Lambda deniedFields stay HTTP 200 with null data and errors[].

* test(appsync): execute GraphQL over HTTP with an SDK-created API key

Cover data-plane success with x-api-key and 401 without credentials after management CreateGraphqlApi/CreateApiKey.

* fix(appsync): match missing-header 401 text and SigV4 precedence

AWS returns Missing authorization header when credentials are absent, evaluates auth before schema, and routes SigV4 Authorization ahead of x-api-key without falling back to the API key.

* fix(appsync): emit field-level Unauthorized GraphQL errors

AWS AppSync returns HTTP 200 with errorType Unauthorized and
Not Authorized to access {field} on type {type}, not UnauthorizedException.

* fix(appsync): omit sourceIp from OIDC identity

Official AppSync OIDC identity is only sub, issuer, and claims.

* fix(appsync): round API key expiry down to the hour

CreateApiKey and UpdateApiKey store expires as epoch seconds rounded
down to the nearest hour, matching the AWS API Reference.

* fix(appsync): match duplicate auth provider BadRequestException text

AWS names the 1-based additional provider index and the repeated type.

* fix(appsync): reject API key expiry outside 1-365 days

CreateApiKey and UpdateApiKey now raise ApiKeyValidityOutOfBoundsException
when expires is not between 1 and 365 days from now.

* fix(appsync): set ApiKey deletes to expires plus 60 days

AWS keeps expired da2 keys for 60 days and returns deletes as epoch
seconds rounded down to the hour.
2026-08-19 11:46:11 -04:00