Commit Graph
533 Commits
Author SHA1 Message Date
lex00 631df1dc01 feat(cloudformation): provision AWS::Backup::BackupVault (#3125)
Per-service provisioner over BackupService. Ref and Fn::GetAtt
BackupVaultName are the vault name and Fn::GetAtt BackupVaultArn its ARN. The
name is the physical id and createOnly, so an unnamed vault keeps its
generated name across updates instead of getting a second vault, and a rename
is refused as a replacement. EncryptionKeyArn is createOnly as well.
BackupVaultTags are driven to the template's set on update, untagging dropped
keys since TagResource only adds. Stack deletion deletes the vault and leaves
the non-empty-vault refusal to surface as on AWS.

The docs generator gains a label and row position for the new AWS::Backup
namespace.

Ported from lex00/floci#118. Tracked in lex00/floci#192.
2026-09-06 22:18:18 -05:00
lex00 3a4982c294 feat(cloudformation): provision AWS::ApiGateway::UsagePlan and UsagePlanKey (#3123)
* feat(cloudformation): provision AWS::ApiGateway::UsagePlan and UsagePlanKey

Per-service provisioner over ApiGatewayService. A plan's Ref and Fn::GetAtt
Id are the plan id. Every plan property is mutable, so an update patches name
and description in place and adds or removes API stages as the template moves
them. Tags are driven to the template's desired state through the new
replaceUsagePlanTags.

A key's Ref and Fn::GetAtt Id are <keyId>:<usagePlanId>, as on AWS. All three
of its properties are createOnly, so a change to any of them is refused as a
replacement rather than re-associating a different key under the old id. The
composite id is what lets delete find the association without scanning every
plan.

Stack deletion removes the plan and the association and tolerates either
being gone already.

Ported from lex00/floci#118. Tracked in lex00/floci#192.

* fix(cloudformation): validate usage plan key properties and survive a recreated plan

An association only counts as still there while its plan does. deleteUsagePlan
leaves associations behind, and a plan recreated after an out-of-band delete has
a new id, so the stale association no longer reads the new UsagePlanId as a
rename. KeyType must be API_KEY and both ids must be present, per the registry
schema, and a non-list ApiStages is refused instead of read as empty.
replaceUsagePlanTags strips the reserved id-override tags the way createUsagePlan
does rather than refusing them.

* fix(cloudformation): check a usage plan key's KeyId even while recovering drift

The createOnly checks sat behind the association lookup, so a template that
changed KeyId while its plan was missing created an association for the new key
instead of refusing the change. KeyId is checked against the prior composite id
either way now. UsagePlanId stays conditional, since a plan recreated after an
out-of-band delete legitimately has a new id.
2026-09-06 22:09:54 -05:00
Kenshin Okinaka 2c6a92c07d feat(ses): implement v1 receipt filters (CreateReceiptFilter, ListReceiptFilters, DeleteReceiptFilter) (#3163)
Adds the three v1 receipt-filter actions as a stored-but-inert IP filter
store alongside the receipt-rule-set domain: filters round-trip through the
management API but never filter an inbound connection, since Floci accepts
none.

Validation follows real AWS as probed: the filter name is a single
service-level layer (no Smithy pattern, unlike rule and rule-set names) with
"Not a valid filterName" for every malformed shape and its own message for
an empty name; IpFilter members are Smithy-enforced (not-null paths and the
[Allow, Block] policy enum); the Cidr member accepts a single IPv4 or IPv6
address or an in-range CIDR block and rejects everything else with
"Invalid CIDR block"; duplicates are AlreadyExists with the original kept;
deletes are idempotent with only an absent FilterName rejected; and the
101st filter in a region is rejected with LimitExceeded "Too many filters".
List responses are name-sorted for determinism since the probe could not
pin the wire ordering.

Covered by unit tests, Query-protocol integration tests, an AWS SDK
compatibility test, and Terraform/OpenTofu compat coverage for
aws_ses_receipt_filter.
2026-09-06 21:00:42 -05:00
Franklin G. Mendoza 6264b09a28 feat(identitystore): add full service emulation (#3159)
* feat(identitystore): add groups users and memberships

* feat(identitystore): add full service emulation

* fix(identitystore): validate update attribute paths
2026-09-06 21:51:19 -04:00
Max Freedom Pollard 60a8a9d252 fix(eventbridge,scheduler): read cron day-of-week as AWS 1-7 SUN-SAT (#3147)
Both schedule parsers built their cron definition with cron-utils' default
day-of-week field, which is Unix numbering: 0-6 for SUN-SAT. AWS numbers that
field 1-7 for SUN-SAT, so every numeric day was read one day late and Saturday
could not be expressed at all.

cron(0 12 ? * 2 *) is Monday to AWS and fired on Tuesday. AWS's own documented
example cron(15 10 ? * 6L 2022-2023), the last Friday of the month, fired on the
last Saturday. cron(0 12 ? * 7 *) did not parse at all, failing with "Value 7 not
in range [0, 6]". Day names were always correct, because cron-utils resolves them
against its own numbering, so only expressions written with numbers were wrong.

The definitions are at ScheduleExpressionParser.java:32 (eventbridge) and
SchedulerExpressionParser.java:55 (scheduler). Both now pin the field with
withValidRange(1, 7) and withMondayDoWValue(2), the same shape cron-utils uses
for Quartz, whose day-of-week dialect AWS follows. 7 parses as Saturday, and 0 is
rejected in line with AWS's documented 1-7 range.

The existing eventbridge test getNextFireTimeFirstMondayOfMonth encoded the old
behavior: it parsed cron(30 2 ? * 2#1 *), named itself for the first Monday, then
asserted the fire day was a Tuesday. It now asserts 2026-03-02, which is the
first Monday of that month.
2026-09-06 18:41:17 -04:00
Kenshin OkinakaandPriamo fd665a08cc feat(ses): implement v1 receipt rules with locally validated action targets (#3119)
* feat(ses): implement v1 receipt rules with locally validated action targets

Adds the five v1 receipt-rule actions (CreateReceiptRule, DescribeReceiptRule,
UpdateReceiptRule, DeleteReceiptRule, SetReceiptRulePosition) on top of the
stored-but-inert receipt-rule-set domain. Rules route no mail, but ordering
semantics follow real AWS as probed: a rule created without After is inserted
at the front, SetReceiptRulePosition without After moves a rule to the front,
update replaces the whole rule in place, and rule delete is idempotent while
rule-set delete cascades.

Action targets are validated against the local emulator the way real SES
validates them against the account: any TopicArn must be an existing SNS
topic, an S3 BucketName an existing bucket, a Lambda FunctionArn an existing
function, and a BounceAction Sender a verified identity, using the probed
error codes (InvalidSnsTopic, InvalidS3Configuration, InvalidLambdaFunction,
InvalidParameterValue). Smithy-layer validation reproduces the probed member
paths and combined violation messages; only the members real SES enforces are
required (S3 BucketName, SNS TopicArn, and Stop Scope may be absent).

Covered by unit tests with mocked resource services, Query-protocol
integration tests, an AWS SDK compatibility test, and Terraform/OpenTofu
compat coverage for aws_ses_receipt_rule.

* fix(ses): match probed AWS semantics for action-list gaps and present-struct required members

Probing triggered by the upstream review corrected two earlier conclusions.
A gap in the action list (an empty struct serializes to no Query keys) is
not compacted by AWS: the gap is padded into an empty action slot and
rejected with InvalidParameterValue "Exactly one action type must be
specified for each ReceiptAction", with Smithy paths keeping the wire
index. member.0 is rejected outright with MalformedInput
"0 is not a valid index".

The earlier "optional" verdict for S3Action.BucketName, SNSAction.TopicArn,
and StopAction.Scope was an artifact of empty structs never reaching the
wire: once an action carries any member, the type's required members are
enforced as Smithy violations. BounceAction violations are reported in the
probed smtpReplyCode, sender, message order, and SNSAction reports a bad
Encoding enum before the missing TopicArn.

* fix(ses): honor original receipt-action index spellings and require stop actions last

Probing the leading-zero report pinned AWS's index semantics exactly: index
tokens are grouped by numeric value, ordered by length then lexicographically,
and the i-th token must parse to i, or the padded empty slot is rejected with
the exactly-one-action-type error. member.01 alone is therefore a valid slot 1
whose action must be parsed under its original spelling instead of a rebuilt
canonical one, while mixed spellings such as member.01 plus member.2 are
rejected because the one-digit token sorts first.

The same probes surfaced an unrelated service-level rule now reproduced too:
a stop action anywhere but the last position is rejected with
"Stop action, if any, must be placed at the end of the actions list".

* chore(ses): log best-effort compat-test cleanup failures with resource context

The three cleanup catches in the receipt-rule compatibility suite swallowed
failures silently. They now report the failed step and resource on stderr,
the form the other suites in this module already use, so leaked test
resources stay diagnosable.

* chore(lambda): log functionExists resolution failures at debug level

The catch converts a resolution failure into the predicate's negative
answer; the debug line keeps a surprising false diagnosable (which
reference was rejected, and why) without turning ordinary existence
misses on a query path into log noise.

* fix(ses): restrict receipt-action index tokens to ASCII digits

Character.isDigit also accepts non-ASCII Unicode digits, so a key such as
Rule.Actions.member.<fullwidth 1> parsed as a real index. No AWS Query
index grammar recognizes those spellings; the key is now skipped like any
other unmodeled parameter, pinned by an integration test.

---------

Co-authored-by: Priamo <pgermosen@gmail.com>
2026-09-06 18:01:33 -04:00
Vũ Thế Huy 4570bf62c5 feat(redshift): emulate Redshift UNLOAD TO s3 over Simple Query protocol (#3129)
* feat(redshift): parse UNLOAD TO s3 statements

* feat(redshift): add S3Service.authorizeAnonymousPutObject for the UNLOAD writer

* feat(redshift): simulate Redshift UNLOAD TO s3 via CopyOut

* feat(redshift): dispatch UNLOAD via the intercepting bridge

* test(redshift): cover UNLOAD to S3 end to end

* docs(redshift): document UNLOAD to S3 support

* fix(redshift): drain backend on UNLOAD streaming failure and handle final slice error

* refactor(redshift): clean up inline FQCN imports across main and test sources

* fix(redshift): address review feedback on UNLOAD to S3 simulator

* fix(redshift): authorize ListBucket on UNLOAD prefix probe and clean up manifest on backend EOF

* fix(redshift): authorize UNLOAD cleanup deletes and skip them under ALLOWOVERWRITE

* fix(redshift): fail open on UNLOAD MAXFILESIZE above the buffering ceiling

* feat(redshift): repeat the UNLOAD header row at the start of every slice

* test(redshift): cover UNLOAD to S3 over JDBC in the SDK compatibility suite

* docs(redshift): document UNLOAD per-file header, MAXFILESIZE bytes, and over-cap fail-open

* fix(redshift): clean up new UNLOAD slice objects even under ALLOWOVERWRITE

deleteWritten previously bailed entirely when ALLOWOVERWRITE was set, to avoid
destroying a pre-existing object a slice key had overwritten. That also left
genuinely new slice keys behind on a MANIFEST failure, exposing a partial result
with no manifest. Track which slice keys existed before the write and skip only
those on cleanup.

* fix(redshift): never delete UNLOAD output under ALLOWOVERWRITE

The preExistingKeys heuristic could not distinguish an overwrite from a fresh
write atomically: two concurrent UNLOADs to the same prefix could both classify a
key as new, and one operation's cleanup could then delete the other's output.
Drop the heuristic and simply never delete under ALLOWOVERWRITE. Non-overwrite
runs verified the prefix was empty, so their cleanup is still safe. A failed
MANIFEST + ALLOWOVERWRITE UNLOAD may leave data objects without a manifest, which
is now documented.

* fix(redshift): read UNLOAD objects via getObject in the integration test

listObjects returns metadata-only S3Object entries whose getData() is null, so
unloadToS3PrefixWritesRowsAsObjects and unloadGzipWritesCompressedObject threw
NullPointerException in CI. Fetch each body with getObject, as the MANIFEST test
already does.
2026-09-06 15:58:37 -05:00
Mario Toffia ee2f55b784 feat(iot): MQTT over TLS listener on 8883 (#3142)
* feat(iot): floci.services.iot.mqtt.tls-port (default 8883)

* feat(iot): key manager that follows the TLS registry's current default certificate

* feat(iot): MQTT over TLS listener on 8883

Second MqttServer sharing the plaintext handlers, opened when floci.tls.enabled
is true. Its key material is the TLS registry's default configuration through a
reloading key manager, so a server certificate reissued for a learned hostname
is presented on the next handshake without rebuilding the listener. Client
certificates are requested and carried through the handshake, not yet verified.

* docs(iot): MQTT over TLS on 8883

* feat(iot): keep retired server key material readable for the life of a handshake

A retired generation of ReloadingKeyManager stays readable for 60 seconds after
its replacement, longer than Vert.x's 10 second handshake timeout, and is dropped
on the next reload after that. Any number of reloads between JSSE choosing an
alias and reading its key and chain now resolve to matching material.

* fix(iot): wait for a failed MQTT listener to close before reporting the start failure
2026-09-06 15:55:19 -05:00
Facundo ParedesandFacundo Paredes e3230a74ab fix(stepfunctions): reject the QueryLanguage definitions AWS rejects (#2972)
* test(stepfunctions): pin that JSONata-only fields are rejected on a JSONPath state

Output, Arguments and Items exist only in JSONata. AWS rejects each on a
JSONPath state and locates the diagnostic at the state, not at the field.
A Map's own QueryLanguage is inert for the states inside its ItemProcessor:
the two definitions of the first test fail identically on AWS, so the
equality of their diagnostic lists is what is asserted.

* test(stepfunctions): locate QueryLanguage field errors at the state, as AWS does

Two assertions expected /States/<state>/<field>. Measured on AWS, this
message family carries no field suffix: /States/X for a JSONata Pass with
InputPath, /States/M for a MaxConcurrencyPath on a JSONata Map. Both turn
red until the diagnostic moves.

* fix(stepfunctions): reject JSONata-only fields on a JSONPath state

Output, Arguments and Items are refused on a JSONPath state, the mirror of
the JSONPath-only list already refused on a JSONata state. Assign stays off
the list: AWS accepts it under both query languages.

This family of diagnostics is located at the state itself rather than at the
offending field, so both directions now travel through the marker that
already carried Field 'X' is not supported past the generic converter.

* test(stepfunctions): pin the JSONPath downgrade and QueryLanguage on a sub-workflow

A JSONata state machine cannot be reverted state by state to JSONPath, and
the ItemProcessor or branch object carries no QueryLanguage of its own: it
is not a state. Both messages and both locations are as AWS returns them.
The two accepting cases keep the guard reading the machine's language rather
than the presence of the field.

* fix(stepfunctions): refuse a JSONPath state under a JSONata machine and QueryLanguage on a sub-workflow

A state declaring JSONPath under a JSONata state machine is rejected at the
state's path; the upgrade in the other direction stays legal, so the guard
reads the machine's language rather than the presence of the field.

The ItemProcessor, Iterator and branch objects are key-checked for
QueryLanguage, which they cannot carry: they are sub-workflows, not states.
validateNestedStates becomes validateSubWorkflow and takes the sub-workflow
object, so the check and the paths derived from it live in one place.

* test(stepfunctions): pin that an ItemProcessor state runs as the machine's query language

A JSONata Map evaluates its own Items expression while the bare Pass inside
its ItemProcessor still resolves Parameters with .$, which exists only in
JSONPath. Both halves land in one execution, and the outputs are the
literals the real service returned. Propagating the Map's language into the
ItemProcessor makes two of the three cases produce the raw item instead.

* docs(stepfunctions): record why the sub-workflow gets the machine's query language

The three call sites that hand a nested sub-workflow the state machine's
query language now say so, citing the ASL specification clause that calls
the enclosing Map's or Parallel's declaration independent of it.

* test(stepfunctions): pin the downgrade diagnostic alone and a QueryLanguage outside the enum

* fix(stepfunctions): report the QueryLanguage downgrade alone and the enum value at its field

* test(stepfunctions): pin the diagnostic order, the legacy Iterator and a bare ItemProcessor Pass

* fix(stepfunctions): emit QueryLanguage field diagnostics in a fixed order

* test(stepfunctions): pin that only the exact string JSONPath makes a state JSONPath

* fix(stepfunctions): resolve a QueryLanguage to JSONPath only on the exact string

* test(stepfunctions): name the Map fixtures after the repo's state naming

The nested Map fixtures used SCREAMING_SNAKE state names, which no other
fixture in this repo does. ItemsMap and SubItemsMap sit next to the
HelloWorld pass they enclose.

---------

Co-authored-by: Facundo Paredes <25681464+facuparedes@users.noreply.github.com>
2026-09-06 15:53:47 -05:00
Priamo Germosen 81b8127de0 feat(ram): support resource-share invitation accept/reject (#3120)
Closes the last open piece of #2313. Resource shares and associations
already existed; GetResourceShareInvitations was hardcoded to return
empty and there was no Accept/RejectResourceShareInvitation at all, so
aws_ram_resource_share_accepter had nothing to work against.

Adds real invitation records for bare AWS account-id principals added
while organization sharing is off (an organization/OU principal never
gets one, matching real AWS's own auto-accept behavior for org-based
sharing, and neither does an account principal once organization
sharing is enabled). Accept/reject are receiver-only and terminal once
resolved, matching the modeled error shapes
(OperationNotPermittedException,
ResourceShareInvitationAlready{Accepted,Rejected}Exception,
ResourceShareInvitationArnNotFoundException, MalformedArnException).
GetResourceShareInvitations only returns invitations the caller
received, not ones it sent, matching the API reference ("invitations
that you have received").

Deliberately not a visibility gate: GetResourceShares/ListResources
under OTHER-ACCOUNTS keep showing every non-owned share regardless of
invitation status, same as before this change, since floci's launched-
container credentials all resolve to one default account and gating on
acceptance would hide shares from the very consumers real AWS invited.

Invitation creation and accept/reject are each serialized behind a
synchronized(this) scoped to just this new code, closing two TOCTOU
races (duplicate invitations from concurrent associates on the same
principal; a double-accept both succeeding) without touching the
pre-existing, already-unsynchronized share-mutation paths.
2026-09-06 15:51:49 -05:00
Franklin G. Mendoza d80734e6de feat(account): add alternate contact operations (#3118)
* feat(account): add alternate contact operations

* fix(account): complete alternate contact contracts
2026-09-06 15:49:12 -05:00
Facundo ParedesandFacundo Paredes 504203f8e8 fix(stepfunctions): abort executions abandoned by a restart (#2969)
* test(stepfunctions): cover executions abandoned by a restart

* fix(stepfunctions): abort executions abandoned by a restart

An execution runs inside the Floci process, so a restart leaves it stored as
RUNNING with no worker behind it: DescribeExecution reported RUNNING forever
and GetExecutionHistory reported nothing, so a caller waiting for a final
status hung until its own timeout with no diagnosis.

EmulatorLifecycle.onStart now calls StepFunctionsService.abortAbandonedExecutions
after storageFactory.loadAll(), which retires every still-RUNNING execution with
status ABORTED, a stopDate, error ExecutionAbandoned and a cause naming the
restart, and seals its history with a single ExecutionAborted event. ABORTED is
the status AWS gives an execution ended from outside its own definition, and it
is the only terminal status that keeps the execution inside RedriveExecution's
reach.

The sweep runs with no request context, so it scans every account and writes
each execution back under the account that owns it. The terminal write is shared
with StopExecution, which handled the same window for its own half already.

* fix(stepfunctions): file the abort history under the storage key

markAborted read the history key off the stored value. An execution whose
executionArn field is null made computeIfAbsent throw out of the startup sweep,
which EmulatorLifecycle.onStart calls unguarded, so the process did not boot and
the sweep stopped mid list with earlier entries flipped in memory and never
written back. A field that disagreed with the storage key filed the
ExecutionAborted event where GetExecutionHistory does not look. The key is now a
parameter: StopExecution passes the ARN it was called with, the sweep passes the
key the entry came under.

The tests bound the stopDate between two literal epoch-second instants instead of
asserting it is non-null, so a wrong unit fails; assert the sweep stays silent
when nothing is RUNNING, which is what the count guard is for; and pin the WARN
record by level and count rather than by its whole sentence. The lifecycle test
whose plain verify was subsumed by the ordered one is gone.

The documentation no longer claims the ExecutionAborted event survives a further
restart: histories live in memory, so the event is written on the boot that
aborts the execution, while the status, error and cause persist.

* test(stepfunctions): require the AWS shape of an abort with no reason

The startup sweep is measured against us-east-1 with StopExecution called
without --error and --cause: status ABORTED, DescribeExecution omitting both
keys, and executionAbortedEventDetails present and empty. The persistence test
pins the sweep, and the integration test pins the wire shape, where an omitted
key is distinguishable from a null one.

* fix(stepfunctions): abort abandoned executions the way AWS aborts

ExecutionAbandoned is a code AWS never emits, and the sweep was the only
producer of it. Measured against us-east-1 with StopExecution called without
--error and --cause, the abort reports status ABORTED, DescribeExecution omits
the error and cause keys, and the terminal event carries an empty
executionAbortedEventDetails. The sweep now takes that same path; the WARN line
with the count is where the reason lives.

markAborted keeps both parameters: StopExecution passes the caller's error and
cause through them.

---------

Co-authored-by: Facundo Paredes <25681464+facuparedes@users.noreply.github.com>
2026-09-06 15:44:31 -05:00
Matheus Oliveira 5cf10ece18 fix(cloudcontrol): reject ListResources for unsupported resource types instead of returning empty (#3141)
Unsupported TypeName values now fail with UnsupportedActionException
(HTTP 400) instead of an empty ResourceDescriptions, which was
indistinguishable from a genuinely empty result. Documents the
supported type list and the new error behavior.

Closes #2043

Signed-off-by: Matheus Oliveira <matheus.6148@gmail.com>
2026-09-06 15:28:43 -05:00
lex00 17af9590c7 feat(cloudformation): provision AWS::AutoScaling::ScalingPolicy (#3124)
* feat(cloudformation): provision AWS::AutoScaling::ScalingPolicy

Per-service provisioner over AutoScalingService. Ref and Fn::GetAtt Arn are
the policy ARN and Fn::GetAtt PolicyName the generated name, since the type
has no PolicyName property. PutScalingPolicy is an upsert keyed by group and
name, so an update reuses the name recorded at create time and rewrites the
policy in place. AutoScalingGroupName is createOnly, so moving the policy to
another group is refused as a replacement rather than left behind on the old
group. Omitted ScalingAdjustment and Cooldown take the Query handler's
defaults.

Ported from lex00/floci#118. Tracked in lex00/floci#192.

* fix(cloudformation): scope the scaling policy lookup to its group

Policy names are unique only within a group. The update path now looks for the
recorded name on the template's group first and treats a same-named policy on
another group as a move only when it is not there, so an unrelated group's
policy cannot block a valid update.

* fix(cloudformation): take a scaling policy's identity from its recorded group

Finding the recorded name on the group the template asks for read the
destination group's own same-named policy as this resource, so a move
overwrote that policy and orphaned the original. The group is recorded on the
resource at create time and compared directly instead, which drops both
DescribePolicies lookups. A resource provisioned before the attribute existed
has no prior group and keeps the previous behaviour.
2026-09-06 15:13:58 -05:00
lex00 cbde58f238 feat(cloudformation): provision AWS::ApiGateway::ApiKey (#3122)
* feat(cloudformation): provision AWS::ApiGateway::ApiKey

Per-service provisioner over ApiGatewayService. Ref and Fn::GetAtt APIKeyId
both yield the key id. Description, Enabled and Tags update in place. Name,
Value and GenerateDistinctId are createOnly, so a change to any of them is
refused as a replacement rather than applied to the existing key. A template
that omits Name keeps its generated name across updates instead of minting a
second key. Stack deletion deletes the key and tolerates one already gone.

ApiGatewayService gains replaceApiKeyTags so an update can drop a tag the
template no longer declares.

Ported from lex00/floci#118. Tracked in lex00/floci#192.

* fix(cloudformation): keep an API key's create-time reserved tags across updates

replaceApiKeyTags checked the whole desired map against the reserved list,
so a key created with a reserved floci tag could never change an ordinary tag
afterwards. Only a reserved tag that is new or changed is an update-time
override attempt and is refused now. Adds a test that dropping Description
from the template clears it on the key.
2026-09-06 15:12:50 -05:00
lex00 ba3dd657b6 feat(cloudformation): provision AWS::SNS::TopicPolicy (#3126)
Adds the type to SnsCfnProvisioner beside Topic and Subscription. A topic
policy is not an entity of its own: it writes the Policy attribute of every
topic the template lists, so re-applying on UpdateStack is what an update
means. The document goes through resolveJsonAttribute like FilterPolicy, so a
Ref to a topic inside Resource resolves to the ARN. The physical id is
synthetic and stays put across updates, as AWS::SQS::QueuePolicy does, and Ref
and Fn::GetAtt Id both return it. An empty Topics list or a missing
PolicyDocument is refused. Delete touches nothing, as with QueuePolicy.

Ported from lex00/floci#118. Tracked in lex00/floci#192.
2026-09-06 15:11:42 -05:00
Mario Toffia 024bfa0a5c feat(docker): containers Floci launches trust the Floci CA (#3091)
* feat(tls): write a CA bundle for launched containers at boot

Containers Floci launches need to trust Floci's HTTPS endpoint from any runtime
without losing access to public HTTPS. A bundle that carries the JVM's public
roots followed by Floci's trust anchor makes that possible: the variables that
replace a runtime's trust store (SSL_CERT_FILE and friends) can then point at
it safely.

ContainerCaBundle writes {persistent-path}/tls/floci-ca-bundle.pem from the
JVM's default trust anchors plus the certificates in the anchor file: the local
CA, or the user-provided certificate file in custom-certificate mode. Only
certificates are copied out of that file, so a combined certificate-and-key
file never leaks its key into a container. The file is swapped in atomically
from a uniquely named temporary file. TlsConfigSource writes it in both
certificate modes; a failure is logged and never stops the boot.

hostPath(config) resolves the bundle in the directory the bootstrap used, so a
persistent path set only in application.yml cannot point it elsewhere, and
appendEnv(env) adds SSL_CERT_FILE, CURL_CA_BUNDLE, REQUESTS_CA_BUNDLE,
NODE_EXTRA_CA_CERTS and AWS_CA_BUNDLE without overriding a key the caller set.

The bootstrap now records its TLS directory in every TLS-on mode, not only when
it issues the leaf, so the CA producer and the bundle lookup read from the
directory the boot wrote to even when a persistent path is set in
application.yml alone. A missing bundle is reported once per process.

* feat(docker): every launched container gets the CA bundle and the trust variables

ContainerLifecycleManager.create is the single path every emulator-created
container passes through, so injecting trust there covers Lambda, ECS, MWAA,
Flink, RDS, ElastiCache, Batch and the rest at once.

With TLS on and the bundle present, create appends the five trust variables
after the spec's own environment (a value from a task or function definition
wins) and copies the bundle to /etc/floci-ca-bundle.pem in the created, not
yet started, container. A copy rather than a bind mount, because when Floci
itself runs in Docker its persistent path is not a host path the daemon can
mount. A failed copy is logged with its consequence and the container still
starts. With TLS off, or without a bundle, nothing changes.

* refactor(lambda): take container CA trust from the lifecycle manager bundle

The Lambda launcher no longer resolves, copies or announces the CA itself: the
lifecycle manager does that for every container. Its append-only policy
(NODE_EXTRA_CA_CERTS and AWS_CA_BUNDLE only, never SSL_CERT_FILE) existed
because a bare CA would have cut a function off from public HTTPS; the bundle
carries the public roots, so the policy and the test that guarded it go.

The Kubernetes launcher publishes the bundle in its ConfigMap instead of the
bare CA, mounts it at /etc/floci-ca-bundle.pem, and appends the trust
variables after the function's own environment so a function value wins, as
in the Docker launcher.

* test(docker): a launched container trusts Floci and public roots through the bundle

The unit tests pin the variables and the copy, not that a runtime reading them
actually trusts Floci and still reaches public HTTPS. A python:3.12-alpine
container launched through the lifecycle manager, with the image's own root
directory pointed away so only the bundle can supply roots, fetches
https://host.docker.internal:<port>/_floci/ca.pem and https://public.ecr.aws/
with no setup of its own. Skipped without a Docker daemon, like the other
*DockerIntegrationTest classes; the image is prefetched in CI with the
others.

* docs(tls): containers Floci launches trust the Floci CA

Describe the bundle every launched container receives, the five variables that
point at it, that a value set on the function or task definition wins, and
that the JVM ignores these variables so a Java workload still needs its own
trust store.

* fix(docker): recreate a container without the trust variables when the bundle cannot be copied

SSL_CERT_FILE, CURL_CA_BUNDLE and REQUESTS_CA_BUNDLE replace a runtime's trust
store, so a container whose bundle copy failed (an image without /etc) used to
start pointing them at a file that was not there, and lost every HTTPS
connection instead of only the ones to Floci. The lifecycle manager now removes
that container and creates it again without the variables, so it keeps the
image's own trust store. The host configuration, and with it any dynamic host
port, is built once and reused.

* fix(tls): serve only the certificate blocks of a user-provided file from ca.pem

In custom-certificate mode GET /_floci/ca.pem returned the configured
certificate file byte for byte, so a combined certificate-and-key file, the
form OpenSSL tooling produces, handed the server's private key to any caller.
The endpoint now goes through the same certificate-only parsing the container
bundle uses. TlsUserCertIntegrationTest boots on a combined file and asserts
the response holds the user certificate and the local CA and no key.

* test(cloudformation): wait for DeleteStack to finish before asserting on deleted resources

DeleteStack hands the work to an executor and answers at once. Seven tests in
CloudFormationIntegrationTest asserted on the deleted resources right after the
answer; one of them, deleteStack_ecs_leavesNoOrphans, failed shard 1 of this
pull request's CI 44 ms later with the cluster still ACTIVE, while the same
shard had passed on the previous push.

A shared awaitStackDeleted polls DescribeStacks until the stack reports
DELETE_COMPLETE or no longer exists, fails on DELETE_FAILED or after ten
seconds, and replaces the three inline copies of that loop as well.

* docs(tls): restore the learned-hostnames section and the ACM wording that #3079 dropped

#3079's docs commit (dc3e9ee6a) was written against a tls.md that predated
#3086 and, once squashed onto main, removed the "Custom Domains Learned at
Runtime" section #3086 had added and reworded the intro to place ACM
certificates "in a later release", although AcmService has issued them from
the local CA since #3086. Both are restored here, next to the new section,
because a separate PR would conflict with this one on the same lines.
2026-09-06 14:57:08 -05:00
Mario Toffia d45c64545d feat(iot): evaluate the SQL subset of topic rules (#3021)
* feat(iot): evaluate the SQL subset of topic rules

Topic rules only extracted the FROM topic filter and sent the whole
payload to every action. The SELECT list and the WHERE clause were
ignored, so a rule fired on every matching topic and its actions never
received the projected document.

Add a small hand written parser and evaluator under services/iot/rules
for the SELECT/FROM/WHERE subset AWS rules use most: '*', dotted field
paths, topic() and topic(n) with optional AS aliases, and a WHERE of
startswith, endswith, comparison operators, AND, OR, NOT and
parentheses. A missing field or a mismatched type is Undefined as in
AWS, so an undefined predicate never fires the rule.

A statement outside the subset is not rejected. It is stored as sent and
keeps its previous behaviour, firing on every matching topic with the
whole payload, and logs one WARN naming the token that could not be
parsed. floci.services.iot.rule-sql-strict, off by default, rejects it
with SqlParseException the way AWS does.

Each rule is parsed once: the result is held on the rule object as a
transient field that is never persisted and is rebuilt on the first
publish after a restart.

* fix(iot): count real tokens in the rule SQL limit and compare numbers exactly

The token limit counted the end marker, so a statement with exactly 1000
tokens was rejected and the error named the end of input. Mixing a whole
number with a decimal literal went through double, so 9007199254740993
compared equal to 9007199254740992.0.

* fix(iot): keep rule SQL decimal literals exact

Double.parseDouble rounded a decimal literal before evaluation, so
level = 9007199254740993.0 matched a payload holding 9007199254740992.

* fix(iot): treat a rule SQL number too large for a double as Undefined

Comparing an infinity, which Jackson produces for a JSON number wider than
a double, converted both operands to the same infinity and made distinct
values compare equal.

* fix(iot): follow the AWS IoT SQL operator tables and harden the rule parser

The comparison and logic semantics did not match the operator tables in
the AWS IoT SQL reference: = and <> on mismatched types are false and
true rather than Undefined, JSON null is a value that equals only NULL,
the ordering operators convert numeric strings, AND, OR and NOT accept
the strings "true" and "false" and give Undefined for anything else
instead of three valued logic, and startswith and endswith convert
non-string arguments. String literals may use double quotes, as AWS's
own examples do, and an unsupported function is named before its
arguments are parsed so the WARN reports the function rather than a
token inside it.

Add a corpus of AWS reference statements sorted into parsed and
unparsed, a deterministic mutation fuzz that requires the parser to
raise nothing but RuleSqlParseException and the evaluator nothing at
all, and tables for keyword prefixed field names, spacing, associativity,
unicode and literal forms.

* fix(iot): treat a rule SQL numeric string with an overflowing exponent as Undefined

A payload string such as "1e-2147483648" matches the numeric string form
but BigDecimal cannot hold its exponent, and the NumberFormatException
escaped the publish path. It now evaluates as Undefined, and the fuzz
payloads carry such strings.

* docs(iot): name the AWS null functions, not IS NULL, in the rule SQL limitations

* fix(iot): read rule SQL payload numbers exactly instead of through a double

Jackson read payload floats as doubles, so 9007199254740993.0 arrived
as 9007199254740992, 1e-400 as 0 and 0.30000000000000004 as 0.3 before
the evaluator compared them against an exact literal, and a predicate
could fire or stay silent for the wrong reason. The representability
guard only caught the infinity case of that loss.

Payload numbers are now read as BigDecimal, kept as written, so every
comparison is exact at any size or precision as AWS's Decimal is, a
projected number keeps its text, and the infinity handling is gone
because no double is ever produced.

* docs(iot): awsIotSqlVersion is stored and echoed, only its array semantics are not modelled
2026-09-06 14:30:36 -05:00
Allen Sanborn 94b9665c32 fix(ec2): reclaim instance containers orphaned by a hard restart (#3031)
* fix(ec2): reclaim instance containers orphaned by a hard restart

TerminateInstances flips the record to shutting-down synchronously and removes
the container on the async executor; launch persists the container id only once
Docker has created it. A process killed across either edge -- SIGKILL, OOM,
`docker kill` -- leaves a container on the daemon that no surviving record refers
to, so nothing on the next run ever collects it.

Neither existing path reaches these. `Ec2Service.stopManagedContainers` only runs
on the graceful ShutdownEvent, and the startup restore loop's
`needsMetadataRegistration` deliberately skips records in terminated or
shutting-down. Once `pruneTerminatedInstances` drops the record an hour later,
the container is unreferenced for good.

Sweep them on startup, right after the restore loop so anything legitimately
revived is already accounted for. Containers are matched on the existing
`io.floci.service=ec2` identity label and removed only when no live record claims
them. Stopped instances are explicitly not orphans -- their containers are what
StartInstances revives -- so a record in any non-terminal state keeps its
container.

The sweep is scoped by a new `floci_owner_port` label to this Floci's own API
port. Several emulators can share one Docker daemon, and an unscoped sweep would
reap a sibling's live instances; `floci_namespace` is the documented mechanism
for that but is absent unless a resource namespace is configured, so it cannot
scope the default configuration. Containers created before this label existed
carry no owner and are never swept.

Off with FLOCI_SERVICES_EC2_RECONCILE_CONTAINERS_ON_STARTUP=false.

Upstream's #2029 (createAndStartContainer/failLaunch/isLaunchCancelled)
independently landed the launch-cleanup half of the original floci-5ie fix, so
this rewrite carries only the reconciler, which upstream still lacks.

* fix(ec2): scope the orphan sweep by account and deployment, not port alone

Review on #3031 found two ways the startup sweep could delete a container that is
still in use, plus a missing config entry. All three are addressed here.

Account identity was dropped on the record lookup. reconcileOrphanedContainers runs
from @PostConstruct, outside any request, where an AccountAwareStorageBackend resolves
to the default account. A container belonging to a non-default account looked up as
absent, so the sweep classified it an orphan and removed it, leaving a live persisted
instance with no Docker runtime. findAnyInstance() now consults every account, using
the same instanceof-and-fall-back shape findAnyVpcEntry() already uses in this class.
The lookup is read-only, so a cross-account hit stays in its owner's partition.

Ownership keyed on the API port alone collided. Two independently namespaced Floci
processes sharing a Docker daemon on the same internal port stamped the same
floci_owner_port label, so starting either one reaped the other's live containers.
ownerIdentity() composes docker.resource-namespace -- the documented mechanism for
exactly this arrangement -- in front of the port. An unnamespaced single Floci keeps
the bare port it already stamped, so nothing changes for the common case.

Adds reconcile-containers-on-startup to the main application.yml, which AGENTS.md
requires for any new configuration and which the original commit omitted.

The new test fails with the old port-only ownership and passes with the fix.

* fix(ec2): put reconcile-containers-on-startup under services, not storage

The previous commit added the key to floci.storage.services.ec2. Ec2ServiceConfig
maps to floci.services.ec2, as its own env var name says
(FLOCI_SERVICES_EC2_RECONCILE_CONTAINERS_ON_STARTUP), and application.yml has an
ec2 block under each root. SmallRye rejects a key that maps to no root rather than
ignoring it, so this was not a quietly inert setting: every @QuarkusTest failed to
boot with SRCFG00050, and the native images built but could not start, which is why
the compat and sdk-test jobs timed out at exit 124.

Verified by running a @QuarkusTest rather than only compiling: Ec2ImageCatalogTest
now boots and passes, and no SRCFG00050 remains.
2026-09-06 14:28:12 -05:00
Franklin G. Mendoza 41022d09fb feat(cloudformation): support service-managed stacksets (#3055)
* feat(cloudformation): support service-managed stacksets

* fix(cloudformation): restrict service-managed account targeting

* docs(cloudformation): sync resource type table

* fix(cloudformation): align service-managed stackset contracts

* test(cloudformation): isolate stackset organization fixture

* fix(cloudformation): preserve stackset update handling after rebase

* fix(cloudformation): preserve stackset OU deletion targets

* fix(cloudformation): preserve overlapping stackset targets

* fix(cloudformation): reconcile stackset deployment targets
2026-09-06 13:59:54 -05:00
Mario Toffia dec348d382 feat(iot): provision AWS::IoT::Thing, Policy and TopicRule (#3014)
* feat(iot): provision AWS::IoT::Thing, Policy and TopicRule

CloudFormation now creates, updates and deletes things, policies and
topic rules through the existing IoT operations. Ref returns the name;
Fn::GetAtt returns the thing ARN and id, the policy ARN and id (the
name, as on AWS) and the rule ARN. Attribute payloads are replaced in
place, a changed policy document becomes a new default version, a rule
is replaced in place, and a rename replaces the entity. The topic rule
payload is handed to the service in the API's own shape. A policy is
detached from its principals before it is deleted.

* test(iot): keep policy variables verbatim in a stack-created policy

* fix(iot): cap a policy at five versions and prune the oldest on a stack update

CreatePolicyVersion refuses a sixth version with VersionsLimitExceededException (HTTP 409), as AWS does, and every policy version write runs under one lock so racing creates cannot slip past the check. A stack update with a changed document now does what the AWS CloudFormation handler does when the service refuses: it deletes the oldest version, after moving the default to the newest when the oldest is the default, and creates the new version again. Before this change the versions of a policy updated by a stack piled up without limit.

* fix(iot): keep pruning when another version fills the slot before the retry

The prune and the retry are separate calls, so another client could create a version between them and the single retry failed the stack update. The provisioner now prunes and tries again, up to as many times as a policy has versions, before it gives up.

* fix(iot): delete the oldest policy version in one step under the version lock

A stack update pruning a full policy selected the oldest version, moved the default and deleted it in separate service calls, so a direct client could delete or promote that version in between and the stale delete failed the update. The selection, the default move and the delete are now one step in IotService under the version lock; the provisioner only asks for it and retries.

* fix(iot): make room for a policy version in one step and lock the policy delete

A policy persisted before the cap can hold more than five versions, and the one-version prune then needed one failed stack update per four surplus versions. The service now deletes the oldest versions until one more fits, in one step under the lock, and the provisioner asks for that. DeletePolicy takes the same lock: a version created in the middle of a delete used to put the policy back after the delete had returned. The limit error now carries the message AWS sends, and the tolerated limit error is logged at debug level.

* docs(cloudformation): regenerate the resource-type table after the rebase onto main
2026-09-06 11:06:47 -04:00
Franklin G. Mendoza aebed6e15c feat(accessanalyzer): add analyzer lifecycle (#3117)
* feat(accessanalyzer): add analyzer lifecycle

* fix(accessanalyzer): complete service contracts

* test(accessanalyzer): make SDK cleanup best effort

* test(accessanalyzer): use project logging for cleanup
2026-09-06 10:55:17 -04:00
Mario Toffia 9b28388d89 fix(acm): report SUCCESS domain validation once a certificate is issued (#3112)
DescribeCertificate returned Status ISSUED together with
DomainValidationOptions[].ValidationStatus PENDING_VALIDATION for every
public certificate, forever. Clients that wait on the validation status
rather than the certificate status never finished: the AWS SDK
CertificateValidated waiter polls only ValidationStatus, and the CDK
DnsValidatedCertificate custom resource uses that waiter, so its stack
waited for the Lambda's timeout and rolled back.

The validation status now follows issuance: SUCCESS on an ISSUED
certificate, PENDING_VALIDATION while the configured validation wait is
running. A pending certificate is issued, with its validations marked
SUCCESS and the change stored, on the first read after
validation-wait-seconds has passed; before this the documented transition
never happened.
2026-09-06 10:48:30 -04:00
Mario Toffia c67e598594 feat(iot): real device certificates issued by the local CA (#3079)
* feat(iot): CreateKeysAndCertificate issues a real client certificate from the local CA

certificateId is sha256(DER) in lowercase hex as on AWS; the returned RSA 2048
key pair matches the certificate. CreateCertificateFromCsr parses the PKCS#10,
checks its self-signature and key strength (RSA 2048 or more, EC P-256/384/521),
signs the CSR's key with the same CA and returns no private key, as on AWS.

* docs(iot): describe the CA-issued device certificates

* fix(iot): accept only the NIST curves AWS IoT names and never store a device private key

The CSR key check reads the named-curve identifier instead of the field size,
so secp256k1 and explicit curve parameters are refused as on AWS. The stored
certificate record no longer carries the private key; it is returned once.

* feat(iot): device certificates expire at the end of 2049 and DescribeCertificate reports validity

AWS IoT-issued client certificates all carry notAfter 2049-12-31T23:59:59Z.
CertificateGenerator gains an overload with an explicit validity window;
DescribeCertificate adds validity.notBefore, validity.notAfter and
certificateMode DEFAULT. The Java SDK compatibility test asserts the shape.

* fix(iot): a device certificate never outlives its issuing CA

A new local CA is valid until the end of 2050, past AWS's fixed 2049 device
expiry; a CA created earlier (ten years) caps the device certificates it signs
at its own expiry, so a chain never expires before its leaf.

* fix(iot): derive CA and device expiry from creation time, never mint an expired certificate

A CA created after 2050 lives ten years from creation instead of ending on
the fixed date; after 2049 a device certificate lives a year, still capped
at its CA. The Python compatibility suite now sends a real PKCS#10 request,
since the placeholder it used is refused as on AWS.

* docs(tls): the local CA now signs IoT device certificates

* test(iot): pass the certificate authority to IotServiceTest's constructor
2026-09-06 10:39:57 -04:00
Niels Kootstra 0fce2d2407 fix(lambda): bound ZIP extraction resources (#3127)
* fix(lambda): bound ZIP extraction resources

Limit Lambda ZIP compressed and expanded sizes and configurable entry counts for function and layer deployments. Preserve previous extracted code when a package exceeds a resource limit.

* refactor(test): centralize ZIP fixture encoding

* docs(test): explain ZIP fixture headers
2026-09-06 10:31:50 -04:00
Franklin G. Mendoza 162211de0c feat(route53): support cross-account VPC associations (#3116)
* feat(route53): support cross-account VPC associations

* test(route53): add SDK cross-account compatibility coverage

* fix(route53): harden cross-account VPC ownership

* fix(ec2): scope default resources by account
2026-09-06 00:05:31 -04:00
Franklin G. Mendoza 3927c66040 feat(macie2): add organization administration operations (#3105)
* feat(macie2): add organization administration operations

* test(macie2): validate organization administration with sdk

* fix(macie2): harden delegated administration routing
2026-09-05 23:49:52 -04:00
Vũ Thế Huy 85180a4d88 feat(redshift): emulate Redshift COPY FROM s3 over Simple Query protocol (#3100)
* feat(redshift): parse COPY FROM s3 statements

* feat(redshift): simulate Redshift COPY FROM s3 via CopyIn

* feat(redshift): mediate the intercepting bridge pump with a backend lock

* feat(redshift): dispatch COPY FROM s3 via intercepting bridge

* test(redshift): cover COPY from S3 end to end

* docs(redshift): document COPY from S3 support

* fix(redshift): harden the S3 COPY simulator error and protocol handling

Address code review findings on the Part 4 COPY simulator:

- Guarantee exactly one client response on a mid-copy failure. The abort
  path sent CopyFail, relayed the backend's ErrorResponse/ReadyForQuery,
  then also synthesized its own, desynchronizing the client. It now emits
  one response: the backend's, or a synthesized one only when the backend
  is unreachable.
- Catch RuntimeException (AwsException) while streaming objects. A key that
  vanished between listing and reading previously propagated out of the
  bridge and closed the connection with the backend stuck in CopyIn.
- Reply to the client when the backend closes before CopyInResponse
  instead of returning silently and leaving the client blocked.
- Stop doubling backslashes when quoting DELIMITER / NULL values. Under
  standard_conforming_strings a backslash is literal, so NULL AS '\N' was
  reaching the backend as '\N' and nulls loaded as text.
- Reject COPY statements carrying an option the simulator cannot honour
  (PARQUET, JSON, MAXERROR, credentials, ...) or a trailing statement,
  so they fail open to PostgreSQL rather than loading with wrong framing.
- Scan option keywords with string literals blanked, so NULL AS 'csv' no
  longer flips the format and DELIMITER ';' no longer trips the trailing
  check.
- Report the failed-transaction status ('E') in a synthesized error when
  the client is in a transaction block; track it from the backend's
  ReadyForQuery in the bridge.
- Bound the backend read timeout during an owned exchange (60s) instead of
  blocking forever; back off between idle-wait retries.
- Relay asynchronous backend messages (NoticeResponse, ParameterStatus)
  to the client instead of dropping them; log every tolerated AwsException.
- Honour the BackendExchange return value so a future interceptor can
  decline before touching the backend.

Tests: cover the mid-copy abort (one E + one Z), backend EOF, literal
NULL AS '\N', the unsupported-clause and trailing-statement rejections,
failed-transaction status, plus a GZIP end-to-end case; the missing-object
integration test now seeds its own bucket.

* fix(redshift): address review feedback on COPY option parsing, prefix pagination, and tx state

* fix(redshift): handle backend tx abort sync failure and log socket close

* fix(redshift): verify backend transaction status 'E' after abort query
2026-09-05 23:46:49 -04:00
Vũ Thế Huy ee5c87d6d6 feat(lambda): support self-managed Apache Kafka event source mappings (#3062) (#3082)
* feat(lambda): support self-managed Apache Kafka event source mappings (#3062)

- Add SelfManagedEventSource, Topics, and SourceAccessConfigurations metadata to EventSourceMapping
- Omit EventSourceArn in REST response when null to comply with AWS wire protocol
- Support Kafka source discrimination in LambdaService and guard pollers against null EventSourceArn
- Forward Kafka ESM properties in CloudFormation provisioner
- Add serialization, service, integration, and CloudFormation tests

* fix(lambda): address review comments for self-managed Kafka ESM

* fix(lambda): handle batch size validation, function target update, and cfn access config clearing

* fix(lambda): bind qualified function targets correctly in event source mappings

* fix(cloudformation): use CfnDeletes.safeDelete in Lambda ESM provisioner

* fix(cloudformation): throw AwsException on missing FunctionName in Lambda ESM provisioner

* fix(lambda): handle create-only ESM update, allow AT_TIMESTAMP for Kafka and populate EventSourceMappingArn

* test(cloudformation): assert exact Fn::GetAtt attributes for Lambda ESM
2026-09-05 23:41:44 -04:00
Mario Toffia 67bbd2cf13 feat: serve custom domains over TLS as soon as they are created (#3086)
* feat(tls): record runtime-learned hostnames in the certificate metadata

* feat(tls): TlsCertificateManager.ensureHost grows the server certificate at runtime

Reissues the leaf from the local CA with the same key pair and the new SAN,
replaces certificate and metadata by atomic renames (the key file is never
rewritten), reloads the default TLS configuration and fires
CertificateUpdatedEvent so the HTTPS listener swaps immediately.
Names must be well-formed host names under a local suffix; anything else is
refused with a WARN and never throws.

* feat(tls): keep runtime-learned hostnames across a boot regeneration

* test(tls): ensureHost is visible to the next TLS handshake without a restart

* docs(tls): custom domains learned at runtime

* test(tls): pin the certificate contracts of a runtime reissue

The reissued leaf keeps the boot leaf's shape (subject, issuer, EKU, CA flag,
validity, new serial, configured names first), a wildcard covers exactly one
label, an IP allowed by the base URL becomes an iPAddress SAN, and a client
that verifies the server's identity for the new name (SNI plus RFC 6125
matching) fails before ensureHost, succeeds after it, and fails again after
reset, while the configured name keeps serving HTTPS throughout.

* fix(tls): retry a failed listener reload and keep served names across a boot

A name is known only once the HTTPS listener serves it: a reload that
returns false, a missing default TLS configuration or a failing listener
now leaves the in-memory state untouched, so the next ensureHost call for
that name writes and reloads again instead of reporting it as covered.

At boot, a SAN the served certificate carries beyond the metadata's
configured list is treated as learned, so a reissue whose metadata rename
did not complete cannot lose the name in a later regeneration.

The allow-list is checked after coverage, so a default SAN such as
host.docker.internal no longer logs a refusal on a no-op call.

Tests are split by concern: TlsCertificateManagerTest (reissue, reload,
reset, failure, races) and TlsCertificateManagerNameRulesTest over a
shared fixture; TlsConfigSourceLearnedHostnamesTest holds the boot paths.

* fix(tls): carry a name whose reload failed into later reissues and resets

The learned list now follows the files and the known set follows the
listener. A name written to disk but not yet served is kept by every
later reissue instead of being dropped when a second name is learned,
and a reset whose reload failed is retried by the next reset.

Two pre-existing em dashes in TlsConfigSource log messages replaced with
commas, as AGENTS.md asks.

* feat(acm): issue AMAZON_ISSUED and PRIVATE certificates from the local CA

RequestCertificate now returns a TLS server leaf (serverAuth and clientAuth)
signed by Floci's local root CA, and CertificateChain is that CA's PEM, the
same bytes GET /_floci/ca.pem serves. Certificate plus CertificateChain from
GetCertificate therefore build a chain that validates, as they do on AWS, for
both certificate types, and ExportCertificate returns the same chain. The
requested KeyAlgorithm is still honoured and DescribeCertificate reports the
CA as the issuer.

The bundled amazon-root-ca.pem and its startup check are gone: nothing Floci
issues chained to it, and the file was corrupt (its base64 payload could not
decode), so every GetCertificate handed out an unparsable chain.

AcmPaginationTest walks a store shared with every other ACM test class; its
page cap now leaves room for the suite to grow instead of failing once the
shared store passes fifty certificates.

* refactor(acm): drop the cosmetic Amazon issuer generator

CertificateGenerator.generateCertificate signed a leaf with its own key under a
CN=Amazon issuer DN that no client could ever verify. Its last production caller
now issues from the local CA, so the method and the DN are gone and the
self-signed builder no longer carries an issuer and CA flag that were always the
subject and true. Tests that only needed some certificate use the self-signed
generator; the ones that need a leaf that is not a CA issue it from a throwaway
CA.

* docs(acm): certificates chain to the local CA

Say that every issued certificate is signed by the local root CA, that
GetCertificate returns that CA as CertificateChain, and that trusting
/_floci/ca.pem once validates both the HTTPS endpoint and ACM certificates.

* test(acm): the SDK compatibility suite validates the certificate against its chain

GetCertificate's certificateChain() must contain the issuing CA and that CA
must verify certificate(), as on AWS. A chain that does not parse or does not
sign the leaf now fails the suite instead of passing a BEGIN CERTIFICATE check.

* docs(acm): say when the CA is created and what Issuer reports

ACM issuance now creates the local CA under {persistent-path}/tls/ on first
use, also with TLS off and in memory storage mode, and DescribeCertificate
reports the CA's name as Issuer where AWS reports Amazon. The CA javadoc no
longer calls ACM a later step.

* test(acm): pin key size, an imported chain and the persisted chain

The import fixture is now a server certificate from a throwaway CA, uploaded
with that CA as its chain, and GetCertificate must hand both back unchanged.
The RSA and EC chain tests also check the key size and curve, and the
persistence test checks the chain survives a restart.

* test(acm): the python compatibility suite verifies the certificate against its chain

The key-algorithm case checked the certificate's self-signature, which only
held while ACM certificates were signed by their own key under a cosmetic
issuer. On AWS, and now here, the signer is the issuing CA that GetCertificate
returns first in CertificateChain, so the case verifies that signature and the
issuer name instead.

* fix(acm): write EC private keys as PKCS#8 and classify keys by interface

JcaPEMWriter turned a JDK EC private key into a bare SEC1 structure with
no curve and no public half, which neither OpenSSL nor parsePrivateKey
could read, so every EC certificate stored an unusable key and
ExportCertificate on one failed. EC keys now go out as PKCS#8, RSA keys
stay PKCS#1 as AWS IoT hands them out, and a SEC1 key without a public
half parses through its private-key info.

Private keys are told apart by the ECKey interface rather than by name:
a BouncyCastle provider, when one is registered, names an EC key ECDSA.

* test(acm): AcmServiceTest pins issuance from the local CA

Service level, no Quarkus: every KeyAlgorithm yields a leaf of that key
signed by the CA with the CA PEM as chain and metadata read from the
certificate; PRIVATE is issued at once; a pending certificate already
holds its leaf and chain; an idempotent replay mints nothing; imports
keep their own chain; exports return the stored chain, also for EC
keys; sixteen concurrent requests each get their own valid certificate.

* feat(apigateway): serve a custom domain over TLS as soon as it is created

CreateDomainName hands the domain name to TlsCertificateManager.ensureHost
after the domain is stored, outside the uniqueness lock. The certificate
manager never throws, so the API response is unchanged.

* feat(iot): serve a customer-managed domain over TLS as soon as it is configured

CreateDomainConfiguration hands a customer-managed domain name to
TlsCertificateManager.ensureHost after the configuration is stored. A
configuration without a domain name describes the default endpoint and
registers nothing.

* feat(cognito): serve a custom domain over TLS as soon as it is created

CreateUserPoolDomain hands a custom domain to TlsCertificateManager.ensureHost
after the domain is stored. A prefix domain lives under amazoncognito.com on
AWS, a name Floci does not serve, and is left alone.

* docs: custom domains are served over TLS on creation

One sentence each in the API Gateway, IoT Core and Cognito pages, and the
TLS page now names the operations that add hostnames to the server
certificate.

* test(compat): custom domain reachable over TLS trusting only the ACM chain

RequestCertificate, CreateDomainName with regionalCertificateArn, then a TLS
handshake with SNI that trusts only the returned CertificateChain and
verifies the hostname. Probes for TLS on the endpoint host and port, because
the workflow hands the tests an http:// URL while Floci serves both, and
skips when the probe fails.

* docs(tls): say which ensureHost outcomes are logged as warnings

* test: pin the custom domain TLS hooks against the service contracts

Service tests for API Gateway, IoT Core and Cognito: the exact name is
handed over once, after the record is stored, with no service lock held
(a concurrent create must not wait for the TLS reload), and never for a
rejected request, an ENDPOINT configuration, an AWS-managed configuration,
a prefix domain or a later update or delete. A CloudFormation stack with
the three types registers every domain and a replacement, not an in-place
update or the delete. With TLS on, a client trusting only the ACM chain
reaches all three names by SNI with hostname verification, and a reset
takes them back.

* test(acm): build the InUseBy test service with the local CA

AcmInUseByTest landed on main with #3035 using the constructor that
predates the local CA; AcmService now takes the certificate authority
it issues from, so the test loads a throwaway CA in its temp directory
like AcmServiceTest does.

* test(cognito): request an issued ACM certificate in the custom domain TLS tests

Since #3035 a custom domain needs an issued ACM certificate, so the wire
test requests one and the service test stubs AcmService. Two new cases pin
that a certificate ACM does not know, or has not issued, is refused before
the hostname is registered.

* test(cognito): a concurrent create does not wait for the TLS reload

The custom domain hook sits after the domain lock #3095 introduced, so a
second create is not queued behind the HTTPS listener switch; pinned the
same way as for API Gateway and IoT Core. The routing test #3095 added
constructs the service with the certificate manager as well.
2026-09-05 22:05:40 -04:00
Franklin G. Mendoza 1bf7494e99 feat(ssoadmin): add permission sets and assignments (#3103)
* feat(ssoadmin): add permission sets and assignments

* test(ssoadmin): validate account assignments with sdk

* fix(ssoadmin): complete pagination and lifecycle contracts
2026-09-05 21:46:20 -04:00
Matheus Oliveira c22ded931a fix(rds): run IAM PostgreSQL sessions as the role named in the token (#3106)
* fix(rds): run IAM PostgreSQL sessions as the role named in the token

The proxy validated the token and then connected as master. It now hands
the session over with SET SESSION AUTHORIZATION, so the role's own
privileges apply and an unknown role is refused.

Closes #3087

Signed-off-by: Matheus Oliveira <matheus.6148@gmail.com>

* fix(rds): keep IAM PostgreSQL sessions from switching back to master

The backend connection is master underneath, so RESET SESSION AUTHORIZATION
regained superuser. The proxy now watches PostgreSQL's own
session_authorization report and terminates the session when it changes.

Signed-off-by: Matheus Oliveira <matheus.6148@gmail.com>

---------

Signed-off-by: Matheus Oliveira <matheus.6148@gmail.com>
2026-09-05 21:24:39 -04:00
Guilherme Scaranse a9df872956 fix(dynamodb): route Kinesis CDC to the table owner's account and retry failed forwards (#3063)
* fix(dynamodb): resolve Kinesis CDC forwards against the table owner's account

DynamoDB->Kinesis CDC forwarding resolved the target stream against the ambient
account. Out of request scope -- notably the TTL sweep, which forwards a REMOVE per
expired item after the request completes -- the ambient account falls back to the
default, so CDC records could be written into the default account's same-named stream
(a cross-tenant leak) or dropped as ResourceNotFound. This was a live bug on the TTL
path.

- Add KinesisService.putRecordForAccount: resolve, append and persist against a
  specified account (a null account preserves the ambient behavior). It keeps the
  per-stream append lock keyed on region+stream (not account) so explicit-account
  appends stay serialized with request-path producers, preserving the concurrent-
  append fix; and it migrates a legacy unprefixed stream into the account partition on
  write (ownership validated by the stream's ARN/account) so installs upgraded from
  pre-multi-account storage keep forwarding.
- KinesisStreamingForwarder.forward now takes the table owner account and forwards via
  putRecordForAccount.
- DynamoDbService passes the owner account at every forward site: the request paths use
  the request account; the TTL sweep uses the account it derives from the storage key.

AWS Compatibility: CDC records land in the table owner's stream, matching AWS
per-account isolation. Known residual: the DynamoDB Streams subsystem
(DynamoDbStreamsService) has the same ambient-account exposure and is not addressed
here.

* fix(dynamodb): retry and park failed Kinesis CDC forwards instead of dropping them

Change data capture forwarding to a Kinesis streaming destination dropped the
change event whenever putRecord threw, so a transient Kinesis error silently
lost DynamoDB INSERT/MODIFY/REMOVE (and TTL) events.

Forwarding is now a bounded best-effort, in-process retry queue. The write path
only enqueues (it never blocks or throws), and a per-destination single-flight
background drain performs the send outside the lock:

- transient/unknown failures retry with capped exponential backoff (250ms->8s,
  up to 10 attempts) instead of dropping on the first exception;
- deterministic terminal failures (Validation/InvalidArgument) drop only the
  poison record without wedging the queue behind it;
- per-destination FIFO is preserved across retries;
- the buffer is bounded (1000 records per destination, oldest evicted on
  overflow);
- after the retry budget is exhausted the episode gives up, and a later event
  starts a fresh episode that self-heals once the stream recovers.

Disabling a destination or deleting the table discards its buffered records and
stops all future sends for it (a send already in flight may still complete).
Dropped records are counted and per-destination delivery health
(forwarded/retried/dropped, queue depth, last error) is tracked for inspection.
Buffered records are in memory only and are not durable across restarts.

* style(dynamodb): remove em dashes from lines this branch adds

AGENTS.md requires colons, commas or periods instead of em dashes. Comment,
javadoc and docs prose only; no code or string literals change.

* fix(kinesis): resolve the stream inside the append lock, not before it

putRecordInternal resolved the stream before taking the per-stream monitor. That
resolve is not a read: for a legacy unprefixed stream it migrates the entry, and
the two migration paths disagree. The explicit-account path moves it into the
account partition behind an ownership predicate and is synchronized on the
backend, while AccountAwareStorageBackend.get adopts it into the request account
with no ownership check and no synchronization. Racing outside the monitor, an
ambient producer and the owner's CDC producer could migrate the same stream
concurrently, forking it across partitions or adopting it into the default
account, which is the cross-account leak this branch set out to close.

Resolve and validate inside the monitor instead. The separate pre-lock resolve is
gone, so there is one resolve rather than two, and deleteStream holding the same
monitor still makes a concurrently deleted stream fail cleanly.

Residual, pre-existing and not addressed here: AccountAwareStorageBackend.get
still adopts an unprefixed entry into the request account unchecked and
unsynchronized for callers that do not hold a per-resource lock.

* fix(storage): migrate a legacy unprefixed entry under the account monitor

AccountAwareStorageBackend has two migrate-on-read paths that disagree.
getForAccountMigratingLegacy is synchronized and ownership-gated; get is neither.
Because get does not take the monitor the migrating variants hold, two readers
resolving the same pre-multi-account key from different account contexts can each
copy it into their own partition, and the two copies then diverge independently.

The migration branch now runs under that same monitor and re-checks the prefixed
key inside it, so a reader that lost the race returns the winner's entry instead
of migrating again. The hit path stays outside the monitor, so only a miss pays
for it.

This closes the fork for every caller rather than one at a time. The preceding
commit fixed it for KinesisService.putRecordInternal by resolving inside the
append lock, but the Kinesis batch PutRecords handler and roughly twenty read
paths (DescribeStream, GetRecords, GetShardIterator, tag reads) resolve without
any per-resource lock and were still exposed.

Not addressed here: get still adopts an unprefixed entry into whatever account
the request context resolves to, with no ownership check. get is generic over the
stored type and has no notion of an owner, which is why getForAccountMigratingLegacy
takes the predicate from its caller. Gating it generically needs a per-resource-type
predicate and is filed separately.
2026-09-05 21:20:44 -04:00
Franklin G. Mendoza 6a728f1b9f feat(cloudwatchlogs): add cross-account policy operations (#3089)
* feat(cloudwatchlogs): add cross-account policy operations

* fix(cloudwatchlogs): align cross-account policy contracts

* fix(cloudwatchlogs): enforce account policy quotas

* fix(cloudwatchlogs): validate field index policy scopes

* fix(cloudwatchlogs): parse field index criteria safely

* fix(cloudwatchlogs): align field index quota parsing
2026-09-05 21:08:07 -04:00
Franklin G. Mendoza b199894e19 feat(controltower): add enabled control operations (#3056)
* feat(controltower): add enabled control operations

* fix(controltower): harden baseline state and pagination

* fix(controltower): register persisted control model
2026-09-05 20:19:56 -04:00
Mario Toffia b4d80a5596 feat(cognito): route custom domains by Host (#3095)
* feat(cognito): route /oauth2 requests on a custom domain by Host

CognitoCustomDomainFilter (PreMatching, priority 12) resolves the request
Host against the domain store and rewrites /oauth2/token and
/oauth2/userInfo onto the /cognito-idp/oauth2 handlers. The pool the domain
belongs to travels in a request property, so the controllers pin exactly the
pool the filter matched and a caller cannot supply it. The token endpoint
refuses a client of another pool with invalid_client and userInfo refuses a
token of another pool with invalid_token, as AWS does. The lookups scan
every account because an OAuth call carries no SigV4 account.

The discovery document advertises https://<domain>/oauth2/... for a pool
with a custom domain. S3VirtualHostFilter skips a request the Cognito
filter routed, the way it already skips CloudFront ones, since a custom
domain under a Floci suffix looks like a bucket host.

* docs(cognito): custom domain routing

* fix(cognito): run custom domain requests in the domain's account and keep domain names unique

A request on a custom domain carries no AWS credential, so AccountContextFilter
put it in the default account and the client, pool and user lookups missed a
domain created under another account. The Cognito filter now pins the domain's
account in a request property that AccountContextFilter honours before header
resolution. Domain creation checks the name across every account, as AWS's
single domain namespace does, and a name two accounts already hold from older
data is not routed.

Also adds the OAuth contract tests for the routed endpoints (client_secret_post,
error codes, token claims, userInfo refusals, unserved paths, prefix domains,
interleaved requests on several threads) in a second integration class.

* fix(cognito): make the domain uniqueness check and write one step

Two accounts creating the same custom domain at once both passed the
cross-account scan and wrote under their own account-prefixed keys, leaving a
name that routing then refused as ambiguous. The check and the write now run
under one lock, the way identity-provider mutations already do. A 16-thread
unit race and a two-account integration race pin exactly one owner.
2026-09-05 16:56:01 -04:00
TATSUNO “Taz” Yasuhiro 64f06e090f perf(docker): shrink image by 28% using ubi9-micro (109 MB to 78 MB compressed) (#3085)
* perf(docker): move the native image to ubi9-micro

The binary needs only libc, and since #3037 the entrypoint needs only
bash and coreutils. ubi9-micro has both at 7 MB compressed instead of
ubi9-minimal's 40 MB. Measured on arm64 with the nightly-09042026
binary: 109 MB to about 78 MB compressed, 313 MB to 229 MB uncompressed.

ubi9-micro has no useradd and no curl, so the user is one /etc/passwd
line and the healthcheck is a bash /dev/tcp probe. Dockerfile.native
gets the same runtime stage and loses its unused gosu tools stage.
Dockerfile.compat needs microdnf, so it now starts from ubi9-minimal
and copies /app out of the native image.

* chore(docker): share the health probe and split the compat tools stage

The bash health probe is now docker/healthcheck.sh, used by all three
Dockerfiles. Dockerfile.compat gets a version independent tools stage;
the aws CLI shim test and the cache warm job build target: tools, so
they pull no floci image and their cached layers stay stable. ARG
VERSION and the native RUN steps move so only the binary copy changes
between builds.

* fix(docker): copy healthcheck.sh into the compat image from the build context

* ci(compat): build the whole compat image on pull requests and check it starts healthy
2026-09-05 14:46:41 -05:00
Mario Toffia 3c6c005ff1 feat(tls): a local root CA that signs Floci's server certificate (#3078)
* refactor(acm): one issuer-signing primitive in CertificateGenerator

buildCertificate always signed with the subject's own key. signCertificate now
takes the issuer DN and key explicitly; generateCaCertificate and
generateIssuedCertificate sit on top of it, with serverAuth or clientAuth EKU on
leaves. Existing public methods keep their signatures and output; metadata now
follows ACM: colon-separated hex serial and the certificate's real signature
algorithm in upper case.

* refactor(cloudhsmv2): sign emulated hardware certificates through CertificateGenerator

Deletes the private generateCert copy; the shared primitive also marks the two
CA levels of the chain as CAs, which the old code did not.

* refactor(acm): normalize imported certificate metadata and check issued key relationships

ImportCertificate now stores the serial as colon-separated hex and the
signature algorithm in upper case, the same shape generated certificates
report. generateIssuedCertificate verifies the leaf against the issuer's
certificate and refuses a supplied key pair whose halves do not match.

* refactor(acm): refuse a supplied key pair that is not of the requested algorithm

* refactor(acm): match a supplied EC key pair by named curve, not field size

* feat(tls): FlociCertificateAuthority, a persistent local root CA

Loads or creates {persistent-path}/tls/floci-root-ca.{crt,key} with an
owner-only key, signs serverAuth and clientAuth leaves through
CertificateGenerator, and regenerates with a WARN when the pair is corrupt,
expired, not a CA, or the key does not match the certificate. A CDI producer
exposes the same pair to beans, using the directory the config bootstrap used.

* feat(tls): issue the HTTPS server certificate from the local CA

The leaf is floci-server.{crt,key}, signed by floci-root-ca; a pre-CA
self-signed leaf, a leaf from a regenerated CA and an expired leaf are replaced
on boot. Published through quarkus.tls.key-store.pem.0.* so the TLS registry
owns it and can reload it. The server key is written owner-only.

* feat: serve the local CA at GET /_floci/ca.pem

TlsLocalCaIntegrationTest boots the HTTP server on the TLS registry keys and
completes a handshake trusting only the PEM this endpoint serves.

* fix(lambda): inject the local root CA into containers instead of the server leaf

The leaf will be reissued as SANs grow; pinning it would break after the first
reissue. The CA is stable.

* docs(tls): trust the local CA once instead of disabling verification

* feat(tls): create private key files owner-only and log why a CA was regenerated

* feat(tls): serve the user certificate from ca.pem in custom-cert mode, log the CA fingerprint

With floci.tls.cert-path set, GET /_floci/ca.pem returns that file, the same
file the Lambda launcher mounts, and creates no local CA. The CA's SHA-256
fingerprint is logged at startup so an out-of-band copy can be checked, and a
file system without POSIX permissions gets a WARN instead of a silent default.

* feat(tls): ca.pem is a bundle in custom-cert mode; clear the bootstrap directory on every boot

With a user-provided certificate the endpoint returns that file followed by
the local CA, so both the HTTPS endpoint and anything Floci issues validate
from one file. TlsConfigSource resets its resolved directory on construction
so a later boot in the same JVM with TLS off or a user certificate never
reuses a stale value.

* docs(lambda): drop two em-dashes from the CA trust javadoc

* test(tls): cover an expired leaf, an expired CA, a missing CA key and the producer's directory choice

* docs(tls): describe IoT device certificates as a follow-up of the local CA
2026-09-05 15:35:30 -04:00
Scott Steen 0471d6f488 feat(bedrock-runtime): stream ConverseStream incrementally (#3043)
ConverseStream previously buffered the whole proxied response, translated it in
one shot, and returned it as a single byte[]. Both backends now write frames
through a JAX-RS StreamingOutput as they're known, and the proxy backend reads
the upstream SSE response via HttpResponse.BodyHandlers.ofLines() instead of
ofString() - text deltas reach SDK clients as the model generates them instead
of landing all at once when the response finishes.

Once the StreamingOutput starts writing, JAX-RS has already committed the 200
response, so a failure discovered only after streaming begins - a stream that
never reaches a finish_reason or "[DONE]" (upstream connection dropped
mid-generation) - can no longer become an HTTP error status. It's now reported
as a modelStreamErrorException event, the same wire shape (:message-type:
exception, :exception-type: <name>) and modeled exception real Bedrock uses
for a mid-stream failure, verified to decode correctly through
BedrockRuntimeAsyncClient's generated ConverseStreamResponseHandler. A stream
that completes normally (finish_reason or "[DONE]" seen) with no content is
now treated as a legitimate empty completion rather than an error, matching
real Bedrock.

Added a compatibility-tests/sdk-test-java case exercising
BedrockRuntimeAsyncClient.converseStream end to end, proving the emitted
event-stream frames decode correctly through the real AWS SDK rather than
only Floci's own byte-level assertions.
2026-09-05 15:17:39 -04:00
Mihai BlidaruandMihai Blidaru 724be0a6a7 fix(s3): return composite multipart checksums and match S3 on UploadPart, GetObjectAttributes and CopyObject responses (#3093)
* fix(s3): return composite checksums for multipart uploads

CompleteMultipartUpload stored the checksum of the whole object but labelled
it COMPOSITE, so clients that recompute the composite value from the part
checksums, as the AWS documentation describes, never matched it.

Follow the AWS checksum type rules, verified against real S3:

- SHA1/SHA256 are always COMPOSITE, CRC32/CRC32C default to COMPOSITE and
  CRC64NVME is always FULL_OBJECT. x-amz-checksum-type on CreateMultipartUpload
  selects FULL_OBJECT for CRC32/CRC32C; incompatible combinations fail with
  InvalidRequest, and the response echoes x-amz-checksum-algorithm/-type.
- The composite value is the algorithm applied to the concatenated binary part
  checksums, Base64 encoded, with a "-<part count>" suffix. It is returned by
  CompleteMultipartUpload, HeadObject and GetObject (with x-amz-checksum-type),
  while GetObjectAttributes omits the suffix, as AWS does.
- A checksum sent on CompleteMultipartUpload is validated against the stored
  type: a mismatching value is a BadDigest (the composite is accepted with or
  without its suffix), a checksum type different from the one the upload was
  created with is an InvalidRequest, per-part checksums in the request body
  that do not match the uploaded parts are an InvalidPart, and a COMPOSITE
  upload completed without the checksum of every part is an InvalidRequest
  (FULL_OBJECT uploads need none, as on S3). A non-numeric
  PartNumber is a MalformedXML instead of a 500.
- UploadPart echoes the part checksum (x-amz-checksum-<algorithm>) when the
  upload declared an algorithm, as S3 does; without one no header is returned.
- CopyObject writes a single object without a part manifest; a composite source
  gets a full-object checksum recomputed with its algorithm, and CopyObjectResult
  carries the checksum elements, matching AWS.
- GetObjectAttributes lists part-level checksums only for COMPOSITE objects: a
  FULL_OBJECT multipart object reports its PartsCount alone and a single-part
  object has no ObjectParts element.

The algorithm and type rules live in two new enums, ChecksumAlgorithm and
ChecksumType, parsed once from the request headers; S3Checksum builds the
full-object, composite and GetObjectAttributes views of a checksum.

The boto3 compatibility suite gains multipart upload_file cases for SHA256 and
for the SDK's default CRC32, asserting the composite value and the part list.

The S3 docs drop the stale note that checksum responses focus on SHA-1 and
SHA-256 (CRC32, CRC32C and CRC64NVME have been supported since #877) and list
the AWS algorithms Floci rejects.

* fix(s3): return the GetObjectAttributes ETag without quotes

S3 returns the ETag element of GetObjectAttributes without the surrounding
quotes that HeadObject, ListParts and CompleteMultipartUpload keep. Verified
against real S3 with the same object: head_object gives "af3c...-3" while
get_object_attributes gives af3c...-3, and the AWS CLI reference shows the same
in its get-object-attributes example. Floci echoed the quoted value, so a client
comparing both saw different strings on Floci and equal ones nowhere.

* fix(s3): give a copied object its own ETag

CopyObject kept the ETag of the source, so the copy of a multipart object
carried the "<md5-of-md5s>-N" value of its parts. S3 writes a copy as a single
object and returns the MD5 of the whole content as its ETag, in CopyObjectResult
and HeadObject alike (verified against real S3: source "af3c...-3", copy
"a5f04f..."). The copy now keeps the ETag storeObject computes.

* fix(s3): send CopyObjectResult as application/xml

The CopyObject response carried Content-Type: text/plain;charset=UTF-8 for an
XML body. S3 labels it application/xml like every other XML response.

* test(s3): cover multipart checksums in every SDK compatibility suite

Each SDK implements flexible checksums differently, so the multipart flows are
exercised per client rather than once: the Go transfer manager (what
terraform-provider-aws uses), @aws-sdk/lib-storage for Node, the Java SDK v2 both
low-level and through S3TransferManager on the multipart-enabled async client, the
AWS CLI (s3api, aws s3 cp --checksum-algorithm and a plain aws s3 cp that goes
multipart on its own) and boto3. Every case asserts the composite or full-object value computed in the
test itself, the UploadPart echo, the suffix-less GetObjectAttributes checksum
and unquoted ETag, the rejected Complete without part checksums, and the copy
of a multipart object as a single full object with its own ETag. The default
algorithm cases accept whatever the SDK version declares (CRC32 composite or
full object, or none) and check the stored value against it.

* test(terraform): upload a large aws_s3_object with Terraform and OpenTofu

The IaC suites created buckets but never an object, so the code path that
surfaced the composite checksum bug, an aws_s3_object above the provider's part
size uploaded through the SDK transfer manager, was not covered. Both suites now
upload a 12 MiB file generated by the test setup with checksum_algorithm SHA256
and check that HeadObject reports a COMPOSITE checksum equal to the composite
computed locally over the part sizes GetObjectAttributes lists, that the state
attribute holds the same value, and that re-planning the object shows no drift.

compat-opentofu moves to the same aws-cli image as compat-terraform (2.34.32):
2.15 predates the S3 checksum type and cannot show ChecksumType in its output.

* fix(s3): reject x-amz-checksum-type without a checksum algorithm

CreateMultipartUpload only parsed x-amz-checksum-type when an algorithm was
declared, so a type sent on its own, valid or not, was silently ignored. S3
validates the header regardless: an unknown value is InvalidRequest "Value for
x-amz-checksum-type header is invalid." and a valid one without an algorithm is
InvalidRequest "The x-amz-checksum-type header can only be used with the
x-amz-checksum-algorithm header." (both verified against real S3).

* test(s3): log cleanup failures in the multipart checksum compat tests

The Java, Node and Go cases swallowed errors while deleting their objects and
bucket. They now report what could not be deleted and why, so a leftover is
diagnosable instead of silent.

---------

Co-authored-by: Mihai Blidaru <mihai.blidaru@lynxfctech.com>
2026-09-05 15:12:13 -04:00
Mario Toffia ebdf092cce feat(iot): firehose and cloudwatchLogs rule actions (#3013)
* feat(iot): firehose and cloudwatchLogs rule actions

A topic rule can now deliver to a Kinesis Data Firehose delivery stream
(separator appended to each record, batchMode splitting a JSON array
into one record per element) and to CloudWatch Logs (one log event per
publish, or per array element with batchMode, in a stream named after
the rule that is created in the log group on first use).

* fix(iot): take timestamp and message from each batched cloudwatchLogs element and check the firehose separator

With batchMode the cloudwatchLogs action wrote every array element as one
log event whose message was the element's JSON text and whose timestamp was
the publish time. AWS requires a batched payload to be an array of
{"timestamp": <epoch ms>, "message": "<text>"} objects and takes both from
each element. The action now does the same; an element without a numeric
timestamp is stamped with the publish time and one without a message is
logged as its JSON text, so a batch that ignores the format still lands.

CreateTopicRule and ReplaceTopicRule reject a firehose separator that is
not a newline, tab, Windows newline or comma, the FirehoseSeparator pattern
of the IoT API model, with InvalidRequestException.
2026-09-05 14:02:24 -05:00
Matheus Oliveira 37faaa8abe feat(kms): support ImportKeyMaterial for Origin=EXTERNAL keys (#3068)
CreateKey accepts Origin=EXTERNAL, GetParametersForImport issues a real RSA
wrapping key, and ImportKeyMaterial unwraps and installs the material.
Expiry and DeleteImportedKeyMaterial return the key to PendingImport.

Fixes #1916

Signed-off-by: Matheus Oliveira <matheus.6148@gmail.com>
2026-09-05 14:00:44 -04:00
Franklin G. Mendoza 532e27986e feat(servicequotas): add quota request history lookup (#3054)
* feat(servicequotas): add quota request history lookup

* fix(servicequotas): validate history tokens and quota scope
2026-09-05 13:52:22 -04:00
Ben YounesandBen Younes a006b27694 fix: honor Kinesis ExplicitHashKey routing (#3069)
* fix: honor kinesis explicit hash keys

* fix(kinesis): reject numeric ExplicitHashKey and migrate legacy shard ranges (#3069)

Address the two review findings on explicit-hash-key routing:

- Reject a non-string ExplicitHashKey JSON node with SerializationException
  in PutRecord and PutRecords, instead of letting asText coerce a JSON number
  into an accepted decimal string, preserving AWS wire-protocol fidelity.
- Repartition legacy multi-shard streams whose open shards still carry the old
  full-span hash range into disjoint contiguous ranges before explicit-hash
  routing, so an explicit key no longer collapses onto the first shard after an
  upgrade. Already-disjoint (new/split/merged) streams are left untouched.

RED -> GREEN: 3 new tests failed on the prior HEAD
(putRecordRejectsNumericExplicitHashKey, putRecordsRejectNumericExplicitHashKey,
putRecordMigratesLegacyOverlappingShardRangesForExplicitHashKey), all green
after the fix. Kinesis suite: 118 run, 0 failures.

---------

Co-authored-by: Ben Younes <2910651+ousamabenyounes@users.noreply.github.com>
2026-09-05 12:35:06 -04:00
Franklin G. Mendoza b6489ac933 feat(guardduty): add member account operations (#3052)
* feat(guardduty): add member account operations

* fix(guardduty): align member creation semantics
2026-09-05 12:29:30 -04:00
Vũ Thế Huy 0ab9979edf fix(athena): register every Glue database as a DuckDB schema so <db>.<table> resolves (#2993)
* feat(athena): extract GlueViewDdlBuilder with schema qualification and aliases

* feat(athena): wire GlueViewDdlBuilder into AthenaService

* docs(athena): document Glue database schema registration and aliases

* fix(athena): propagate getDatabases failure and harden DDL table quoting

* fix(athena): skip Glue tables with nonexistent S3 bucket and cleanup AthenaTest

* fix(athena): avoid redundant table fetch and add qualified query compatibility test

* fix(athena): do not skip views for tables with nonexistent S3 bucket
2026-09-05 11:19:46 -04:00
Vũ Thế Huy 4daba7ed6a feat(redshift): wire the Simple Query DDL interceptor into the proxy (#3029)
* feat(redshift): add PostgresWireDecoder for frontend wire-message framing

* feat(redshift): intercept Simple Query DDL through RedshiftInterceptingBridge

* test(redshift): end-to-end DDL rewrite over the Simple Query protocol

* docs(redshift): document the Simple Query DDL interceptor

* fix(redshift): remove em-dashes and address review feedback on bridge

* fix(redshift): stream opaque non-query frames without size limit

* fix(redshift): stream oversized simple query frames to passthrough

* test(redshift): import stream types in RedshiftInterceptingBridgeTest

* test(rdsdata): fallback to direct H2 driver on classloader mismatch

* test(redshift): remove oversized socket test from RedshiftInterceptingBridgeTest
2026-09-05 10:36:34 -04:00
Guilherme Scaranse 5512db0e05 fix(lambda): persist, validate and enforce event source mapping FilterCriteria (#3060)
* fix(lambda): persist and validate event source mapping FilterCriteria

CreateEventSourceMapping/UpdateEventSourceMapping accepted FilterCriteria,
returned 200, then silently dropped it (get-event-source-mapping reported
null): EventSourceMapping had no such field and the hand-maintained
parse/response allowlists never mentioned it.

Persist it as a typed nested FilterCriteria/Filter on EventSourceMapping
(Jackson round-trips it via EsmStore); parse and validate it at create and
update (well-formed JSON object patterns whose values are non-empty match
arrays or nested objects; max 5 filters; max 4096-char pattern; empty
object / empty Filters / null clear); echo it back omit-when-unset. Add
EsmFilterCriteriaUtils to wrap a stored FilterCriteria as the
{"FilterCriteria":{"Filters":[...]}} node PipesFilterMatcher consumes and
to correlate matched records to their sources by identity.

Poller enforcement (Kinesis/DynamoDB/SQS) follows in a separate change.

* fix(lambda): enforce event source mapping FilterCriteria in the pollers

Round 1 persisted and validated FilterCriteria; this wires it into the three
Lambda event-source pollers so filters actually take effect, reusing the
existing PipesFilterMatcher (unchanged) via EsmFilterCriteriaUtils.

- Kinesis: filter against the AWS dialect, top-level base64-DECODED `data`
  (plus `partitionKey`), while the delivered event keeps `kinesis.data`
  base64. The shard checkpoint now advances to the newest FETCHED sequence
  whenever a batch is disposed of (successful invoke OR fully filtered out),
  so filtered-out records are consumed rather than re-read forever; an invoke
  that errors or is throttled still leaves the checkpoint unmoved.
- DynamoDB Streams: same checkpoint discipline; the per-record node
  (top-level eventName + dynamodb.*) is both the delivery and filter shape.
- SQS: non-matching messages are deleted immediately (AWS consumes filtered
  SQS messages), a fully-filtered batch returns without invoking, and all
  post-filter delete/return logic operates only on the matched subset.

Unfiltered mappings are unchanged (no filter nodes built, same list reference).
Adds KinesisEventSourcePollerTest and extends the DynamoDB/SQS poller tests
(matching-only delivery, fully-filtered checkpoint-advance/delete, invoke-error
and throttle no-advance with same-window retry, dialect pin, non-JSON drop).

Also documents FilterCriteria in docs/services/lambda.md.

* style(lambda): remove em dashes from lines this branch adds

AGENTS.md requires colons, commas or periods instead of em dashes. Comment,
javadoc and docs prose only; no code or string literals change.

* fix(lambda): validate filter-pattern operators, arity and operand types

The structural check accepted any non-empty match array, so a malformed operator
reached the matcher and corrupted delivery silently, in whichever direction the
matcher happened to fail. {"numeric":[">","abc"]} coerced its operand to zero and
matched every positive value; {"numeric":[">"]} matched every record because the
comparison loop never ran; an unknown operator matched nothing, so the pollers
checkpointed past or deleted every record. Enforcement makes an unsatisfiable
pattern destructive rather than inert, so it is now rejected at create/update.

Each match element must be a string, number, null, or an object carrying exactly
one operator. Operands are checked per operator, and numeric must be a sequence
of comparison/value pairs. An operator AWS documents but the matcher does not
implement (cidr, wildcard) is rejected with a distinct message rather than
silently dropping records. This couples the validator to PipesFilterMatcher's
operator set, which the previous comment avoided on purpose; that trade no longer
holds now the pollers act on the result.

Stricter than AWS for cidr, wildcard and boolean literals, all of which AWS
accepts. Docs record the deviation and the reason.
2026-09-05 10:32:42 -04:00
Vũ Thế Huy 6653b9a4e4 feat(iam): support DynamoDB fine-grained access control (#2926) (#3011)
* refactor(iam): make the policy condition context multi-valued

Condition keys such as dynamodb:LeadingKeys and dynamodb:Attributes are set-typed by definition, but the evaluator carried the request context as Map<String,String> from the filter all the way into the condition block, so a set could not be represented at all.

Change the type to Map<String,List<String>> across evaluate, simulateCustomPolicy, simulatePrincipalPolicy and the condition helpers, and update the three in-tree call sites. Non-set operators keep today's semantics by comparing only the first value, which is behaviour-preserving for every key that is single-valued today. normalizeConditionContext now preserves an empty list, which the set operators need to distinguish an empty set from an absent key.

* feat(iam): support ForAllValues and ForAnyValue set operators

ForAllValues: and ForAnyValue: appeared nowhere in the IAM package, so
evaluateConditionBlock stripped only an IfExists suffix and the whole
prefixed string reached the operator switch as an unknown operator, which
yields false. Every policy scoping DynamoDB access through
ForAllValues:StringLike therefore denied the requests it was written to allow.

Parse the quantifier prefix ahead of the IfExists strip so
ForAnyValue:StringEqualsIfExists composes, and evaluate the quantifier over
the request's value list, reusing evaluateSingleCondition for each member so
every existing operator works under a quantifier with no new operator code.
Empty-set semantics follow AWS: ForAllValues matches vacuously, ForAnyValue
does not. An absent key still fails closed without IfExists.

* fix(iam): read every SimulatePrincipalPolicy context key value

extractContextEntries read only ContextKeyValues.member.1 and dropped the
rest, which was invisible while the condition context was single-valued but
silently breaks set operators: a ForAnyValue: condition satisfied by the
second supplied value evaluated as implicitDeny. Reuse extractIndexedValues
to collect the whole member list per context entry.

* feat(dynamodb): add a KeyConditionExpression partition-key value reader

IAM condition-key extraction needs the value a Query pins its partition key
to, which today only DynamoDbAccessPathValidator can compute and only as a
side effect of validation. Add a narrow package-internal reader over the
existing ExpressionEvaluator instead of widening the validator's visibility.
Anything it cannot resolve returns null, which the policy layer treats as an
unknown leading key and fails closed on.

* feat(dynamodb): extract LeadingKeys, Attributes and Select from a request

Add a static extractor covering GetItem, PutItem, UpdateItem, DeleteItem,
Query, BatchGetItem and BatchWriteItem. Partition-key values come from Key,
Item, the Query KeyConditionExpression or the per-table RequestItems entries;
attribute names come from Key/Item fields, AttributesToGet,
ProjectionExpression, UpdateExpression targets and ExpressionAttributeNames.

Whatever cannot be determined is absent rather than guessed, so an
unresolvable leading key yields an empty list and the policy layer fails
closed on it.

* feat(iam): populate the DynamoDB condition keys from the request

IamConditionContextResolver supplied s3:* keys only and returned null for every other service, so dynamodb:LeadingKeys, dynamodb:Attributes and dynamodb:Select were never in the request context and no DynamoDB fine-grained policy could match. Add a dynamodb branch that reads the body already buffered by ResourceArnBuilder, resolves the table's key schema through a lazily injected DynamoDbService, and emits the three keys.

A key that cannot be resolved is omitted rather than guessed, so a policy scoping access through it denies the request.

* test(iam): cover the DynamoDB LeadingKeys scenario end to end

Add the issue #2926 acceptance criteria at evaluator level, plus an HTTP test
with enforcement enabled where one scoped session reads USER_alice and is
denied USER_bob against the same table, and a request whose Key omits the
partition attribute is denied because its leading key cannot be proven.

* docs(iam): document the set operators and the DynamoDB condition keys

Record ForAllValues:/ForAnyValue: with their empty-set semantics, the three dynamodb:* condition keys and the actions they cover, and the fail-closed consequence for a request whose leading key cannot be determined.

* fix(iam): correct negated-operator, empty-set and locale handling in conditions

Three fail-open gaps in the condition evaluator, all more reachable now that the
set operators make multi-valued and negated conditions common:

- A negated operator (StringNotEquals, ArnNotLike, NotIpAddress, ...) against a
  condition that lists several values was ORed across them, so the value matched
  as long as it differed from any one entry. AWS ANDs the negated match across
  the list; a ForAllValues:StringNotEquals deny-list on dynamodb:Attributes now
  actually denies.
- Null treated a present-but-empty set as present, so the Null:{key:"false"}
  guard that policies pair with ForAllValues did not block the vacuous empty-set
  allow. An empty set now counts as absent for Null, matching AWS.
- The per-key lower-casing used the default locale while the context map is
  normalised with Locale.ROOT, so under a Turkish locale a key would never match
  its own Deny statement. Both sides now use Locale.ROOT.

* perf(iam): resolve the table key schema without the item-count scan

IamConditionContextResolver called DynamoDbService.describeTable on every
enforced DynamoDB request, and describeTable refreshes the table's item count
by calling size() on a ConcurrentSkipListMap ??? an O(items) traversal ??? before
the request is even authorized. The resolver only needs the HASH key name.

Add DynamoDbService.findTable, which returns the stored definition without the
count refresh, and switch the resolver to it. findTable returns Optional and
never throws, so the surrounding try/catch, its Logger and the now-unused
injected ObjectMapper go away.

* feat(dynamodb): widen condition attribute extraction and support legacy KeyConditions

dynamodb:Attributes under-reported: it collected item/key fields, AttributesToGet,
the projection and update expressions and ExpressionAttributeNames, but never the
names a FilterExpression, ConditionExpression or KeyConditionExpression references.
A Query projecting only allowed attributes while filtering on a forbidden one would
slip past a ForAllValues:StringEquals on dynamodb:Attributes. Walk the parsed
expression tree so literal names, not only #aliases, are captured.

A Query using the legacy KeyConditions map instead of KeyConditionExpression
produced no dynamodb:LeadingKeys at all. Read the EQ entry for the partition key
from that map as a fallback, and take attribute names from KeyConditions and
QueryFilter.

Also pins DynamoDbKeyConditionParser on begins_with (never an equality) and a
top-level OR (not constrained to one partition), both of which must yield null.

* docs(iam): note negated-operator, empty-set and widened Attributes semantics

Record that a negated condition operator ANDs across multiple policy values
(making ForAllValues:StringNotEquals a usable deny-list), that Null treats a
present-but-empty set as absent, and that dynamodb:Attributes now also reflects
filter / condition / key-condition expression names and the legacy KeyConditions
EQ entry.

* fix(dynamodb): replace em-dash with colon in DynamoDbConditionKeys

* fix(dynamodb): resolve GSI partition keys and capture UpdateExpression read attributes

* docs(dynamodb): clarify fail-closed Javadoc applies to LeadingKeys not Attributes
2026-09-05 10:19:17 -04:00
Mario Toffia d771783afb feat(cognito): check the custom domain certificate in ACM and mark it in use (#3035)
* feat(cognito): require an issued ACM certificate for a custom domain and track it as in use

CreateUserPoolDomain and UpdateUserPoolDomain stored any CertificateArn
as given. The certificate must now exist in ACM, in us-east-1, with
status ISSUED, as AWS requires; anything else is rejected with AWS's
InvalidParameterException message.

While a domain uses a certificate, ACM lists the domain's CloudFront
distribution under InUseBy and DeleteCertificate refuses with
ResourceInUseException. Deleting the domain, or moving it to another
certificate, releases the old one. AcmService gains addInUseBy and
removeInUseBy for this; the refusal on delete already existed.

DeleteStack deleted resources in reverse insertion order, so a
certificate added by a later update was deleted before the domain that
still used it and the stack ended in DELETE_FAILED. Resources are now
deleted in reverse dependency order from the stack's template, as on
AWS, with insertion order as the fallback when the template cannot be
read.

* feat(cognito): register the certificate before storing the domain and require a certificate ARN

Review follow-ups:

- The domain was stored before it was registered on its certificate,
  so a certificate deleted between the check and the registration left
  a stored domain that ACM did not protect. Registration now comes
  first on create, and a changed certificate is checked and registered
  before an update touches the domain; the old certificate is released
  after the store. A certificate that disappears in that window fails
  with the same InvalidParameterException as a missing one.
- The ARN check accepted any ACM resource. It now also requires the
  resource to be certificate/<id>, before ACM is asked.
2026-09-05 10:06:53 -04:00