Commit Graph
3236 Commits
Author SHA1 Message Date
Mario Toffia c1cd5af2bd fix(ecr): advertise the registry at the published address (#4863)
ECR built repositoryUri, the GetAuthorizationToken proxyEndpoint and
the Lambda and ECS image rewrites from floci.port, the port Floci
listens on inside its own container. The Docker daemon performs login,
push and pull, and reaches Floci through the host port that container
publishes. When Floci ran as docker run -p 54321:4566, every advertised
address named port 4566 on the host, where nothing answers, so docker
login, CDK container asset publishing and ECS or Lambda image pulls
failed.

EcrRegistryManager now has advertisedPort(): the host port Floci's
container publishes for floci.port, read through the existing
CurrentContainerNetworkResolver.resolvePublishedPort as RDS does for
its proxy endpoint, or floci.port when Floci is not in a container or
the port is not published. repositoryUri (hostname and path style,
plain and TLS URI mode), proxyEndpoint and rewriteImageUri all use it.

The EKS registry mirror keys must match the URIs pods name, so they
use the same advertised port. The mirror endpoint stays Floci's
in-network address on floci.port.

The resolver now caches every published-port answer, "not published"
and a failed inspect included, as it already caches the network: a
running container's port bindings cannot change, and an inspect that
fails fails the same way next time. ECR requests therefore do not
inspect the container each time.
2026-10-08 20:11:30 -04:00
Allen Sanborn e22bd2c59a feat(ec2): support transit gateway peering attachments (#5122)
* feat(ec2): support transit gateway peering attachments

Add CreateTransitGatewayPeeringAttachment, DescribeTransitGatewayPeeringAttachments,
AcceptTransitGatewayPeeringAttachment and DeleteTransitGatewayPeeringAttachment, the
calls the Terraform provider's aws_ec2_transit_gateway_peering_attachment and
_accepter resources make. Previously each answered UnsupportedOperation.

An attachment is created in pendingAcceptance and moves to available when accepted
from the accepter's region. One attachment id serves both sides, so a cross-region
peering is visible from either region and the transit-gateway-id filter matches either
side's gateway, which is how the accepter finds it. Tags come from the shared tag
store, so CreateTags on the accepter side round-trips through describe.

* style(ec2): order the TransitGatewayPeeringAttachment import

* fix(ec2): hold peered transit gateways and accept peerings only as the peer

DeleteTransitGateway now refuses with IncorrectState while a non-deleted
peering attachment names the gateway at either end, as it already does for
VPC attachments; creation takes the same topology lock so neither lands in
between.

A peering is stored under the requester's account, so lookups search every
account's partition and admit only the two parties, as VPC peering does.
Accept requires the caller to be the accepter's account in the accepter's
region, so a requester can no longer accept its own cross-account request,
and the peer account can now see and accept it. The local-owner-id and
remote-owner-id filters are relative to the viewer's side.

* test(ec2): cover transit gateway peering attachments in the AWS CLI compatibility suite

* style(ec2): drop em dashes from the peering attachment comments

* refactor(ec2): make the peering attachment store final and pass it through the constructor

The StorageFactory constructor now hands the factory-backed store to the
terminal constructor, and the hermetic overload passes an InMemoryStorage,
the same way the other EC2 stores are wired.

* fix(ec2): clear both sides' tags when a cross-account peering attachment is deleted

Tags are per account: each party to a peering sees the tags its own account
set. Deleting the attachment cleared only the caller's, so the other
party's tags outlived it.

* fix(ec2): let a pending peering's accepter delete its transit gateway

Anyone can name any gateway as their peer, so a peering that has not been
accepted no longer holds the accepter's gateway. Deleting that gateway
declines the peering, leaving it rejected. Accepted peerings still hold
both ends, and a pending one still holds its requester's.

* fix(ec2): accept a transit gateway peering only for a gateway the accepter owns

The peer gateway is recorded unresolved at create, so an account could name
another account's gateway as the peer with its own account as PeerAccountId,
accept it, and pin that gateway against its real owner's DeleteTransitGateway.
Accepting now requires the peer gateway to exist in the caller's account and
region, the same lookup create makes for the requester's gateway.

* fix(ec2): route transit gateway peering actions to ec2 without a credential scope
2026-10-08 19:59:39 -04:00
Vũ Thế Huy dc41417e79 fix(ec2): avoid Docker waits on the first CreateVpc (#5179)
* fix: avoid Docker waits on first EC2 CreateVpc

* fix(ec2): reseed default VPC resources after a state reset

Ec2Service now implements Resettable: clear() forgets the seeded account
scopes and seeds the default region again, so a reset followed by
DescribeVpcs still returns the default VPC and subnets.

Also run Ec2CreateVpcLatencyTest in the non-mock EC2 compatibility job,
where VPC planning is active and a regression of the first-call Docker
wait would be caught.

* refactor(ec2): share one default-region seeding method between startup and reset

Ec2Startup and Ec2Service.clear() repeated the same enabled check and seed call. Both now go through Ec2Service.seedDefaultRegionIfEnabled() so they cannot drift apart. Also reorder the Resettable import.
2026-10-08 19:25:31 -04:00
Matt Van HornandMatt Van Horn 37e66ee371 fix(s3): reject aws-chunked S3 uploads whose trailing checksum mismatches (#5176)
* fix(s3): reject aws-chunked S3 uploads whose trailing checksum mismatches

The decoder now keeps each trailer line, keyed by lower-case header
name, and exposes that map once the body has been read. After PutObject,
UploadPart, and the in-memory body read hash the decoded payload, the
checksum named by x-amz-trailer is compared with the computed digest; a
mismatch, a missing trailer line, or a line for a different algorithm
raises 400 BadDigest and the object or part is not published. An
aws-chunked body is hashed with every checksum algorithm so the trailer
can be checked even when it is not the algorithm stored on the object.
Header mismatches use the same text, "The CRC32 you specified did not
match the calculated checksum.", and x-amz-trailer-signature is not
treated as a checksum.

Fixes #5136

* fix(s3): hash only the declared trailer checksum and frame trailer bodies

An aws-chunked body is no longer hashed with every checksum algorithm.
Only the algorithm named up front in x-amz-trailer is added to the
digest set, so a chunked upload with no trailer does no extra hashing.

The decoder keeps just the declared x-amz-checksum-* trailer line and
discards other trailer lines, so trailer storage is bounded. Any other
x-amz-checksum-* line, including one sent with no x-amz-trailer at all,
fails the request with 400 BadDigest.

A body with Content-Encoding: aws-chunked and an x-amz-trailer header
but no streaming x-amz-content-sha256 is now decoded through
AwsChunkedInputStream, so its trailer is verified like a streaming
upload. Without x-amz-trailer the lenient decode is unchanged.

* refactor(s3): resolve x-amz-checksum-* names in one ChecksumAlgorithm helper

Add ChecksumAlgorithm.fromChecksumHeader, which maps an x-amz-checksum-*
header name to its algorithm and returns null for a name it does not
know. S3Controller.trailerChecksumAlgorithm and AwsChunkedInputStream
now both use it, and the stream's private knownChecksum lookup is gone.
fromWireValue shares the same lookup and still throws for unsupported
or unknown algorithm values.

---------

Co-authored-by: Matt Van Horn <455140+mvanhorn@users.noreply.github.com>
2026-10-08 19:18:14 -04:00
MIdhun 63ef2d3a2d fix(kms): return an empty body for operations without output (#5318)
EnableKey, DisableKey, key rotation toggles, aliases, tags, key policy,
description and grant revocation have no output shape. AWS answers them
with HTTP 200 and an empty body; Floci sent {}, which strict clients that
deserialize the output as a unit type reject.
2026-10-08 19:00:18 -04:00
Sam Fakhreddine 89f59dea62 fix(dns): forward queries without per-context ordering (#4643)
Forwards ran through the one-argument executeBlocking, which is ordered per
Vert.x context. Every forward is submitted from the DNS socket's event-loop
context, so one unresponsive upstream or rule target held up forwarding for
every other query until it timed out. Both forwarding paths now go through
submitForward, which passes ordered=false, the same as planQuery already does.

Unordered forwards could otherwise take every thread of the shared worker pool
during a burst of queries to a dead resolver, starving planQuery and the rest
of the emulator, so they run on a dedicated shared executor capped at 8 threads.

Fixes #4606
2026-10-08 18:31:24 -04:00
David PhillipsandJason van Zyl aa94969704 fix(ec2): validate subnet tags before creation (#5306)
* fix(ec2): validate subnet tags before creation

Reject invalid subnet tag specifications before creating a subnet, so
failed requests do not leave resources behind. Include the enclosing
specification in nested tag errors.

* fix(ec2): preserve subnet tag parsing and clean up failures

---------

Co-authored-by: Jason van Zyl <jason@vanzyl.ca>
2026-10-08 15:39:31 -04:00
Mario Toffia 8b1ece9c24 fix(ecr): retry occupied registry ports (#4857)
* fix(ecr): retry occupied registry ports

The backing registry reserved one port from the configured range and gave
up when Docker refused to publish it, although the next port was free. The
allocator's probe races `docker run`, and from inside a container it cannot
see a host process holding the port, so a refusal is expected and not fatal.

A start Docker refuses as a host-port collision now moves on to the next
port in the range; any other failure still fails at once. Refused ports stay
reserved until the start finishes so each is tried once, then are released.
When the range runs out the error names the refused ports. EC2's collision
check moves to PortAllocator so both callers share it.

Closes floci-io/floci#4856

* chore(ecr): keep the port retry tests independent of host ports

The unit tests now use an allocator that skips the host probe, so a busy
6100 or 6101 on the machine cannot change their outcome. The integration
test picks its port pair with the Docker-aware allocator, so a container
already publishing a port is skipped as well, and drops its logger.

* docs(ecr): say other registry start errors still fail at once

The paragraph said startup fails only when the range is full, but a daemon
or image failure still fails without trying another port. The exhaustion
tests now also allocate the last refused port, so releasing only some of
them fails.

* refactor(ec2,ecr): share the port retry loop in PortAllocator

Review asked for the allocate, start and retry loop itself to live in one
place, not just the collision check. PortAllocator.allocateAndStart takes
the start as a callback, moves past ports Docker refuses as in use, and
releases the refused ports when it returns. ECR and EC2 both call it.

EC2 used to mark a refused SSH port reserved for the life of the process.
It now releases it after the launch, as ECR does, so a port whose holder
goes away is usable again.

With the loop moved, a launch cancelled between attempts can now reach
the worker's failure path. When Docker is also gone that path marked the
instance running without a container, so it now goes through markRunning
and leaves a cancelled instance terminated.

* test: share one host-blind PortAllocator across the port tests

PortAllocatorTest, EcrRegistryManagerTest and the ECR port-conflict
integration test each built their own allocator that skips the host
probe. HostBlindPortAllocator replaces the three copies.
2026-10-08 15:31:03 -04:00
Mario Toffia f248eb51af fix(cloudformation): send the stack's StackId to custom resources (#4861)
AWS documents StackId in every Create, Update and Delete request as the
ARN of the stack that contains the custom resource, and handlers rely on
it. #4973 now passes the engine's stack id and stashes it for Delete, but
an engine with no stack ARN still leaks a non-ARN: Cloud Control's
standalone engine uses the stack name as its id, so its custom resources
got StackId "cloudcontrol".

A stack id is now minted when there is no stack ARN to send. A resource
created through Cloud Control has its minted id stashed at Create, so its
Delete repeats it. A resource stashed by an earlier release with no
__FlociStackId, or with a non-ARN one, gets a freshly minted ARN on
Delete, because the delete path does not reach the stack.

An integration test drives Create, Update and Delete through a mocked
handler and checks the event's StackId against Ref AWS::StackId and
DescribeStacks, including a nested stack's own id, and the docs say so.
2026-10-08 14:43:01 -04:00
TATSUNO “Taz” Yasuhiro ebd364e23e fix(lambda): end the invocation when a checkpoint closes a durable execution (#5299)
* fix(lambda): end the invocation at the checkpoint that closes a durable execution

On AWS a checkpoint that closes the execution also ends the invocation.
The history shows InvocationCompleted before ExecutionSucceeded or
ExecutionFailed. A chained invoke started in that batch comes between
them. What the handler returns after that checkpoint is ignored.

The invocation now runs under a request id that Floci picks, so
InvocationCompleted names the same request the function saw.

* fix(lambda): answer a closing durable checkpoint with no operations

AWS answers the checkpoint that closes the execution with an empty
Operations list and no token, even when the batch changed other
operations.

* fix(lambda): fail an unreachable chained invoke before the invocation ends

When a chained invoke target cannot be invoked, AWS logs
ChainedInvokeStarted at its place in the batch and ChainedInvokeFailed
after the batch, before InvocationCompleted. This also holds in a batch
that closes the execution, where Floci logged no ChainedInvokeFailed.
A target that can be invoked still starts after the batch, and after
InvocationCompleted when the batch closes the execution.
2026-10-08 14:34:34 -04:00
Simone Primarosa 6fc957a3b4 feat(eks): join EC2 instances to a cluster as nodes (#5091)
Support joining real EC2 instances to an EKS cluster as Kubernetes nodes.
Inspect instance user data during RunInstances for bootstrap scripts or
nodeadm YAML targeting an EKS cluster, recording pending joins and
reconciling node registration asynchronously via the readiness poller.

Ensure RunInstances returns without blocking on kubectl or shared locks,
and guard storage mutations under the deletion lock so deleted clusters
cannot be resurrected. Scope restoration tracking per account.
Support AL2023 MIME multipart nodeadm configurations, and share the
in-use IP check and cursor loop between subnet and subnetless launches.

Update node metadata derivation to match AWS conventions, using instance
private DNS names for node names and aws:///<az>/<instance-id> for
provider IDs, with topology and instance-type labels.
2026-10-08 11:56:43 -04:00
Hector Ventura 0d4b8cda74 fix(route53): return the health check on a CreateHealthCheck retry (#5298)
* fix(route53): return the health check on a CreateHealthCheck retry

CreateHealthCheck refused any CallerReference already in use with
HealthCheckAlreadyExists. AWS treats the same reference with the same
settings as a retry and returns the health check it already created;
only different settings are refused. The Go SDK resends the same input
after a transient failure, so a Terraform or OpenTofu apply failed on
Floci where it succeeds on AWS. A matching retry now returns the
existing health check, and the docs note that a deleted health check's
reference is reusable at once here, while AWS keeps refusing it.

* fix(route53): compare a CreateHealthCheck retry on every setting it sends

The retry check compared only the seven HealthCheckConfig fields Floci
models, so two requests that differed in an unmodelled setting such as
EnableSNI passed as a retry, and a retry stating RequestInterval or
FailureThreshold at its default was refused as different from one that
omitted it. The controller now records the request's settings in a
canonical form, every value under HealthCheckConfig sorted (Regions and
ChildHealthChecks are sets), with an omitted RequestInterval or
FailureThreshold counted as AWS's default of 30 or 3 except for
RECOVERY_CONTROL, and a retry must match it. A non-numeric Port,
RequestInterval or FailureThreshold is now InvalidInput instead of being
dropped.

* refactor(route53): read the health check settings with XmlParser.extractElementTree
2026-10-08 11:39:52 -04:00
Hector Ventura 4927f71ce1 fix(ecs): look up a task definition without failing on a stored record with no ARN (#5296)
* fix(ecs): look up a task definition without failing on a stored record with no ARN

resolveTaskDefinitionOrThrow compared each stored definition's ARN with
d.getTaskDefinitionArn().equals(ref), so a family or family:revision lookup
threw a NullPointerException when the region held a definition with no ARN.
The comparison is now null-safe, and EcsTaskDefinitionLegacyKeyTest covers a
family lookup next to such a record.

* fix(ecs): answer a missing task definition reference with ClientException

A null or blank reference reached the lookup's comparisons and threw a
NullPointerException, a 500, once the region held any task definition:
the family fallback's family.equals(...) failed even before the
null-safe ARN comparison. It is now refused up front with the same
ClientException an unknown reference gets.

* test(ecs): cover the family lookup in the existing no-ARN test
2026-10-08 11:15:40 -04:00
Vũ Thế Huy d39c7e1381 fix(s3): reject unverified credentials and malformed auth in account routing (#4825) (#5059)
* fix(s3): enforce SigV4/SigV4A algorithm prefix in AccountResolver

* fix(s3): require X-Amz-Algorithm in AccountContextFilter presigned query resolution

* fix(s3): reject malformed Authorization header in S3HeaderSignatureFilter

* fix(s3): reject query presigned requests missing X-Amz-Algorithm in PreSignedUrlFilter

* test(s3): add reproduction tests for unverified credential account routing (#4825)

* fix(s3): isolate presigned query auth and permit SigV4A headers (#4825)

* fix(s3): gate signature checks on validation setting and restore unsigned presigned steering (#4825)

* fix(s3): stop unverified credentials from selecting an account (#4825)

Account selection now requires a SigV4/SigV4A Authorization scheme or a
query string carrying X-Amz-Algorithm. A bare "Credential=" header or an
X-Amz-Credential without X-Amz-Algorithm keeps feeding region resolution
only, so it can no longer steer a request into another account.

Credentials rebuilt outside the header (IAM presigned query, presigned
POST form) now carry the AWS4-HMAC-SHA256 scheme so IAM enforcement still
recognises them. With signature validation on, a query holding only
X-Amz-Signature is rejected with AuthorizationQueryParametersError.

* fix(s3): ignore unsupported Authorization headers for region and keep credential-only download URLs working (#4825)

A header without a SigV4/SigV4A scheme now selects neither account nor
region, so it cannot misattribute S3 data events to another region.

Floci's own download URLs (Lambda layers, Kubernetes init containers)
carry only X-Amz-Credential, so that parameter steers the account and
region again without X-Amz-Algorithm.

* fix(s3): let a present Authorization header win over X-Amz-Credential in account routing (#4825)

IamEnforcementFilter reads the query credential only when no Authorization
header exists. AccountContextFilter fell back to the query whenever the
header was unrecognised, so a malformed header plus X-Amz-Credential picked
an account that IAM then skipped. Both filters now use the same precedence.

* fix(s3): treat a whitespace-only Authorization header as absent in account routing (#4825)

S3's authorization parser ignores a blank header and uses the presigned
query credential, so AccountContextFilter must do the same instead of
falling back to the default account.

* fix(iam): treat a whitespace-only Authorization header as absent in IAM enforcement (#4825)

AccountContextFilter and S3 already ignore a blank header and use the
presigned query credential. IamEnforcementFilter only checked for null, so
a blank header made it find no access key and skip authorization for the
account the query credential had selected. All three now agree.

* fix(s3): presign internal lambda download URLs

* test(macie2): include SigV4 algorithm in account routing check

* docs(s3): list the SigV4A and incomplete presigned URL 400s under signature verification (#4825)

* docs(s3): say Floci does not verify SigV4A signatures yet instead of cannot
2026-10-08 10:58:38 -04:00
Priamo Germosen df4fa58ea1 fix(iam): take service-linked role names and suffix support from AWS evidence (#5293)
CreateServiceLinkedRole guessed both things it cannot derive. The role name came
from capitalising the principal, which is wrong for 141 of the 162 services the
table covers: acm.amazonaws.com is AWSServiceRoleForCertificateManager on AWS and
was AWSServiceRoleForAcm here. And a CustomSuffix was accepted for every service,
where AWS refuses one for 68 of the 71 it has been recorded against, so the
emulator minted roles AWS would have rejected outright.

Both now come from iam/service-linked-roles.tsv, generated by
tools/slr/service_linked_roles.py and gated by make slr-check. One table, because
both facts come out of one pass over the same AWS-validated snapshot: the name
from a recorded create response, the suffix verdict from the test's own
parameterisation. Writing either by hand only captures what someone noticed, and
every finding behind this change came from grepping.

Sources, each row recording its own: recording, actual create responses and the only
source that can establish suffix support; policy-documents, role ARNs in the vendored
AWS managed policies, names only; and docs, from AWS's own service-linked role
pages, quoted and linked in the generator. Counts live in the table's header, where
this script keeps them right.

Two shapes in the policy documents have to be refused rather than read, and both
were being read. A name followed by `*` is a prefix pattern: the policy writes
AWSServiceRoleForAmazonCognitoIdpEmail* where the recorded create returns
AWSServiceRoleForAmazonCognitoIdpEmailService, so reading the prefix invents a role
AWS never mints. Twenty-one principals rested on nothing but such a prefix. And a
role name is unique per account, which these documents ignore: they point
maintenance.elasticbeanstalk at the parent's AWSServiceRoleForElasticBeanstalk, so
taking that at face value made the sibling's create fail as a duplicate of a role
it does not own. A collision guard drops the weaker row back to the derived
fallback and says so; an unresolvable collision is an error for a human.

KNOWN_SOURCE_CONFLICTS is empty as a result. Its one entry was never a
disagreement between sources, only that truncated prefix read as a name. The
mechanism stays for a real one.

make slr-check runs offline: policy-documents rows must still match the vendored
JSON, every vendored service must be in the table, it must be sorted, and a suffix
verdict on a non-recording row is an error because nothing but a recording can
establish one. Three extraction traps have a test each, all three being ones the
real data walked into: an underscore can be part of a name, so splitting on the
CustomSuffix separator truncates ApplicationAutoScaling_CassandraTable; a policy
matching suffixed roles writes the prefix with a trailing separator; and a
wildcard ARN names a role without saying which principal mints it, which is how an
earlier pass handed plain GuardDuty the MalwareProtection role's name.

The name was not only wrong against AWS, it was inconsistent within the tree.
ConnectService built an ARN for AWSServiceRoleForAmazonConnect while
CreateServiceLinkedRole minted AWSServiceRoleForConnect for the same principal:
two roles for one purpose. GuardDutyService, MacieController and RamController
each hard-coded their own name too, and all four were right where IamService was
wrong. They read the table now, and a test fails if a principal any of them builds
an ARN for loses its row, since the fallback would quietly derive a name again.

ApplicationAutoScalingService was wrong a different way. It maps a namespace to a
dimension itself, and had no arm for appstream, cassandra, ec2 or sagemaker, so
all four fell to CustomResource where AWS names them AppStreamFleet,
CassandraTable, EC2SpotFleetRequest and SageMakerEndpoint. It prefers the table
now and keeps its switch for the namespaces nothing records, where the shape is
right even when the dimension is a guess. Its dynamodb arm is gone with the rest:
the table covers that namespace, so the arm was unreachable and a second copy of a
fact the table owns, free to disagree with it while never running. A test pins
dynamodb resolving through the table, since removing the arm is what left nothing
else covering it.

Two behaviour changes worth calling out. rds.amazonaws.com is AWSServiceRoleForRDS
rather than the derived Rds, which flipped one existing expectation. And two table
names are long enough that a suffix alone breaches the 64-character RoleName
limit, ApplicationDiscoveryService's ContinuousExport role leaving three
characters and SageMakerEndpoint six, so that check now reports "The role name"
rather than "The derived role name", which stopped being true.

cloud9 is in the table because deleting IamService's three-entry override map
dropped it: autoscaling and ram were covered, cloud9 was not, and it regressed to
the derived AWSServiceRoleForCloud9. Two tests caught it. Rather than restore the
literal, which is the circular sourcing this work exists to remove, its User Guide
settles it and the row carries that citation.

The table is registered in quarkus.native.resources.includes rather than exempted
from it. AwsManagedPolicies is exempt because parsing its 3.5 MB at image build time
and keeping the result in the heap beats shipping the source twice; at 13 KB that
saving is not worth depending on the static initialiser running at build time, and
NativeImageResourceIncludesTest is the thing that says so.

The header records the sha256 of the snapshot the recording rows came from, because
that half cannot be rechecked offline and --check can only say so rather than fix
it. A digest makes the next --refresh a diff against a known source: an unchanged
digest means any difference in the table came from the vendored policy documents,
and a changed one says the recordings moved with it. --check cannot verify the
digest without the snapshot, but it does reject a table that has quietly lost the
line, or one claiming no snapshot while carrying recording rows.

Refs #5084
2026-10-08 07:49:50 -05:00
Priamo Germosen e452ce8671 feat(codeartifact): add DescribePackage for all package formats (#5308)
DescribePackage returns a package's format, namespace, name, and origin
controls, and answers ResourceNotFoundException for a package that does not
exist. Existence is checked where the package actually lives: stored
generic-format package versions for generic, and each format's sidecar for
maven, npm, and pypi. A package whose name merely starts with another's name
does not match it.

Origin controls are reported as publish ALLOW and upstream BLOCK, the default
CodeArtifact assigns to a package whose first version was published directly.
Floci never ingests packages from upstream and does not store origin controls,
so these values are fixed.

For maven, npm, and pypi the existence check starts that repository's sidecar
if it is not already running, the same side effect the asset bridge has.
RepositorySidecarManager gains packageExists, implemented by each sidecar client.
2026-10-08 07:49:38 -05:00
Mario Toffia 5a8694e97a fix(ecs): accept a service ARN in ListTasks (#4859)
ListTasks looked the serviceName filter up by the string it was given,
so only a bare service name matched. A service ARN, which is what CDK
passes, found no service, and the call returned an empty taskArns list
even while the service had running tasks.

The filter now goes through extractServiceName, the helper UpdateService
and DeleteService already use, which keeps the last path segment. A
name, a full service/<cluster>/<name> ARN, the older service/<name> ARN
and <cluster>/<name> all resolve to the service in the request's
cluster. AWS accepts each of these forms. An unknown service still
lists nothing, which is unchanged.
2026-10-08 07:41:20 -04:00
Hector Ventura ddc47a465d fix(core): make Docker read timeouts real on a Unix-socket host, except for long-lived streams (#5294)
* fix(core): make Docker read timeouts real on a Unix-socket host, except for long-lived streams

docker-java's UnixSocket reads through a blocking channel stream that
ignores SO_TIMEOUT, so on the default unix:// Docker host no call ever
timed out: a 2-second response timeout let a container wait run 153
seconds, and a hung daemon blocked its caller forever. It is also why
httpclient5's stale-connection check, a read with a 1 ms timeout, cannot be
enabled there.

FlociDockerHttpClient now connects to a unix:// host through
UnixDomainSocket, which keeps the channel non-blocking and waits on a
selector, so a read with a timeout fails with SocketTimeoutException. Making
the timeout real would cut off streams that are silent while healthy, so
requests that hold a stream open (container wait, exec and attach output,
followed logs, streamed stats, events, image pulls and builds) get no
response timeout on any host, which also keeps a TCP host's container wait
from dying at five minutes. Every other call keeps the 5-minute timeout.

* fix(core): keep the Unix socket's failures IOExceptions on close and interrupt

Closing the socket while another thread waited in a read or write could
end that wait with the selector's unchecked ClosedSelectorException,
since close() may shut the selector between select() and
selectedKeys(); callers expecting an IOException did not handle it. It
is now a SocketException. A thread reading a silent stream with no
timeout spun once interrupted, because select() returns at once while
the interrupt flag is set; it now closes the socket and throws
ClosedByInterruptException, as the blocking channel it replaced did.

The tests wait with a timed get that expects a TimeoutException rather
than a fixed sleep, so an early return fails at once, and cover a close
during a blocked read and an interrupted read.
2026-10-08 07:27:04 -04:00
Hector Ventura c09c7ae62b chore(elasticache): put restoreCacheCluster's Javadoc back on its method (#5297)
The regionOf helper was inserted between restoreCacheCluster's Javadoc
and the method, so the block describing how a cache cluster is restored
documented regionOf instead, and restoreCacheCluster had none. The
helper now sits above that Javadoc. No behaviour changes.
2026-10-08 07:21:48 -04:00
Priamo Germosen ea77da8a2a refactor(codeartifact): split the pypiserver sidecar into a manager and a client (#5281)
PypiserverSidecarManager now owns only the container lifecycle: starting,
readiness, release, and teardown. The HTTP protocol and PEP 427/440 filename
matching move to PypiserverSidecarClient, which implements
RepositorySidecarManager and is what the registry and CodeArtifactPypiController
use, matching the Verdaccio and Reposilite pairs.

Wire-contract tests move to PypiserverSidecarClientTest against a JDK
HttpServer fake. No behavior changes.
2026-10-07 23:32:27 -05:00
Clement 0848fa6a48 feat(elasticache): add user groups and associate them with replication groups (#4435)
CreateUserGroup, DescribeUserGroups, ModifyUserGroup and DeleteUserGroup
returned UnsupportedOperation, and ModifyReplicationGroup read
UserGroupIdsToAdd as user ids, so RBAC could not be set up the way AWS
and Terraform (aws_elasticache_user_group, user_group_ids) do it.

User groups are now stored resources. CreateReplicationGroup takes
UserGroupIds and ModifyReplicationGroup adds and removes user groups; the
proxy authenticates the members of a replication group's user groups, read
at AUTH time so a ModifyUserGroup applies at once, each by its own
authentication mode. A replication group with a user group associated
admits only its members, even while the group is empty. An id in
UserGroupIdsToAdd that names no user group but names a user still
associates that user directly, so existing setups keep working.

A cache uses either its AUTH token or user groups, as on AWS: while a user
group is attached the token is not accepted and AuthTokenEnabled reads
false. ModifyReplicationGroup takes AuthTokenUpdateStrategy DELETE, which
removes the token and is only allowed together with a user group, and
RemoveUserGroups. Removing the last user group leaves the cache without
access control, still encrypted in transit; a token that was never deleted
applies again. The proxy reads the cache's auth mode per connection, so
these changes take effect without a restart.

Validation follows the RBAC rules: a redis user group needs a user named
default (DefaultUserRequired), members cannot share a user name
(DuplicateUserName), valkey users only join valkey groups, a valkey group
cannot hold a no-password user or serve a redis cache, association needs
in-transit encryption, and a user group in use cannot be deleted
(InvalidUserGroupState). ModifyUser refuses an engine or authentication
change that a user group holding the user would reject. Deleting a user
removes it from its user groups.
2026-10-08 00:24:28 -04:00
Hector Ventura da53fc1c05 docs(partition): document deployment, test coverage and known gaps (#5292)
* docs(partition): document deployment, test coverage and known gaps

partitions.md said every partition-dependent rule had integration tests
over all eight partitions and that the China compat allowlist only
shrinks. Neither is accurate now: most services are tested in China
alone, and the allowlist is empty. The page now states the coverage as
it is (unit tests over every partition, IAM, Step Functions and the
cross-service smoke test through the emulator, China end to end), gives
a recipe for running a China, GovCloud, ISO or EUSC deployment, and
lists the known gaps: global state shared across partitions in one
process (now naming the Identity Center instance, which the smoke
test's inventory exempts for that reason), the commercial managed-policy
catalog, and client tooling untested outside the commercial partition.

API Gateway, IAM and Step Functions gain a Partitions section, and the
WAFv2 scope note names the partition's CloudFront region and where the
CLOUDFRONT scope exists.

* docs(partition): say only custom domains refuse EDGE, and when FLOCI_HOSTNAME is enough

The API Gateway Partitions section said EDGE was refused outside the
commercial partition and that REGIONAL and PRIVATE worked everywhere.
Only custom domains are checked: createRestApi and the REST API update
path accept EDGE in any partition, and createDomainName refuses PRIVATE
in all of them. The section now says so.

The deployment recipe offered FLOCI_HOSTNAME for a different port, but
it replaces only the host and keeps FLOCI_BASE_URL's port, so a
different port needs FLOCI_BASE_URL.
2026-10-07 23:47:52 -04:00
Matheus Oliveira f6e76bbe30 fix(cloudformation): default CreateChangeSet type to UPDATE (#5287)
Follow-up to #5015.

Signed-off-by: Matheus Oliveira <matheus.6148@gmail.com>
2026-10-07 22:36:43 -04:00
Matheus Oliveira 673c809eff fix(lambda): add cookies array to function URL events (#5288)
* Fix #5255

Signed-off-by: Matheus Oliveira <matheus.6148@gmail.com>
2026-10-07 22:35:51 -04:00
Hector Ventura 985921c3db fix(core): fail a Docker call after 30 seconds when its connection pool is full (#5285)
* fix(core): fail a Docker call after 30 seconds when its connection pool is full

With no connection-request timeout set, a call that could not lease a
pooled connection waited httpclient5's default three minutes before failing.
A full pool means the emulator is saturated, so the wait is now configurable
through floci.docker.connection-request-timeout-seconds (default 30), applied
to both pools. The transport retry already treats a lease timeout as pool
exhaustion and never replays it, so the call fails once, after the timeout.

* fix(core): reject a Docker lease timeout below one second

httpclient5 reads a zero connection-request timeout as no timeout, so
floci.docker.connection-request-timeout-seconds=0 let a call on a full
pool wait forever, and a negative value reached the client unchecked.
It now has to be at least 1, checked the way the two pool sizes are,
through one helper that names the setting and its environment variable.

The two producer tests that build the beans from a mocked config now
stub the timeout; they ran with zero before. The lease test's socket
list is shared with the acceptor thread, so it is a concurrent list.
2026-10-07 20:59:11 -04:00
Hector Ventura 2c2ac5dbfa test(partition): smoke-test ARN minting across partitions and gate new minting services (#5282)
* test(partition): smoke-test ARN minting across partitions and gate new minting services

Partition behaviour was proven in the emulator for a few services only.
PartitionCrossServiceSmokeIntegrationTest creates one resource in each of
the seven non-commercial partitions for SNS, Kinesis, Firehose, API
Gateway V2, ELBv2, Glue, IoT, ACM, CodeBuild, Batch and EFS and asserts
the ARN or host carries the request's partition, skipping only where the
vendored data says the partition does not offer the service.

PartitionSmokeInventoryTest scans the service packages that mint ARNs or
AWS hosts and fails unless each is covered by the smoke test or listed
with a reason in src/test/resources/partition/smoke-exemptions.tsv, so a
new minting service cannot arrive without a partition check. The file
starts with 92 rows: 10 covered by an existing partition test, 82 not
yet covered. AGENTS.md adds the step to the new-service checklist.

* test(partition): count direct Arn construction as minting and pin the HTTP API host

The inventory scan did not match new AwsArnUtils.Arn(...), so ssoadmin,
which mints its instance ARNs that way, was neither covered nor
exempted. The scan now matches the constructor, and ssoadmin is exempt
with its reason: one Identity Center instance per account, minted in
its primary region's partition, so a request signed in another
partition sees that ARN (BL-243). AGENTS.md names the constructor too.

The HTTP API case checked only the DNS suffix, so an endpoint minted
with another region of the same partition passed. It now asserts the
whole <apiId>.execute-api.<region>.<suffix> host.
2026-10-07 20:58:44 -04:00
Hector Ventura a3027c07cf fix(lambda): keep watching for a runtime exit after the wait stream fails (#5284)
* fix(lambda): keep watching for a runtime exit after the wait stream fails

The exit watcher streams Docker's wait-for-exit and was never re-armed once
that stream ended with an error. On a tcp:// Docker host the control-plane
client's five-minute response timeout becomes the socket read timeout, and
the stream sends nothing until the container exits, so any container alive
past five minutes lost its watcher: a runtime that crashed after that was
reported as Function.TimedOut instead of Runtime.ExitError, the case #3314
fixed. Any other stream failure (a dropped connection, a daemon restart) had
the same effect on every host.

The watcher moves to LambdaExitWatcher. When the stream ends with an error it
inspects the container: still running re-arms the watch, already exited
reports the inspected exit code, and gone reports nothing. Repeated immediate
failures stop the re-arming, so a daemon that cannot hold the stream does not
spin it.

* fix(lambda): retry the exit watch after a delay, and through a failed inspect

A dropped connection or a daemon restart usually fails the inspect that
follows the stream error too, and that path ended the watch for good;
the quick re-arms also ran back to back, spending the whole budget
within milliseconds of the daemon going away. A failed inspect now
counts as a quick failure, and each quick failure re-arms after a delay
that starts at one second and doubles, up to five in a row (31 seconds
in all). A stream that lived past five seconds still re-arms at once
and resets the count.

The clock and the scheduler are injected, so the tests drive the
backoff, the reset after a long-lived stream, and a failed inspect
followed by the exit it then reports.
2026-10-07 20:46:28 -04:00
TATSUNO “Taz” Yasuhiro 362d89f74f test(iot): retry the Paho WebSocket handshake race in concurrent tests (#5286)
* test(iot): retry the Paho WebSocket handshake race in concurrent tests

Paho 1.2.5 encodes the Sec-WebSocket-Key and checks the server's
Sec-WebSocket-Accept with one Base64 encoder that every client shares
unlocked. Clients that connect at the same time can read each other's
value and fail with "Incorrect Sec-WebSocket-Key" before the server is
involved. The concurrent WebSocket tests now retry that failure only.

* test(iot): set MQTT 3.1.1 inside the Paho WebSocket connect helper

With the default version, Paho answers a failed handshake by reconnecting
as MQTT 3.1, which the broker closes, so the race shows up as
"Connection lost" and is not retried. That is the EOFException of #3763.
The helper now sets 3.1.1 itself, so the race always surfaces as the
handshake error it retries and callers cannot forget the pin.

* test(iot): drop the unit test of the Paho WebSocket connect helper
2026-10-07 20:30:51 -04:00
jwoa95 ecdecf2ae2 fix(apigatewayv2): infer the 2.0 response body and answer function errors with a message (#5153)
* fix(apigatewayv2): infer the 2.0 response body and answer function errors with a message

* fix(apigatewayv2): keep format 1.0 response rules for 1.0 integrations on HTTP APIs
2026-10-07 19:31:34 -04:00
Priamo Germosen 1f1d4f94dd fix(cloudfront): stream origin responses and viewer request bodies (#5278)
A distribution read every origin response whole before answering the
viewer: an S3 origin's object through getObject, a custom origin's body
through the HTTP client into a byte array. A viewer's POST, PUT, PATCH
or DELETE body was likewise read whole before it was forwarded. So an
object or upload of about 2 GiB or more failed, and a smaller one could
run the heap out of memory.

S3 origins now open the object as a stream, the snapshot GetObject
serves, and custom origins return their response before its body is
read; either body is written to the viewer as it arrives, with its
Content-Length, or chunked as the origin sent it. A viewer's body is
streamed to the custom origin with its Content-Length, or chunked when
the viewer sent it chunked or, as HTTP/2 allows, with no length.

An origin response closed before its end, as when the viewer goes away
or a custom error page replaces it, cancels its request instead of
reading the rest of the body to reuse the connection. Since a streamed
response holds its connection for the whole transfer, one origin may
now use the whole connection pool, as CloudFront sets no per-origin
limit.
2026-10-07 18:02:42 -05:00
Priamo Germosen f5d48bb5e0 test(core): compare every Query handler's dispatched actions with its routing (#5279)
#5032 was 28 IAM operations that had drifted out of AwsQueryController's IAM set,
and nothing stopped the two lists drifting apart again, or caught the same gap in
the other Query services. This adds the comparison as a test and pins the gaps
that exist today so they can only shrink.

The test calls inferServiceFromAction itself rather than re-reading the routing
sets, so it measures what requests actually experience, including the chain order.
Only the dispatched-action list is parsed out of handler source, bounded to the
one switch the handler dispatches on: taking every case label in the file picks up
parameter names and state values from other switches, which is why the docs
generator carries per-service exclusions to undo exactly that.

Brace counting runs over a masked copy of the source rather than the source, so a
closing brace inside a comment or a literal cannot end the switch early. Greptile
raised that on the first version, and it is the worst way for this test to fail:
a truncated switch shortens the action list, and a handler with no listed gaps
would keep passing both checks while no longer checking anything. Masking the
comments also stops a commented-out case arm counting as a dispatched action.
Measured across all seventeen handlers, no truncation was happening today, so the
counts below are unaffected; five parser tests cover the cases, each failing with
the masking removed.

Three parity assertions, each probed by breaking it. Dropping a correctly routed
name from its set fails the first. Fixing a listed gap without delisting it fails the
second, which is what stops the list rotting into a place regressions can hide.
The third caught a real mistake while this was being written: StsQueryHandler
lives in the iam package, and the registry pointed at a path that does not exist.

The gaps are 189 entries over 10 services, in a data file so that fixing one is a
line removed. They are not all the same problem, and the file separates them:

  171 fall through to the chain's `return "sqs"` because no set holds the name.
      Mechanical to fix per service, the way #5032 did for IAM, once checked that
      no earlier service claims the name.

   18 are claimed by a service earlier in the chain, so adding the name to the
      right set changes nothing. EC2 owns DeleteTags and Auto Scaling, Redshift
      and ELBv2 all dispatch it; SNS owns ListTagsForResource over RDS,
      CloudWatch, DocDB and Neptune; IAM owns CreateUser and DeleteUser over
      ElastiCache. These need the Version form field, the way isElbClassicRequest
      already reads it, which is a cross-service routing change of its own.

Two things the measurement turned up that are worth knowing. SQS is in the list
despite being the fallback the chain ends in, because being the default does not
help a name an earlier service claims: AddPermission and RemovePermission reach
SNS. And the five services named in the #5227 discussion are ten, the additions
being CloudWatch, CloudFormation, SES, the ELB pair and SQS.

No production code changes here. Fixing any of the 189 is a separate change per
service, each of which deletes its lines from the file.

Refs #5032
2026-10-07 18:01:17 -05:00
Hector Ventura d1fc2654a9 ci: cap open PRs at 4 with drafts and 2 ready for review (#5283)
Describe the new open-PR limits (floci-loft decision 0021) in CONTRIBUTING.md
and the PR template, and grant the caller contents: write, which the shared
workflow needs to convert a PR back to a draft.

Signed-off-by: Hector Ventura <hectorvent@gmail.com>
2026-10-07 17:49:31 -05:00
yarammanasa2001-maxandyarammanasa2001-max 9934b39a42 feat(redshiftserverless): add snapshot and restore operations (#5184)
* feat(redshiftserverless): add snapshot and restore operations

Adds CreateSnapshot, GetSnapshot (by name or ARN), ListSnapshots (filterable
by namespace), DeleteSnapshot and RestoreFromSnapshot on top of the existing
workgroup support. A snapshot is AVAILABLE as soon as it is created, so a
snapshot created in a standby region stands in for a cross-region copy.
RestoreFromSnapshot restores into an existing namespace and workgroup and
never creates either.

* docs(redshiftserverless): document snapshot and restore actions

* docs(redshiftserverless): update service matrix operation count

* fix(redshiftserverless): validate snapshot restore and ARN lookup

Reject a RestoreFromSnapshot workgroup that belongs to another namespace,
resolve snapshotArn only for this account and Region, and register the
snapshot model for reflection so persisted snapshots survive a native restart.

* fix(redshiftserverless): harden snapshot restore and add lifecycle tests

Validate namespaceName and snapshot names, accept snapshotArn on
RestoreFromSnapshot, read the snapshot once during restore, and cover the
handler with an integration lifecycle test and a Java SDK compatibility test.

* feat(redshiftserverless): dump and restore snapshot data and model retention, tags and filters

CreateSnapshot dumps a running workgroup with pg_dump and RestoreFromSnapshot
empties the public schema and replays the dump, reusing the provisioned
Redshift container manager. Snapshots now report adminUsername, kmsKeyId and
retention, accept tags (taggable by ARN), ListSnapshots filters by
namespaceArn, ownerAccount and a time window, and RestoreFromSnapshot rejects
snapshotName and snapshotArn together.

* fix(redshiftserverless): make snapshot restore atomic and strict

Dump the current contents before a restore and put them back when the replay
fails, drop every user schema rather than only public, run psql with
ON_ERROR_STOP so a failing statement fails the restore, and fail a restore
whose recorded dump file is missing.

* fix(redshiftserverless): keep the catalog bootstrap schema out of snapshot restore

The reset dropped floci_internal and with it the pg_catalog svv_external_*
views, so the strict replay failed. Leave that schema out of the reset and
out of the dump.

* fix(redshiftserverless): drop large objects when resetting before a restore

* refactor(redshift): share container lookup and defaults in the container manager

* docs(redshiftserverless): document the bootstrap schema left out of snapshots

* style(redshiftserverless): order imports in the runtime test

---------

Co-authored-by: yarammanasa2001-max <271440416+yarammanasa2001-max@users.noreply.github.com>
2026-10-07 17:08:39 -04:00
Aniket Shukla 43c616d757 test(lambda): clean up hot reload functions (#5205)
* test(lambda): clean up hot reload functions

* test(lambda): preserve creation failures during cleanup
2026-10-07 16:50:27 -04:00
Niels Kootstra 13738f89de fix(cloudformation): reject resources that depend on each other in a cycle (#5208)
* fix(cloudformation): reject resources that depend on each other in a cycle

A template whose resources form a dependency cycle was created anyway: the
topological sort appended the resources it could not order and created them in
template order. CloudFormation rejects such a template with a ValidationError
naming the resources, before any of them is created.

The sort now throws that error when resources remain unsorted, and the
synchronous pre-check that runs before CreateStack, UpdateStack and
CreateChangeSet calls the sort instead of repeating its dependency checks, so
the request fails before any stack state is created.

* fix(cloudformation): keep dependency order when deleting a stack saved with a cyclic template

A stack saved before circular templates were rejected can still carry one.
Deleting it hit the new circular-dependency error while ordering its resources,
so the delete fell back to insertion order for every resource and could remove
a resource before one still using it. The delete now orders what it can and
places the circular resources after it, as before.

* fix(cloudformation): order resources that depend on a cycle when deleting a saved stack

A resource that depends on a dependency cycle cannot be ordered either, so the
delete of a stack saved with a cyclic template ranked such resources in
template order and could remove a target group before the listener using it.
When the sort stalls it now releases a resource on the cycle itself and goes on,
so everything that depends on the cycle keeps its dependency order.

* fix(cloudformation): delete linked dependency cycles in dependency order

When a saved stack's template has a cycle that depends on another cycle, the
sort could release a resource of the dependent cycle before the cycle it uses
was placed, so the delete removed that cycle's resources first. When the sort
stalls it now releases a resource from the first strongly connected component
Tarjan's algorithm completes over the resources left, which depends on no other
cycle.

* fix(cloudformation): order a saved cyclic stack in one pass and name only the cycle

Breaking one cycle at a time searched again at every stall and recursed, so a
long dependency chain could exhaust the thread's stack and stop the delete of a
stack saved with a cyclic template. The resources left at a stall are now
ordered in one pass by their strongly connected components, dependencies
first, with an iterative Tarjan search. The circular-dependency error names only
the components that are cycles, not resources that merely depend on one.

* test(cloudformation): cover circular dependency rejection with the AWS SDK

* test(cloudformation): assert only the cycle's resources in the SDK test's message
2026-10-07 16:39:14 -04:00
Mario Toffia 0f94d6213c fix(apigateway): resolve component parameter references on REST import (#4855)
An OpenAPI 3 operation that listed a parameter as
$ref: '#/components/parameters/<Name>' failed ImportRestApi, PutRestApi
and AWS::ApiGateway::RestApi with an HTTP 500: the document is parsed
without reference resolution, so the parameter arrived with no "in" and
the switch on it threw a NullPointerException.

The import now looks the reference up in components.parameters and maps
the parameter exactly as one written in place. It also accepts the
Swagger 2 form '#/parameters/<Name>', which an
x-amazon-apigateway-any-method keeps because the ANY method is read from
the raw vendor extension after conversion, and skips one naming a body
or formData parameter, as the in-place form is skipped. A reference that
names no component, or a chain of references that loops, fails the
import with a BadRequestException.
2026-10-07 16:07:46 -04:00
Sam Fakhreddine f661923faf feat(codepipeline): roll back a single stage from a successful target execution (#4618)
* feat(codepipeline): roll back a single stage from a successful target execution

RollbackStage now validates the stage and target, then re-runs only the source stages and the target stage as a ROLLBACK execution.

* fix(codepipeline): keep a rollback's stage filter across restart and retry

Persist the rolled-back stage name and derive the include-stages filter from it on start, resume and retry.

* fix(codepipeline): tighten RollbackStage eligibility, trigger type, events and source pinning

* fix(codepipeline): report a busy pipeline from RollbackStage as ConflictException

* fix(codepipeline): refuse rollbacks of source stages, rollback targets and running stages

RollbackStage now answers UnableToRollbackStageException when the stage is a source stage, when the target execution is itself a ROLLBACK execution, or when another execution is still running the stage, per the CodePipeline User Guide considerations for rollbacks.

* fix(codepipeline): reject RollbackStage on PARALLEL pipelines and close the concurrent rollback window

RollbackStage now answers ValidationException for PARALLEL pipelines, checks for a running stage (including a rollback still fetching sources) under the pipeline start lock, records the manual-start triggerDetail instead of the target id, and shares one source-action helper.
2026-10-07 15:54:47 -04:00
Sam Fakhreddine b9625bf7f7 fix(lambda): check the RevisionId precondition in UpdateFunctionCode (#4641)
* fix(lambda): check the RevisionId precondition in UpdateFunctionCode

Fixes #4639

- M1 PASS: RED run: [ERROR] io.github.hectorvent.floci.services.lambda.LambdaServiceTest.updateFunctionCode_withMismatchedRevisionId_throwsPreconditionFailedException -- Time elapsed: 0.457 s <<< FAILURE!
- M2 PASS: gates green, last summary: [INFO] Tests run: 192, Failures: 0, Errors: 0, Skipped: 0
- M3 PASS: 2 file(s), all in scope
- M4 PASS: no new public members in main code
- M5 PASS: main diff 11 changed lines, limit 25
- M6 PASS: no em-dash in added lines
- A1 PASS: `LambdaService.java:+671-+678` throws `AwsException("PreconditionFailedException", "...", 412)`; `LambdaServiceTest.java:+1780-+1781` asserts exact code, status, and message literals.
- A2 PASS: `LambdaService.java:+671-+678` sits before all `fn.set...` calls; `LambdaServiceTest.java:+1770-+1788` captures `initialRevisionId` before call and asserts `unchangedFn.getRevisionId()` matches it.
- A3 PASS: `LambdaServiceTest.java:+1790-+1794` sends matching RevisionId and asserts update succeeds; Gate 2 output `Tests run: 192, Failures: 0, Errors: 0, Skipped: 0` confirms no regression.
- A4 PASS: `LambdaServiceTest.java:+1779` invokes public `service.updateFunctionCode(...)`; `LambdaServiceTest.java:+1780-+1781` asserts literal error code `"PreconditionFailedException"` and status `412`.
- G1 PASS: `LambdaService.java:+671-+678` directly implements the missing optimistic locking logic identified in the diagnosis, not a test workaround.
- G2 PASS: `LambdaServiceTest.java:+1780-+1781` asserts hardcoded literals for errorCode, httpStatus, and message; `LambdaServiceTest.java:+1788` asserts exact pre-call `initialRevisionId` value.
- G3 PASS: Diff modifies only `LambdaService.java:+671-+678` (a guard clause); Gate 2 shows 0 failures across the full suite, proving other paths are untouched.
- G4 PASS: `LambdaServiceTest.java:+1780-+1781` enforces AWS-correct `PreconditionFailedException` and `412`; `LambdaServiceTest.java:+1788` verifies state is unmutated after rejection.

* refactor(lambda): share the RevisionId precondition check

UpdateFunctionCode and UpdateFunctionConfiguration now call one helper. The stale-RevisionId test also asserts CodeSha256 is unchanged after the rejected call, so it fails if the check moves below code extraction.

* fix(lambda): use the RevisionId mismatch message AWS returns
2026-10-07 15:50:23 -04:00
Salil Chincholikar d0fec13cae fix(s3): url-encode event record keys and add sequencer (#5192)
* fix(s3): url-encode event record keys and add sequencer

S3 event notification records now carry s3.object.key form URL-encoded
as AWS sends it (space as +, + as %2B, / kept) and an s3.object.sequencer
of 18 uppercase hex digits that increases for every event.

* fix(s3): assign the event sequencer when the object is stored

The sequencer was taken when the notification was built, after the bucket
lock was released, so two concurrent writes to one key could get values in
the reverse of the order they were stored in. It is now assigned in
storeObjectInternal under the bucket lock and carried on the stored object
for its ObjectCreated event. Any other event names an object that already
existed, so it still takes a new value when it is built.

* fix(s3): take annotation event sequencers under the bucket lock

putObjectAnnotation and deleteObjectAnnotation fire their notification
after the bucket monitor is released, so an overwrite of the key landing
in between could get a lower sequencer than the annotation event for the
object it replaced. Both now take the sequencer inside the synchronized
block and hand it to fireNotifications, as the delete paths already do by
firing inside it.
2026-10-07 15:36:27 -04:00
Kenshin Okinaka 86371d86cb fix(ses): match AWS tag ARN parsing and configuration set name errors (#5235)
* fix(ses): match AWS tag ARN parsing and configuration set name errors

The SES v2 tag endpoints rejected malformed ARNs with messages that were
never checked against AWS, refused ARNs whose service was not "ses", and
compared the region before checking the resource exists. Configuration
set names were rejected with an invented message on both APIs.

Probed against AWS in us-west-2:

- Every malformed ARN (missing partition, service, account or resource
  name, unknown type, ":" or "/" in the name) is BadRequestException
  "ResourceArn is not the expected format", including an unknown type,
  which was a 404.
- The partition and service are required but never compared.
- An invalid configuration-set name in the ARN is a message-less
  ValidationException after the account check.
- TagResource and UntagResource check existence before the region.
- An omitted ResourceArn on Tag/Untag is a message-less
  ValidationException. ListTagsForResource keeps a 400 where AWS
  answers 500.
- "ResourceArn=" is read raw, since @QueryParam binds an empty value
  as null.
- Configuration set names use AWS's three messages on every v1 and v2
  operation, including sends: must be specified, cannot exceed 64
  characters, and invalid characters.

* refactor(ses): share the configuration set name check and map tag domains by type

The v1 helper and the v2 CreateConfigurationSet handler now call the
service's validateName instead of repeating the empty-name check, and the
name pattern no longer restates the 64-character limit the length check
owns.

The seven taggable domain services implement SesTaggable, and SesService
keys them by ARN type in one map. That map replaces the type set and the
three dispatch switches, whose default arms could no longer be reached.
2026-10-07 14:27:36 -04:00
Salil Chincholikar 74b3cecf78 feat(ses): support Content.Simple.Attachments in SESv2 SendEmail (#5190)
* feat(ses): support Content.Simple.Attachments in SESv2 SendEmail

Parse and validate Simple attachments, assemble them into one MIME message
with the relay's encoder, run the content scan over it as for raw sends,
relay them over SMTP, and expose them in the /_aws/ses mailbox as an
Attachments summary plus the base64 MIME message in RawData.

* fix(ses): sort SesService imports and document attachment encoding and RawData recipients

RawData keeps the To and Cc recipients the request named, including any
suppression later kept from delivery, and ContentTransferEncoding is validated
but every attachment part is base64-encoded. Both are now stated in the SES docs.

* fix(ses): reject line breaks in attachment MIME header members

ContentType, ContentDescription and ContentId are written verbatim into the
attachment part's MIME headers, so a CR or LF in any of them added header lines
to that part. They are now refused with BadRequestException by the same rule
MessageHeader.isSafe applies to custom headers. missingHeaderMember now builds
its message through constraintViolation.

* fix(ses): refuse attachments with unsupported file extensions

SES does not accept attachments whose file names end in one of the
extensions listed under "SES unsupported attachment types" in the developer
guide. The content scan now walks the parsed MIME for attachment file names,
from Content-Disposition or the Content-Type name parameter, and both the
Simple-with-attachments and raw send paths refuse such a message with
MessageRejected before anything is recorded.

* refactor(ses): share one MIME part walk between the content scans

hasBlockedAttachment repeated the worklist entityContains already used.
Both now go through anyPart, which walks every part, forwarded messages
and multiparts included, and runs the given check on each.
2026-10-07 14:22:34 -04:00
Allen Sanborn 4eae79d546 fix(ec2): canonicalize VPC and subnet CIDR blocks on create (#5214)
* fix(ec2): canonicalize VPC and subnet CIDR blocks on create

AWS stores the IPv4 CidrBlock of CreateVpc and CreateSubnet in canonical
form ("100.68.0.18/18" becomes "100.68.0.0/18"); Floci stored it
verbatim. Canonicalize once at the top of createVpc and createSubnet so
the stored block, the VPC CIDR association, the subnet conflict check and
the network declaration all use the canonical value. A null subnet CIDR
(IPv6-only subnet) stays null.

The CloudFormation VPC and subnet provisioners compare the template's
CidrBlock against the stored one to decide reuse on update; compare in
canonical form so an unchanged template with host bits set is not
replaced on every update.

* fix(cloudformation): compare saved VPC and subnet CIDRs canonically on update

VPCs and subnets persisted before CIDR canonicalization can still hold host
bits (10.0.1.9/24). Canonicalizing only the template side made an unchanged
range look changed after upgrade: the subnet path called createSubnet and hit
InvalidSubnet.Conflict, the VPC path created a replacement. Canonicalize both
sides of the reuse comparison.

* docs(ec2): generalize canonicalizeIpv4Cidr to its VPC and subnet callers

The helper now canonicalizes CreateVpc and CreateSubnet CIDRs as well as
route destinations, but its Javadoc and parameter name still described
DestinationCidrBlock only. Rename the parameter to ipv4CidrBlock, cover all
three callers in the Javadoc, and drop its em-dashes. No behavior change.

* refactor(cidr): add CidrCanonicalizer.sameBlock for the provisioner comparisons

The subnet and VPC reuse checks each canonicalized both sides inline. Move
that comparison into one helper next to canonicalize, with the same
fallback to the raw string for an unparseable side and the same null
handling. No behavior change.
2026-10-07 14:09:24 -04:00
TATSUNO “Taz” Yasuhiro ee2d1a68a6 feat(cloudformation): pass Lambda DurableConfig through (#5218)
* feat(cloudformation): pass Lambda DurableConfig through

AWS::Lambda::Function.DurableConfig reaches CreateFunction and
UpdateFunctionConfiguration. As on AWS, a RetentionPeriodInDays the
template leaves out is 14 on update too, a durable function created
without Timeout gets min(ExecutionTimeout, 900), and adding or removing
DurableConfig replaces the function.

* test(terraform): cover aws_lambda_function durable_config

The provider creates a durable function, reads it back without a diff,
updates execution_timeout in place, and before destroy stops a RUNNING
durable execution through ListDurableExecutionsByFunction,
StopDurableExecution and GetDurableExecution.

* fix(cloudformation): honor AWS::NoValue, cleared keys and large numbers in DurableConfig

A DurableConfig that Fn::If removes with AWS::NoValue leaves the
function plain. A KMSKeyArn the template leaves out or sets to "" clears
the key, as CloudFormation does on AWS, since Lambda keeps a stored key
when the update omits the member. A number beyond an integer reaches
Lambda unchanged, so its range check rejects it.

* fix(cloudformation): reject a DurableConfig that is not an object

Only an intrinsic that resolves to AWS::NoValue removes DurableConfig.
CloudFormation rejects a string, number or list in its schema check
before the function is touched, so an update with one no longer
replaces and deletes a durable function.

* test(cloudformation): cover Lambda DurableConfig with the AWS SDK

The CloudFormation and Lambda SDK clients create a durable function,
update DurableConfig in place, and remove it by replacing the function.

* fix(cloudformation): require ExecutionTimeout and known members in DurableConfig

CloudFormation checks DurableConfig against the schema on update too: an
update without ExecutionTimeout, or with a member the schema does not
list, fails before the function is touched. Floci let such an update
through and kept the old timeout.

* refactor(cloudformation): look up a Lambda function once per deploy

The name choice and the replacement decision now share one lookup and one
durable check, so they cannot disagree.
2026-10-07 12:39:36 -04:00
Younes Beriane bdb37f0ca3 fix(rds-data): accept parameter names that start with a digit (#5119)
* fix(rds-data): accept parameter names that start with a digit

* fix(rds-data): do not treat array-slice bounds as numeric parameters

* fix(rds-data): decide array slices at the opening bracket

A [ right after a name other than ARRAY, a ] or a ) is a subscript, and a
:digit directly inside it is a slice bound however it is spaced. ARRAY[:1]
is a constructor, so :1 there stays a parameter. Tests use no var.

* fix(rds-data): track the last operand to tell slice bounds from parameters

Inside an array subscript a :digit is a slice bound only after an operand
(or directly after the opening bracket) and a parameter after an operator,
comma or paren, so arr[1 + :1] binds :1. The scan now remembers the last
significant token, skipping comments, so arr /* note */ [1:2] is still a
subscript.

* fix(rds-data): drop clause words from the non-operand keyword list

SET, BY, VALUES, SELECT, FROM, WHERE, ON and RETURNING never sit right
before a [ or a :digit inside a subscript, and a column may carry such a
name, so set[1:2] no longer turns :2 into a parameter. Make
isNonOperandWord a switch expression.
2026-10-07 11:29:50 -04:00
jwoa95 c6369b321a fix(apigatewayv2): send cookies and comma-joined duplicates in the 2.0 event (#5152)
* fix(apigatewayv2): send cookies and comma-joined duplicates in the 2.0 event

* fix(apigatewayv2): send cookies and comma-joined duplicates to the 2.0 Lambda authorizer

The HTTP API Lambda authorizer gets the same 2.0 payload as the integration, so both builders now share one helper for cookies, headers and queryStringParameters.
2026-10-07 10:53:50 -04:00
jwoa95 1199f3a790 fix(rds): forward PostgreSQL startup parameters through the proxy (#5151)
* fix(rds): forward PostgreSQL startup parameters through the proxy

The RDS proxy parsed the client's StartupMessage but opened the backend
session with only user and database, so options, application_name and
every other run-time parameter were silently dropped.

Forward them in the order the client sent them. The proxy keeps setting
user and database itself, and drops _pq_. protocol extension requests,
which it does not negotiate with the backend.

An IAM login for a role other than the master still sends only user and
database: its backend session is the master's until the handover, and a
startup "-c role=<master>" would outlive SET SESSION AUTHORIZATION, so
RESET ROLE would regain the master. Redshift keeps today's behaviour, as
its drivers send parameters PostgreSQL rejects.

* fix(rds): relay PostgreSQL's refusal of the backend login to the client

Forwarding startup parameters makes new backend refusals possible, such as
replication=true with no pg_hba.conf entry allowing it. PostgreSQL answers
those with an ErrorResponse where the proxy expected an Authentication
message, and the proxy reported only "Backend database authentication
failed". Every read that expects an Authentication message now reads a
refusal whole and the proxy sends it to the client unchanged, so the client
sees PostgreSQL's SQLSTATE and reason. This covers a refusal before the
password exchange and one after it. Other unexpected replies keep the
generic error.

* test(rds): reuse the IAM auth harness and the handler's startup parser

Fold the IAM startup-parameter check into iamSessionRunsAsTheRoleNamedInTheToken, let backendStartupFor start its auth thread through startIamAuth, and make PostgresProtocolHandler.parseStartupParams package-private so the test no longer keeps its own copy.
2026-10-07 10:42:11 -04:00
Mario Toffia efd9512578 fix(cloudformation): accept the stack ID in UpdateStack and CreateChangeSet (#4846)
* test(cloudformation): cover UpdateStack and CreateChangeSet by stack ID against AWS

* fix(cloudformation): accept the stack ID in UpdateStack and CreateChangeSet

StackName is "the name or the unique stack ID" for both actions, but an
UPDATE change set looked the stack up by the raw value, so a stack ARN
missed the name-keyed map and failed with "Stack with id ... does not
exist". Resolve the canonical stack name first, as ExecuteChangeSet
already does, and record it on the change set. CREATE change sets are
unchanged.

Closes #4842

* fix(cloudformation): refuse updating a stack that has finished deleting

A delete marks the stack DELETE_COMPLETE before it leaves the live map, so an
update in that window was accepted and its persist could revive the stack.
An update of a DELETE_COMPLETE stack now reports that the stack does not exist.

* test(cloudformation): delete each stack once after the stack ID tests

* test(cloudformation): wait until a deleted stack's name is free before reusing it

Floci reports DELETE_COMPLETE just before it drops the stack, so a same-name CreateStack
could hit AlreadyExistsException; wait until DescribeStacks no longer finds the name.

* test(cloudformation): name the stale stack ID test plainly

* fix(cloudformation): refuse a deleted stack's ID with AWS's DELETE_COMPLETE message

UpdateStack and UPDATE change sets given the stack ID of a deleted stack now fail with
"Stack:<id> is in DELETE_COMPLETE state and can not be updated.", as measured on AWS.
A stack name, or a stack ID that never existed, still gets "does not exist".
2026-10-07 10:14:11 -04:00
Aniket Shukla d8b170a144 fix(rds): restrict custom endpoint mutations to Aurora (#5206)
* fix(rds): restrict cluster endpoints to Aurora

* fix(rds): preserve legacy cluster endpoints

* fix(rds): align cluster endpoint restrictions
2026-10-07 09:52:42 -04:00
Hector Ventura 9d49e619c1 fix(appsync): front custom domains with the partition's CloudFront zone (#5237)
* fix(appsync): front custom domains with the partition's CloudFront zone

CreateDomainName returned a random hosted zone id and an appsync-api
regional host as appsyncDomainName. AppSync serves a custom domain
through CloudFront: the CDK aliases appsyncDomainName into the
partition's CloudFront hosted zone (aws-route53-targets AppSyncTarget),
so a DNS alias built from Floci's answer pointed at a zone that does not
exist. The domain now gets a CloudFront distribution name on the
configured CloudFront suffix and the partition's CloudFront hosted zone
(Z2FDTNDATAQYW2 in aws, Z3RFFRIM2A3IF5 in aws-cn), as an edge-optimized
API Gateway domain does.

* refactor(appsync): share the CloudFront front with edge-optimized API Gateway domains

An AppSync custom domain and an edge-optimized API Gateway domain both
get a CloudFront distribution name and the partition's CloudFront hosted
zone, and the two services built that pair with the same copied
statements. CloudFrontEdgeDomain now builds it once for both.

RequestRegionArnIntegrationTest still expected appsyncDomainName to
carry the request region; it now asserts the CloudFront form, while its
domain ARN assertion keeps checking the region.
2026-10-07 09:34:02 -04:00
Allen Sanborn 73133b472a fix(mq): return CreateBroker members from DescribeBroker (#5211)
* fix(mq): return CreateBroker members from DescribeBroker

CreateBroker accepted securityGroups, subnetIds, logs,
maintenanceWindowStartTime, storageType, authenticationStrategy,
encryptionOptions and configuration, but discarded them, so
DescribeBroker never returned them. Carry them through
CreateBrokerParams to the persisted Broker and into the DescribeBroker
response, with configuration reported as configurations.current as in
the AWS shape. Absent members are omitted, and brokers persisted before
this change still load.

RabbitMQ users stay out of DescribeBroker (#1951).

* fix(mq): report DescribeBroker logs as a LogsSummary

general and generalLogGroup are required in LogsSummary; general defaults
to false and the log group is /aws/amazonmq/broker/<broker-id>/general.
audit/auditLogGroup are reported only when audit logging was requested.

* fix(mq): report only the general log group in LogsSummary

Audit logs are ActiveMQ-only, and Floci emulates RabbitMQ brokers.
Document DescribeBroker's logs as a LogsSummary rather than an echo.

* fix(mq): stream broker logs to the general log group DescribeBroker reports

RabbitMqManager streamed container logs to /aws/amazonmq/broker/<id>
while DescribeBroker named /aws/amazonmq/broker/<id>/general. Both now
take the name from Broker.generalLogGroup().
2026-10-07 09:14:41 -04:00