Commit Graph
2457 Commits
Author SHA1 Message Date
XuJian 3df7fb17ee fix(ec2): decode CloudFormation launch template user data (#4711)
* fix(ec2): decode CloudFormation launch template user data

* fix(ec2): bound and recover launch template user data

* fix(ec2): honor explicit user data over legacy templates
2026-09-30 21:45:28 -05:00
Mario Toffia a338a430cc feat(cloudformation): provision Cloud Map namespaces and services (#4599)
* feat(cloudformation): provision Cloud Map namespaces and services

AWS::ServiceDiscovery::PrivateDnsNamespace, PublicDnsNamespace,
HttpNamespace and Service were stubbed, so a stack reported them created
while nothing existed in Cloud Map and Fn::GetAtt resolved to literals.

CloudMapCfnProvisioner creates them through CloudMapService. Ref returns
the id; Fn::GetAtt exposes Id and Arn, HostedZoneId on a DNS namespace and
Name on a service. An unnamed service is named <LogicalId>-<12 chars>, as
measured on AWS. Description, DnsConfig, HealthCheckConfig and Tags update
in place; a createOnly change replaces the resource through
ReplacementCleanup, and a rolled-back replacement restores the createOnly
record. A Ref to a Number parameter is coerced back to a JSON number for
DnsRecords TTL and FailureThreshold.

Closes #4596
* fix(cloudformation): roll back in-place Cloud Map updates

An in-place namespace or service update followed by a later resource
failing left the Cloud Map changes live and the stack in
UPDATE_ROLLBACK_FAILED, since rollbackUpdate only undid replacements.
The provisioner now keeps the description, DnsConfig, HealthCheckConfig
and tags an in-place update overwrites and puts them back on rollback;
a committed update drops the snapshot.
* fix(cloudmap): reject DNS record type changes on service update

UpdateService only changes the TTLs of a service's existing DNS records on AWS. An in-place CloudFormation update that changes the record types, or gives a DnsConfig to a service without one, now fails with InvalidInput instead of being applied, so it rolls back like on AWS and a rollback never has to remove a DnsConfig.
* fix(cloudmap): accept only TTL changes in a service DnsConfig update

UpdateService carries only DnsRecords on AWS and CloudFormation does not support a RoutingPolicy update. Comparing the record types as a set let a RoutingPolicy change or an added record of the same type through; the requested and stored DnsConfig now have to match apart from the TTLs.
* fix(cloudmap): ignore DNS record order in a service DnsConfig update

A TTL-only update that listed the same records in another order was rejected. The comparison now uses the sorted record types, so counts, types and RoutingPolicy still have to match.
* test(cloudformation): restore a real HealthCheckConfig in the Cloud Map rollback test

The in-place rollback test went from a null health check config to null, so dropping it from the snapshot would have passed.
2026-09-30 21:45:18 -05:00
jwoa95 31038ee2a4 feat(cognito): add GetUserAuthFactors (#4764)
* feat(cognito): add GetUserAuthFactors

* fix(cognito): refuse access tokens with no scope claim where a scope is required

* fix(cognito): use AWS's message for a missing access-token scope
2026-09-30 21:45:10 -05:00
jwoa95 a0be062f9f fix(cognito): honour admin_only account recovery (#4762) 2026-09-30 21:45:00 -05:00
TATSUNO “Taz” Yasuhiro 7654a7cbec fix(appsync): supply reflection config so VTL runs on native image (#4729)
* test(appsync): run a VTL resolver in the native compatibility suite

AppSyncTest created and updated resolvers but never queried one, so no native test evaluated a VTL template. The new test runs a query whose templates touch everything VTL reaches through reflection: the #return directive, $ctx and the JDK maps, lists and strings behind it, each $util helper, and $util.error.

* fix(appsync): register what VTL reaches through reflection in the native image

Velocity loads the #return directive by class name and calls every template method through reflection. None of it was registered, so in the native image every AppSync mapping template failed. Register the directive, the $util helpers, and the JDK maps, lists and strings that $ctx, literals and $util results are made of.
2026-09-30 21:44:51 -05:00
stodan 123941dd03 chore(cloudformation): remove the unused hasPendingRollbackCleanup hook (#4515) 2026-09-30 21:22:44 -05:00
Abhigya d73e33fe4b fix(ecs): pull task images at launch so a moved tag reaches the next task (#4583)
* fix(ecs): pull task images at launch so a moved tag reaches the next task

Floci resolved an image reference to an image id the first time it saw it and
reused that id for the life of the process, so a rebuilt :latest pushed to the
registry never reached a new task, even through a new task definition revision
and a forced deployment, and nothing reported the mismatch.

ECS now pulls every container image when a task starts, before creating any of
its containers, following the agent's ECS_IMAGE_PULL_BEHAVIOR (configurable as
floci.services.ecs.image-pull-behavior, default "default": pull, and fall back
to the cached image when the pull fails). The cached image is whatever the
local tag names at launch rather than a remembered id. Each container reports
the manifest digest it runs as containers[].imageDigest.

* fix(ecs): create task containers from the image id their pull resolved to

An overlapping RunTask could pull the same moved tag between this task's pull
and its container creation, so the container was created from whatever the
shared tag cache named by then while reporting the digest this task pulled.
resolveForLaunch now returns the resolved image id with its digest, and ECS
builds each container from that id, so the image a task runs and the digest it
reports always come from the same pull.

The pull also now uses the reference the container is created from, including
floci.docker.image-registry-base, instead of the unprefixed name.

* fix(ecs): launch image ids without a pull and report the digest the pull resolved

A bare sha256 image id under always, or on the first once launch, went to the
registry as if it were a repository reference and failed the task although the
image was local. resolveForLaunch now runs an image id as it is, like
ensureImageExists.

The reported digest took the first RepoDigests entry for the repository, which
is not necessarily the manifest the tag resolved to when the image holds more
than one (an index and a platform manifest). It now comes from the Digest line
the daemon streams for the pull, kept while the tag still names that image; a
cached image falls back to its repo digest only when there is exactly one.

The shared test config uses prefer-cached so the other ECS Docker suites stop
adding a registry round trip per launch; the image pull integration test pins
default in its own profile. ContainerBuilder imports are back in order.

* fix(ecs): report a pull's digest only for the launch that pulled

The digest a pull reported was kept per reference and reused while the tag
still named the same image id, but on the classic image store an id is the
config digest and several manifests can share it, so an outside pull could move
the tag to another manifest and leave the reused digest stale. Only the launch
that pulled now uses the streamed digest. A cached launch uses the image's
repo digest for the repository when there is one, or the one equal to the id
(the containerd store names an image by its manifest), and otherwise none.

Also sorts the ContainerLifecycleManager imports.

* fix(ecs): pull the image-pull test's busybox and registry from Docker Hub

EcsImagePullDockerIntegrationTest pulled both images through the
public.ecr.aws/docker/library mirror, whose anonymous quota is shared per
runner IP; shard 3 failed on toomanyrequests: Data limit exceeded. Take
them from TestImages like the other Docker-backed tests, pinning the
registry image there, and prefetch both for the shard that runs the class.

* test(ecs): name the registry readiness probe's tolerated exception expected
2026-09-30 22:14:50 -04:00
XuJian bc42cee767 fix(rds): warn once for failed cluster member relays (#4721)
* fix(rds): warn once for failed cluster member relays

* fix(rds): reset member relay warning after restart

* fix(rds): retain relay warning state until recovery
2026-09-30 21:52:16 -04:00
TATSUNO “Taz” Yasuhiro be21e86057 fix(sqs): match AWS on stale, gone and invalid receipt handles (#4730)
* fix(sqs): reject empty, malformed and foreign receipt handles

* fix(sqs): accept receipt handles of gone and re-received messages

* fix(sqs): reject expired FIFO receipt handles

* fix(sqs): reject receipt handles that were never issued

* chore(sqs): parse receipt handles once and share the handle checks

* fix(sqs): sign receipt handles with a configurable secret

* test(sqs): merge the receipt handle error tests into one table

* fix(sqs): give a message moved by a move task a new message id
2026-09-30 21:29:09 -04:00
Allen Sanborn bd0f468d3e fix(ecs): delete a service's deployment records with the service (#4757)
DeleteService left the service's ServiceDeployment and ServiceRevision
records behind, so ListServiceDeployments still returned them,
DescribeServices on the INACTIVE service still named a current deployment,
and a service recreated under the same name inherited them. AWS deletes
both with the service; DescribeServiceDeployments and
DescribeServiceRevisions now report the old ARNs as MISSING failures.

This replaces the interim stop-on-delete: a deleted service's deployments
no longer exist, so there is nothing left to mark STOPPED or settle. The
three EcsServiceDeploymentStatusTest cases that pinned a record surviving
the delete are removed, and the steady-state waiter IT that proved
stoppedAt and statusReason reach the wire now reaches STOPPED by
supersession, the route that remains.
2026-09-30 21:17:55 -04:00
Daniël van ZielandPriamo e377148a52 fix(autoscaling): retain membership when instance termination fails (#4115)
* fix(autoscaling): retain membership when instance termination fails

* fix(autoscaling): keep stopped terminating instances and bound failure status

A Terminating instance whose termination failed was pruned as stale when
its EC2 state was stopping or stopped, recording a successful cleanup and
leaving the instance behind. A stopped instance still exists, so only a
missing, shutting-down or terminated record now counts as gone for a
Terminating member; Pending keeps the wider set.

The failed activity's StatusMessage is capped at 255 characters, the
XmlStringMaxLen255 limit, and falls back to the exception type when there
is no message. A repeated failure is deduplicated against the latest
activity with the same description rather than the latest activity
overall, so two failures alternating in one pass no longer defeat it.

* fix(autoscaling): record a termination failure again when its error changes

A repeated termination failure was skipped whenever the latest activity
for the same instances had failed, so a failure that changed cause kept
reporting the old reason. It is now skipped only when the previous
failure carried the same StatusMessage.

---------

Co-authored-by: Priamo <pgermosen@gmail.com>
2026-09-30 21:16:47 -04:00
Hector Ventura 0bc85f3ef8 fix(sts): mint global STS and IAM ARNs per partition and add a strict partition mode (#4743)
* fix(sts): mint global STS and IAM ARNs per partition and add a strict partition mode

GetCallerIdentity's root fallback, the AssumeRole family's session ARNs, the
OIDC provider ARN and GetFederationToken built their ARNs with an empty
region, which falls back to the commercial partition, so they carried arn:aws:
whatever partition the request signed. They now go through
RegionResolver.buildGlobalArn. GetAccountSummary reports
GlobalEndpointTokenVersion only where the partition publishes a global STS
host, which is aws alone.

floci.partitions.strict (FLOCI_PARTITIONS_STRICT, default false) refuses a
request signed for a service AWS publishes in another partition but not in
the request's one (CloudFront in GovCloud, IAM in aws-eusc) with the
unknown-service guard's 404, mirroring the host that never resolves on AWS.
endpoints.json omits the services that ship only an endpoint ruleset, so a
service the data lists nowhere is served everywhere. Credential scopes carry
signing names, and 46 of them differ from the endpoints.json keys they cover
(73 keys, such as ecr for api.ecr); regen_partitions.py vendors that map as
signingNames and AwsPartition.offersSigningName joins it.

Part of #4272

* fix(core): read the gzipped botocore models the pip package ships when collecting signing names

The botocore wheel ships each service model as service-2.json.gz, while the checkout under local/aws/botocore ships it plain. collect_signing_names looked only for the plain file, so in CI, which resolves botocore to the installed package, it found no models, generated an empty signingNames and failed aws-data-check against the committed map. It now reads either form, as regen_dynamodb_shapes.py already does.

* fix(sts): keep an assumed-role session in its role's partition, and answer strict-mode Query requests in XML

GetCallerIdentity rebuilt an assumed-role session's ARN with an empty region, which falls back to the commercial partition, so a session AssumeRole issued as arn:aws-cn:sts:: came back as arn:aws:sts::, and a chained AssumeRole was then refused by a China trust policy as a caller from another partition. The session ARN now takes the partition its role ARN names.

Strict partition mode refused a form-encoded Query request (IAM in aws-eusc) with a JSON body; it now returns the Query XML error the unknown-region guard beside it already returns for such requests.

* fix(iam): mint IAM resource ARNs in the request's partition and keep them there

CreateUser, CreateGroup, CreateRole, CreatePolicy, CreateInstanceProfile and
CreateOpenIDConnectProvider minted arn:aws: whatever partition the request
signed, while STS now followed the request. Under China that denied
AssumeRoleWithWebIdentity (the trust policy names the arn:aws: provider ARN
CreateOpenIDConnectProvider returned, matched against arn:aws-cn:), and
AssumeRole reported the request's partition while GetCallerIdentity reported
the role's.

An IAM resource is now created in the request's partition and keeps it:
UpdateUser and UpdateGroup re-mint in the stored ARN's partition. Anything
derived from a stored role follows the role: all three AssumeRole handlers,
resolveCallerArn and the web identity OIDC provider ARN take the role ARN's
partition through AwsArnUtils.partitionOrDefault. The credential report's
root row takes the request's partition.

* fix(sts): mint a session from the stored role, and keep one credential report per partition

AssumeRole, AssumeRoleWithWebIdentity and AssumeRoleWithSAML find the role by
account and name, but minted the session ARN from the RoleArn the request
named. A China role assumed with an arn:aws: RoleArn therefore came back as an
arn:aws:sts:: session, while AssumeRole registered the session under the
stored role's ARN, so GetCallerIdentity reported aws-cn. All three handlers
now mint the session from the stored role's ARN when the role exists and
register it under the same ARN.

The credential report was cached once per account, so a report generated for
one partition was handed to a caller in another for four hours, with the
wrong partition's root row. It is now kept per partition.
2026-09-30 20:48:20 -04:00
Daniël van ZielandPriamo 865dd1d658 fix(networkfirewall): validate replacement before replacing state (#4114)
* fix(networkfirewall): validate replacement before replacing state

* fix(networkfirewall): require UpdateToken and keep unchanged fields on update

UpdateRuleGroup and UpdateFirewallPolicy now require the current
UpdateToken and reject a stale one with InvalidTokenException, as the
API reference documents. The replacement is built from the stored
resource, so Capacity and Tags, which neither update request models,
and any field the request leaves out carry over instead of being
dropped.

A rule group's Type can't change after creation, UpdateFirewallPolicy
requires FirewallPolicy, and UpdateRuleGroup requires exactly one of
RuleGroup or Rules, so a request without a definition no longer wipes
the stored one. Rule group and firewall policy create, update and
delete now share the service lock, so a delete can't be undone by an
overlapping update and two updates holding the same token can't both
apply.

---------

Co-authored-by: Priamo <pgermosen@gmail.com>
2026-09-30 18:42:11 -04:00
Priamo Germosen 4e2c1d11ff fix(sts): evaluate AssumeRole trust-policy conditions against the real caller (#4716)
With IAM enforcement on, AssumeRole matched a trust policy on its Action and
Principal only. The Condition block was never read and the ExternalId request
parameter was ignored, so a role guarded by sts:ExternalId, the documented
confused-deputy guard, could be assumed without it, and a conditional Deny
applied whether or not its condition held.

Trust-policy conditions now go through IamPolicyEvaluator's condition engine,
through a new package-private conditionMatches, so they get the same operators
as identity and resource policies. The request context holds sts:RoleSessionName,
sts:ExternalId when the caller sends one, the global keys the enforcement filter
already provides, and aws:PrincipalArn.

A role session is now matched as the role that issued it, through that role's
own ARN, path included. AssumeRole records it on the session when it issues
one, and a new IamService.resolvePrincipalArn reads it back as is, so an old
session keeps naming its role even after a same-named role replaces it. The
evaluator used to rebuild the role ARN from
the assumed-role session ARN, which names the role without its path, so a
session of role/team/App was compared as role/App: a Principal naming the role
refused it, and a condition on aws:PrincipalArn saw the wrong value. IAM stores
a Principal naming a role as the role's unique ID, and aws:PrincipalArn is the
ARN of the role that was assumed, so both are the full role ARN.

A negated operator on an absent key now holds, as the IAM User Guide says for
every condition operator but the IfExists forms and Null: "If the policy
condition requires that the key is not matched, such as StringNotLike or
ArnNotLike, and the right key is not present, the condition is true."
evaluateConditionBlock failed every operator on an absent key, so once trust
conditions were evaluated a Deny with StringNotEquals on sts:ExternalId stopped
refusing a call that omits ExternalId. The change is in the shared engine, so
identity, resource and SCP conditions get the same rule; the set operators keep
their own rule for an absent key.

The AppSync service-trust path from #4555 had its own small condition evaluator
for aws:SourceArn and aws:SourceAccount. It now uses the same engine with those
two keys as its context, which also makes negated operators such as
StringNotEquals work there instead of refusing the document. A Condition that
is not an object of non-empty operator objects still invalidates the whole
trust document, now on every path.

The trust check also resolved the caller's account from the Authorization
header alone, where only a 12-digit key names an account. An IAM user's or a
role session's key, and any presigned request, therefore counted as the default
account and could assume a role that trusts only that account. The check now
uses the account the request was resolved to, and reads a presigned caller's
key from X-Amz-Credential.
2026-09-30 17:39:45 -05:00
Abhigya 55d37cfc41 feat(ecs): let the startup container sweep be turned off, and derive the credentials proxy owner from the shared helper (#4696)
* feat(ecs): let the startup container sweep be turned off, and derive the credentials proxy owner from the shared helper

The ECS startup sweep removes every task container carrying this deployment's
floci_owner_port label, so two Flocis sharing a Docker daemon with the same API
port and no resource namespace remove each other's task containers. EC2's sweep
already has an opt-out; ECS now has the same one,
FLOCI_SERVICES_ECS_RECONCILE_CONTAINERS_ON_STARTUP (default true). With it off,
containers are left alone and tasks start at once. The recorded load balancer
targets and Cloud Map instances are still released, since each Floci releases
only what its own persisted state recorded.

EcsCredentialsProxy.owner() now uses ContainerStorageHelper.ownerIdentity and
OWNER_LABEL instead of its own copy of the rule.

* fix(ecs): leave task-role credentials proxies alone when the startup sweep is off

The credentials proxy removed every proxy carrying this deployment's owner label
at startup regardless of reconcile-containers-on-startup. With the sweep off for
two instances sharing an owner identity, the second instance's startup still
tore down the first's proxy, and its running tasks lost their credentials
endpoint. The proxy's startup reap now follows the same setting.
2026-09-30 17:22:46 -05:00
Allen Sanborn 18128b432a fix(organizations): start a new root with no policy types enabled (#4756)
CreateOrganization (and EnableAllFeatures) seeded the root with
SERVICE_CONTROL_POLICY already ENABLED, so the first EnablePolicyType a
caller issues was rejected with PolicyTypeAlreadyEnabledException. That
is exactly what Terraform's aws_organizations_organization does with
enabled_policy_types right after CreateOrganization, so the common
"create the org and turn on SCPs" configuration failed at its first
resource.

On AWS a new root has an empty PolicyTypes list: the provider's
acceptance test for a plain organization asserts roots.0.policy_types
is empty, and its enabled_policy_types test enables SCPs on a fresh
organization successfully.

DescribeOrganization's AvailablePolicyTypes used to read the root's
list, which is what the seed was standing in for. It is now reported
separately and, as AWS documents for the deprecated field, lists only
SERVICE_CONTROL_POLICY for an ALL organization.

Tests that relied on the seed now call EnablePolicyType first, as a
real caller must. The CloudFormation test creates the stack without its
SCP, enables the type, then adds the SCP by UpdateStack, because no
CloudFormation resource enables a policy type.
2026-09-30 18:12:38 -04:00
Mario Toffia b5c428319f fix(apigateway): create API keys disabled unless enabled is set (#4731)
* fix(apigateway): create API keys disabled unless enabled is set

AWS creates an API Gateway API key disabled when the CreateApiKey request has no enabled field, and the AWS::ApiGateway::ApiKey CloudFormation schema declares Enabled with a default of false. Floci created such keys enabled, and a CloudFormation update whose template omitted Enabled switched the key on. AWS SDKs that model enabled as a plain boolean, such as the AWS SDK for Go v2, leave the field out of the request when it is false, so a client asking for a disabled key received an enabled one.

* fix(cloudformation): restore an API key when its stack update rolls back

When a stack update changed an AWS::ApiGateway::ApiKey and a later
resource in the same update failed, the stack ended in
UPDATE_ROLLBACK_FAILED and the key kept the new customer id,
description, enabled flag and tags. The provisioner had no rollback.

The provisioner now records those four values on the stack resource
before it changes the key, and puts them back when the stack update
rolls back. It also replaces the tags before patching the other
fields, so a refused tag change leaves the key untouched.

* fix(cloudformation): delete an API key an update recreated when the update rolls back

When a stack update found that its API key had been deleted outside
CloudFormation, it created a new key. If a later resource then failed
the update, the rollback reported success and left the new key live,
while the stack resource still named it.

The update now records the key it created, and the rollback deletes
that key and points the stack resource back at the previous key id.

The API key CloudFormation integration test now waits for the stack
to reach a final status before checking it, because stack create and
update run in the background.

* fix(cloudformation): put an API key's tags back when its own update fails

An API key update replaces the tags first and then patches the other
fields. If the patch failed after the tags were replaced, the stack
rolled back but the key kept the new tags. For a resource whose own
update fails, the stack restores the stored resource record and does
not call the provisioner's rollback, so nothing put the tags back.

The update now copies the tags before replacing them and puts the copy
back when the patch fails, then rethrows the original error.

* fix(cloudformation): undo the whole API key when its own update fails

An API key update replaces the tags and then patches the customer id,
description and enabled flag. Either call can fail after it has
already changed the stored key. Before, a failure only put the tags
back, and a failure to put them back was hidden, so the stack could
report a clean rollback while the key kept the failed update's values.

Now any failure in either call puts the key's four values back from
the snapshot taken before the update. If that restore also fails, the
resource is marked so the stack ends in UPDATE_ROLLBACK_FAILED, and
the original error is rethrown with the restore error attached.

* fix(cloudformation): roll an API key back by writing only what changed

Rolling back an API key update wrote every saved value back, even when
the update had changed nothing. For example, the service refuses a
reserved tag change before it writes anything, yet the rollback still
rewrote the tags and fields. That changed the key's last-updated time
for no reason, and if one of those writes failed, the stack reported
UPDATE_ROLLBACK_FAILED for an update that had not changed the key.

The rollback now reads the key as it is and writes back only the tags
and fields that differ from the saved values. The update and the
rollback share one function to decide which fields differ.

Also, when the rollback fails with the same exception object as the
update, it is no longer attached to itself, which threw an
IllegalArgumentException and hid the original error.

* fix(cloudformation): put back a reserved API key tag when an update rolls back

An API key can be created with a reserved tag, such as the id-override
tag _custom_id_. A stack update may remove that tag. When a later
resource failed the update, the rollback tried to put the tag back
through the same call the update uses, which refuses a reserved tag
that is being added. The stack then ended in UPDATE_ROLLBACK_FAILED
and the key stayed without its tag.

The API Gateway service gains a call that sets a key's tags exactly as
given, without the reserved-tag check. The rollback uses it. Tag
changes from a template still go through the checked call.

The test helper that applies patches now uses a switch expression, as
the repository's code style asks.
2026-09-30 15:48:46 -04:00
Aniket Shukla 055c411b9a fix(iam): share case-sensitive condition matching (#4725)
* fix(iam): share case-sensitive condition matching

* fix(iam): use iterative glob matching for conditions

* fix(iam): match wildcard before literal asterisk
2026-09-30 14:59:42 -04:00
Kenshin Okinaka 0b53580969 fix(ses): reject send addresses longer than 320 characters (#4749)
* fix(ses): reject send addresses longer than 320 characters

* fix(ses): ignore quotes and commas inside comments when splitting address headers
2026-09-30 14:50:59 -04:00
Aymen JAMAAOUI b0f30ae94d fix(ssm): reject SendCommand with more than 50 InstanceIds (#4754) 2026-09-30 14:36:26 -04:00
Niels Kootstra efbd990ef7 fix: run MWAA CLI commands without a shell (#4750)
* fix: run MWAA CLI commands without a shell

The MWAA CLI endpoint passed the request body to sh -c inside the Airflow
container, so shell syntax such as ; | $(...) ran arbitrary commands.
Split the command with POSIX quoting rules and exec airflow directly.

* fix: follow POSIX word splitting for MWAA CLI arguments

Only spaces, tabs and newlines separate arguments, and a backslash-newline
pair is removed instead of kept.
2026-09-30 14:32:06 -04:00
Sam Fakhreddine 49501acb5a feat(dns): transparent AWS endpoint interception for spawned containers (#4610)
* feat(dns): resolve amazonaws.com to Floci inside spawned containers when spoof-aws-endpoints is on

SDK clients built with explicit real-AWS endpoints override AWS_ENDPOINT_URL and would otherwise escape to real AWS; off by default.

* fix(tls): cover every region and S3 endpoint form in the spoof SANs

The default-region-only SANs failed the TLS handshake for any other region.

* fix(dns): warn when spoof-aws-endpoints is set where the TLS certificate cannot see it

Startup logs a WARN when the flag is only in application.yml and TLS is on.

* fix(dns): derive spoofed AWS suffixes and SANs from partitions

Intercept every partition DNS and dual-stack suffix and name each region's
certificate SANs under its own partition suffix, so China, EUSC and ISO
endpoints are covered and cn-* regions are no longer named under the
commercial suffix. Add the s3-control SAN, drop the lambda-url SAN (function
URLs live under on.aws, which is not intercepted), and log the startup
warning with LOG.warnv.

* test(dns): name the new certificate tests as sentences

* docs(dns): document every AWS partition suffix spoof-aws-endpoints intercepts

The flag covers each partition's DNS and dual-stack suffix, not just amazonaws.com. List them in the config comments, env-var docs and EmulatorConfig javadoc, call out that live suffixes like api.aws and amazonaws.eu resolve to Floci, and use a single literal in the TLS visibility warning. Rename the certificate regeneration test to a sentence.
2026-09-30 13:42:08 -04:00
Aniket Shukla 894f20bb81 fix(lambda): reject invalid configuration numbers before mutation (#4726)
* fix(lambda): reject invalid configuration numbers before mutation

* fix(lambda): validate configuration ARN types and memory limit
2026-09-30 13:31:55 -04:00
Aniket Shukla 45b00779b7 fix(cognito): fail authentication when token triggers fail (#4727)
* fix(cognito): fail authentication when token triggers fail

* fix(cognito): reject empty Lambda trigger responses
2026-09-30 13:29:20 -04:00
Allen Sanborn c6b8a70ea8 fix(ecs): a service reaches steady state, and a finished deployment stays finished (#4694)
* fix(ecs): name a service revision by the deployment's task set id

A service created against Floci never reached STABLE for a client that asked
to wait for it. `aws_ecs_service` with `wait_for_steady_state` sat on tfPENDING
for its whole 20-minute timeout while the emulator reported the service ACTIVE,
at its desired count, with one PRIMARY deployment whose rolloutState was
COMPLETED and one RUNNING task. Six of the first sixteen terraform-aws-ecs
Terratest suites failed that way, three burning the full waiter.

Nothing in DescribeServices was stuck; every field that waiter used to read
settles in about ten seconds. Since provider 6.x a service under the ECS
deployment controller whose PRIMARY deployment started after the operation is
not judged from DescribeServices at all. The provider reads deployments[0].id,
which is "ecs-svc/<taskSetId>", then takes the ListServiceDeployments brief
whose targetServiceRevisionArn *contains that id*, and polls
DescribeServiceDeployments on it:

    if strings.Contains(aws.ToString(deployment.TargetServiceRevisionArn), taskSetID)

AWS makes that join work by naming the service revision with the very id the
deployment reports -- its own docs pair "ecs-svc/1485800978477494678" with
".../service-revision/<cluster>/<service>/1485800978477494678". Floci minted
the two from independent UUIDs, so the join matched nothing,
findPrimaryDeploymentARN returned nil, and that path returns tfPENDING with no
error, forever. The emulator's request log for one hung apply shows 50
ListServiceDeployments calls and zero DescribeServiceDeployments: the provider
never got past the join. DescribeServiceDeployments itself was fine all along.

recordServiceDeployment now names the revision by the deployment's task set id.

The status that join leads to has to mean something too, so it is derived for
the deployment a service is currently on, the same way deploymentsFor derives
rolloutState: IN_PROGRESS until runningCount has reached desiredCount,
SUCCESSFUL once it has. Recording every deployment SUCCESSFUL with a finishedAt
at create time, as before, would have turned wait_for_steady_state into a wait
that can never fail -- a silent false pass in place of a loud timeout -- and
terraform-aws-ecs's own failure tests deliberately break the container and
assert the apply errors. A deployment the service has moved off keeps what it
was last recorded with. What that derivation still does not model -- a terminal
failure state, rollback, closing out superseded deployments -- is filed
separately.

Measured end to end on the example that timed out: the service now converges in
13s, with one ListServiceDeployments and seven DescribeServiceDeployments, so
the wait is gated on real convergence rather than passing instantly.

* test(ecs): say what the zero-desired deployment test guards

One of the five tests added with the fix passes on the build the bug was found
on, because there every deployment was born SUCCESSFUL and a zero-desired
service was trivially SUCCESSFUL too. That makes it a guard rather than a
repro, and an undocumented guard reads as slack: the next reader counts five
tests, sees four bite, and assumes the fifth is padding.

Measured rather than asserted. Mutating settleStatus to refuse to call a
zero-desired service converged -- adding `&& svc.getDesiredCount() > 0`, the
shape a defensive "nothing was asked for, so nothing succeeded" slip takes --
turns it red with `expected: <SUCCESSFUL> but was: <IN_PROGRESS>` while both
desiredCount-1 tests in the same class stay green. It is the cheap cousin of
deriving the status on a reconciler tick instead of at read time, which for a
service that never needs a tick amounts to the same thing.

The comment also records that it is not independent coverage: the same mutation
reddens this fix's integration twin and the pre-existing
EcsFargateEdgeCaseIntegrationTest.aServiceDeploymentPointsAtTheRevisionItDeployed,
both of which use desiredCount 0 as well. It is kept because it is the only one
of the three whose failure names the condition; the others report a wire
assertion.

* fix(ecs): settle a deployment on its own tasks, not the service's

A service's runningCount counts every RUNNING task it owns, including the ones
still draining from the deployment a rolling change replaced. Deriving a
deployment's status from it reported a task-definition change finished the
instant UpdateService returned, on the strength of the OLD revision's task. The
provider joins to that deployment and stops polling on its first tick, so
wait_for_steady_state on an image change -- the most common real use of the
flag -- returned immediately and a new image that could not start read as
stable.

The create path in the preceding commit was right because a new service owns no
tasks yet, so the service-wide count and the deployment's own count agree. They
diverge exactly when a deployment replaces another, which is the case that
commit did not test. Adding that test is what found this.

runningOnCurrentDeployment counts the service's RUNNING tasks that are not
stale for the current deployment, reusing the ownedBy and isStaleForDeployment
predicates the reconciler already applies. It recomputes rather than caching
what the reconciler derived one line above where it sets runningCount: that
value is a fact about the last tick, and a deployment is read on demand between
ticks -- right after UpdateService, which is the moment that matters.

Applied to the two other places that asked the same question of the wrong
number, both of which predate this branch:

  deploymentsFor  rolloutState, and the Deployment's own runningCount, which is
                  per-deployment in AWS. Left alone it would overstate the count
                  mid-rollout and contradict the ServiceDeployment resource that
                  is now derived correctly -- two Floci views of one deployment
                  disagreeing is worse than both being wrong together.
  eventsFor       the steady-state event, emitted on the same condition.

Measured as a side effect: convergence is now visible one tick earlier, because
the count is taken from the tasks at read time instead of from runningCount,
which the reconciler sets from a snapshot taken before it launches anything. A
test comment that documented the old one-tick lag is updated.

Adjacent cases now covered: a deployment whose task dies goes back to
IN_PROGRESS and withdraws its finishedAt; two updates with no tick between them
settle only the newest; scaling to zero reports converged while the task is
still draining, which is recorded as measured behaviour rather than asserted as
ideal, since AWS's waiter compares with == and would hold it pending.

* fix(ecs): make a finished deployment terminal, and settle onto a copy

Two faults with one root: a deployment's status was derived from a live count
on every read, with nothing to stop it moving.

SUCCESSFUL is terminal in AWS. A completed deployment does not un-complete
because the service later became unhealthy, and finishedAt records when the
deployment finished, not the last time it was asked about. Deriving afresh let
tasks dying afterwards flip a finished record back to IN_PROGRESS, blank a
finishedAt it had already published, and stamp a new one on recovery. Scoping
the count to the deployment's own tasks does not fix this -- when its own tasks
die that count drops too -- so the transition now runs once and never reverses.
Measured both ways: the new test goes red against the preceding commit, which
has the scoped count but no latch, and that commit's update-path test goes red
against the one before it, which has the latch's absence but the wrong count.
Neither fix subsumes the other.

Reads no longer hand out the stored record. settleStatus writes to it and the
response is serialised after it returns, so one request's settle could land
inside another's serialisation; ServiceDeployment's fields are plain and
non-volatile, and a reader could see status=SUCCESSFUL beside a finishedAt that
had not arrived. The transition and the copy now happen under one lock, so a
caller sees a single consistent moment.

Also reverts this branch's changes to deploymentsFor and eventsFor. They were
made to stop rolloutState contradicting the ServiceDeployment resource, but a
terminal SUCCESSFUL makes the two legitimately diverge when tasks die later --
the record stays finished, the live rollout state does not -- so the
consistency argument for touching them no longer holds. Reverting also restores
the property that DescribeServices output is byte-identical to upstream for
services that never ask to wait, which keeps this branch to the one API the bug
is about. The same miscount is still there in rolloutState, predates this
branch, and is recorded on floci-n5kb.

The task scan sits after the is-this-the-current-deployment guard, so a call
costs at most one scan however many deployments it returns, and none once one
has latched.

* fix(ecs): derive rolloutState from the deployment's own tasks too

Reinstates the deploymentsFor and eventsFor half that the previous commit
reverted, because the reason given for reverting it was wrong.

That reason was: once SUCCESSFUL latches, the deployment record and
rolloutState legitimately diverge when tasks die later, so "keep the two views
consistent" is no longer a reason to touch rolloutState. The first half is
true; the conclusion does not follow. It generalises from the one case where
divergence is correct to the case that actually matters, and they are different
questions.

Late divergence is two questions with two right answers: the record is history
and stays finished, rolloutState is live and follows the service. Divergence
DURING a rollout is one question with two answers. Immediately after a
task-definition change, both are describing a rollout that has not started --
and with rolloutState still derived from the service-wide count it reported
COMPLETED while the record correctly said IN_PROGRESS. A client reading
DescribeServices was told the rollout was done when it had not begun, and had
no way to tell which of Floci's two answers to trust.

So the quantity is corrected in all three places that ask the question, while
the latching stays only on the record, where it belongs. Deployment.runningCount
becomes this deployment's count, which is what the field means in AWS; a count
that means something different in two places is the same class of bug as the
one being fixed.

Cost is bounded by the latch rather than by this change: the SUCCESSFUL test is
the first conjunct in settleStatus and && short-circuits, so a settled
deployment never runs the scan, and the is-this-the-current-deployment guard
skips it for the rest. A converged service pays what it always did.

Adds a test pinning both directions: the two views agree while a rollout is in
flight, and the steady-state event stays withheld until it lands.

* test(ecs): pin the two behaviours that survived their own mutants

Both new behaviours on this branch were asserted from a state where the defect
they describe cannot manifest, so removing either production change left the
suite green.

The agree test changed the task definition one reconciler tick after create.
reconcileService sets svc.runningCount from a snapshot taken before it launches,
so one tick short of a steady state that field is still 0 -- and the buggy
derivation, which reads it, gives the right answer by accident. Any service
alive longer than one 5-second tick is past that window, which is every service
anyone actually changes an image on. It now ticks twice and asserts
runningCount == 1 as an explicit precondition, so a future change to tick timing
cannot quietly move it back into the window where it stops testing anything.

The task-death test only re-read the record after the tasks died, when the
converged branch is not taken, so it never exercised the latch itself. Deleting
the already-SUCCESSFUL clause left it green while finishedAt was re-stamped on
every read of a converged deployment. It now re-reads once while still
converged, before stopping the task.

Measured with each production change reverted in turn:
  deploymentsFor/eventsFor -> svc.getRunningCount()
    expected: <IN_PROGRESS> but was: <COMPLETED>
  the SUCCESSFUL clause deleted from settleStatus
    expected: <2026-09-29T18:01:10.537673Z> but was: <...538869Z>

Also from review, three fixes and one correction:

settleStatus folds its guard into the synchronized condition, so every copy is
taken under the lock. "Current" is decided against a deploymentId UpdateService
can mint at any moment, so two threads can disagree about which deployment is
current and the unsynchronised early-return copy could have run beside the
write -- the torn record the lock exists to prevent.

runningOnCurrentDeployment resolves the task definition the same way the
reconciler does. isStaleForDeployment falls back to comparing that against a
task's ARN for tasks minted before deployment ids were stamped, so passing the
raw family reference would have marked every task stale and reported a running
service as having none. Extracted resolvedTaskDefinitionArn, shared by both
callers; the reconciler still caches the resolution, the read path does not,
because a read has no business writing to the service.

currentServiceDeployment now settles like every other read instead of handing
out the stored record. Its caller reads only the two ARN fields, so this was
safe by accident rather than by construction, and copyOf's contract is that no
read returns the stored object. That makes it a third read path depending on
the copy, which is noted at the call site: the copy is load-bearing there, not
tidiness.

The cost note is corrected. The short-circuit bound covers settleStatus alone;
deploymentsFor and eventsFor call runningOnCurrentDeployment unconditionally,
because there is nothing to latch on the live side. The comment said "none at
all once one has latched", which was true of the method and false of the
response.

* docs(ecs): replace the guessed scan cost with a measured one

The note said deploymentsFor and eventsFor call runningOnCurrentDeployment
"unconditionally". True of deploymentsFor, which is a bare call. False of
eventsFor, whose call is the last disjunct of an || chain and so is skipped
entirely for a service that is absent or not ACTIVE -- checkable by reading the
three lines, which is how review caught it.

The number was guessed too. Measured instead, by counting calls to
runningOnCurrentDeployment per DescribeServices per service on a clean tree:

  ACTIVE, first poll after a create or a rollout   3   (1 + 1 + 1)
  ACTIVE, every later poll of a settled service    2   (1 + 1 + 0)
  not ACTIVE, or the service is gone               0

The third term is currentServiceDeployment, which settles and therefore scans
until the current deployment latches and never again -- the poll that reads 1 is
the poll that latches it. So the steady-state cost a polling waiter actually
pays is 2, not the 3 of its first call, and an earlier claim of "none at all
once one has latched" was true only of settleStatus in isolation.

An earlier attempt at this measurement read 0 for deploymentsFor, which is
impossible against a bare call, and that impossibility is what exposed a
corrupted worktree rather than a surprising result. Those numbers were voided.
This run refuses to start unless the tree is clean and restores with git
checkout, so the baseline is a commit rather than a byte copy taken at an
unknown moment.

* docs(ecs): the unlatched cost is every poll, not the first one

The row read "first poll after a create or a rollout", which implies later
polls of a rollout in progress cost 2. They cost 3. A deployment stays unlatched
until it converges, so a slow rollout -- or one that never converges -- pays the
third scan on every poll for its whole duration, which is precisely when a
waiter is polling hardest.

The measured numbers were right and the prose beneath them was right
("scans until the current deployment latches and never again"); only the label
contradicted both. Worth recording that it survived into the commit whose
purpose was to replace a guessed cost with a measured one: measuring the right
thing does not stop you describing it wrongly, and the description is what the
next reader acts on.

* style(ecs): drop em dashes, and the unreachable region literal

Two upstream policy gates on #4694, neither a defect in behaviour.

AGENTS.md prohibits em dashes in any content. Thirteen in lines this branch
adds, replaced with colons, commas or periods as each sentence needed. Em
dashes on lines the branch does not touch are left alone, so the diff stays
about this change.

The partition gate flagged a new region literal in serviceRegion, the helper
added for resolvedTaskDefinitionArn:

    return regionResolver != null ? regionResolver.getDefaultRegion() : "us-east-1";

It was copied from the sibling taskRegion, which upstream annotated with
// partition-literal in #4494. Mirroring that annotation would have been the
cheap route and the wrong one: the guard is unreachable. Nothing constructs an
EcsService without a resolver, and the class dereferences regionResolver
unguarded in the create paths, so a null one fails long before this line. The
literal is therefore dead code that is also wrong in any non-default partition,
which is the worst combination available. Routed through the resolver instead,
which is the gate's own first suggestion, and the dead branch is gone rather
than documented. taskRegion is left as upstream wrote it.

The REGION = "us-east-1" constant in the new test matches four existing ECS
test classes and was not flagged; test fixtures are not partition-sensitive.

* style(ecs): import Map rather than qualifying it inline

AGENTS.md wants the import. Every other ECS test class already does it this
way.

* fix(ecs): count every task a DAEMON service owns, stale or not

Scoping the count to the current deployment is right for REPLICA and wrong for
DAEMON, and left unqualified it created for DAEMON exactly the hang this branch
removes for REPLICA.

reconcileDaemonService has no notion of staleness anywhere in it: no
deploymentId, no task-definition comparison. It decides which tasks to keep
purely by which container instances they cover, so after a task-definition
change the old revision's task holds its slot and no replacement is launched.
A deployment-scoped count therefore sits at zero for ever.

Measured across four reconciler ticks on a DAEMON service with one active
container instance, before this commit and with the count reverted to main's:

  after task-def change   this branch             main
  tick 1 .. tick 4        IN_PROGRESS / nofin     COMPLETED / SUCCESSFUL
                          events 0                events 1
  tasksRunning = 1, and it is the OLD revision's task, throughout

So wait_for_steady_state on a DAEMON image change would have hung until its
timeout where main returned promptly. Counting every owned RUNNING task keeps
DAEMON exactly as main behaves, which makes this branch a strict improvement:
REPLICA fixed, DAEMON unchanged.

This is a mitigation, not a claim that DAEMON is correct. Reporting a
deployment finished while the previous revision is what is running is wrong,
and the real fault is that DAEMON services never roll on a task-definition
change, which is a pre-existing reconciler defect this branch only made
visible. Fixing it means changing daemon scheduling, which does not belong in
a change about when a deployment is finished; it is filed separately.

The test pins the limitation as well as the fix: it asserts the surviving task
is still the old revision's, so the day DAEMON rolling is implemented, the test
says so rather than silently passing.

* docs(ecs): the DAEMON count matches main from tick one, not exactly

The comment claimed counting stale tasks "keeps DAEMON exactly as it behaves on
main". Off by one tick. An identical probe across create, two ticks, a
task-definition change and four more ticks matches main on every row from tick
one onward, and differs on exactly one: a DAEMON deployment with no tasks
running yet reads IN_PROGRESS here and SUCCESSFUL on main.

That difference is the birth-state fix applied uniformly, which is this
branch's whole subject, so DAEMON is a strict improvement rather than merely
unchanged. "Exactly" claimed both less and more than the measurement supports.

The same correction cannot be made to the preceding commit's message, which
carries the original wording. Force-push is barred here and rightly so, so it
is corrected here instead: read that message with this commit beside it.

The test's note on why the limitation is pinned is also sharpened. It said the
assertion stops a mitigation outliving its reason. The coupling is stronger
than that: once DAEMON rolls, counting stale tasks would reproduce on DAEMON
the exact REPLICA bug this branch removes, so the DAEMON branch of the count
has to come out at the same moment, and this assertion is what forces it.

* fix(ecs): stop a deployment the next one supersedes

settleStatus finishes only the deployment a service is currently on, so
a deployment superseded before its tasks converged could never be moved
again: it stayed IN_PROGRESS with no finish time for the life of the
emulator, describing a rollout that could no longer happen. Listing a
service's deployments returned a growing pile of them apparently in
flight at once, and a listing filtered on IN_PROGRESS returned every
rollout the service had ever abandoned.

Recording a deployment now lands the ones it takes over from in STOPPED,
which is the status AWS uses for a deployment that ended without
completing, stamping finishedAt and updatedAt. Only a deployment still
in progress is moved, so one that had already reached SUCCESSFUL keeps
its status and the instant it finished at: that record is history, not
something a later rollout rewrites. The scan is scoped to the one
service ARN.

The write is made under the same monitor settleStatus writes under,
because the two race: a read settling the outgoing deployment can run
beside the update minting its replacement. Both transitions now require
IN_PROGRESS, so whichever lands second finds a terminal status and
leaves it alone and neither can undo the other. That tightens
settleStatus's own guard from "not SUCCESSFUL" to "still IN_PROGRESS",
which is the same condition for every status it can legally advance.

* fix(ecs): stop the deployment a deleted service leaves unfinished

Superseding a deployment was one of the two ways a deployment could be
put permanently beyond settleStatus. This is the other. settleStatus
finishes a deployment only while its service is ACTIVE, and deleteService
sets the service INACTIVE without touching the deployment records at all,
so deleting a service before its first rollout converged left that
deployment IN_PROGRESS with no finish time for ever. No later update
could supersede it, because there are no later updates on a deleted
service. ListServiceDeployments filtered on IN_PROGRESS returned it
indefinitely, which is the same symptom a superseded deployment had,
reached through a different door.

Both routes now go through one helper, which stops only the deployments
of the one service that are still in progress.

Deliberately narrower than AWS, which documents that it "deletes the
service deployment when you delete a service". Stopping the records
removes them from an IN_PROGRESS listing, which is the actual harm,
without turning a DescribeServiceDeployments a client is mid-poll on into
a failure. Deleting them would match AWS and destroy history a client may
still be reading, which is a larger and less reversible change than this
fix warrants; full parity is tracked separately.

Also adds stoppedAt and statusReason to the deployment model, the
response writer and the detached copy every read hands back. Both are
members of AWS's ServiceDeployment shape and neither was written at all,
so a client asking when a stopped deployment ended, or why, got nothing.
AWS files STOPPED under its "Completed" lifecycle stage, so a stopped
record carries finishedAt as well as stoppedAt; a deployment that is
running or that succeeded carries neither field, absent rather than null.

* docs(ecs): drop private tracker ids from javadoc

Four javadoc references named issues in a private tracker, so a reader of
this code upstream could not resolve any of them. The behaviour each one
described is stated in the surrounding prose already, which is where it
belongs: a comment has to stand on its own for whoever reads it next.

* test(ecs): name the deployment asserted on, never its index

The superseded-deployment assertion read the listing's index 1 and 2.
listServiceDeploymentsDetailed sorts on createdAt and List.sort is
stable, so three deployments minted inside one clock tick share a
timestamp and their order in that listing is ConcurrentHashMap iteration
order. The assertion held here only because Instant.now() resolves finer
than the cost of minting a deployment on this machine; where the clock is
coarser it would pass or fail by hash order. Each record is now selected
by its own task set id, which is what the rest of the class already does
and what its javadoc already claimed of the whole file.

Also records why the supersede pass runs before the new deployment is
published rather than after, since that ordering looks arbitrary and is
not: two concurrent UpdateService calls can leak one stale IN_PROGRESS
record this way, whereas publishing first and stopping everything but
self lets one caller stop the current deployment and hang a steady-state
wait, which is the failure this branch exists to remove. Locking is not
the answer at this level, because updateService already mutates the
shared service model unsynchronised.

Drops an unreachable null check on the service ARN: the caller
dereferences the same value before calling in, so a null cannot arrive.

* fix(ecs): stop a deleted service's deployments before zeroing its count

deleteService wrote status INACTIVE and desiredCount 0, then stopped the
service's unfinished deployments several statements later. Both fields are
plain non-volatile fields of a service model shared with every reader, and
settleStatus reads them under synchronized (deployment), a monitor nothing
takes for the service. So in that window a reader could see the new
desiredCount of 0 beside a status it still read as ACTIVE, and zero
running tasks satisfies the convergence test trivially: the deployment
latched SUCCESSFUL, reporting a rollout that never happened as having
succeeded. The already-terminal guard cannot help, because the record is
still IN_PROGRESS at that point and its revision ARN still matches.

Stopping the records between the two setters closes the window rather than
narrowing it. A reader arriving earlier still sees the honest pre-delete
desiredCount, so it can only finish a deployment that really converged.
One arriving later finds the record already STOPPED, so the guard blocks
the latch whatever it sees of the service. The dangerous pairing becomes
observable only once the record is terminal anyway.

The call is safe in its new position because the helper reads nothing
about the service: it takes an ARN, a timestamp and a string, and branches
only on each deployment's own status. It stays below the force-flag
validation, so a request that throws still stops nothing.

The ordering is a correctness constraint rather than a style choice, and
nothing in the code said so, so the call site now does: moving
setDesiredCount up, or the helper back down, silently reopens this.

Reasoned, not pinned. The window is a memory-visibility race between two
threads, so single-threaded execution cannot distinguish the two orders at
all: both leave identical state. Reverting the move fails no test.

* test(ecs): identify the stopped deployment after the delete, not before

The wire test read DescribeServices to find the deployment before deleting
the service, and its javadoc claimed determinism on the grounds that
nothing read the service in that window. That read was the window. Every
response serialising a service settles that service's current deployment,
so a reconciler tick landing between the create and the read would launch
the task, the read would latch the deployment SUCCESSFUL, and the delete
would then correctly leave a terminal record alone, failing the
assertions. A few milliseconds against a 5000ms period.

The service is created once and never updated, so it has exactly one
deployment and needs no join to identify. Deleting first and listing
afterwards removes the read, and a terminal record cannot change under a
read anyway.

One window remains and is now written down rather than papered over: a
tick between CreateService putting the service in the map and that same
response being serialised would still latch it. Sub-millisecond, and not
closable from a test without stubbing the clock. The behaviour is pinned
without timing in the unit suite; this test exists for the wire mapping.

Also restores the null check on the service ARN in the stop helper. The
reason given for removing it was only half right: recordServiceDeployment
does dereference that field first, but deleteService does not, so at that
call site the check was load-bearing and removing it turned a silent
no-op into an NPE inside DeleteService. A service model can arrive by
deserialisation from the store rather than through createService, so a
non-null ARN is not an invariant, and ownedBy guards the same field for
the same reason.

* fix(ecs): settle the outgoing deployment when UpdateService supersedes it

A converged deployment was only marked SUCCESSFUL when something read it
while it was still current, so an update with no read in between left it
STOPPED. UpdateService now settles it first, before it changes the desired
count or task definition, which the settle judges against.

* docs(ecs): trim the deployment comments to what the code needs

Drops branch history and private tracker references, and corrects the
recordServiceDeployment Javadoc, which described AWS's revision ARN form
rather than the service-revision/<id> one it builds.

* fix(ecs): DeleteService settles a converged deployment before stopping it

A deployment whose tasks were up when the service was force-deleted was
marked STOPPED unless something had read it first. DeleteService now
settles it against the service as it stands, as UpdateService does.

The integration test that stops a deployment through a delete retries on
a fresh service when the reconciler converges it first, instead of
failing on that race.
2026-09-30 13:12:20 -04:00
Vinícius Macedo 5ee81e7006 fix(s3): emit ObjectRemoved:Delete when deleting a specific object version (#4710)
* fix(s3): emit ObjectRemoved:Delete when deleting a specific object version

DeleteObject with a versionId permanently removed the version but was
the only delete branch that never fired a notification. It now sends
ObjectRemoved:Delete carrying the deleted versionId, including when the
version is a delete marker. A versionId that matches nothing fires
nothing.

Closes #4680

* fix(s3): carry version-id in EventBridge S3 event details

The EventBridge detail for an S3 event listed the object's key, size and
etag but never its version, so the Object Deleted event for a permanent
version delete could not say which version went. Add object.version-id
whenever the object has one, as AWS does for versioned buckets.

* test(s3): disable the versioned bucket's EventBridge notification in cleanup

* fix(s3): set deletion-type on EventBridge Object Deleted events

AWS tells the two kinds of deletion apart in the EventBridge detail:
"Permanently Deleted" for an object or version that is gone, and
"Delete Marker Created" for a marker. Floci set neither, so the
permanent version delete looked the same as a marker to a rule written
for AWS. Derive it from the event name.
2026-09-30 11:34:32 -04:00
Niels Kootstra 888a718924 fix(s3): stream GetObject bodies from disk instead of the heap (#4691)
* fix(s3): stream GetObject bodies from disk instead of the heap

GetObject read the whole object into a byte array before responding, so
every concurrent download of a large object held a full copy in the heap.

Add S3Service.openObject, which runs the same dataGeneration check as
getObject but opens a file channel instead of reading the bytes. Writes
replace the object file with an atomic move, so the open channel keeps
serving the version its headers describe. Full, Range and website index
responses stream from it and close it on every early exit.

* fix(s3): close the object stream when a response fails to build
2026-09-30 10:57:53 -04:00
Vũ Thế Huy 184b50e2ba feat(elasticache): authenticate each RBAC user by its own authentication mode (#4536)
* feat(elasticache): authenticate each RBAC user by its own authentication mode

Resolve issue #4457.

- Add hasMembers and memberAuthMode resolution to ElastiCacheService and PasswordValidator callback.
- Allow AuthMode.NO_AUTH users to be admitted with any password (Redis ACL nopass semantics).
- Refactor ElastiCacheAuthProxy to validate each user according to their configured AuthMode (IAM, PASSWORD, NO_AUTH) when the cluster has members.
- Fallback single-arg AUTH to authToken or default user.
- Add comprehensive unit and integration tests.

* fix(elasticache): address review feedback on per-user RBAC authentication

- Allow passwordless access when default member requires no auth
- Support explicit default username with group auth token
- Clean up group associations when deleting users to avoid lockout
- Reject duplicate usernames in ModifyReplicationGroup with DuplicateUserNameFault
- Validate password strictly against the resolved user's auth mode

* fix(elasticache): require auth when default member is missing and handle HELLO AUTH

- ElastiCacheAuthProxy: require auth when group has members but no default member

- AbstractRedisAuthProxy: intercept HELLO with AUTH option on open caches and validate credentials before forwarding

- Add unit and integration tests for missing default user and HELLO AUTH on open cache

* fix(elasticache): require auth for disabled default user and reject disabled members

- ElastiCacheUser: evaluate ACL accessString to determine whether user is enabled (on) or disabled (off)

- ElastiCacheService: reject authentication for disabled users and exclude them from memberAuthMode

- ElastiCacheAuthProxy: remove obsolete unreachable comment on NO_AUTH switch arm

- Add unit and integration tests covering disabled default user and disabled members
2026-09-30 10:41:51 -04:00
mitsukado-shinagawaandmitsukado-shinagawa 955c11dc56 fix(stepfunctions): record the iterations a failing Map iteration cuts, and the state each was in (#4724)
* fix(stepfunctions): record the iterations a failing Map iteration cuts, and the state each was in

AWS records, for each iteration an inline Map failure cuts, a
MapIterationAborted and then the TaskStateAborted or WaitStateAborted
of the state it was in, all chained to the failing iteration's last
event and ahead of MapIterationFailed and MapStateFailed. Floci cancelled
the iterations and recorded nothing for them.

MapIterationScheduler cancelled the in-flight iterations without knowing
their chains, so the Map saw them only after they had left their states.
It now calls back with each in-flight index before cancelling, and the
Map reads and cuts each one in one step through abandonInState, as the
Parallel does. The failing iteration's MapIterationFailed is recorded by
the Map after the cut, so the aborted events come first; its
previousEventId is unchanged.

Closes #4722

* fix(stepfunctions): never report a Map iteration both ended and cut

The scheduler names every iteration it has not yet taken off its queue,
so an iteration that finished after the failing one was dequeued was
cut as well and recorded MapIterationAborted after its own
MapIterationSucceeded. The iteration's end event is now published under
the chain's lock together with an ended marker, and the cut reads that
marker in the same step it reads the state, so an iteration is reported
either ended or cut, never both.

* fix(stepfunctions): record the iterations a Map failure cut only with its MapIterationFailed

A States.Runtime failure records no MapIterationFailed. When it was a
declared tolerance that failure exceeded, the Map ended with
States.ExceedToleratedFailureThreshold instead, which passed the check
for the cut iterations, so they were recorded aborted without the
MapIterationFailed of the iteration that cut them. Both now follow the
one condition.

* fix(stepfunctions): record a cut Map iteration by the rule of the event it accompanies

The cut iterations are recorded right before MapStateFailed and now
follow its rule, that the failure ending the Map is not States.Runtime,
while MapIterationFailed keeps the iteration's own. Tying both to the
iteration's condition had dropped the cut iterations for an ItemSelector
that fails before its iteration starts, which has nothing to report
itself but still cuts the others and still records MapStateFailed.

An iteration is also reported cut only when its MapIterationStarted is
recorded: the start is published under the chain's lock with a started
marker, read by the cut in the same step, so an iteration cut while its
ItemSelector was still being evaluated records neither a start nor an
abort.

---------

Co-authored-by: mitsukado-shinagawa <mitsukado-shinagawa@users.noreply.github.com>
2026-09-30 10:33:37 -04:00
mitsukado-shinagawaandmitsukado-shinagawa fd094aee05 fix(stepfunctions): return the PascalCase execution envelope from states:startExecution, .sync and .sync:2 (#4737)
AWS returns, as the Task result of the optimized states:startExecution
integration (measured in ap-northeast-1 on 2026-09-30):

- request-response: the StartExecution response, {ExecutionArn, StartDate},
  StartDate in epoch milliseconds
- .sync: the child's DescribeExecution response, PascalCase with its keys
  in alphabetical order, dates in epoch milliseconds, Input and Output as
  JSON strings
- .sync:2: the same envelope with Input and Output as JSON values

Floci returned camelCase with dates in seconds for the first two and the
child's output alone for .sync:2, so a state machine written against AWS
found nothing at $.Output, $.ExecutionArn or $.Status.

The failure cause of the two .sync modes already built this envelope
(#4675). It now builds the success result too: a SUCCEEDED child carries
Output, OutputDetails and RedriveStatusReason and reports NOT_REDRIVABLE.
Request-response returns the response TaskSubmitted already records.

This changes the result shape for state machines written against Floci's
earlier one: the child output of .sync:2 moves from $ to $.Output.

Closes #4723

Co-authored-by: mitsukado-shinagawa <mitsukado-shinagawa@users.noreply.github.com>
2026-09-30 10:14:12 -04:00
Langning Zhang d267ba3a9d fix(ses): validate EventBridge default bus ARNs (#4677)
* fix(ses): validate EventBridge default bus ARNs

Signed-off-by: boulea7 <zln1905391059@163.com>

* fix(ses): reject EventBridge bus account and Region mismatches

Signed-off-by: boulea7 <zln1905391059@163.com>

---------

Signed-off-by: boulea7 <zln1905391059@163.com>
2026-09-30 10:00:19 -04:00
Hector Ventura 99c1c4129a fix(iam): derive the AWS managed policy catalog per partition (#4742)
The bundled managed policy catalog is the commercial one, so
arn:aws-cn:iam::aws:policy/AdministratorAccess did not resolve and a China
deployment listed commercial ARNs. Every other partition's catalog is now
derived from the bundled data on first use and cached per partition: every
arn:aws: inside a document takes the partition, as AWS's SAM translator does
for managed policy ARNs (arn_generator.py), and the region-bearing
kms:ViaService hosts (s3.*.amazonaws.com) take the partition's DNS suffix.
Bare service principals and service-linked role paths are universal (#4633)
and are left alone, as is the ::aws:policy/ owner slot.

IamService resolves a managed policy under the partition its ARN names, so a
China ARN resolves under any signing scope, and ListPolicies lists the catalog
of the caller's partition.

Partition literal baseline 4 -> 3.

Part of #4272
2026-09-30 09:20:49 -04:00
David 5aad012e78 feat(emr-serverless): tag, untag and list tags for applications (#4667)
EMR Serverless had no tagging API: no TagHandler was registered for the
emr-serverless ARN service, so TagResource, UntagResource and
ListTagsForResource could not be routed, and a tagged
aws_emrserverless_application could not be planned.

Register an emr-serverless handler with the shared /tags dispatcher,
answering 200 as the model does, over the tags already stored on the
application. Validate keys and values, the user guide's 50 tag limit
and its reserved aws: prefix, refuse job run ARNs as not found, and
synchronize the application mutators so a tag write cannot lose a
concurrent update.

Closes #4662
2026-09-30 09:11:04 -04:00
Priamo Germosen 48214e04e0 fix(codeartifact): extend idempotent asset republish to Published versions (#4708)
Two follow-ups hectorvent flagged on #4619, approved but marked as
separate-PR material:

Compares an existing asset's persisted SHA-256 instead of reading its
bytes. The hash is normal metadata (not @JsonIgnore like the content
field), so this needs no disk read, no in-memory-store lookup, and no
special case for a backing file that happens to be missing - a stored
hash never "goes missing" the way a file can, and a genuinely different
republish still conflicts even when the file is gone, closing a gap the
previous byte-comparison approach had.

Extends the idempotent-retry allowance to an already-Published version.
AWS's "Overwriting package assets" rule isn't scoped to Unfinished, and
the terminal publish call (the one that actually finishes a version) is
the likeliest one a client retries after a dropped response. A brand-new
asset name against a Published version still always conflicts; only a
byte-identical replay of an asset that's already there is idempotent.
2026-09-30 08:00:43 -05:00
Priamo Germosen f752946acf refactor(secretsmanager): build the rotation function ARN with Lambda's own helper (#4709)
Follow-ups from the review of #4697.

rotationFunctionArn built the partial-ARN case by string concatenation while the bare-name case went
through AwsArnUtils.Arn. Turning a FunctionName reference into a full function ARN is Lambda's
knowledge, so it now lives in LambdaArnUtils.functionArn, next to eventSourceMappingArn: the
reference is read with LambdaArnUtils.resolve, the parser Lambda itself uses, and every case is
minted through AwsArnUtils.Arn from the parts. Secrets Manager calls it with the secret's partition
and account, and keeps no Lambda layout of its own. ResolvedFunctionRef also carries the account a
full or partial ARN names (null for a bare name), which the helper needs.

A reference Lambda cannot read, such as a Region-prefixed partial ARN, is now refused with Lambda's
InvalidParameterValueException before the permission check, instead of being minted with the Region
twice and failing later at the function lookup.

The missing-function message names its service principal through ServicePrincipals.of, as AGENTS.md
now asks, in place of the literal marked partition-invariant in #4697.

The comment on the caller == null branch of IamEnforcementFilter.authorizeAdditionalResource said the
path only served a presigned POST whose signature was already verified. It now also serves CopyObject,
RotateSecret and SSM GetParameter, and even for the presigned POST the signature check runs after
it, and only when S3 auth enforcement is on. The comment now says what actually makes an unknown key
safe on each path.
2026-09-30 08:00:21 -05:00
Niels Kootstra 6df2a6cfc2 fix(ssm): run direct executions on virtual threads (#4689)
* fix(ssm): bound direct-execution threads for SendCommand

Each SendCommand target backed by a Floci EC2 container ran on a cached
thread pool, so a command with many targets started one thread per target,
each held for the whole container exec (up to TimeoutSeconds). Use a fixed
pool of max(4, availableProcessors) daemon threads instead; extra targets
wait in the executor queue and still complete.

* fix(ssm): run direct executions on virtual threads

* fix(ssm): keep a cancelled invocation cancelled when its exec finishes
2026-09-30 08:43:47 -04:00
mitsukado-shinagawaandmitsukado-shinagawa 6ca104042b fix(stepfunctions): fail a Parallel the moment any branch fails, whichever is listed first (#4713)
executeParallelState joined the branch futures in declaration order, so a
failure in a later branch was only seen once every earlier branch had
returned: a .sync Task listed before the failing branch kept the Parallel
running until its job ended on its own, and a Wait listed first until the
Wait ended. AWS fails the Parallel within about 0.1 s of the failing branch
either way (measured in #4646).

The branches now go through an ExecutorCompletionService, as the Map
iterations already do, and are polled as they complete under the same two
deadlines. The failed branch is the one whose future came off the queue, so
continueFrom and the aborted-state events of #4660 attach to the same chain.
The outputs are collected by branch index and still come back in declaration
order.

Closes #4646

Co-authored-by: mitsukado-shinagawa <mitsukado-shinagawa@users.noreply.github.com>
2026-09-30 07:00:42 -04:00
Daniël van Ziel b0b191e0bc fix(lambda): poll Kinesis event source in the mapping account (#3964) 2026-09-30 06:40:52 -04:00
mitsukado-shinagawaandmitsukado-shinagawa 2eadc106c5 fix(stepfunctions): record TaskSubmitted for a .sync Task, named as AWS names it (#4719)
* fix(stepfunctions): record TaskSubmitted for a .sync Task, named as AWS names it

AWS records TaskSubmitted for every .sync Task once the call that starts
the job has returned and before it waits on the job, chained to
TaskStarted and carrying that call's response as output in PascalCase:
{ExecutionArn, StartDate} in epoch milliseconds for states:startExecution
.sync and .sync:2, {Failures, Tasks} for ecs:runTask.sync. Floci recorded
nothing between TaskStarted and the terminal event, so a client reading
the job's id from the history found nothing until the Task ended.

The two poll loops do not have the HistoryChain; invokeResource hands
them a callback that publishes the event. The SDK's SdkHttpMetadata and
SdkResponseMetadata, which AWS folds into the response, are left out,
as everywhere else in Floci.

The task event profile also split a well-formed integration id at its
last colon, so every event of a .sync:2 Task read resourceType
states:startExecution.sync, resource 2. AWS reports states /
startExecution.sync:2, so a parsed id now splits at its service.

Closes #4648

* test(stepfunctions): name the types in the TaskSubmitted history test

* fix(stepfunctions): stop the job when TaskSubmitted cannot be recorded

TaskSubmitted is the first event after the job exists. When it is the
event that hits the 25,000-event history limit, the publish throws
before the poll loop whose catch stops the job is entered, so the parent
failed with States.Runtime while the child execution or ECS task ran on.
Both loops now abort the job on that path, the way the wait would have.

---------

Co-authored-by: mitsukado-shinagawa <mitsukado-shinagawa@users.noreply.github.com>
2026-09-30 06:35:09 -04:00
Mario Toffia 560de5c13f fix(tagging): find resources by the tags their own service holds (#4563)
* fix(tagging): list resources by the tags their own service holds

GetResources, GetTagKeys and GetTagValues merge the tagging store with every
ResourceProvider, so SQS, Lambda and Logs tags are discoverable. Resource type
filters now parse colon and leading-slash ARNs (function:f, log-group:x, /apikeys/k),
and TagResources/UntagResources write through to the owning TagHandler.

* fix(apigateway): expose tagged resources and API key tags to the tagging API

ApiGatewayService is a ResourceProvider for REST APIs, stages, API keys, usage plans and
domain names, and ApiGatewayTagHandler serves /apikeys/<id> ARNs, so GetResources finds
API Gateway resources by tag and tagging-API writes land on the API key itself.

* fix(cloudformation): forward AWS::Lambda::Function Tags

CreateFunction now receives the template Tags; an in-place UpdateStack untags dropped keys and retags the desired set, mirroring SqsCfnProvisioner.

* fix(tagging): scope global-ARN resources by region and clamp stale page tokens

Provider resources with an empty ARN region use their own region, stale page tokens
past the end return an empty page, and provider tags are copied inside the skip guard.

* test(compat): discover SQS, Lambda, Logs and API Gateway resources by tag

* docs(tagging): describe owning-service discovery

* fix(tagging): forward tags only for resources the owning service lists

* fix(apigateway): report the calling account and tag usage plans

* docs(cloudformation): note Lambda tag reconciliation on update

* fix(tagging): match declared resource types and scope owner writes to the request

API Gateway API key and usage plan ARNs must now name the key or plan at the
start of the resource part, so a nested /apikeys/ segment no longer tags the key.

* fix(tagging): match AWS type filters, regions and failure codes

Compared against a live AWS account: type filters, IAM listing, cross-region
TagResources and FailedResourcesMap entries now answer as AWS does.

* fix(cloudformation): keep Lambda tags added outside the template

* fix(tagging): route TagResources to V1 tag handlers too

* fix(apigateway): reject sub-resource ARNs when tagging a REST API

* fix(tagging): write tagging API tags through to SQS, Lambda and Logs

TagResources and UntagResources now reach the queue, function or log group's own tags through TagHandler beans qualified @TaggingApiOnly, so ListQueueTags, Lambda ListTags and Logs ListTagsForResource show them. The qualifier keeps these handlers off the /tags/{arn} and /v1/tags/{arn} paths, since each service defines tags in its own protocol.

* fix(cloudformation): forward SSM parameter tags

AWS::SSM::Parameter now applies its Tags after the overwriting put. On UpdateStack only the keys the previous template set and the new one drops are removed, tracked in the internal FlociSsmTemplateTagKeys attribute, so tags added outside the template are kept.

* fix(tagging): hide tagging-store copies of global resources

GetResources no longer lists an IAM role or user tagged through TagResources, since AWS never lists global resources.

* fix(tagging): reject every wildcard log group ARN

TagResources and UntagResources now send a log group ARN ending in :* to CloudWatch Logs even when the group does not exist, so it is rejected as in AWS instead of stored.

* fix(tagging): clear store tags on every untag

UntagResources now removes the keys from the tagging store for every ARN, even one the owning service rejects, so a copy stored earlier can always be cleared.

* fix(cloudformation): tag an adopted Lambda function

When CreateFunction conflicts and the provisioner adopts the existing function, the template's tags are now applied to it.

* fix(apigateway): tag only exact domain and stage ARNs

A domain or stage segment nested elsewhere in an API Gateway ARN, such as /restapis/<id>/domainnames/<d>, is now rejected instead of tagging that domain or stage.

* fix(cloudformation): leave an adopted Lambda function's tags alone

Adoption uses the existing function as it is, as before, so a function outside the stack keeps its tags.

* fix(cloudformation): record no template tag keys for an adopted Lambda function

An adopted function keeps its own tags, so a later update adds the template's tags without removing any it never set.

* fix(tagging): never list IAM ARNs from the tagging store

A role tagged through TagResources stays hidden after DeleteRole, as AWS never lists IAM resources.

* fix(tagging): fail a write when an owning service cannot be read

A provider that fails while routing TagResources or UntagResources now returns InternalServiceException instead of writing the tagging store and reporting success.

* fix(tagging): fail only unresolved ARNs when a provider cannot be read

A provider failure no longer fails the whole TagResources or UntagResources call; only ARNs whose owner could not be resolved are reported in FailedResourcesMap.

* fix(tagging): report another account's ARN instead of storing it

TagResources and UntagResources report an ARN from another account in FailedResourcesMap with AccessDeniedException, as AWS reports it per ARN, and never write it to the tagging store.

* fix(tagging): keep stored tags for an ARN an untag could not resolve

UntagResources leaves the tagging store unchanged for an ARN it reports as unresolved or from another account; an ARN its owner rejected is still cleared.

* fix(tagging): fail an unresolved ARN only when its own service cannot be read

A provider failure now only affects unlisted ARNs of the services that provider declares.

* fix(tagging): copy stored tags under the writers' lock

GetResources, GetTagKeys and GetTagValues no longer race a concurrent TagResources on a stored mapping.

* fix(apigateway): reject reserved tags when tagging a usage plan

TagResources on a usage plan now refuses floci:override-id as the other API Gateway tag paths do, instead of dropping it and reporting success.

* fix(apigateway): reject tag ARNs with an account or another region

The /tags path now answers an ARN with an account segment with BadRequestException and one naming another region with NotFoundException, as AWS does, instead of resolving the id in the caller's region.

* fix(ssm,lambda): reject tag keys outside the AWS pattern

AddTagsToResource, PutParameter, TagResource and CreateFunction now reject a tag key outside the AWS pattern or 1 to 128 characters with ValidationException, as AWS does, which also keeps the CloudFormation managed-key attributes lossless.

* fix(ssm,lambda): validate CloudFormation tag keys before changing the resource

* docs(tagging): say every handled ARN ending in :* reaches its service

* fix(tagging): read a negative pagination token as the first page
2026-09-30 06:10:27 -04:00
vamsiakandVamsi Akavarapu af3d387140 fix(apigateway): route REST execute-api virtual hosts (#4553)
* fix(apigateway): route REST execute-api virtual hosts

* fix(apigateway): preserve REST connection paths

* fix(apigateway): prioritize WebSocket connection routes

* fix(apigateway): honor explicit REST domain routes

* fix(apigateway): preserve WebSocket domain connections

* fix(apigateway): scope base path routes to REST APIs

* fix(apigateway): retain API type for domain mappings

* fix(apigateway): find WebSocket connection routes across accounts

---------

Co-authored-by: Vamsi Akavarapu <16164447+vamsiak@users.noreply.github.com>
2026-09-30 06:07:57 -04:00
XuJian a5dd3c2f2e fix(cloudhsm): add issuer key identifiers to hardware chain (#4707)
* fix(cloudhsm): add issuer key identifiers to hardware chain

* fix(cloudhsm): certify the shared hardware key twice

* chore(cloudhsm): sort service imports
2026-09-30 06:00:13 -04:00
Niels Kootstra 70efa35fe3 fix(codebuild): keep only the tail of phase output for failure messages (#4690)
* fix(codebuild): keep only the tail of phase output for failure messages

runPhase buffered every byte a phase printed in a ByteArrayOutputStream,
but only the last 512 characters reach the failure message. A phase with
gigabytes of logs held them all in the heap, and past 2 GiB the buffer
threw OutOfMemoryError. Keep a fixed 4 KiB tail instead.

Strip trailing whitespace before taking the last 512 characters. The
offset was computed on the unstripped text, so more than 512 trailing
whitespace characters replaced the message with an index error.

* fix(codebuild): keep the last error when a phase ends in long whitespace

* test(codebuild): name runner test after the class it covers
2026-09-30 05:54:50 -04:00
TATSUNO “Taz” Yasuhiro e6ee346761 feat(sqs): expire messages after MessageRetentionPeriod (#4706)
* feat(sqs): expire messages after MessageRetentionPeriod

ReceiveMessage, GetQueueAttributes counts, the inspection endpoint and
StartMessageMoveTask skip messages older than the queue's retention
period. A sweeper frees expired messages every 60 seconds.

As on AWS, a standard DLQ keeps the original enqueue time, while a FIFO
DLQ and StartMessageMoveTask start the retention period over.
SentTimestamp is kept in all cases.

* fix(sqs): drop messages that expire during a rate-limited move task

* test(sqs): cover a failing retention sweep

* test(sqs): make the rate-limited move task expiry test deterministic

* test(sqs): assert the expiring message is live when the move task starts

* fix(sqs): reject MessageRetentionPeriod outside 60 to 1209600 seconds
2026-09-30 00:03:48 -04:00
Allen Sanborn 6b7d17698c fix(ec2): an interface VPC endpoint reports its network interfaces, and they resolve (#4598)
* fix(ec2): report an interface VPC endpoint's network interfaces

DescribeVpcEndpoints never emitted networkInterfaceIdSet, so an interface (PrivateLink)
endpoint came back with no interfaces at all. Terraform's aws_vpc_endpoint surfaces that
element as network_interface_ids, and modules feed the output downstream to
security-group rules, flow-log filters and DNS, so the empty list does not merely differ
from AWS: it propagates into whatever consumes it.

The interfaces already existed. Ec2Service.endpointNetworkInterfaces derives one per
subnet deterministically, with a stable id, the subnet's availability zone and
interfaceType vpc_endpoint, so flow-log generation can attribute AWS-service traffic to a
stable endpoint address. Nothing reported them on the wire.

So this adds a reader rather than a new resource. endpointNetworkInterfaceIds returns the
same ids that endpointNetworkInterfaces synthesizes, reusing endpointEniId, deliberately
derived instead of stored: a second, stored copy could disagree with the one flow-log
attribution reads, and then two answers would exist for one question. It mirrors the
existing endpointDnsEntries accessor, which the same XML writer already calls.

A Gateway endpoint is a route-table entry and owns no interfaces. AWS reports none for
one, and so does this: the element is omitted rather than emitted empty.

Ec2VpcEndpointNetworkInterfaceIdsIntegrationTest covers one interface per subnet with
distinct ids, the ids being stable across two DescribeVpcEndpoints calls (Terraform reads
them between plan and apply), a single-subnet endpoint reporting exactly one, and a
gateway endpoint reporting none. That last case is what stops a change that simply
emitted the set unconditionally from passing.

Verified by reverting the emission alone: 2 of the 3 tests fail, and the gateway case
correctly still passes. Restored, all 3 pass.

Ec2*Test is 1246 tests with 2 failures, both in Ec2VolumeBlockDeviceDockerIntegrationTest
(Docker block devices, mke2fs). Measured on a clean checkout of upstream/main with these
changes removed: the same 2 fail. Pre-existing and environment-specific, not from this
change.

* fix(ec2): reattach the DnsEntries javadoc to its own method

The previous commit inserted endpointNetworkInterfaceIds and its javadoc between the
endpointDnsEntries javadoc and endpointDnsEntries itself. Java binds a doc comment to the
next declaration, so that left two consecutive blocks on the new method -- the first
dangling, the second the real one -- and endpointDnsEntries documented by nothing.

Moving the new method above the DnsEntries javadoc restores that binding and puts the
accessor next to endpointEniId, the helper whose ids it returns. Comment placement only;
no behaviour changes.

Ec2VpcEndpointNetworkInterfaceIdsIntegrationTest: 3 tests, 0 failures.

* refactor(ec2): derive endpoint ENI ids from the interfaces, not beside them

Review found that the javadoc on endpointNetworkInterfaceIds asserted an invariant the
code did not have. It said the ids were derived from endpointNetworkInterfaces so a
second copy could not disagree with what flow-log attribution reads. They were not
derived from it: both called endpointEniId independently, and they filtered differently.
endpointNetworkInterfaces skips a subnet whose record has gone; the id method emitted one
for every entry of getSubnetIds() unconditionally.

The gap is reachable. deleteSubnet checks only for transit-gateway attachments, so
nothing stops a subnet being deleted out from under a live endpoint, and the two were
then measured reporting different sets -- two answers to one question, with flow-log
attribution reading the shorter. Real AWS answers DependencyViolation to that delete and
Terraform's graph destroys the endpoint first, so the state is reachable only in an
emulator. That is the argument for the emulator staying self-consistent in it, not
against.

Extracts endpointNetworkInterfacesOf(VpcEndpoint). The region-wide
endpointNetworkInterfaces(String) is now that method looped, and the id list is mapped
over it, so one copy of the subnet-existence filter serves both and congruence holds by
construction rather than by inspection.

A distinct NAME rather than an overload: endpointNetworkInterfaces(VpcEndpoint) beside
endpointNetworkInterfaces(String) makes a Mockito any() ambiguous, and
FlowLogServiceTest:31 already uses one. Caught by the compiler; a new method should not
make an existing test stop compiling.

Incidental saving: vpcEndpointXml called the region-wide scan once per endpoint in a
response, so DescribeVpcEndpoints was quadratic in subnet lookups. It no longer is.

THE TEST WAS DECORATIVE UNTIL IT WAS MEASURED. Its first draft compared the wire ids to
the service's list for an endpoint whose subnets all still existed -- a case where both
derivations trivially agree, and it passed against the buggy version. It now deletes a
subnet out from under the endpoint first. Verified both ways: it FAILS on the old
independent derivation and PASSES on this one.

Ec2VpcEndpoint*, FlowLogServiceTest, Ec2ServiceTest and Ec2NetworkInterfaceIntegrationTest:
1251 tests, the only failures being Ec2VolumeBlockDeviceDockerIntegrationTest's known 2
of 8 (Docker block devices, mke2fs), measured identically on a clean upstream/main
checkout.

Not addressed here, filed separately: the ids this publishes do not resolve through
DescribeNetworkInterfaces, which never consults endpointNetworkInterfaces. Real AWS
returns endpoint ENIs there as requester-managed with interfaceType vpc_endpoint. That
gap predates this branch; publishing ids makes it visible rather than creating it, and no
corpus module looks one up today.

* docs(ec2): narrow the congruence claim to what the code actually guarantees

Three findings from review of #21, none behavioural.

The javadoc said the wire ids are BY CONSTRUCTION "the interfaces flow-log attribution
reads". Within one account that is exact -- vpcEndpoints.scan and subnets.get share a
prefix and both stores are account-wrapped. But FlowLogService runs on a scheduler with
no request context, so it reads the default account while this path reads the caller's;
for a non-default account the flow-log side sees no endpoints at all. Each side stays
internally consistent, which IS the property the refactor established and the one worth
claiming. Both seeing the same endpoints is not, and the absolute phrasing claimed it.
Restated as shared derivation rather than shared view.

endpointNetworkInterfacesOf was public with no caller outside the class -- not in
Ec2QueryHandler, which calls endpointNetworkInterfaceIds, and not in any test. Every
sibling helper in the same block is private (endpointEniId, endpointDnsDiscriminator,
endpointServiceToken, endpointPrivateIp), so public was the outlier. Now private. The
javadoc's argument for the distinct NAME stands untouched; that was about the Mockito
ambiguity, not the visibility.

The same javadoc cited FlowLogServiceTest:31 for that ambiguity. The line is 44 on this
base, and a comment carrying a line number is wrong again at the next rebase, so it now
names the stub instead.

Also drops a stray backslash in "method\'s" that survived from the heredoc the comment
was written in.

* test(ec2): say what the gateway case actually catches, which is less than claimed

The class javadoc and the PR description both said the gateway assertion is "what stops a
change that simply emitted the set unconditionally from passing". It is not. The emission
is guarded by `if (!endpointEniIds.isEmpty())`; remove that guard and a gateway endpoint
gets an empty `<networkInterfaceIdSet/>`, whose `item` list is empty, so
`eniIdsOf(...).isEmpty()` still holds and the test still passes.

Found by review of #21. Third claim on this branch that asserted more than the code
delivered -- after the javadoc that claimed a congruence invariant the code lacked, and
the one that claimed both sides see the same endpoints across accounts.

Not fixed by tightening the assertion to pin absence, which was the obvious move and the
wrong one: real AWS emits the empty element where this omits it. Absent and empty are
indistinguishable to any ec2query SDK, and Terraform's TypeSet lands both as an empty set,
so the behaviour is fine -- but an assertion pinning absence would pin the side of that
choice further from AWS, and make a later move toward AWS look like a regression.

So the comment now states the limit instead. The case still earns its place as a
regression guard: a gateway endpoint must never report interface ids.

Also orders the new test's imports like the sibling SubnetConfiguration suite.

* fix(ec2): an endpoint on a subnet whose CIDR is not dotted IPv4 must still answer

Both findings from the Greptile review of #4598.

P1. endpointPrivateIp splits the subnet's CidrBlock on dots and reads parts[1] and
parts[2]. CreateSubnet calls setCidrBlock with whatever it was given and never validates
the address family, so the value is not guaranteed to be dotted IPv4 -- "2001:db8::/56"
splits to one element and parts[1] throws.

This PR is what makes that reachable from a request. Deriving an endpoint's interfaces
used to happen only on the flow-log scheduler, where a throw was contained; it now also
happens while rendering CreateVpcEndpoint and DescribeVpcEndpoints, so the same odd subnet
turns into a failed EC2 response rather than a degraded address. Measured, with the guard
removed:

  Unhandled error dispatching Query action CreateVpcEndpoint for service ec2:
  java.lang.ArrayIndexOutOfBoundsException: Index 1 out of bounds for length 1

Falls back to the same default the existing null-CidrBlock branch already uses, so "no
usable IPv4" has one behaviour instead of two. Deliberately NOT fixed by validating in
CreateSubnet: rejecting a non-IPv4 CidrBlock is what AWS does and is probably right, but
it is a behaviour change with a wider blast radius than this PR should carry, and it would
not help an IPv6-only subnet, which legitimately has no IPv4 CIDR at all.

anEndpointOnASubnetWithoutIpv4StillAnswers is a regression guard and states so. Measured
both ways: it FAILS at CreateVpcEndpoint without the guard and PASSES with it. Reviewer
found the defect by reading; the test is what keeps it found.

P2. Import order -- io.restassured sorts before jakarta. I reordered the first two imports
in an earlier commit and did not notice the same rule applied further down the block.

Ec2VpcEndpoint* and FlowLogServiceTest: 52 tests, 0 failures.

* fix(ec2): the non-IPv4 fallback gave every subnet on an endpoint the same address

Second Greptile round on #4598, and a defect introduced by the fix for the first.

The crash fix fell back to a CONSTANT network, 172.31.0.0. The host octet is derived from
the ENDPOINT, so it is identical across that endpoint's interfaces; on the IPv4 path the
only thing making them distinct is each subnet supplying its own network. Collapsing the
network to a constant threw that away, so every non-IPv4 subnet on one endpoint got the
same private address -- a crash traded for a silent collision. Measured:

  got [172.31.0.249, 172.31.0.249]

The third octet now comes from the subnet id, restoring the property the IPv4 path has by
construction rather than by luck. The ENI ids were never affected -- endpointEniId already
mixes the subnet in -- and the new test asserts both, so a later change cannot fix one and
break the other.

twoSubnetsWithoutIpv4GetDistinctAddresses measured both ways: it FAILS on the constant
fallback with the collision above and PASSES with the subnet-derived one. The existing
non-IPv4 test could not have caught this: it uses a single subnet, where a collision has
nothing to collide with.

Ec2VpcEndpoint*, FlowLogServiceTest, Ec2ServiceTest, Ec2NetworkInterfaceIntegrationTest:
264 tests, 0 failures.

* test(compat): validate the endpoint's network interface ids through the Java SDK

Greptile's P2 on #4598. The integration test asserts the wire element over RestAssured,
which is deliberate -- an absent networkInterfaceIdSet and an empty one are different
things and only raw XML can tell them apart. But AGENTS.md's "Management APIs should be
validated with AWS SDK clients, not only handcrafted HTTP requests" sits under AWS Protocol
Rules, not under Compatibility Project, so it is general and "not only" is the operative
phrase. Both, not either.

src/test cannot host it: the main module has no AWS SDK dependency at all. sdk-test-java is
where the repo keeps SDK validation and already had 60 EC2 tests, covering
DescribeVpcEndpointServices but not an endpoint's own interfaces.

What this proves that the XML assertions cannot: that the real Java SDK DESERIALIZES the
element into networkInterfaceIds(). A response can be well-formed XML and still not populate
the model -- a wrong element name or nesting fails silently and leaves an empty list rather
than raising, which is the exact symptom this PR fixes.

Asserted on CreateVpcEndpoint and again on DescribeVpcEndpoints, and that the two agree,
because Terraform reads from one and re-reads from the other between plan and apply.

DeleteVpc moves from @Order(50) to @Order(51) so this runs while the shared VPC still
exists.

* fix(ec2): an endpoint's published interface ids have to resolve too

Blocking finding from hectorvent on #4598, and the gap it names is one this branch
filed as separate work (floci-5wby) on reasoning that turns out to be wrong.

DescribeVpcEndpoints publishes one ENI id per subnet in networkInterfaceIdSet.
describeNetworkInterfaces enumerated instance-attached interfaces and the standalone
CreateNetworkInterface store only, never endpointNetworkInterfaces, so asking about a
published id got InvalidNetworkInterfaceID.NotFound from the same emulator that had
just handed it over.

WHY IT CANNOT SHIP SEPARATELY. The bead argued no corpus module writes
data "aws_network_interface", so nothing resolves one. The corpus check was right and
the conclusion was wrong: the provider does the lookup ITSELF, inside its own read of
aws_vpc_endpoint. resourceVPCEndpointFlatten calls
findSubnetConfigurationsByNetworkInterfaceIDs over every id in network_interface_ids to
build subnet_configuration, and returns the lookup error rather than tolerating a
NotFound -- it handles retry.NotFound for the prefix list a few lines above and
pointedly does not here. So the blast radius is not "modules that look up an ENI", it is
every interface endpoint read. Publishing the ids without this turns an empty list on
main into a hard read failure, which is a regression against main rather than a
pre-existing gap left unfixed.

Endpoint interfaces now answer describeNetworkInterfaces: listed unfiltered, resolvable
by id, and selectable by interface-type, subnet-id and vpc-id. interface-type had no arm
at all, so it matched everything through the default; requester-managed is new alongside
it.

WIRE SHAPE. interfaceType vpc_endpoint and requesterManaged true, which is what AWS
reports for an interface it creates on the customer's behalf, and requesterManaged is now
emitted for every interface, false included, as the documented sample response does.
requesterId is left unset on purpose: real AWS reports an internal service account there,
which floci cannot know, and an invented twelve-digit id would be a wrong answer rather
than a missing one. No attachment block, for the same reason -- AWS reports one carrying
an AWS-side owner alias that would have to be fabricated, and the provider reads none of
it.

The new arm is deliberately NOT account-scoped, unlike the two above it. describeVpcEndpoints
is not account-scoped either, so scoping here would leave an id that IS published to a
caller unresolvable BY that caller -- the exact defect being closed. Its ids are added to
foundIds before the filter check, matching the other arms, so an id asked for by name and
then excluded by a filter is absent from the answer rather than NotFound.

Measured both ways at 1608dc7. Before: 5 of the new class's 6 tests fail, the id lookup
answering

  <Code>InvalidNetworkInterfaceID.NotFound</Code>
  <Message>The network interface ID 'eni-787c7b66a5503789b' does not exist</Message>

for an id DescribeVpcEndpoints had just published. After: 6 of 6 pass. The sixth is the
guard that an id which was never published still does not exist, and it passes both ways --
a store that resolves everything would satisfy the other five.

Ec2VpcEndpoint*, Ec2NetworkInterfaceIntegrationTest, FlowLogServiceTest, Ec2ServiceTest,
Ec2IntegrationTest, plus the two internal describeNetworkInterfaces callers
(EcsFargateTaskIntegrationTest, EksVpcRouteProgrammingTest) and CloudControlIntegrationTest:
504 tests, 2 failures, both in Ec2VolumeBlockDeviceDockerIntegrationTest and both measured
failing identically on this head with the change reverted -- a loopback mount inside the
container returning EINVAL on this machine, which no ENI path reaches.

* docs(ec2): drop the private tracker ids from shipped source

Second point on #4598: floci-5vs is an id in a private tracker, so an upstream reader
cannot resolve it. The sentence it sat in stands on its own -- the parenthetical was
the only part carrying the dangling pointer.

Two more of the same kind, both introduced by the previous commit on this branch rather
than pre-existing: floci-5wby on the new describeNetworkInterfaces arm, and the same id
in the new test class's javadoc. The test keeps its floci-io/floci#4598 reference, which
is this PR and resolves for anyone reading it.

The PR's diff now adds no tracker-shaped id at all. Note that upstream main already
carries several on lines this branch does not touch -- floci-kt9 appears eleven times in
Ec2Service alone, plus floci-k41 and the floci-3wz the review cites -- so this is the
convention changing, not a slip being corrected, and the rest is left where it is rather
than widened into this fix.

Deliberately NOT the javadoc trimming the review asks for in the same breath. That was
sequenced as a separate follow-up PR and the branch-history lines it targets are a
different problem from an unresolvable id.

Comment-only. Ec2VpcEndpoint*, Ec2NetworkInterfaceIntegrationTest, FlowLogServiceTest:
89 tests, 0 failures.

* fix(ec2): an endpoint's interfaces carry its security groups, and own their owner

Third review round on #4598. One finding is real, one rests on a misreading I had
written into the code myself, and the correction runs the other way from what was asked.

SECURITY GROUPS -- the real one. An interface endpoint's security groups are enforced ON
its interfaces; that is the entire mechanism by which a PrivateLink endpoint is
firewalled, and AWS reports them in each interface's groupSet. Floci reported an empty
groupSet, so a group-id filter excluded the very interfaces the group is attached to.
The group name is best-effort: it is cosmetic, the id is what filters and rules match on,
and the lookup reads the caller's account while FlowLogService runs on the default one,
so a miss omits the name rather than inventing one.

ACCOUNT SCOPING -- the misreading, and it was mine. The previous commit justified leaving
this arm unscoped by asserting that describeVpcEndpoints is not account-scoped either,
citing its vpcEndpoints.scan(k -> true). That is wrong. Plain scan on an
AccountAwareStorageBackend filters to the caller's partition before the predicate runs:
k -> true selects every KEY within one account, not every account. The endpoint side was
scoped all along, and so is the subnet lookup inside endpointNetworkInterfacesOf, which
would yield no interfaces for a foreign endpoint even if one were reached. Two
independent layers, neither visible at the call site.

So the review's conclusion -- that this arm exposed other accounts' interfaces -- does
not hold, and neither did my stated reason for writing it that way. Measured rather than
argued: deleting an account filter from the describe arm changes no observable behaviour,
because the scoping is not there to begin with. The arm is therefore left as it was and
the COMMENT is corrected, since the comment was the defect.

ownerId is the part of that finding with a real kernel, and it is fixed: it now comes
from callerAccountId(), the account these interfaces were actually read under, instead of
from safeAccount. The explicit-account overload can set safeAccount to an account this
ambient-scoped arm cannot honour, and labelling a resource with an account it did not
come from is worse than either showing or hiding it.

Also: the not-found matcher is statically imported rather than inline-qualified, per
AGENTS.md.

TESTS. anEndpointInterfaceCarriesTheEndpointsSecurityGroups measured both ways -- it
FAILS with the group loop removed ("expected: <[sg-13d37d8313c325d98]> but was: <[]>")
and passes with it, and it asserts the group-id filter as well as the groupSet, since the
empty-groupSet bug satisfies neither. anotherAccountsEndpointInterfacesAreInvisible is
labelled in the source as what it is: a characterization test that passes with and
without an account filter, kept because it pins the behaviour a reviewer doubted rather
than the mechanism, and positioned to fail if either scoping layer changes.

Ec2VpcEndpoint*, Ec2NetworkInterfaceIntegrationTest, FlowLogServiceTest, Ec2ServiceTest,
Ec2IntegrationTest, EcsFargateTaskIntegrationTest, EksVpcRouteProgrammingTest,
CloudControlIntegrationTest: 499 tests, 0 failures.

* test(compat): the endpoint SDK test creates the fixtures it needs

The ordered suite shares mutable fixtures, so what exists at a given point is a function
of position. @Order(44) deletes the shared subnet and sets subnetId to null and
@Order(45) deletes the shared security group, both before this @Order(50) test ran: it
was passing a null subnet id to CreateVpcEndpoint and asserting groups() was non-empty
while supplying no group at all.

It now creates its own subnet and security group, uses them, and deletes them in the
same finally block that already removed the endpoint.

Worth noting why neither half failed loudly enough to catch earlier: compatibility-tests
is not a module of the root pom, so `./mvnw test` never compiles or runs it. Verified
here by building the module directly.

Authored by Allen; committed from the branch worktree alongside the review round.
2026-09-29 22:28:01 -04:00
Simone Primarosa c0ec98b43e feat(ec2): return spot price history for known instance types (#4698)
* feat(ec2): return spot price history for known instance types

* fix(ec2): address review feedback on spot price history pagination and platforms

* style(ec2): fix import ordering and inline qualified class names
2026-09-29 22:05:16 -04:00
XuJian 433893d298 feat(cognito): support software-token MFA setup and challenges (#4620)
* feat(cognito): require TOTP MFA after primary authentication

* test(cognito): verify TOTP MFA with Java SDK

* fix(cognito): reject disabled users completing TOTP challenges

* fix(cognito): preserve new-password trigger through TOTP

* fix(cognito): gate custom password auth with required MFA

* fix(cognito): limit failed TOTP verification attempts

* fix(cognito): report code mismatch for invalid TOTP setup
2026-09-29 19:43:09 -05:00
XuJian e6894119f4 fix(iam): populate PrincipalIsAWSService for signed requests (#4695)
* fix(iam): set PrincipalIsAWSService for signed IAM requests

* fix(iam): apply global conditions to additional resources

* fix(iam): accept JSON booleans in Bool conditions
2026-09-29 20:37:36 -04:00
Hector Ventura 43ed79d15b fix(core): service principals are universal in every partition; accept the legacy forms (#4633)
* fix(core): service principals are universal in every partition; accept the legacy forms

A service principal is <service>.amazonaws.com in every partition, the rule the CDK applies
(region-info.ts, principals.ts). Floci now emits it through ServicePrincipals.of: generated trust
policies, SAM's Lambda permissions, CloudTrail's eventSource, service-linked role paths (Macie,
GuardDuty, Connect, Application Auto Scaling, RAM, SSO) and the Redshift COPY trust check.

Policies may still name a service in the per-partition form AWS accepted before
(elasticmapreduce.amazonaws.com.cn, logs.cn-north-1.amazonaws.com.cn, config.c2s.ic.gov), and AWS
still honours them. ServicePrincipals.canonical folds a published DNS suffix and a regional label
away, and the trust-policy evaluator and CreateServiceLinkedRole compare in that form, so either
spelling matches.

DescribeVpcEndpointServices now lists China's S3 interface service, cn.com.amazonaws.<region>.s3,
beside the com.amazonaws gateway one, each with its own type; where the names agree it stays one
service carrying both types.

Partition literal baseline 34 -> 4 occurrences. The web-identity and pod-identity audiences keep
their commercial literals, escaped for the STS phase.

Part of #4272

* fix(iam): put a legacy-named service-linked role under the universal principal

CreateServiceLinkedRole derived the role name from the universal principal but kept the caller's legacy spelling (es.amazonaws.com.cn) in the path and the trust policy. All three now use the universal principal, so the role lists under /aws-service-role/es.amazonaws.com/ like one created from the universal name.

ServicePrincipals.canonical no longer lower-cases: service-principal matching is exact and case-sensitive since #4555, and AWS matches principals case-sensitively, so only a suffix written the way AWS publishes it folds.
2026-09-29 20:33:07 -04:00
Abhigya cea6d3e99f fix(s3): journal the object index under persistent storage (#4642)
* fix(s3): journal the object index under persistent storage

Under persistent mode every PutObject, CopyObject and DeleteObject
rewrote s3-objects.json in full, and that file holds the metadata of
every object in every bucket, so the cost of one write grew with the
total object count (two rewrites per write on a versioned bucket).

Create the object store with WriteProfile.APPEND_HEAVY, as CloudWatch
Logs events already are: a change is appended to s3-objects.wal and the
JSON file is rewritten on the WAL compaction interval and at shutdown.
An existing s3-objects.json is read as the first snapshot.

* fix(s3): journal both index entries of a current version's metadata update

A versioned put indexes the new object under its version key and the latest
key. Tagging, retention, legal hold, ACL and the SSE-C fields set on multipart
completion wrote back only one of the two. With the object index journaled,
each entry replays on its own, so a restart before compaction brought the
other entry back with the old metadata.

Write both entries when the update targets the current version. The restart
tests now shut down every factory and replay a copy of the stopped process's
directory, so no two writers share a journal.

* test(lambda): stub the WriteProfile overload for S3 stores in the stream poller test

* fix(s3): write object metadata under the bucket lock and the owner account

A metadata update checked whether the latest key still pointed at the object
and then wrote it without holding the bucket lock that puts and deletes take,
so a concurrent delete marker or overwrite could be replaced by the object it
had superseded. The check and both writes now run under that lock, and the
latest key is written only while it still refers to the updated object.

Multipart completion wrote the SSE-C fields back through the caller's account
partition, so with the global bucket namespace a cross-account completion
left a shadow latest entry and version in the caller's partition. It now goes
through the same helper with the bucket owner's account.
2026-09-29 19:18:51 -05:00