Commit Graph
277 Commits
Author SHA1 Message Date
Alex BannaandAlexander Banna e4010ec12f feat(rds): model DB proxies and their target groups (#1813)
* feat(rds): model DB proxies and their target groups

Add DB proxies as first-class RDS resources for both the RDS Query API
and CloudFormation:

- RdsService: two persisted stores plus the proxy lifecycle
  (create/register-targets/describe/delete). A proxy exposes a bare-host
  endpoint on the engine family's default port; in non-mock mode
  registering a target starts an auth relay (via RdsProxyManager) that
  forwards 1:1 to the target cluster/instance, re-armed on restart.
- RdsQueryHandler: CreateDBProxy, DeleteDBProxy, RegisterDBProxyTargets,
  DescribeDBProxyTargetGroups, DescribeDBProxyTargets, and a real
  DescribeDBProxies listing (2014-10-31 XML shapes).
- AwsQueryController: route the six DBProxy actions to RDS.
- CloudFormation: provision/delete AWS::RDS::DBProxy and
  AWS::RDS::DBProxyTargetGroup.

This models DB proxies for provisioning and discovery; it does not add
real connection pooling (the relay forwards 1:1), so it does not close
#1679.

* fix(rds): reserve DB proxy port so same-engine proxies get distinct ports

createDbProxy used the engine family's default port (5432/3306/1433)
directly without reserving it, so two proxies for the same engine got
the identical port and the second relay failed to bind in non-mock
mode. Reserve the default port via reserveOrAllocateProxyPort, falling
back to an allocated pool port when it is already taken — the first
proxy keeps the clean bare-host default port, later ones get a distinct
port, and the persisted port stays canonical across restarts.

* fix(rds): harden DB proxy lifecycle compatibility

* fix(rds): complete DB proxy compatibility hardening

* fix(rds): make DB proxy lifecycle rollback-safe

* fix(rds): default omitted proxy target group

* test(dynamodb): retain Quarkus port for cleanup

---------

Co-authored-by: Alexander Banna <abanna@users.noreply.github.com>
2026-08-14 23:34:56 -05:00
Kenshin Okinaka 80d1dc732e feat(ses): implement PutAccountVdmAttributes and return VdmAttributes from GetAccount (v2) (#2265)
* feat(ses): implement PutAccountVdmAttributes and return VdmAttributes from GetAccount (v2)

Add the SES v2 PutAccountVdmAttributes action (PUT /v2/email/account/vdm) and surface the
account's VDM settings in GetAccount under VdmAttributes. The settings (VdmEnabled,
DashboardAttributes.EngagementMetrics, GuardianAttributes.OptimizedSharedDelivery — each an
ENABLED/DISABLED FeatureStatus) are stored per region and round-trip through GetAccount. VDM
is opt-in, so each flag defaults to DISABLED. An invalid FeatureStatus value is a
BadRequestException, matching AWS; Floci stores the settings but does not run VDM analytics.

* fix(ses): reject non-string FeatureStatus values in PutAccountVdmAttributes

parseFeatureStatus coerced any JSON node via asText(), so a boolean or
object VdmEnabled produced a misleading enum error instead of being
rejected as a type mismatch. Guard on isTextual() before matching the
ENABLED/DISABLED enum, consistent with the other SES v2 parsers.

* fix(ses): match AWS GetAccount VdmAttributes shape

GetAccount always emitted VdmAttributes with the nested Dashboard/Guardian
objects. AWS instead omits VdmAttributes entirely until VDM has been
configured for the region, and once present adds the Dashboard/Guardian
sub-objects only while VdmEnabled is ENABLED. Return VdmAttributes only
when the region has stored VDM state, and gate the nested objects on the
stored VdmEnabled flag.

* test(ses): record live-AWS confirmation that unconfigured VDM omits VdmAttributes

eu-west-1 and ap-northeast-1 (never configured) omit the VdmAttributes key,
while a configured-then-disabled region reports VdmEnabled DISABLED.
2026-08-14 21:45:16 -04:00
lex00 30a61646ac feat(ec2): support CreateImage (create AMI from instance) (#1979)
* feat(ec2): support CreateImage from an instance

Validates the source instance exists, then registers an image the same
way RegisterImage does. Unblocks AMI-baking flows (e.g. CDK
AwsCustomResource calling ec2:CreateImage on a stack-created instance).

Fixes #1978

* fix(ec2): CreateImage reboots the source and produces a launchable AMI

Two review findings.

CreateImage ignored the default reboot. AWS reboots the source instance unless
NoReboot=true so the image is captured from a quiesced file system; the action
only checked that the instance existed. NoReboot is now parsed and the reboot
runs by default.

The resulting AMI kept nothing of what it was captured from. registerImage was
called with null architecture, root device and block device mappings, so
DescribeImages reported a generic x86_64 /dev/sda1 image with no devices, and
RunInstances on the new id fell through to the catalog default guest because a
generated ami-* is not in the catalog. The image now inherits architecture,
root device name and block device mappings from the source instance's image,
and records the launchable ancestor so RunInstances starts the same guest.
CreateImage on an instance launched from a created AMI follows the chain back.

Tests: unit coverage for the reboot default and its NoReboot opt-out, and for
chained images resolving to the catalog ancestor rather than the generated id;
integration coverage that an arm64 source yields an arm64 AMI that launches.

* fix(ec2): a capture of a catalog AMI reports its root device

CreateImage inherits the source image's block device mappings, but a catalog
entry describes only its root device name and carries no mappings, so an AMI
captured from a catalog-launched instance was registered with no devices and
DescribeImages reported none.

The root device is now rebuilt from the catalog entry, with a snapshot
registered through the existing RegisterImage path.

* fix(ec2): a capture takes its own snapshot of each device

CreateImage handed the source AMI's mappings straight to RegisterImage, so the
captured image reported the source's snapshot ids and the two images shared one
snapshot. The mappings are now copied with fresh snapshot ids, keeping the
device name, size, type and encryption.

* fix(ec2): a capture includes the volumes attached after launch

CreateImage read only the mappings of the AMI the instance was launched from, so
a data volume attached afterwards was missing from the captured image. AWS
records block device mapping information for those volumes as well.

The instance's attached volumes are now added to the capture, each with its
device name, size, type and a fresh snapshot. The root volume is skipped because
the source AMI already describes that device.

Also lists CreateImage and RegisterImage in the AMIs action table. That table is
hand-maintained because Ec2QueryHandler is a deferred handler.

* fix(ec2): a capture reports the root volume type the source actually has

The catalog-source fallback in sourceImageMappings recorded the rebuilt root
device as gp2, while RunInstances creates the source instance's root volume as
gp3. DescribeImages therefore reported a type the instance never had.

Both sites now read one DEFAULT_ROOT_VOLUME_TYPE constant, alongside the
existing DEFAULT_ROOT_VOLUME_SIZE_GIB, so the two cannot drift apart again.
2026-08-14 18:33:46 -04:00
thejrose1984andPriamo Germosen 0971cf6f64 fix(cloudformation): resolve ASG launch templates by id and MixedInstancesPolicy (#2005) (#2019)
An AWS::AutoScaling::AutoScalingGroup that pointed at its launch template
any way other than by LaunchTemplateName failed with "The specified
launch template does not exist."

provisionAutoScalingGroup collapsed LaunchTemplateId into the launch
template name argument, and Auto Scaling matches names exactly, so a
valid lt- id — including one that a Ref to an in-stack
AWS::EC2::LaunchTemplate resolves to — never matched. The id and name are
now passed to createAutoScalingGroup separately.

MixedInstancesPolicy was never read from template properties, so a
mixed-instances group reached Auto Scaling with no launch source and
failed validation. It is now built in the same shape the Query API parser
produces, including Overrides[].InstanceType and InstancesDistribution; a
non-integer distribution value fails the stack rather than being silently
dropped.

CloudFormationAsgLaunchTemplateIntegrationTest covers resolution by name,
by id, through a Ref to an in-stack launch template, and through
MixedInstancesPolicy.

Closes #2005

Co-authored-by: Priamo Germosen <6233424+pgermosen@users.noreply.github.com>
2026-08-14 16:17:47 -04:00
Bill DeMoss 7d66bf087a fix(cloudformation): expand SAM AutoPublishAlias into Version + Alias (#1961)
* fix(cloudformation): expand SAM AutoPublishAlias

AutoPublishAlias was read nowhere in the codebase, so the SAM transform
silently dropped it: the stack reached CREATE_COMPLETE, the function
deployed with only $LATEST, and an alias-qualified invoke then failed
with "Alias not found" far from the deploy that caused it. The
"Unsupported SAM resource type" debug arm only covers unknown resource
types, not unknown properties, so nothing was logged either.

Expand it into the AWS::Lambda::Version + AWS::Lambda::Alias pair real
SAM generates, and provision those two types. Both halves are needed:
the transform alone emits resources the provisioner ignores, and the
provisioner alone is unreachable from a SAM template.

The Lambda service already implements publishVersion and the alias APIs,
so this is plumbing rather than new service behavior. The new types go
through CfnResourceProvisioner rather than the legacy switch, following
the registry migration. Ref/GetAtt on the emitted properties give the
function -> version -> alias ordering that topologicalSort already
follows, so no explicit DependsOn is needed.

An intrinsic alias name (e.g. !Ref StageName) is passed through to Name
for the engine to resolve at provision time; only the generated logical
id needs a literal and drops the suffix in that case.

* test(cloudformation): cover Version/Alias provisioner directly

The SAM integration test drives provisioning end to end but cannot reach
two paths: the already-exists fallback (createAlias conflicting with an
alias that outlived a stack delete) and delete(), which its @AfterEach
invokes but never asserts on — a broken delete was silent.

Add LambdaVersionAliasCfnProvisionerTest alongside the existing Sqs and
Rds provisioner tests: attribute wiring for both types, the conflict
fallback, non-conflict failures still propagating, alias delete parsed
out of the ARN, delete idempotency when the alias is already gone,
version delete as a no-op, and a physical id that is not an alias ARN
(the generic fallback's shape on stacks predating this provisioner).

Also stop pinning the alias's FunctionVersion to a literal "1" in the
integration test: assert it is a number and not $LATEST, which is what
the assertion is actually for. Pinning the first version fails
confusingly when an earlier run leaks the function and its counter.

* fix(cloudformation): point the SAM alias at $LATEST

Real SAM points AutoPublishAlias at the published version, and the first
revision of this change did the same. Floci cannot invoke a published
version: the snapshot carries no code path, so a version-qualified
invoke times out on a cold start (#1987), and silently runs $LATEST's
code when a warm container happens to exist (#1988). Emitting the
faithful form therefore broke the alias-qualified invoke this expansion
exists to enable — strictly worse than not expanding the property.

Point the alias at $LATEST instead. The Version resource is still
emitted, so the resource set and GetAtt still match SAM; only the
alias target differs, and it flips back to the version in one line once
#1987 lands.

The integration test asserted the alias record existed with a numeric
FunctionVersion, which the broken form satisfied — so it passed while
the behavior was broken. It now invokes through the alias and asserts
the function actually runs, which fails against the version-pointing
form (verified by reverting it with the record assertion relaxed).

* fix(cloudformation): point the SAM alias at $LATEST

Restores the change d753187e was supposed to carry. That commit landed
only its unit-test half — the main-code change and the integration
test's invoke assertion were lost to a `git checkout --` used to undo a
verification experiment, leaving a test asserting $LATEST against code
still emitting the version pointer.

Real SAM points AutoPublishAlias at the published version. Floci cannot
invoke a published version: the snapshot carries no code path, so a
version-qualified invoke times out on a cold start (#1987) and silently
runs $LATEST's code when a warm container happens to exist (#1988).
Emitting the faithful form broke the alias-qualified invoke this
expansion exists to enable.

The Version resource is still emitted, so the resource set and GetAtt
match SAM; only the alias target differs, and it flips back in one line
once #1987 lands.

The integration test now invokes through the alias instead of only
asserting the alias record exists — the record assertion was satisfied
by the broken form. Verified load-bearing by re-applying the version
pointer with the record assertion relaxed: the invoke fails at the
function timeout.

* fix(cloudformation): sanitize the generated alias logical id

The AutoPublishAlias expansion built the alias resource's logical id by
concatenating the alias name raw. Lambda alias names may contain '-' and
'_', neither of which is valid in a CloudFormation logical id, so
`AutoPublishAlias: blue-green` emitted `MyFuncAliasblue-green`.

Route the suffix through the sanitize() helper this file already uses
for every other derived logical id. The alias name sent to Lambda is
untouched -- only the logical id changes.

Also corrects the expandAutoPublishAlias javadoc: with FunctionVersion a
literal $LATEST there is no version -> alias ordering edge, only
function -> version and function -> alias. None is needed, since the
alias does not reference the version; the edge returns with the GetAtt
form once #1987 lands.
2026-08-14 14:43:42 -04:00
12154297b5 feat(iam): support account aliases (#2103)
* feat(iam): support account aliases

Implement ListAccountAliases, CreateAccountAlias and DeleteAccountAlias.
An account holds at most one alias: creating a second returns
EntityAlreadyExists, and deleting requires the current alias by name so a
stale value cannot silently clear it.

FLOCI_SERVICES_IAM_ACCOUNT_ALIAS seeds an alias at startup for callers that
expect to read one without creating it first.

Closes #2101

* fix(iam): make account alias create and delete atomic

Concurrent CreateAccountAlias calls could all pass the emptiness check and
write, reporting success to every caller while keeping only one value. Unlike
a named resource, where racing creates carry the same name and either winner
is equivalent, racing alias creates carry different values, so a loser is told
their alias was set when another is stored.

Guard the check-then-write on both create and delete, and cover it with a
concurrency trial asserting exactly one winner. Also track the alias created
by the bats delete case in ACCOUNT_ALIAS so teardown clears it if the test
fails midway.

* fix(iam): match verified AWS account alias semantics and unbreak the test fixture

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

Checking the error message against a live AWS account showed the operation
itself was modelled wrongly: CreateAccountAlias does not reject a second alias,
it replaces the current one. EntityAlreadyExists means the requested name is
taken, which for a single-account store is only the alias already held. Create
now replaces and rejects just that case, which also makes the message name the
alias the caller asked for. DeleteAccountAlias applies the same pattern
constraint as create, so a malformed value is a ValidationError.

Concurrent creates therefore all succeed with last-write-wins; the trial now
asserts the store settles on one of the requested values. Seeding logs when it
skips because an alias is already stored, which is otherwise invisible under
persistent storage.

* fix(test): repair iam.bats after the merge fused test bodies

Resolving the merge by keeping both sides concatenated the OIDC and account
alias cases as text, which left the create_oidc_provider helper nested inside an
alias test and dropped a closing brace, so bats could not parse the file and
produced no report at all. Rebuild it from main plus the alias cases, with the
alias tracked in setup and teardown.

* test(iam): pin account alias isolation, and document the two-dash rule

The alias is the only IAM entity keyed by a constant rather than a
caller-supplied name, so every account shares one storage key and the
separation rests entirely on AccountAwareStorageBackend prefixing. Every
integration test here signs as the same account, so that prefixing was never
exercised for aliases. The new case pins it: handing both services the store
unwrapped fails it.

The docs still described the pre-fix constraint. They now carry the
consecutive-hyphen rule and note that the ValidationError message, reproduced
from AWS verbatim, does not itself mention it.

---------

Co-authored-by: Michal Schreiber <michal.p.schreiber@gmail.com>
Co-authored-by: Michal Schreiber <michal.schreiber@benefitsystems.pl>
2026-08-14 12:00:14 -04:00
TiM a6f5f12295 fix(ec2): keep the source on security group rules (#2266)
* fix(ec2): keep the source on security group rules

AuthorizeSecurityGroupIngress and -Egress read only
IpPermissions.N.IpRanges.M.CidrIp, so a rule whose source is another
security group was accepted and then silently stripped: it came back with
no source at all on the authorize response, on DescribeSecurityGroups and
on DescribeSecurityGroupRules. "Allow traffic from security group X" is how
an ALB is wired to its backend tasks, so that whole class of wiring could
be created against Floci but never asserted afterwards.

Parse the source types the permission actually carries: group references,
which the EC2 Query protocol serializes under the wire name Groups rather
than the SDK-facing UserIdGroupPairs, and IPv6 ranges. A reference made by
group name resolves to its group id within the target group's VPC, since
names are unique per VPC and ReferencedSecurityGroup has no name field.

Flatten one SecurityGroupRule per source entry, each keeping its own
description, matching the AWS invariant that a rule holds exactly one
source. A permission with no source at all still yields a single sourceless
rule, as before. The reference is returned as referencedGroupInfo on
DescribeSecurityGroupRules and as UserIdGroupPairs on
DescribeSecurityGroups.

An IPv6-only TCP ingress rule now publishes its host port, which it could
not do while the ranges were dropped at the parse; Ec2PortForwardManager
already treats IPv6 ranges as a CIDR source, and group references stay
unpublished.

Revoke still matches on protocol and port range alone and ignores sources,
unchanged by this.

Closes #2190

* style(ec2): brace the conditionals in the new source parsing

AGENTS.md requires braces on every conditional. The new IPv6 and group
source loops and the group-reference resolution used the unbraced form
the surrounding parse loop happens to use.
2026-08-14 11:41:36 -04:00
Andre Kurait ecad6acf58 feat(swf): add Simple Workflow Service emulation (#2257)
* feat(swf): add Simple Workflow Service emulation

Implements all 39 SWF operations over the JSON 1.0 protocol
(X-Amz-Target: SimpleWorkflowService.*): domain and type registration,
the workflow execution state machine, and the decider/worker task
lifecycle.

Behaviour was derived from botocore's swf-2012-01-25 model and verified
against the live service, which drove several details that are easy to
get wrong from the model alone:

- Faults carry a namespaced __type (com.amazonaws.swf.base.model#Fault)
  in the body but the bare fault name in x-amzn-query-error. botocore
  prefers the header, so a namespaced value there makes the CLI print
  "com.amazonaws.swf.base.model#UnknownResourceFault" where SWF prints
  "UnknownResourceFault". SwfException keeps the two spellings apart.
- Timestamps are epoch-second numbers, not ISO strings.
- Void operations answer 200 with an empty body rather than {}.
- An idle poll returns taskToken "" rather than omitting the member;
  the SDKs read the empty token as "no task".
- ActivityTaskTimedOut reports startedEventId 0 for a task that never
  started, and WorkflowExecutionStarted reports parentInitiatedEventId 0
  on root executions, rather than omitting either member.

State machine:

- One decision task outstanding per execution. Events arriving while one
  is outstanding set a pending flag that is satisfied when it completes,
  so a signal cannot produce two concurrent decision tasks.
- Decisions apply in order; a decision after a closing decision is
  dropped. A decision that cannot be applied appends its *Failed event
  with the AWS cause and gives the decider a fresh task instead of
  failing the request.
- Closing with open activities, timers, or children appends
  UNHANDLED_DECISION and leaves the execution open.
- Timeouts (activity schedule-to-start, start-to-close,
  schedule-to-close, heartbeat; decision start-to-close; execution
  start-to-close; timers) expire from one background sweep rather than a
  timer per task, so a restart leaves nothing to reconcile.
- Child executions link to their parent and report their outcome back;
  the closing parent's childPolicy is applied to open children.

Tests: 29 unit tests drive timeout expiry through a controllable clock,
32 integration tests assert the wire shapes and fault strings captured
from the live service, and a compatibility suite exercises the same
flows through the AWS SDK v2 client so responses must deserialize into
the generated model and faults into typed exceptions.

Long polling, ScheduleLambdaFunction invocation, and retention-based
pruning are not implemented; docs/services/swf.md records each.

Signed-off-by: Andre Kurait <akurait@amazon.com>

* fix(swf): report the child-started event id on ChildWorkflowExecution* events

A ChildWorkflowExecution* event carries two correlation ids, and they point at
different events in the parent's history: initiatedEventId is the
StartChildWorkflowExecutionInitiated id, startedEventId is the
ChildWorkflowExecutionStarted id. Both were reported as the initiated id, so a
decider correlating a child's outcome on startedEventId matched the wrong event.

Verified against the live service, where a parent that starts one child and sees
it complete produces:

  5 StartChildWorkflowExecutionInitiated
  6 ChildWorkflowExecutionStarted        {initiatedEventId: 5}
  8 ChildWorkflowExecutionCompleted      {initiatedEventId: 5, startedEventId: 6}

The child now records the parent's ChildWorkflowExecutionStarted id at start
time and reports it back on every ChildWorkflowExecution* event.

The integration test asserts both ids against the events they name rather than
against a "greater than zero" placeholder, and fails on the previous behaviour
with "startedEventId Expected: <6> Actual: <5>".

Signed-off-by: Andre Kurait <akurait@amazon.com>

* fix(swf): reject a decision batch whose closing decision is not last

RespondDecisionTaskCompleted accepted a batch with decisions after a closing
decision and silently dropped the remainder. The live service rejects the whole
batch instead:

  HTTP 400
  {"__type":"com.amazon.coral.validate#ValidationException",
   "message":"Close must be last decision in list"}

Silently accepting it hides a decider bug and diverges on both the status code
and the response body, so a decider that ships a malformed batch sees success
locally and a 400 against AWS.

The batch is now validated before any state is mutated, matching the live
service's behaviour of leaving the decision task outstanding so the decider can
retry with a corrected batch. Note this fault is namespaced
com.amazon.coral.validate rather than com.amazonaws.swf.base.model.

Tests assert the status code, both fault spellings, the message, that no
DecisionTaskCompleted event is appended, and that the same task token still
works afterwards. They fail on the previous behaviour with "Expected status code
<400> but was <200>".

Signed-off-by: Andre Kurait <akurait@amazon.com>

* fix(swf): name the scheduled event when an activity task has already closed

An activity task token that resolves to a task which is no longer open reported
"Unknown or expired task token". The live service distinguishes the two cases: a
genuine token whose task has closed names the scheduled event instead, because
the token itself was valid.

Captured from the live service, heartbeating a task that a cancel had already
closed:

  HTTP 400
  {"__type":"com.amazonaws.swf.base.model#UnknownResourceFault",
   "message":"Unknown activity, scheduledEventId = 5"}

Both cases are UnknownResourceFault, so SDK error typing was already correct and
only the message diverged — but a worker that logs or matches on the message sees
a different string locally than against AWS.

A token that never existed still reports the bad token; only a resolved token on
a closed task reports the scheduled event. This required keeping the token's map
entry when an activity closes, since removing it made both cases indistinguishable;
reuse is still refused by the existing open-state check.

Test asserts both branches and fails on the previous behaviour with "expected:
<Unknown activity, scheduledEventId = 5> but was: <Unknown or expired task token>".

Signed-off-by: Andre Kurait <akurait@amazon.com>

* fix(swf): serialize execution mutation per domain and guard the sweep interval

Addresses three review findings.

Concurrent StartWorkflowExecution calls for one workflowId all scanned for an
open run before any of them inserted, so each persisted its own run key. Eight
concurrent starts produced eight open runs where SWF admits one, and later
operations without a runId then selected an arbitrary run. The open-run check
and the insert are now one atomic step.

A closing execution mutates its parent (ChildWorkflowExecution* events) and its
children (childPolicy), but held only its own lock, so event-id allocation and
the history list raced. Six children closing against one parent reproduced
ConcurrentModificationException.

Both come from the same mismatch: the lock was per execution while the
invariants span an execution family. The lock is now per domain. A parent and a
child always share a domain, so one lock covers the family and never has to be
nested — nesting would deadlock, since a closing child takes its parent while a
closing parent takes its children. Per-domain granularity is sufficient here:
the emulator serves a single developer's workload, not production concurrency.

A zero or negative timeout-sweep interval reached scheduleWithFixedDelay, which
threw IllegalArgumentException out of the StartupEvent observer and stopped the
whole emulator becoming ready — one bad SWF setting taking down every other
service. A non-positive interval now falls back to 1s with a warning.

Tests fail on the previous behaviour with "expected: <1> but was: <8>",
ConcurrentModificationException, and IllegalArgumentException respectively.
Verified over the wire too: eight concurrent starts yield one success, seven
WorkflowExecutionAlreadyStartedFault, and one open run.

Signed-off-by: Andre Kurait <akurait@amazon.com>

* fix(swf): report the live service's TypeNotDeprecatedFault message

DeleteWorkflowType/DeleteActivityType against a still-registered type
reported the type descriptor, e.g. "WorkflowType=[name=W, version=1]". The
live service answers with prose instead, and uses the same wording for both
type kinds:

  {"__type":"com.amazonaws.swf.base.model#TypeNotDeprecatedFault",
   "message":"The type is currently registered and cannot be deleted in its
              current state"}

Since both variants are identical, the two fault factories collapse into one.
The descriptor form is still correct for the other type faults
(TypeDeprecatedFault, TypeAlreadyExistsFault, UnknownResourceFault), which were
verified unchanged in the same probe.

Also adds integration coverage for the five actions that had none at either
test layer: DeprecateActivityType, UndeprecateActivityType, DeleteActivityType,
ListWorkflowTypes, and RespondActivityTaskFailed. Every assertion is taken from
a live-service capture, including that scheduling a deprecated activity type
appends ScheduleActivityTaskFailed with cause ACTIVITY_TYPE_DEPRECATED and
leaves the execution open, that ListWorkflowTypes filters by registration
status and name, and that a second RespondActivityTaskFailed on the same token
reports "Unknown activity, scheduledEventId = 5".

The message tests fail on the previous behaviour with "Expected: The type is
currently registered ... Actual: WorkflowType=[name=TestWf, version=1.0]".

Signed-off-by: Andre Kurait <akurait@amazon.com>

* feat(swf): invoke real Lambda functions for ScheduleLambdaFunction

The decision was recorded as ScheduleLambdaFunctionFailed with cause
LAMBDA_SERVICE_NOT_AVAILABLE_IN_REGION rather than invoking anything. SWF is
otherwise a pure coordination service — deciders and activity workers are the
user's own processes, so there is no user code for the emulator to run — but
ScheduleLambdaFunction is the one decision where SWF itself executes something,
and Floci already runs Lambda functions in containers. A decider that fans work
out to Lambda could not be exercised locally at all.

Floci now invokes the function through its own Lambda service, the same way the
EventBridge and Scheduler invokers do, and records the outcome. Verified against
the live service:

  5 LambdaFunctionScheduled  {control, id, input, name, startToCloseTimeout}
  6 LambdaFunctionStarted    {scheduledEventId: 5}
  7 LambdaFunctionCompleted  {result, scheduledEventId: 5, startedEventId: 6}
  8 DecisionTaskScheduled

Four behaviours came from that capture and are easy to get wrong:

- A function that cannot be resolved is LambdaFunctionFailed with Lambda's own
  error code as reason (ResourceNotFoundException) — not
  ScheduleLambdaFunctionFailed — and it still reports Started first.
- An execution with no lambdaRole never starts the function at all: Scheduled is
  followed by StartLambdaFunctionFailed with cause ASSUME_ROLE_FAILED and the
  message "No IAM role is attached to the current workflow execution."
- lambdaRole resolves from StartWorkflowExecution's lambdaRole, falling back to
  the workflow type's defaultLambdaRole, and is echoed in the started event.
- An absent input reaches the handler as {}, and reusing an id is accepted —
  there is no ID_ALREADY_IN_USE for Lambda the way there is for activity ids.

SwfService takes a LambdaInvoker seam rather than LambdaService directly, so the
unit tests keep running without a Docker daemon while SwfLambdaInvoker wires the
real thing at runtime. The invocation is RequestResponse because the response
body is what gets recorded as result; the fire-and-forget invokers use Event for
the opposite reason.

The Lambda region comes from the execution's domain ARN, so a workflow in one
region does not invoke a function in another.

Tests: SwfServiceTest covers all four paths against a recording invoker and
fails on the previous behaviour with "the function must actually be invoked
==> expected: <1> but was: <0>". SwfLambdaIntegrationTest and the SDK
compatibility SwfLambdaTest deploy a real function and assert the recorded
result is what the container returned, so neither passes against a synthesised
event. Docker-backed cases live in their own class so a Docker-less run loses
only them rather than the whole SWF wire suite.

Signed-off-by: Andre Kurait <akurait@amazon.com>

* fix(swf): scope state by region and paginate the registration lists

Addresses two AWS compatibility gaps from review.

SWF names are unique per region, but storage keys were the bare name, so
registering a domain in us-east-1 made the same name in eu-west-1 fail as a
duplicate, and describe/list could return the first region's domain and ARN.
Verified against the live service: the same name registers in both regions with
independent descriptions and retention periods, each ARN naming its own region;
a type registered in one region answers UnknownResourceFault in the other; and
executions, including their runIds, do not cross.

Keys are now region-qualified — `<region>:<domain>` for domains,
`<region>:<domain>/<name>/<version>` for types, and
`<region>:<domain>/<workflowId>/<runId>` for executions — and every store scan
is prefixed by region. The region reaches the service on each call and is stored
on the execution, which is also what task tokens resolve through, so a token
issued in one region cannot address another's execution. The per-domain
mutation lock is region-qualified too; leaving it bare would have let two
regions serialize against each other, and would have disagreed with the
sweeper's own lock derived from the storage key.

ListDomains, ListWorkflowTypes and ListActivityTypes ignored maximumPageSize and
nextPageToken and returned everything. They now share one paging helper with the
history and execution listings. Details taken from live captures rather than the
docs: nextPageToken is absent on the final page even when that page is exactly
full, a maximumPageSize of 0 or absent means "no caller limit", above 1000 is
rejected rather than clamped, and a corrupt token answers
`ValidationException: Invalid token` instead of silently restarting at the first
page — which would make a paging loop repeat forever.

Adds AWS SDK regression tests (SwfRegionPaginationTest) driving two clients at
different regions against the same emulator, plus wire-level integration
coverage. Against the previous implementation those SDK tests fail with
DomainAlreadyExists on the second region, "maximumPageSize must cap the page: 5",
and nothing thrown for an oversized page size.

Signed-off-by: Andre Kurait <akurait@amazon.com>

* test(swf): pin reverseOrder as applying before pagination

The registration lists reverse the whole result set and then page it, so with
maximumPageSize=3 and reverseOrder=true the first page is the tail of the
ascending order. That was already the behaviour but nothing asserted it, and the
shared paging helper makes "page first, then reverse the page" an easy
regression to introduce.

Measured against the live service: 5 types at page size 3 reversed returns
Paged4, Paged3, Paged2 and then Paged1, Paged0. Injecting the page-then-reverse
ordering fails the new test with
"Expected: <[Paged4, Paged3, Paged2]>".

Signed-off-by: Andre Kurait <akurait@amazon.com>

* test(swf): cover region scoping at the wire level

The region-scoping tests went in at the service and SDK layers, but every
SwfIntegrationTest request omitted an Authorization header, so nothing asserted
that the region is read from the SigV4 credential scope — the step that decides
which region's state a call addresses.

Adds a wire test that sends a credential scope naming the region, covering the
same name registering in two regions with independent descriptions, retentions
and ARNs, a type being unknown in the other region, and a same-region
re-registration still faulting.

Against 7cc6c0f2 the test fails with
DomainAlreadyExistsFault / "Expected status code <200> but was <400>".

Signed-off-by: Andre Kurait <akurait@amazon.com>

* fix(swf): correct four decision, polling and locking cases from review

An invalid decision anywhere in a batch could still mutate the execution.
respondDecisionTaskCompleted appended DecisionTaskCompleted, dropped the token
and applied earlier decisions before applyDecision's default arm rejected an
unknown decisionType mid-loop, so [RecordMarker, NotARealDecision] grew the
history from 3 to 5 events and burned the token. A try/catch cannot undo that —
decisionTokens is a separate map and the history lands on the in-memory
execution — so the whole batch is now validated up front, extending the shape
requireCloseIsLastDecision already used. Both rules live in one requireValidBatch,
and the accepted types come from SwfConstants.DECISION_TYPES so the check and the
message quoting the enum set cannot drift.

PollForDecisionTask with a nextPageToken claimed a new task instead of paging the
original. AWS states that "calling PollForDecisionTask with a nextPageToken
doesn't return a new decision task", and the live service answers a continuation
with the same startedEventId, previousStartedEventId and workflowExecution, plus
the next contiguous history page. The continuation token now names the task it
belongs to, so a continuation resolves that task rather than polling again.
startAtPreviousStartedEvent was modeled but read nowhere; it now trims the window
to events from previousStartedEventId onward, which the live service treats as
inclusive.

A child that continued as new lost its parent. The successor was built from a
StartWorkflowExecutionRequest, which carries no parent fields, so its parent was
null and the parent kept tracking the closed run — never learning the successor's
outcome and never applying child policy to it. carryParentTo moves the parent
identifiers and repoints the parent's childExecutions entry before the successor's
WorkflowExecutionStarted is appended, so that event names the parent as it does
on the live service.

The Lambda invocation held the domain lock. That lock deliberately covers a whole
domain family, so a cold start stalled every unrelated execution in the domain.
A decision now queues the invocation, records LambdaFunctionScheduled and
LambdaFunctionStarted under the lock, and the invocation runs after the lock is
released; the outcome is recorded under the lock again, so the state transition
around the result stays atomic.

Guards, each failing on the code before it: the batch case with
"a rejected batch must not grow the history ==> expected: <3> but was: <5>", the
continue-as-new case with "the successor of a child must keep its parent ==>
expected: <wf-cn-parent> but was: <null>", the two polling cases on an empty
continuation response, and the liveness case by blocking inside the invoker and
signalling an unrelated execution in the same domain.

Signed-off-by: Andre Kurait <akurait@amazon.com>

* refactor(swf): collapse the paging helpers into one, and cap every operation

Three page-token codecs and three copies of the same offset/limit/token block had
accumulated across the history, execution and registration listings, plus a
fourth for the PollForDecisionTask continuation. There is now one Page record
with one encode/decode pair — the task token is an optional field, which is the
only thing the poll needed — and one pagedList helper the history and execution
listings reuse. Net 62 fewer lines in the service and handler.

Collapsing the two page-size methods surfaced a real divergence rather than just
shortening code: historyPageSize clamped an oversized maximumPageSize while the
registration lists rejected it. The live service rejects it everywhere, measured
on GetWorkflowExecutionHistory, ListOpenWorkflowExecutions and
PollForDecisionTask, and rejects a negative value with its own message
("greater than or equal to 0"). One pageSize method now serves all of them.

Signed-off-by: Andre Kurait <akurait@amazon.com>

* docs(swf): document batch atomicity, poll continuation and the page-size cap

The three behaviours the last two commits changed were only visible in the code: a decision batch is all-or-nothing, a PollForDecisionTask continuation pages the same task rather than claiming a new one (and startAtPreviousStartedEvent is inclusive), and the 1000 page-size cap applies to every paginated operation rather than only the registration lists.

Signed-off-by: Andre Kurait <akurait@amazon.com>

* fix(swf): render the decisionType enum set in the service's own order

The rejection message for an unknown decisionType listed the enum members in the
API model's order. The live service uses a different order, stable across
repeated calls, so a client comparing the message byte-for-byte saw a mismatch:

  service: [CompleteWorkflowExecution, StartTimer, RequestCancelExternal...
  model:   [ScheduleActivityTask, RequestCancelActivityTask, CompleteWork...

Taken from four live responses rather than from the model. The guard now asserts
the whole message instead of a substring, and fails on the previous order with
the two strings diffed in full.

Signed-off-by: Andre Kurait <akurait@amazon.com>

* fix(swf): scope queued Lambda work to the request, not the thread

The queue of deferred invocations was a ThreadLocal drained after the domain lock
was released. On a pooled request thread that outlives the request: if anything
threw between queueing an invocation and draining, the work stayed on the thread
and the next decision response ran it — invoking a real function for a request
that had already failed, and recording the outcome against whatever state that
later execution was in.

The queue is now a local list created per call and threaded through
applyDecisions, so the drain is reachable only after the batch has been applied
and stored. A request that throws leaves the list unreferenced; there is no
cross-request carrier left to leak through.

Signed-off-by: Andre Kurait <akurait@amazon.com>

* test(swf): guard that a failed batch leaves no queued Lambda work

Reaches the leak window by failing the execution store after a Lambda has been queued and the history mutated, then issuing a second request on the same thread.

Signed-off-by: Andre Kurait <akurait@amazon.com>

---------

Signed-off-by: Andre Kurait <akurait@amazon.com>
2026-08-14 11:16:21 -04:00
Michal SchreiberandMichal Schreiber 2d003b52f2 fix(ec2): reject prefix list names AWS reserves for its own lists (#2274)
* fix(ec2): reject prefix list names AWS reserves for its own lists

CreateManagedPrefixList accepted names beginning com.amazonaws., com.amazon. or
com.aws., which AWS refuses with InvalidParameterValue, so a customer list could
shadow a seeded gateway-endpoint one.

The trailing dot is part of each prefix. Checked against a live account:
com.amazonaws-probe and comamazonaws.probe are both accepted there, so matching
without the dot would refuse names AWS allows.

Closes #2273

* fix(ec2): apply the reserved-name rule to a prefix list rename too

ModifyManagedPrefixList persisted any nonblank name, so a list could be renamed
to com.amazonaws.us-east-1.s3 and returned alongside the seeded AWS-managed list
of that name. AWS applies the same rule to a rename, verified against a live
account, and leaves the existing name in place when it rejects one.

Create and rename now share the check.

---------

Co-authored-by: Michal Schreiber <michal.schreiber@benefitsystems.pl>
2026-08-14 09:53:57 -04:00
Alex Banna 5657e35007 feat(cloudfront): enforce signed private content (#1831)
* feat(cloudfront): serve distribution requests from S3 and custom origins

* feat(cloudfront): enforce signed private content

* chore: re-run CI

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

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

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

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

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

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

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

* test(dynamodb): retain Quarkus port for cleanup

* fix(cloudfront): isolate mocked storage backends

* fix(cloudfront): match wildcards in signed policy queries
2026-08-13 23:32:24 -04:00
Alex Banna 97ac3cabb5 feat(stepfunctions): add UpdateStateMachine and update in place on stack updates (#1867)
* feat(stepfunctions): add UpdateStateMachine and update in place on stack updates

* test(dynamodb): retain Quarkus port for cleanup

* chore: rerun CI after download outage

* fix(cloudformation): preserve log group on failed rename

* fix(cloudformation): scope update rollback to attempted resources

* fix(cloudformation): delete resources after stack updates

* test(cloudformation): wire cloudfront fixture dependency

* fix: include Step Functions update date in describe response

* fix: preserve Step Functions describe response shape

* fix: preserve generated Step Functions names
2026-08-13 22:36:15 -04:00
Alex Banna a7da1b9856 feat(stepfunctions): run Map iterations concurrently honoring MaxConcurrency (#1810)
* feat(stepfunctions): run Map iterations concurrently honoring MaxConcurrency

A Map state ran its iterations one after another. AWS runs them
concurrently up to MaxConcurrency (default 0 = unlimited), which is a
correctness requirement, not just a speed-up: a Map whose iterations
coordinate — e.g. a dependency-ordered fan-out where one child blocks
until a sibling completes — deadlocks when the iterations are serialised.

Run each iteration on the shared executor under the execution's account,
gated by a Semaphore sized to MaxConcurrency (unlimited when 0). Results
are written into per-index slots so the output array preserves input order
regardless of completion order, MaxConcurrency=1 stays strictly sequential,
and a failed iteration cancels the rest and fails the Map (fail-fast,
matching the default ToleratedFailureCount of 0).

* fix(stepfunctions): cap Map worker threads with a bounded pool + handle interruption

Address review: submitting every iteration to the shared cached pool behind
a Semaphore spawned one thread per item (a 1000-item Map with
MaxConcurrency=5 created ~1000 threads, ~995 parked). Run iterations on a
fixed-size per-Map ThreadPoolExecutor sized to MaxConcurrency so live
threads are capped and the rest queue. shutdownNow() in finally stops the
iterations on any exit, and an InterruptedException from the driver now
preserves the interrupt status.

* fix(stepfunctions): make Map concurrency bounded and fail-fast

* docs(stepfunctions): document map concurrency

* test(dynamodb): retain Quarkus port for cleanup

* chore: rerun CI after OpenTofu registry flake

* test(stepfunctions): pin Map item selection order
2026-08-13 16:22:54 -04:00
Aniket Shukla 9e7cdad29a fix(rds): preserve configured database images (#2035) 2026-08-13 15:05:02 -04:00
Dixit R Jain 45bb37f1fb feat(apigatewayv2): route execute-api hosts to WebSocket $connect and @connections (#2188)
Consolidates AWS-style execute-api virtual-host support for WebSocket APIs onto the
existing ApiGatewayExecuteApiHostFilter (added in #2054) plus the WebSocket handler,
instead of adding a second host filter.

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

Closes #1871
Closes #1846
2026-08-13 14:40:50 -04:00
Olamide Kosile a235b76835 feat(cloudformation): implement GetTemplateSummary (#2148)
* feat(cloudformation): implement GetTemplateSummary (#1964)

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

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

Addresses two review findings:

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

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

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

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

Spells out why the fallback to the post-transform templateBody exists
(originalTemplateBody has no data for stacks persisted before this
field was added) and that it self-heals on the stack's next
CreateChangeSet/UpdateStack call, in response to review feedback.
2026-08-13 00:29:11 -05:00
Olamide Kosile c48c062117 fix(docker): fall back to Windows named pipe when docker-host is at its unix-socket default (#2030)
Floci defaults docker-host to unix:///var/run/docker.sock, which has
no equivalent on native Windows. Since this hardcoded default always
overrides docker-java's own OS-aware detection, every Docker-backed
operation failed at container-start time on Windows with a low-level
socket error — including Lambda-invoked CloudFormation custom
resources such as CDK's Custom::S3BucketNotifications.

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

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

Fixes #2006.
2026-08-13 00:02:28 -05:00
themark007 486be8f5b0 feat(kinesis): add local inspection endpoints for UI (#1880)
* feat(kinesis): add local inspection endpoints for UI

* fix(kinesis): limit local record inspection

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

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

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

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

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

- Test: strengthened recordsEndpointHonorsLimit to assert which two
  records are returned (pk-2 and pk-3, the newest), not just hasSize(2).
  Added recordsEndpointRejectsNonPositiveLimit to cover the controller-
  level Limit=0 validation.
2026-08-13 00:24:37 -04:00
Saatvik Arya 4215006fe2 feat(logs): support log group deletion protection (#2256)
* fix(logs): accept log group deletion protection lifecycle

* feat(logs): support log group deletion protection
2026-08-12 22:39:39 -04:00
Alex BannaandAlexander Banna d9e4447aeb feat(cloudformation): resolve dynamic references in RDS credentials (#1809)
* feat(cloudformation): resolve dynamic references in RDS credentials

* test(cloudformation): pin secret resolution failures

---------

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

* chore: re-run CI

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

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

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

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

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

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

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

* test(dynamodb): retain Quarkus port for cleanup

* fix(cloudfront): isolate mocked storage backends
2026-08-12 19:34:18 -04:00
Alex BannaandAlexander Banna bc21367cc4 feat(cloudformation): provision AWS::Events::EventBus as a real custom bus (#1807)
* feat(cloudformation): provision EventBridge event buses

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

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

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

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

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

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

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

Two provision-side defects, both surfaced in review:

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

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

* chore: re-run CI

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

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

* test(dynamodb): retain Quarkus port for cleanup

* chore: rerun CI after download outage

* fix(cloudformation): reject unsafe EventBus policy updates

---------

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

* fix(apigateway): disambiguate execute-api routing

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

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

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

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

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

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

* test(dynamodb): retain Quarkus port for cleanup

* fix(apigateway): match disabled HTTP API response

---------

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

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

* fix(lambda): isolate warm pools by version

* test(dynamodb): retain Quarkus port for cleanup

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

---------

Co-authored-by: Alexander Banna <abanna@users.noreply.github.com>
2026-08-12 16:12:39 -04:00
soreavis f1c81977ec fix(cloudwatch): warn on unsupported Logs Insights filter operators (#2170)
parseFilter scans for the leftmost '!=', '==' or '=' outside a quoted
value, so the '=' inside '>=', '<=' and '=~' won. For '>=' and '<=' the
comparison character was absorbed into the field name ("@message >"),
which resolves to null for every row, and passesFilters treats null as
non-matching; for '=~' the value became the literal "~ /ERROR/". Either
way the query came back with no rows and no warning, because as far as
parseFilter was concerned it had found a valid operator.

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

thenAnswer stubs that returned bare InMemoryStorage ClassCast after
create() was typed as AccountAwareStorageBackend; align the remaining
service unit tests with the production return type.
2026-08-12 09:32:03 -04:00
Anders Wasen 19a32ab51d feat(rds-data): adding data-api preparedstatement() support (#1887)
* feat(rds-data): adding data-api preparedstatement() support

* feat(rds-data): addressing greptile comments

* feat(rds-data): addressing PR review comments, fixing timestamp
2026-08-12 07:03:06 -04:00
Olamide Kosile c21337c3b1 feat(iam): add GetAccountSummary support (#1986)
Adds all 34 documented SummaryMap fields: live entity counts (Users,
Groups, Roles, customer-managed Policies, InstanceProfiles,
PolicyVersionsInUse) plus IAM quota values, cross-checked against
AWS's published service quotas and independently verified against
moto's AccountSummary implementation. Resources Floci does not track
(MFA devices, SAML/OIDC providers, server certificates, account
password) report 0 rather than being omitted, so callers indexing
into the full AWS field set don't hit a missing-key error.

Part of #1938.
2026-08-12 00:23:51 -04:00
Dennis O'Connor b6765b3056 feat(apigateway): API key management — UpdateApiKey, DeleteApiKey, UsagePlan custom-id, generateDistinctId (#1883)
* feat(apigateway): implement UpdateApiKey and DeleteApiKey

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

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

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

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

* feat(apigateway): persist and return UsagePlan tags

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Closes #2102

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

---------

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

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

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

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

---------

Co-authored-by: Mihai Blidaru <mihai.blidaru@lynxfctech.com>
2026-08-11 21:40:24 -04:00
lex00 40e8aad55a feat(lambdamicrovms): AWS Lambda MicroVMs service module and its CloudFormation types (#2079)
* feat(lambdamicrovms): AWS Lambda MicroVMs service module

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

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

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

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

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

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

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

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

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

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

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

* fix(lambdamicrovms): wire service state through StorageFactory

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

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

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

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

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

Moving images, microvms and connectors into StorageBackedMap made their model
classes persisted types, and PersistedModelReflectionTest fails on any that lack
@RegisterForReflection because native-image persistence cannot rebuild them on
restart.
2026-08-10 23:10:48 -05:00
Jan Waś f417164d42 fix(rds): advertise reachable endpoints (#2074)
RDS endpoints currently expose the proxy's container port even when
Docker publishes it on a random host port. That works when the host can
route to the container network, but fails with VM-backed Docker
runtimes.

Resolve the current container's published port when an external
endpoint host is configured while preserving the internal proxy port
used by the listener.
2026-08-10 22:03:52 -04:00
Kenshin Okinaka bd01c1a70b feat(ses): implement SendCustomVerificationEmail for v1 and v2 (#2191)
* feat(ses): implement SendCustomVerificationEmail for v1 and v2

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

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

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

Implement CreateManagedPrefixList, DescribeManagedPrefixLists,
GetManagedPrefixListEntries, ModifyManagedPrefixList and
DeleteManagedPrefixList.

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

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

Closes #2100

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

Three defects in the managed prefix list surface:

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

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

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

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

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

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

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

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

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

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

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

---------

Co-authored-by: Michal Schreiber <michal.p.schreiber@gmail.com>
2026-08-10 19:03:26 -05:00
Tim Gibson 50fe67dde6 feat(eventbridge): deliver events to event-bus targets (#1814)
* feat(eventbridge): deliver events to event-bus targets

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

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

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

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

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

* fix(eventbridge): cap bus-to-bus forwarding at one hop, matching AWS
2026-08-10 17:46:13 -04:00
Miguel Carvalho 7e5afae61b feat(eks): support IRSA with a real OIDC issuer and JWT validation (#2108)
* feat(eks): support IRSA with a real OIDC issuer and JWT validation

Every EKS cluster now gets an OIDC identity provider, so the full IRSA flow
works end to end without mocked or hardcoded tokens.

CreateCluster generates an RSA-2048 keypair and an AWS-shaped issuer URL,
returned by DescribeCluster as identity.oidc.issuer. The issuer is a faithful
string for building trust policies but is never dereferenced: STS resolves the
signing key in-process via a new OidcIssuerKeyLookup port, declared in
core.common so services.iam does not depend on services.eks.

Key material lives in storage separate from the Cluster model. Cluster is
serialized straight onto the DescribeCluster wire response, so a private key
carried there would leak; @JsonIgnore would instead lose it across restarts and
break tokens minted earlier.

sts:AssumeRoleWithWebIdentity previously accepted any non-blank token and
returned a hardcoded subject. It now verifies, but only for issuers Floci hosts:

- RS256 signature against the cluster's public key
- iss matches the issuer exactly
- aud contains sts.amazonaws.com
- exp / nbf, with 60s of clock-skew tolerance
- the role's trust policy, via a new WebIdentityTrustPolicyEvaluator matching
  Principal.Federated and the Condition block

The response now carries the token's real claims in
SubjectFromWebIdentityToken, Provider, and Audience. Bad tokens return
InvalidIdentityToken (400); a trust policy that does not permit the subject
returns AccessDenied (403) — a check the web-identity path was missing entirely.

Tokens from an issuer Floci does not host stay permissive, since Floci cannot
verify a third-party signature. Existing behaviour is therefore unchanged and no
configuration flag is required.

WebIdentityTrustPolicyEvaluator is a sibling of AssumeRolePolicyEvaluator rather
than an extension of it: that evaluator serves sts:AssumeRole, hardcodes that
action, reads only Principal.AWS, and ignores conditions. Condition values are
compared with exact, case-sensitive equality instead of the existing
globMatches, which lowercases both operands — case-folding an OIDC subject would
silently admit a different service account.

Because Floci has no kubelet to project a token into a pod, a local-dev harness
can mint one via POST _floci/eks/clusters/{name}/oidc-token and write it to the
file named by AWS_WEB_IDENTITY_TOKEN_FILE. Signing stays server-side so the
private key never leaves Floci. OIDC discovery and JWKS routes are served under
the same _floci namespace, for fidelity rather than because anything fetches
them; the AWS-shaped issuer path is not resolvable by Floci's embedded DNS and
would collide with S3's path-style catch-all.

Adds 51 tests: unit coverage for the verifier, the trust-policy evaluator, and
the OIDC service, plus an end-to-end integration test covering the mint ->
assume -> credentials path and its negative cases (wrong service account,
tampered signature, wrong audience, expired, alg:none).

* fix(iam): close two web-identity validation gaps and backfill cluster OIDC state

Three defects found in review of the IRSA change.

An unsigned "header.payload." token bypassed validation entirely. verify()
split with a -1 limit so a trailing empty segment was preserved, but
parseClaims() — which backs peekIssuer() — did not. Java drops trailing empty
strings by default, so such a token split into two parts, its issuer went unseen,
and STS classified it as an opaque third-party token: signature, claim, and
trust-policy checks were all skipped and credentials were issued for a JWT that
was never signed. Both split sites now pass -1.

StringLike and StringNotLike on an OIDC condition key folded case. They
delegated to IamPolicyEvaluator.globMatches, which lowercases both operands, so
a trust policy scoped to one service account or namespace would admit another
differing only in case — the exact hazard the StringEquals branch was written to
avoid. Adds a case-sensitive glob and uses it for both operators. Action matching
still uses globMatches, which is correctly case-insensitive.

Clusters persisted before this feature never gained an issuer or key, so after an
upgrade DescribeCluster reported no identity.oidc.issuer, minting returned 400,
and the JWKS routes 404'd until the cluster was recreated. EksService now
backfills on startup, and re-runs ensureKey for clusters that already have an
issuer so a restart cannot leave a known issuer without its signing key.

Each fix has a regression test confirmed to fail without it.

* fix(eks): keep IRSA OIDC state scoped to the cluster's owning account

The startup backfill read clusters across every account via scanAllAccounts() but
wrote them back with the request-scoped put(), which resolves to the default
account outside a request context. A cluster owned by any other account kept its
issuer-less record while a duplicate appeared under the default account, leaving
DescribeCluster and the IRSA endpoints broken for the owner. The backfill now
takes the account from the cluster record and writes with putForAccount, per the
pattern StorageFactory documents for work running outside a request.

The same root cause affected key lookup more seriously. findVerificationKey used
the account-scoped scan(), so an issuer owned by a non-default account went
unresolved — and an unresolved issuer is treated as a third-party provider, so
STS accepted the token with no signature, claim, or trust-policy check at all.
It now scans every account, which is correct regardless: an issuer URL is
globally unique, and the account calling AssumeRoleWithWebIdentity need not be
the one that owns the cluster.

deleteKey and findKeyByCluster stay account-scoped; both are only reached from
request-scoped paths (DeleteCluster and the JWKS route), where the caller's
account is the right scope.

Both fixes have a regression test confirmed to fail without them.
2026-08-10 09:04:40 -04:00
Jérémie van der Sande 2594705f9c feat(elbv2): honor preserve_host_header parameter (#2109) 2026-08-09 15:34:30 -04:00
soreavis c8403ac6fc feat(iam): add service-linked role create, delete and deletion status (#2179)
* feat(iam): add service-linked role create, delete and deletion status

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

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

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

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

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

Closes #2122

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

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

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

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

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

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

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

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

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

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

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

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

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

Tests updated accordingly and verified live against the packaged jar.

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

* feat(kinesisanalytics): add CreateApplicationPresignedUrl and SnapshotsEnabled

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

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

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

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

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

Fixes #1900

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

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

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

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

* docs(kinesis): document shard iterator semantics

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

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

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

Addresses review feedback on #1901.

* test(kinesis): cover unknown shard validation across all iterator types
2026-08-09 00:10:16 -05:00
Alex Banna 6d829ff7a4 feat(s3): resolve index documents for static-website directory requests (#1815)
* feat(s3): resolve static website index documents

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

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

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

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

An earlier commit added query-string preservation on the strength of a review
comment asserting AWS behaved that way; the probe shows it does not, and LocalStack's
website_hosting.py agrees with the probe. An SPA whose OAuth callback lands on a
slash-less folder loses its parameters on real AWS too, so the emulator matches
rather than improving on it.
2026-08-08 22:42:26 -05:00
soreavis d943e09a73 feat(ec2): add ReplaceRoute (#2178)
Terraform calls ReplaceRoute whenever an existing route changes target, so
route tables could be created but never updated; the only workaround was
to destroy and recreate the table.

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

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

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

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

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

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

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

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

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

Closes #2174

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

An unverified FromEmailAddress threw NotFoundException/404 from the shared CVET validator, so
the v1 Query wire carried a v2 code. AWS classic SES returns FromEmailAddressNotVerified/400
(verified); throw that v1-native code and map it in remapV1Exception, so v1 is correct while
v2 still returns NotFoundException/404. Pin the v1 code with an integration assertion.
2026-08-08 21:36:21 -05:00
Kenshin Okinaka fa9ed9100e feat(ses): implement SendEmail ListManagementOptions suppression and unsubscribe (v2) (#1875)
* feat(ses): implement SendEmail ListManagementOptions suppression and unsubscribe (v2)

SendEmail now honors ListManagementOptions (ContactListName / TopicName):

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

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

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

Addresses three review findings on the unsubscribe handling:

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

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

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

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

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

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

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

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

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

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

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

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

Content.Simple.Headers / Content.Template.Headers entries declare Name and
Value as required members. A header object missing either member was parsed
leniently and later silently dropped, which is surprising when the request is
otherwise accepted. Reject it at parse time the way AWS does — BadRequestException
with the Smithy "Member must not be null" constraint message anchored at the
offending header path and 1-based index.
2026-08-08 21:33:35 -05:00
Kenshin Okinaka ff8d6efdf3 feat(ses): implement v1 receipt rule set actions (stored-but-inert) (#2128)
* feat(ses): implement v1 receipt rule set actions (stored-but-inert)

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

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

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

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

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

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

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

Address review nits: move the ReceiptRuleSet import into alphabetical position in
SesQueryHandler, and expand the RuleSetName validation comment to record that the
constraints come from probing live SES (the botocore model has no pattern), so the
next reader can re-verify rather than treat them as settled.
2026-08-07 23:23:01 -04:00
Hector Ventura ee15447ba4 docs(cloudformation): document the per-service provisioner path for new resource types (#2153)
New CloudFormation types belong in services/cloudformation/provisioners/, not in the
CloudFormationResourceProvisioner monolith, but nothing outside a gitignored design
doc said so: CONTRIBUTING.md, AGENTS.md, docs/ and the PR template were all silent,
so contributors read the monolith and copied a case.

Adds a step-by-step section to CONTRIBUTING.md and AGENTS.md covering the three
traps behind the recurring review findings: Ref and Fn::GetAtt are separate
mechanisms and a missed attribute resolves to the literal LogicalId.Attr; provision
is also the update path, so creating unconditionally throws AlreadyExists or orphans
the old resource; and an unmapped type is stubbed as CREATE_COMPLETE, so status-only
assertions cannot detect a type that was never wired.

Also refreshes the resource-type table, which had drifted: EC2 gains LaunchTemplate
and VPCGatewayAttachment, EventBridge gains EventBus and EventBusPolicy and its
Events::Rule naming is normalized.
2026-08-07 17:37:36 -05:00
soreavis 9b451ccc82 fix(iot): match topic rules outside the default region (#2169)
* fix(iot): match topic rules outside the default region

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

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

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

Closes #2065

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

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

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

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

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

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

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

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

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

Closes #1563

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

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

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

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

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

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

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

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

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

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

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

Closes #1555
2026-08-07 17:29:48 -05:00