Commit Graph
1263 Commits
Author SHA1 Message Date
Priamo Germosen aaae99282f feat(kinesisanalytics): emit MSF-style JSON CloudWatch logs from Flink (#2656)
* feat(kinesisanalytics): emit MSF-style JSON CloudWatch logs from Flink

The JobManager/TaskManager now start with a log4j-console.properties
that formats every log line as a single JSON object matching real
Managed Service for Apache Flink's CloudWatch Logs schema
(applicationARN, applicationVersionId, locationInformation, logger,
message, messageSchemaVersion, messageType, threadName,
throwableInformation), instead of the stock image's default plain-text
pattern. Applies to Flink's own framework logs and anything a deployed
JAR logs through SLF4J/Log4j2, so a JAR that expects its logs to reach
CloudWatch (or asserts on this schema) sees the same thing here as on
real MSF.

Written into the container before the JVM starts -- log4j2 reads its
config at process boot, so copying the file in after start (the way
application_properties.json already is) would be too late. Required
splitting the JobManager/TaskManager container startup from
createAndStart into create + copyFileIntoContainer + startCreated,
mirroring the create-then-inject-then-start pattern
ContainerLifecycleManager already exposed for exactly this purpose.

* fix(kinesisanalytics): escape log4j2 pattern injection and fail loudly on log4j copy failure

ApplicationName flows unvalidated into the ARN baked into the JSON log
pattern, so a name containing '%' could be interpreted as a log4j2
conversion specifier and a '"' or '\' could break the emitted JSON.
Escape both before embedding, reusing the existing %enc{}{JSON}
wrapper to JSON-encode the value at log time.

Also stop silently swallowing a failed log4j-console.properties copy:
startCluster previously reported success and ran with the stock
(non-JSON) log format if the copy failed. The copy is now required,
so a failure rolls back the cluster the same way a create() failure
already does.

* fix(kinesisanalytics): validate ApplicationName, fix NPE, and block log4j2 Lookup injection

CI failure: startClusterLabelsJobManagerContainerWithResourceIdentity
built a FlinkApplication with no ARN set, and literalForLog4j2Pattern
NPE'd on the null value. Wrap both baked-in values with
String.valueOf() so a null degrades to the literal text "null"
instead of throwing.

Also validate ApplicationName against AWS's real CreateApplication
constraint (Pattern: [a-zA-Z0-9_.-]+, 1-128 chars) instead of only
requiring it non-blank -- this is both a genuine AWS-parity fix and
what keeps '%', '"', '\', or '$' out of the generated log4j2 pattern
in the first place.

Finally, close a gap the previous escaping missed: '$' wasn't
neutralized, so a name containing a log4j2 Lookup ('${env:...}',
'${sys:...}') would have it resolved against the process environment
at config-load time and baked into every emitted log line. Doubling
'$' the way '%' is doubled only defers the lookup to render time
rather than neutralizing it, so literalForLog4j2Pattern now drops '$'
outright.

* fix(kinesisanalytics): reject legacy invalid ApplicationName at StartApplication too

Greptile follow-up: an application persisted before the
ApplicationName validation existed (e.g. one with '$' in its name)
would bypass CreateApplication's new check entirely, and
StartApplication would silently generate a CloudWatch-log
applicationARN with the '$' dropped -- mismatching the real
ApplicationARN.

I verified empirically (a standalone harness against the actual
log4j-core jar) that there's no safe way to preserve '$' here: doubling
it or backslash-escaping it both still let log4j2 resolve the Lookup
and leak the referenced environment variable, so dropping it was the
only safe option. Given that, StartApplication now re-validates the
name and fails loudly for such legacy state instead of quietly
emitting a mismatched ARN -- real AWS could never have had this state
to begin with, so refusing to start it is the more AWS-faithful
outcome anyway.

* fix(kinesisanalytics): fix test compile error from Mockito generic inference

when(storageFactory.create(...)).thenReturn(store) failed to compile:
create()'s type parameter defaults to Object with no target-type
context to unify against the pre-declared, concretely-typed 'store'
variable, so thenReturn(store) rejected it as a type mismatch.
Switch to doReturn(store).when(storageFactory).create(...), matching
the same pattern already used for this exact scenario elsewhere in
this file (readinessPollerPersistsFlinkJobIdAssignedBeforeReachingRunning).
2026-08-29 09:15:52 -05:00
Facundo ParedesandFacundo Paredes ff61c2b2a5 feat(stepfunctions): describe a distributed Map run after it finishes (#2694)
* feat(stepfunctions): describe a distributed Map run after it finishes

DescribeMapRun was not implemented, and arn:aws:states:::aws-sdk:sfn:describeMapRun
reached the end of the dispatch chain in invokeResource, so a distributed Map could
not be inspected once it was over: the Map run ARN was minted from a fresh UUID,
written into the S3 manifest, returned in the Map result and then dropped.

A run is now retained where the ResultWriter mints that ARN, which is also the only
place an ASL author reads it. The manifest is no shortcut to the counters, since it
writes FAILED and PENDING as empty arrays and puts every item under SUCCEEDED, so
the run carries the item count taken where the iterations complete.

A Map fails on the first item that fails, so a retained run is one whose every item
succeeded. That fixes the status, both tolerances and the redrive counters at the
values us-east-1 reports for such a run, and leaves succeeded, total and
resultsWritten as the item count. An unbounded Map, which ASL spells as MaxConcurrency
0 or by omitting it, is reported as Integer.MAX_VALUE.

The Task integration recases the wire response rather than restating it, so the two
renderings of a run cannot drift, and renders both dates as the SDK's ISO-8601.

Closes #2671

* refactor(stepfunctions): close a Map run's window on the export that mints its ARN

recordMapRun sampled the wall clock and then folded the child timings into both
ends of the run's window, but the clock is read after MapIterationScheduler has
joined every child and after applyResultWriter has exported, so it is at or past
every child's stop. Math.max over the timings could therefore never move stop off
that sample, and the javadoc promised a last-item stop the code never computed.

The sampled value is the faithful one: AWS closes a Map run's window on the export
rather than on the last item, and the sample is taken immediately after it. Only
start is recovered from the timings, which is the one end the Map state records
nowhere else. DescribeMapRun returns the same startDate and stopDate as before.

* test(compatibility): cover DescribeMapRun through the AWS SFN SDK client

StepFunctionsDescribeMapRunIntegrationTest only exercises the endpoint via
RestAssured, leaving the SDK's own request serialization, endpoint routing
and response deserialization untested, contrary to AGENTS.md's rule that
management APIs be validated with AWS SDK clients.

---------

Co-authored-by: Facundo Paredes <25681464+facuparedes@users.noreply.github.com>
2026-08-29 00:05:50 -04:00
Luis Ruiz PavónandPriamo 9b3aee6a03 fix(eventbridge): AWS-conformant InputTransformer from CloudFormation and PutTargets (#1885)
* refactor(eventbridge): parse InputTransformer via shared InputTransformer.fromJson

* fix(eventbridge): substitute InputTransformer placeholders with AWS-conformant JSON representation

* feat(cloudformation): carry AWS::Events::Rule target InputTransformer into the rule

* test(eventbridge): verify native PutTargets InputTransformer delivers transformed body to SQS

* chore(eventbridge): log swallowed escape failure and use idiomatic indexOf guard in transformer engine

---------

Co-authored-by: Priamo <pgermosen@gmail.com>
2026-08-28 23:39:36 -04:00
Facundo ParedesandFacundo Paredes ea11e67719 fix(stepfunctions): fail the state when a JSONata expression returns nothing (#2689)
* fix(stepfunctions): fail the state when a JSONata expression returns nothing

An expression that returned nothing lost its key and the execution carried on
down the happy path. Real AWS fails the state with States.QueryEvaluationError,
names the field the expression was written in and a Catch on that error fires.
Three of the positions changed control flow rather than data: a Choice took
Default, a Wait did not wait, and a Task sent its request with the argument
omitted.

evaluateField evaluates one expression and fails the state on a missing node.
resolveTemplate calls it at every leaf, carrying the field it is inside and
extending it with /key per object key and [i] per array index, so the cause
names Output/a/b[0][1] the way AWS does. Choices[n]/Condition, Seconds, Error,
Cause, MaxConcurrency and Items call it directly.

Three pieces go with it, all of them things a missing node used to need. An
undefined array element was a States.Runtime special case with its own wording;
AWS answers States.QueryEvaluationError and Output/values[0], the same shape as
every other position. resolveTemplateNode existed to let resolveTemplate turn a
whole field that returned nothing into a null, so the output would still
serialize; there is no output to serialize once the state fails. And the two
ResultWriter guards fired only on a key resolveTemplate had dropped, which can
no longer happen.

An explicit JSON null is a value and still succeeds, everywhere.

Closes #2665

* fix(stepfunctions): name a Choice rule's and a Catch clause's own fields under their index

A matched Choices[i] rule and a matching Catch[i] clause carry their own Assign and
Output, and applyJsonataAssignAndOutput named them 'Output' and 'Assign' as if they
were the state's. AWS names them under the rule or the clause: Choices[1]/Output/v,
Choices[0]/Assign/x and Catch[1]/Output/v, each measured on the account. The index is
the position in Choices or Catch, not the position among the entries that matched.

The Catch label was unobservable until now. doExecute calls handleCatch from inside
its own catch (FailStateException), so an expression failure raised while resolving
the clause's own Output escaped both that clause and its sibling catch (Exception),
reaching the method-level handler that answers States.Runtime with the raw message.
The execution now fails with the clause's own error, which is what AWS reports and
what the clause was catching no longer is.

* test(stepfunctions): follow the field path through the crashing evaluator stub

* test(stepfunctions): put the Catch clause under test on a Task, as AWS requires

aCatchClauseNamesItsOwnOutputUnderTheClauseIndex carried Catch on a Pass state,
which AWS refuses: validate-state-machine-definition answers SCHEMA_VALIDATION_FAILED,
"Field 'Catch' is not supported" at /States/Boom. The label the test pins is right,
Catch[1]/Output/v, and the state now fails on its own Arguments the way the measured
execution did, so the definition is one AWS accepts.

* docs(stepfunctions): drop the deviation this change removes

The key dropped by an expression that returned nothing is no longer Floci's
own behaviour: the state fails, as the section below records.

---------

Co-authored-by: Facundo Paredes <25681464+facuparedes@users.noreply.github.com>
2026-08-28 23:34:46 -04:00
Facundo ParedesandFacundo Paredes 5534460492 fix(stepfunctions)!: reject JSONata top-level references at definition time (#2699)
* fix(stepfunctions)!: reject JSONata top-level references at definition time

A Step Functions JSONata expression is evaluated with no context item: the
execution input arrives as $states.input and an Assign variable as $name. A
path whose first step is a bare name reads a context item that does not exist,
and real AWS refuses the definition from CreateStateMachine,
UpdateStateMachine and ValidateStateMachineDefinition with
UNSUPPORTED_JSONATA_EXPRESSION: Reference to '<name>' at the top level is not
supported. Floci accepted those definitions and failed the execution instead.

Every JSONata string in a JSONata state is now walked before the state machine
is stored, and each distinct top-level name is reported with the message and
the /States/... location AWS prints. Only the first step of a path is read
against the top-level context, so later steps, predicates, sort terms and
group expressions stay legal; a lambda body keeps the defining context and is
walked. Syntax errors and $$ keep their current behaviour.

The parse tree of com.dashjoin:jsonata is package-private and Quarkus loads
application classes and dependency jars under different class loaders, so the
tree fields are read reflectively, resolved once at class initialization and
registered for native image.

BREAKING CHANGE: state machines whose JSONata expressions reference a bare
top-level name are now rejected at creation, as on AWS. Anchor the reference
with $states.input.<name> for input or $<name> for an Assign variable.

* fix(stepfunctions): parse a JSONata payload key named after an ASL field

The deny list of fields AWS does not parse as JSONata was applied to every
key at every depth, so a payload key named Next, Comment, Resource, Retry,
Default, ErrorEquals, Credentials, Branches, ItemProcessor or Iterator hid
its expression. AWS parses a payload whole: `Assign: {"Next": "{% phone %}"}`
and `Arguments: {"Payload": {"Comment": "{% phone %}"}}` are both refused
with `Reference to 'phone' at the top level is not supported.` The deny list
now stops applying once the walk enters Output, Assign, Arguments,
ItemSelector or BatchInput.

The same walk refused `ItemReader.ReaderConfig.CSVHeaders`, which holds
literal column names: `validate-state-machine-definition` returns OK for it
and `create-state-machine` stores the machine, so CSVHeaders joins the list.

---------

Co-authored-by: Facundo Paredes <25681464+facuparedes@users.noreply.github.com>
2026-08-28 22:50:04 -04:00
Matan Baruch 0090739617 fix(rds): clear CLIENT_SSL before forwarding the TLS-terminated handshake response to the backend (#2698)
Real MySQL clients keep CLIENT_SSL set in the HandshakeResponse41 they send
over the encrypted stream after the SSLRequest. The proxy terminates TLS
itself and forwards that response to the plaintext backend verbatim, and a
MySQL server treats any first packet carrying CLIENT_SSL as an SSLRequest:
it waits for a TLS ClientHello that never comes while the proxy waits in
relayConnectionPhase for an auth verdict that never comes. Every TLS
connection through the proxy (mysql's default ssl-mode PREFERRED included)
hung until the client timed out; only --ssl-mode=DISABLED worked.

Clear the bit before the response reaches the backend, mirroring
forceClientSslCapability on the server handshake. The TLS tests now send
real-client-shaped responses (CLIENT_SSL set) and assert the backend never
sees the bit; the assertion fails without this fix.
2026-08-28 22:23:41 -04:00
14112b8ace feat(stepfunctions): dispatch the seven Task service integrations of #2663 (#2686)
* feat(sfn): support the aws-sdk:sfn:startSyncExecution task integration

Calling an Express child workflow from a Standard parent goes through
arn:aws:states:::aws-sdk:sfn:startSyncExecution, which reached the end of the
dispatch chain and failed with "Unsupported resource".

The integration reuses the existing StartSyncExecution service call and differs
from the optimized states:startExecution.sync integration in two observable
ways: the response envelope uses PascalCase field names with Output as a JSON
string, and a child execution that fails is reported through Status instead of
failing the calling task.

* feat(stepfunctions): dispatch the six remaining Task service integrations

events:putEvents, aws-sdk:sfn:startExecution, aws-sdk:sfn:sendTaskSuccess,
aws-sdk:sfn:sendTaskFailure, aws-sdk:scheduler:createSchedule and
aws-sdk:scheduler:updateSchedule reached the end of the dispatch chain in
invokeResource and failed with "Unsupported resource", although Floci already
serves all six APIs. Each branch maps the Task Arguments onto the client the
direct call already goes through: putEvents onto EventBridgeHandler, and the
scheduler pair onto the controller's own parse and SchedulerService.

Two conventions of the aws-sdk: integrations, measured against us-east-1 through
test-state, now hold for the whole family and correct the startSyncExecution
envelope with them. A timestamp is the SDK's ISO-8601 rendering rather than the
epoch seconds the wire response carries, and an error names the SDK exception
class, so it always ends in Exception.

SendTaskSuccess and SendTaskFailure report whether the token resolved a waiting
task, which is what lets the Task integration fail with Sfn.InvalidTokenException
instead of reporting a delivery that never happened. The direct API keeps
tolerating an unknown token.

Closes #2663

* fix(stepfunctions): make scheduler argument validation reachable for Retry and Catch

parseScheduleRequest raises the same AwsException the scheduler service raises,
so a Task whose Target.EventBridgeParameters is incomplete failed the execution
with States.Runtime and skipped the state's Catch. It now runs inside the same
translation as the service call and fails with Scheduler.ValidationException.

* fix(scheduler): answer a malformed EcsParameters list with ValidationException

A CapacityProviderStrategy, PlacementConstraints, PlacementStrategy or Tags list
holding anything but objects made ObjectMapper.convertValue raise
IllegalArgumentException, which CreateSchedule and UpdateSchedule answered with
a server error and the aws-sdk:scheduler Task integration turned into
States.Runtime. The conversion failure is now named per field and carries the
400 the rest of the parser's validations carry.

* fix(scheduler): answer a malformed awsvpcConfiguration list with ValidationException

Subnets and SecurityGroups went through a bare ObjectMapper.convertValue, so an
element that is not a string left the same unhandled IllegalArgumentException the
EcsParameters object lists left. They now read through a stringList sibling of
mapList and carry the parser's 400.

* test(stepfunctions): pass the scheduler and eventbridge dependencies to the executor under test

* fix(scheduler): refuse a scalar in an awsvpcConfiguration list instead of coercing it

* fix(scheduler): refuse a non-list EcsParameters field instead of dropping it

* test(stepfunctions): catch a malformed scheduler list as the SDK exception AWS sends

---------

Co-authored-by: Facundo Paredes <naranjax@MAC-69786.local>
Co-authored-by: Facundo Paredes <25681464+facuparedes@users.noreply.github.com>
2026-08-28 22:21:48 -04:00
Sam Fakhreddine a155e66b15 feat(codepipeline): validate ListPipelineExecutions filters and PutApprovalResult inputs (#2696)
* feat: tighten CodePipeline P0 operation contracts

* fix(codepipeline): reject malformed filters and stop stranding approvals on rename

- ListPipelineExecutions: reject non-string succeededInStage.stageName,
  unknown filter/succeededInStage members, and non-integer maxResults
  instead of silently coercing them.
- PutApprovalResult: reject non-string result.summary instead of
  coercing it, and split the "result is required" error from a
  clearer "result must be an object" error for wrong-typed payloads.
- PutApprovalResult: look up the pending approval by token across the
  execution's own captured stage/action names before consulting the
  pipeline's current declaration, so renaming or removing a stage or
  action via UpdatePipeline no longer strands an in-flight approval
  behind a StageNotFoundException/ActionNotFoundException.
- Replace fixed Thread.sleep(100) waits in
  CodePipelineIntegrationTest with polling helpers
  (waitForApprovalToken/waitForApprovalStatus) matching the existing
  waitForJob/waitForExecution pattern, removing test flakiness.
2026-08-28 22:11:07 -04:00
Facundo ParedesandFacundo Paredes 48e0ecd809 fix(stepfunctions): keep a JSONata expression's explicit null in the output (#2684)
* fix(stepfunctions): keep a JSONata expression's explicit null in the output

A JSONata expression evaluating to JSON null lost its key, exactly as an
expression that returned nothing did. Real AWS answers {"v":null} to
Output {"v":"{% null %}"} and keeps the null in a nested object, in an
array, in Assign and in a Task's Arguments.

dashjoin flattens JSONata's null marker into a Java null unless
outputConvertNulls is off, which made the two indistinguishable inside the
evaluator. With it off, $states and the workflow variables bind through
toJsonataValue so an input null stays a null the expression can see, the
result is walked back with the marker mapped to a JSON null and a Java null
mapped to a missing node, and resolveTemplate drops only the missing node.

Closes #2664

* fix(stepfunctions): resolve a whole JSONata field that returned nothing to a null

A MissingNode is how the evaluator says "this expression returned nothing", and
resolveTemplate handed it straight to the executor when the whole Output or
Arguments field was that one expression. exec.setOutput writes the state output
with toString(), and a MissingNode writes itself as the empty string, so
DescribeExecution answered "output": "" instead of JSON.

resolveTemplate is now the boundary and answers a JSON value: a whole field that
returned nothing is a null, which is what it was before the marker existed. The
recursion moves to the private resolveTemplateNode, where "returned nothing" is
still itself in the two positions that read it, an object field it drops and an
array element it fails the state on.

AWS fails such a state with States.QueryEvaluationError; that is #2665 and stays
open.

* test(stepfunctions): read $string() with no argument as nothing, not as null

* docs(stepfunctions): mark the key dropped by an expression that returned nothing as a deviation

---------

Co-authored-by: Facundo Paredes <25681464+facuparedes@users.noreply.github.com>
2026-08-28 22:07:21 -04:00
Facundo ParedesandFacundo Paredes 395401807b fix(stepfunctions): bound JSONata evaluation by time and depth (#2697)
JSONata evaluation ran unbounded. A recursive expression with no base case
pinned a core and left the execution RUNNING for ever: the library optimises
the tail call, so it loops rather than overflowing the stack and no Error ever
reaches the executor. Deep non-tail recursion did throw, but a StackOverflowError
the evaluator's catch cannot see.

Bound each expression with Frame#setRuntimeBounds, which the library has and
Floci never called. Either bound raises a JSONata error, so the existing catch
turns it into States.QueryEvaluationError, and the state fails through the same
path as any other evaluation error: catchable by Catch, retryable by Retry.

Five seconds and 500 levels sit deliberately above AWS. Measured with
test-state, AWS refuses a non-tail-recursive function at a nesting depth of 125
and accepts it at 95, and the widest sequence it accepts evaluates here in about
100 ms, so no expression AWS runs can reach either bound.

Closes #2667

Co-authored-by: Facundo Paredes <25681464+facuparedes@users.noreply.github.com>
2026-08-28 20:55:29 -04:00
Sam Fakhreddine ac94232910 feat(cloudformation): CodeBuild/CodePipeline CFN provisioning (#2685)
* feat(cloudformation): provision CodePipeline pipelines and actions

New CodePipelineCfnProvisioner handles AWS::CodePipeline::Pipeline,
AWS::CodePipeline::CustomActionType, and AWS::CodePipeline::Webhook by
lowering the PascalCase CloudFormation properties into the camelCase
CodePipeline API shapes and delegating to the service, so stacks and the
API produce identical pipelines.

Ref resolves to the pipeline name (generated CloudFormation-style when
Name is omitted), Fn::GetAtt Version and webhook Url are populated, an
existing physical ID routes updates through UpdatePipeline instead of
recreating, DisableInboundStageTransitions is applied after creation,
and deletes tolerate already-removed resources.

(cherry picked from commit 8007d0b7e872d573217309fccd756c66a2d339a4)

* fix(cloudformation): bundle cfn-response into inline ZipFile Lambdas

AWS injects the cfn-response (Node.js) and cfnresponse (Python) modules
into functions created through CloudFormation's inline ZipFile property,
and custom-resource handlers across AWS Solutions templates rely on
that — Landing Zone Accelerator's installer stack fails its very first
Custom::CreateUUID resource with 'Cannot find module cfn-response'
without it.

The bundled modules follow the documented AWS implementations but pick
the transport and port from the ResponseURL instead of hardcoding
https:443, because Floci's custom-resource callback URL is plain http
on the emulator's port.

(cherry picked from commit 7028f5a85daba6ba9d83032dc940cebe45c0b348)

* refactor(cloudformation): extract inline ZipFile packaging

CloudFormationResourceProvisioner is a monolith being dismantled, so the
cfn-response bundling added there moves to its own InlineZipPackager,
ready to travel with the eventual Lambda provisioner extraction. No
behavior change.

(cherry picked from commit d0d4bff84bda9c143606a8922500515dbe5bc0c0)

* fix(cloudformation): keep CodePipeline action config keys verbatim

Action and rule configuration maps carry provider-defined string keys
(Owner, Repo, ProjectName, ...) that executors match exactly; the
PascalCase-to-camelCase property transform was rewriting them, so
CloudFormation-created pipelines could never run their GitHub source or
CodeBuild actions. Configuration subtrees now pass through untouched.

(cherry picked from commit 213e33d9f005ee4df6a66272a91f47ac67a3b7a3)

* feat(cloudformation): provision CodeBuild projects

AWS::CodeBuild::Project was falling through to the stub path, so
CloudFormation-created pipelines referenced build projects that did not
exist — Landing Zone Accelerator's installer pipeline failed its
Install stage with 'Project not found'. The new provisioner lowers the
PascalCase properties into the CodeBuild API shape (including the
irregular all-lowercase buildspec field), supports update-in-place, and
exposes Ref as the project name and Fn::GetAtt Arn.

(cherry picked from commit 7d616b87c7fa58693537dfe7d9d86cd63437ea75)

* fix(codepipeline): correct three CFN provisioning bugs in CodePipelineCfnProvisioner

- DisableInboundStageTransitions is a declarative list: a stage removed from it on
  update must be re-enabled, not left disabled after UPDATE_COMPLETE.
- CustomActionType has no update operation; a change to Category/Provider/Version
  is a replacement (create the new identity, delete the superseded one) rather than
  a silent physicalId swap with no corresponding service call.
- Webhook's RegisterWithThirdParty must be read from the resolved/lowercased node,
  not the raw unresolved props, so intrinsics (Ref, Fn::If) are honored.

* fix(codebuild): convert the JSON handler's Map entity instead of dropping it

CodeBuildJsonHandler.handle(...) returns Response.ok(Map.of(...)), never a
JsonNode, so the instanceof check in CodeBuildCfnProvisioner.handle always
missed and silently fell back to an empty ObjectNode -- forcing the guessed
ARN fallback even when the handler returned the real project ARN. Convert
non-JsonNode entities with ObjectMapper.valueToTree, and close the Response.

* fix(cloudformation): UTF-8 encode the injected Python cfn-response callback body

http.client encodes a str request body as latin-1, raising UnicodeEncodeError
for any response Reason/Data containing non-Latin-1 characters and failing
the callback before it's sent. Encode the JSON body to UTF-8 bytes first.

* docs(cloudformation): merge the duplicate Lambda resource-type row

Two Lambda rows in the supported-resource-types table gave inconsistent
descriptions (one had Version/Alias, the other the cfn-response detail).
Consolidate into a single row.

* fix(codepipeline): fix stage-transition and rename bugs found in re-review

- Only re-enable stage transitions this stack previously disabled (tracked via a
  new __FlociCodePipelineDisabledStages attribute); a stage disabled externally
  (a manual gate, a human) and never listed in DisableInboundStageTransitions is
  no longer touched by an unrelated update.
- Pipeline Name has no rename operation in CodePipeline; a template Name that
  differs from the tracked physical ID is now treated as a replacement (create
  under the new name, delete the old one) instead of calling UpdatePipeline
  against a pipeline that doesn't exist or belongs to someone else.
- Webhook Name rename now deletes the previously-owned webhook after PutWebhook
  upserts under the new name, instead of orphaning it.

* fix(codepipeline): handle legacy stage tracking and failed-replacement cleanup

- A resource stored before __FlociCodePipelineDisabledStages existed has no
  tracking record; fall back to reconciling every declared stage on its first
  post-upgrade update instead of skipping reconciliation and leaving a removed
  entry disabled forever.
- If stage-transition reconciliation fails after a rename's replacement (or a
  fresh create) already succeeded, best-effort delete the just-created pipeline
  before rethrowing. CloudFormation reverts this resource to its previous
  physicalId on a failed update, so without this the new pipeline is orphaned
  and a corrected retry hits PipelineNameInUseException.
2026-08-28 20:23:18 -04:00
Facundo ParedesandFacundo Paredes 09d813d13f fix(stepfunctions): resolve the substitutions in a JSONata error cause (#2687)
The dashjoin port renders a JSONata error message from a catalog in which the
word "function" was replaced by "Object" throughout, through a substituter that
fills the first two placeholders of a template and quotes every value it inserts.
A cause therefore names a function as `Object`, can end in a literal `{{type}}`
or `{{token}}`, and never carries the error code AWS puts in front of the message.

The cause is now composed in JsonataEvaluator from the code and the values
JException carries. T0412 and T2009, the only two templates with a third
placeholder, state what the exception hands over: the offending argument and the
element type for T0412, the two compared values for T2009. The error name stays
States.QueryEvaluationError, so a Catch matches exactly what it matched before.

Closes #2668

Co-authored-by: Facundo Paredes <25681464+facuparedes@users.noreply.github.com>
2026-08-28 20:08:24 -04:00
Sam Fakhreddine f9d28c9649 fix(security): reject unregistered SigV4 access keys and unbound usernames (#2680)
* fix(security): reject unregistered SigV4 access keys and unbound usernames

SigV4Validator.java and RdsSigV4Validator.java both fell back to
`iamService.findSecretKey(accessKeyId).orElse(accessKeyId)` when the
access key wasn't registered. Since the attacker chooses accessKeyId
themselves, they can self-sign a token using secret == accessKeyId,
producing the exact signing key this fallback derives -- a full
signature-forgery auth bypass for any unregistered IAM key. Both now
fail closed when the key isn't registered.

SigV4Validator's ElastiCache username binding
(`expectedUsername != null && user != null && !expectedUsername.equals(user)`)
also skipped the check whenever the token simply omitted the User
query param, letting any expectedUsername through. Dropped the
`user != null` conjunct so a null user now correctly fails the check.

Each fix has a RED test proving the exploit against the unpatched
code (self-signed token with secret == accessKeyId; token missing
User) before asserting the fixed behavior.

RdsSigV4Validator's DBUser check was investigated but is not
vulnerable: DBUser is already required by the missing-parameters
check above it, so the null-skip path is unreachable via a crafted
token. PreSignedUrlFilter's well-known "test"/"test" credential and
its lack of a bucket-ownership check were also investigated and are
not presigned-URL-specific bugs -- see
issues/sigv4-review-remaining-findings.md for the evidence and for
everything else from the review pass deferred out of this PR.

* fix(security): restore well-known local-dev credential, sanitize log lines

The fail-closed fix in the prior commit broke the emulator's default
local-dev credential flow: AwsBasicCredentials.create("test", "test")
is used pervasively by SDK clients against RDS/ElastiCache IAM auth
(and S3) in this project's compat test suite, and was never actually
registered in IamService -- it only "worked" before because the
vulnerable fallback happened to derive the same secret ("test") from
the access key ID by coincidence (accessKeyId == secretKey == "test").

Carve out that exact, already-public pair explicitly in both
validators, mirroring the identical LEGACY_ACCESS_KEY_ID/SECRET_KEY
idiom already used by S3Service/PreSignedUrlFilter -- this does not
reopen the forgery bug, since it only ever matches the literal string
"test", never an attacker-chosen access key.

Also addresses two Copilot review comments: the debug logs added in
the fail-closed fix (and the pre-existing signature-mismatch log)
interpolated the attacker-controlled, URL-decoded accessKeyId with no
sanitization, allowing CR/LF-based log injection. Added a
sanitizeForLog helper (strips control characters) and applied it to
every log line that includes accessKeyId in both files.

* docs(security): update ledger after rebasing past PR #2657's merge

PR #2657 merged with the misleading "always fails the signature check"
comment in both SigV4Validator.java and RdsSigV4Validator.java (not
just the ElastiCache file, as first flagged). Rebasing this branch
onto upstream/main produced real conflicts on both files; resolved by
keeping the fail-closed fix and dropping the comment. Updated the
ledger from future-tense speculation to the resolved outcome.
2026-08-28 19:59:15 -04:00
Facundo ParedesandFacundo Paredes acf88794ca fix(stepfunctions): end the execution when a state throws an Error (#2693)
doExecute caught Exception only, so an Error escaping a state left the
execution RUNNING with no terminal status, no error, no cause and no
ExecutionFailed event, and executeAsync dropped the Future that held it.

The outer handler now catches Error as well, writes the same terminal
FAILED an exception produces with the Error's toString() as the cause, and
rethrows so the failure is not swallowed. executeAsync logs whatever
escapes the worker with its stack trace. The Parallel branch handler
unwraps an Error cause instead of rethrowing the ExecutionException
wrapper, and the per-state runtime catch folds into the outer one so a
single method writes every terminal failure.

Closes #2666

Co-authored-by: Facundo Paredes <25681464+facuparedes@users.noreply.github.com>
2026-08-28 19:28:22 -04:00
Facundo ParedesandFacundo Paredes 2a7ee7a605 fix(stepfunctions): write a large whole number in full in $string (#2683)
$string switched to exponent notation at Long.MAX_VALUE, so $string(1e20)
returned "1e+20" where AWS returns "100000000000000000000". AWS's boundary is
1e21, on both signs. The execution succeeds either way, so a $string used as a
MessageGroupId, an S3 key or a DynamoDB key wrote a different key on each engine
without either reporting an error.

$string is now bound on the evaluation frame next to the six functions of the
Step Functions dialect, with the library's own signature so every arity and type
error stays what it was. Below the boundary a double is replaced by the exact
integer of the shortest decimal that reads back as it, which is the digit string
AWS prints; the library formats everything else.

Closes #2669

Co-authored-by: Facundo Paredes <25681464+facuparedes@users.noreply.github.com>
2026-08-28 19:04:44 -04:00
David e4c690351f fix(lambda): replace the extracted package instead of merging into it (#2672)
* fix(lambda): replace the extracted package instead of merging into it

ZipExtractor wrote entries into the function's code directory without
clearing it first, so each deploy was layered on top of the last. Nothing
on the path resets the directory: CodeStore.delete runs only when a
function is deleted, codeStore.exists() is never called, and every deploy
of a function resolves to the same code path. Extraction was a merge where
the domain requires a replace, so a file removed between two deploys
survived and stayed loadable -- a handler pointing at a deleted module kept
resolving and running stale code. Real AWS replaces the package wholesale.

Extract into a sibling staging directory and swap it in once the whole
archive has been read: on success the old tree is deleted and staging is
moved into place, on failure staging is discarded and the previous
deployment is left untouched. That also makes extraction all-or-nothing.

Safe because the code directory is not bind-mounted into Lambda
containers -- ContainerLauncher tar-copies it into /var/task at launch, and
the only bind for task code is the hot-reload path, which uses a different
directory that never goes through extractTo.

Closes #2647

* fix(lambda): keep the previous package until the new one is installed

The install deleted the live tree and then moved the new one into place, so
a failure in the move left the function with no code at all and nothing to
restore: a failed update destroyed a working deployment.

Rename the old tree aside instead, move the new one in, and delete the old
only once the new one has landed. Every failure path now ends with one
complete package on disk. The interval in which the target is absent is two
renames within a directory rather than a recursive delete followed by a
move; it is narrowed, not closed, because POSIX cannot atomically exchange
two directories, and the javadoc records that limit rather than implying
atomicity.

install() is package private so the failure path can be driven directly. It
is unreachable through extractTo, because a rename between siblings does not
fail under any condition a test can arrange there.

* fix(lambda): do not fail a deployment that already installed

Two failure paths in install() reported the wrong outcome.

Deleting the superseded package threw out of install(), so a filesystem
error at that point failed the deployment even though the new tree was
already in place and serving. The caller then skipped its metadata and warm
pool updates for code that was live. That deletion is now best effort: it
logs and leaves the tree behind, because leaving a directory costs disk and
is recoverable, while misreporting the outcome is not.

Restoring the previous package after a failed move was itself unguarded. If
the restore also threw, its exception replaced the original failure and the
working package was left under a generated name nothing would look for. The
restore is now guarded, the original failure stays the exception thrown, the
restore failure is attached to it, and the stranded path is logged so it can
be moved back by hand.

The cleanup path has a regression test. The restore path does not: reaching
it needs the install rename to fail while the restore rename also fails, and
both are renames in one directory, so either both succeed or the first
rename fails before install is reached.
2026-08-28 18:51:43 -04:00
Ahmed khaled 5c1b69c45f feat(comprehend): add Amazon Comprehend sync text-analysis actions (#2674)
* feat(comprehend): add Amazon Comprehend sync text-analysis actions

Implements DetectSentiment, DetectKeyPhrases, DetectDominantLanguage,
DetectPiiEntities, and ContainsPiiEntities as fixed AWS-shaped stub
responses over the real JSON 1.1 wire protocol
(X-Amz-Target: Comprehend_20171127.*). Input validation (Text and
LanguageCode required, LanguageCode checked against Comprehend's
supported set) matches real API behavior and raises
InvalidRequestException/UnsupportedLanguageException per
botocore's declared error shapes.

The async job/model-training surface (DocumentClassifier,
EntityRecognizer, Flywheel, Dataset, Endpoint) and DetectEntities/
DetectSyntax are out of scope for this PR. Real (non-stub) detection
logic is planned as a follow-up once this lands.

Closes #2660

* fix(comprehend): restrict PII detection to en/es language codes

DetectPiiEntities and ContainsPiiEntities were validated against the
full 12-language set shared with DetectSentiment/DetectKeyPhrases, but
AWS's own operation docs for DetectPiiEntitiesRequest.LanguageCode
state PII detection only supports English (en) and Spanish (es).
Split the allowlist so the two PII operations reject other languages
with UnsupportedLanguageException, matching real Comprehend behavior.

Addresses review feedback on #2674.

* fix(comprehend): reject non-string Text/LanguageCode as SerializationException

getStringField() coerced any JSON value via asText() instead of
enforcing the modeled string type, so a numeric or boolean Text/
LanguageCode silently succeeded instead of being rejected. Reuses the
codebase's existing SerializationException convention (see
JsonErrorResponseUtils.createSerializationErrorResponse()) since a
wrong-typed field is a shape/marshalling mismatch caught before
business logic runs, distinct from a missing field (InvalidRequestException,
a modeled business error). Scoped to ComprehendJsonHandler only.

Addresses review feedback on #2674.
2026-08-28 18:47:22 -04:00
Sam Fakhreddine e5316839ca fix(dynamodb): hybrid persistence (#2677)
* fix: persist DynamoDB index definitions

* test(dynamodb): declare LSI sort key attribute in HybridStorageTest fixture

Real DynamoDB requires every attribute used in a table or index key
schema to appear in AttributeDefinitions; the LSI's sort key (lsiSk)
was missing from the fixture.
2026-08-28 18:14:28 -04:00
Michal Schreiber 5033ace772 fix(rds): store and return the encryption and backup settings given on create (#2617)
* fix(rds): store and return the encryption and backup settings given on create

DescribeDBInstances never returned StorageEncrypted, KmsKeyId,
BackupRetentionPeriod or CopyTagsToSnapshot, and wrote both windows as
constants. Store the six values from CreateDBInstance, apply the backup
settings and windows from ModifyDBInstance, and emit them from the
instance XML. A record persisted without them reads as AWS defaults.

KmsKeyId is resolved against the KMS store in the request's region — a
key ARN, key id, alias ARN or alias name — and stored as the key ARN, as
a live account reports it; a key that does not exist or is not enabled
is KMSKeyNotAccessibleFault.

Validation follows a live account: KmsKeyId needs StorageEncrypted,
window times are checked with AWS's wording, windows are at least 30
minutes and may not overlap; the retention period is not range-checked
since AWS accepted 40 days.

Closes #2611

* fix(rds): check window overlap against the windows that will be in effect

A window given alone was not checked at all: the request's other window
was null, so validate() skipped the overlap check although the instance
kept its stored counterpart on modify and got a default on create. Check
the pair that results from the request — on modify the stored other
window, on create the default, swapped for an alternate default when the
given window overlaps it, since AWS picks a random window clear of the
given one. Verified on a live account: a modify overlapping the stored
window is refused either way, replacing both at once checks only the new
pair.

* fix(rds): detect window overlap across the week boundary in both directions

A Sunday backup window running past midnight lies beyond the end of the
week, so comparing it with a Monday maintenance window needs the
maintenance interval shifted forward as well as back.

* fix(rds): derive the default counterpart window from the given one's end

A fixed alternate default cannot be clear of every window a request can
give — a 00:00-07:00 backup window covers it. When the window given on
create overlaps the usual default, pair it with a 30-minute window that
starts the minute the given one ends, which is clear of a daily window by
construction; the overlap check stays as the backstop.

* fix(rds): refuse a window given alone that leaves no room for the other, in AWS's words

The derived counterpart is clear of any window that leaves a 30-minute
gap (swept over every start and length in DbInstanceSettingsTest); a
window longer than that has no clear counterpart, and a live account
refuses it: "The specified backup window overlaps all available default
maintenance windows. Shrink the backup window or specify a non-overlapping
maintenance window." (mirrored for maintenance), and a maintenance
window of 24 hours or more is "Maintenance window must be less than 24
hours."

* refactor(rds): share the window checks with BackupWindows
2026-08-28 18:07:08 -04:00
Michal Schreiber 46d2f4e70f fix(docdb): refuse an engine version a live account does not list (#2682)
* fix(docdb): refuse an engine version a live account does not list

CreateDBCluster and ModifyDBCluster derived a parameter group family from
any engine version string and assigned "default.<family>" without checking
that the family exists. The versions a live account lists for docdb are
now the catalogue: 3.6.0, 4.0.0, 5.0.0, 5.0.1, 8.0.0, 8.0.1 and the
major.minor form of one; anything else is refused before any change with
"Cannot find version X for docdb". default.docdb8.0 joins the managed
cluster parameter groups.

Closes #2681

* test(docdb): refuse an unlisted engine version through the CLI
2026-08-28 17:55:30 -04:00
Matan Baruch 6c96f47f73 fix(rds): grant the MySQL/MariaDB master user RDS-master-equivalent privileges (#2679)
* fix(rds): grant the MySQL/MariaDB master user RDS-master-equivalent privileges

The stock mysql/mariadb images grant MYSQL_USER only ALL on MYSQL_DATABASE
plus USAGE, so a non-root master user cannot CREATE DATABASE, CREATE USER
or GRANT. Real RDS master users perform these routinely, and the terraform
and pulumi mysql providers run them right after connecting; against Floci
they failed with ERROR 1044.

After the DB container starts, exec a root GRANT ALL PRIVILEGES ON *.*
WITH GRANT OPTION for the master user, reusing the exec-with-retry
machinery the PostgreSQL rds_iam init already uses (extracted into a
shared execUntilSuccess). Real RDS withholds SUPER, FILE and SHUTDOWN
from its master grant list; the emulator grants ALL for simplicity,
mirroring how POSTGRES_USER is already a superuser. A root master is
skipped: the images create no separate user for it and root already
holds every privilege.

* fix(rds): deliver the master grant as a one-time init script and escape the username

Review follow-ups from #2679:

- Escape single quotes and backslashes in the GRANT statement. Floci does
  not enforce AWS's MasterUsername charset anywhere, so an unescaped name
  could break out of the string literal in SQL executed as root.
- Replace the post-start root exec with a /docker-entrypoint-initdb.d
  script installed between container create and start. The images run init
  scripts exactly once, against an empty data directory, as root, after
  creating the master user, so a reboot on a reused volume never re-runs
  the grant and never needs to re-authenticate as root. This removes the
  reboot-after-password-rotation failure: MYSQL_ROOT_PASSWORD only takes
  effect on first initialization, so the rotated password can never open
  a root session on a reused volume.
- The tar-and-copy shape follows CodeBuildRunner.copySourceToContainer.
2026-08-28 17:51:44 -04:00
Sam Fakhreddine be892864db fix(lambda): resolve launched-container placeholder creds to the owning account (#2657)
* fix(lambda): resolve launched-container placeholder creds to the function's owning account

A Lambda that never assumes an execution role falls through to placeholder
credentials, and the literal AWS_ACCESS_KEY_ID=test that ContainerLauncher then
injected is not a 12-digit account ID, so AccountResolver resolved every such
container to the emulator's default (management) account regardless of which
account actually owns the function. Account-partitioned reads and writes then
collide or miss whenever the real resource lives elsewhere -- observed as five
accounts' LoggingStack custom resources simultaneously colliding on one
AWSServiceRoleForAutoscaling during an LZA Stage 1 run, and
non-deterministically, since account IDs are re-minted every pipeline run.

sdkBaselineEnv now takes the workload's owning account and injects it as the
placeholder access key. It wins over Floci's own ambient AWS_ACCESS_KEY_ID: the
server process's credentials describe the server, not a container it launches,
and a deployment that exports AWS_ACCESS_KEY_ID (the floci-lza image sets it
unconditionally) would otherwise make the owning-account branch dead code.
Mounted ~/.aws and real execution-role credentials still take precedence, and
launch paths that don't know the owning account are unaffected.

Recovered from 092cb16a5 + d25f1cefc, re-derived onto upstream's current shape:
the fork's 3-arg overload would collide with upstream's flociEndpoint overload,
so the account rides on the injectedCredentials-carrying signatures instead, and
ContainerLauncher passes the lambdaAccountId it already resolves. The host env
lookup moved behind a package-private seam so the precedence is actually
testable -- the fork's own regression test asserted it without ever forcing the
host env to be set, and so could not have failed. Drops the branch's local-only
issues/*.md ledger entry and scripts/describe-sg-as.sh diagnostic.

* fix(lambda): pass the owning account into Kubernetes-launched Lambda pods too

The pod launcher builds the same baseline AWS environment as the Docker one and
so had the same defect: a Lambda that never assumes an execution role fell
through to the "test" placeholder access key and resolved to the emulator's
default account. It already derives the owning account for its layer downloads,
so it now passes it to sdkBaselineEnv as well.

ECS, MWAA and Flink container managers deliberately stay on the account-less
overload -- those workloads have no owning Lambda function to derive one from.

* fix(lambda): resolve owning-account placeholder AKID to the test secret in SigV4 validation

sdkBaselineEnv gives a Lambda without an execution role and a known owning
account that account ID (a bare 12-digit string) as AWS_ACCESS_KEY_ID, paired
with the "test" placeholder secret. Floci's own SigV4 validators for S3
presigned URLs, ElastiCache IAM auth, and RDS IAM auth look up the secret for
an unregistered access key and previously fell back to either null or the
access key itself, which only coincidentally matched when both sides were the
literal "test"/"test" pair. Once the access key became a 12-digit account ID
instead, the fallback no longer matched the "test" secret the client actually
signed with, and every such presigned URL or IAM auth token failed validation.

Each validator's fallback now recognizes a bare 12-digit access key
specifically as this placeholder and expects the "test" secret for it, while
any other unregistered access key keeps its prior behavior (InvalidAccessKeyId
for S3, signature mismatch for ElastiCache/RDS) so a genuinely unknown key is
still rejected.

* fix(lambda): force test secret and session token on the owner-account placeholder path

The owner-account AKID branch in LaunchedContainerAwsEnv still paired the numeric
owner-account access key with Floci's own ambient AWS_SECRET_ACCESS_KEY when one was
set. The S3, RDS, and ElastiCache SigV4 validators only accept a numeric access key
paired with the literal "test" secret, so a non-test ambient secret produced a
credential pair nothing could verify, breaking presigned URLs and IAM-auth tokens.
Force the secret and session token to "test" whenever the owner-account AKID wins,
and scope the ambient-credential-forwarding warning to the branch where it actually
forwards them.

* fix(security): reject unregistered numeric access keys in SigV4 validators

The S3 presigned-URL filter, RDS SigV4 validator, and ElastiCache SigV4 validator each
treated any unregistered 12-digit access key ID as a valid credential when paired with
the literal "test" secret. Since AccountResolver reads a 12-digit access key ID as the
request's account directly, this let a client forge a signed request or IAM-auth token
for an arbitrary account number using the well-known "test" secret, bypassing S3 auth
enforcement and RDS/ElastiCache IAM authentication for any matching database or cache
user. Remove the numeric-access-key fallback from all three validators; an unregistered
key is rejected the same way any other unknown key is.

This narrows the owner-account placeholder credentials added for launched Lambdas to
paths that don't require a real signature check; ledgered in issues/ for a follow-up
that mints real per-account session credentials instead.

* fix(lambda): reject partial user credential overrides on the placeholder path

Both the Docker and Kubernetes launchers appended a Lambda's own Environment
config after the owner-account/placeholder AWS credential baseline. When the
function defined only a subset of AWS_ACCESS_KEY_ID/AWS_SECRET_ACCESS_KEY/
AWS_SESSION_TOKEN, that partial value overrode just its own key in the
baseline tuple, pairing a user-chosen value with the owner-account's other
credential parts -- a combination no SigV4 validator accepts and which could
resolve requests to the wrong account. Credential injection from a function's
Environment is now all-or-nothing: only a fully-specified triad is allowed to
override the baseline; anything less is dropped so the baseline stays intact.
2026-08-28 17:42:18 -04:00
Sam Fakhreddine e9a379b37a feat(autoscaling): P0 operations and lifecycle-hook delete-by-name (#2673)
* feat(autoscaling): add SetInstanceProtection and SetInstanceHealth

* test(applicationautoscaling): cover DeleteScalingPolicy over the wire

* chore(autoscaling): cede the DeleteScalingPolicy test to feature/applicationautoscaling-delete-policy

The file was byte-identical on both branches; the ApplicationAutoScaling
test belongs on the applicationautoscaling branch by service, and keeping
both would make whichever merges second conflict on an unrelated file.

* fix(autoscaling): validate LifecycleHookName pattern and LifecycleActionToken length

PutLifecycleHook, DeleteLifecycleHook, and CompleteLifecycleAction accepted any
hook name and lifecycle-action token, so a name with characters outside the
modeled [A-Za-z0-9\-_/]+ pattern or a token that wasn't exactly 36 characters
was stored/consumed instead of rejected the way AWS rejects it
(autoscaling/2011-01-01/service-2.json: LifecycleHookName, LifecycleActionToken).

* fix(autoscaling): address maintainer review on instance ops and lifecycle hooks

- SetInstanceProtection: validate InstanceIds before requireGroup (AWS
  validates required members first), compare requested/found instance
  IDs via set containment instead of size-based matching (duplicate
  stored IDs no longer break the check), and report every missing
  instance ID instead of just the first.
- SetInstanceProtection: ProtectedFromScaleIn is a required boolean
  member; reject missing/malformed values instead of silently
  coercing to false via Boolean.parseBoolean.
- SetInstanceHealth: collapse the redundant second instance lookup
  after the orElseThrow already guarantees group membership. Parse
  and pass through ShouldRespectGracePeriod for wire fidelity (not
  yet enforced -- floci has no instance launch-time tracking against
  HealthCheckGracePeriod).
- deleteLifecycleHookByName (CFN delete path): validate the name for
  parity with deleteLifecycleHook instead of silently no-op'ing on an
  unvalidatable name.
- validateLifecycleHookName: split null/length/pattern checks so the
  thrown message matches the actual failure instead of always citing
  the regex pattern.
- Style: import java.util.regex.Pattern instead of fully qualifying
  it, and fix switch-case column alignment for the two new instance
  ops.

* fix(autoscaling): allow completeLifecycleAction without a token when InstanceId identifies the action

LifecycleActionToken and InstanceId are both optional in CompleteLifecycleActionType
per the service model — only LifecycleHookName, AutoScalingGroupName, and
LifecycleActionResult are required. A caller identifying the action by
InstanceId + LifecycleHookName + AutoScalingGroupName alone was rejected with a
length-36 error even though real AWS accepts it.
2026-08-28 17:11:56 -04:00
Sam Fakhreddine 3bd9bcc62b feat(acm): certificate validation records and revocation (#2655)
* feat(acm): add certificate revocation, renewal, options and email resend

Adds RevokeCertificate, RenewCertificate, UpdateCertificateOptions and
ResendValidationEmail, with a RevocationReason enum modelling the accepted
values. Limitations documented in docs/services/acm.md.

* test(acm): stop asserting global-empty state in the pagination filter test

Other classes sharing the full-suite JVM revoke certificates of their own, so a
REVOKED filter is not globally empty. Assert instead that none of this class's own
certificates appear, which is what the test is actually about.

* feat(acm): add ResendValidationEmail and certificate revocation reasons

* fix(acm): validate Domain/ValidationDomain on ResendValidationEmail

Domain and ValidationDomain were accepted verbatim after a
null/blank check, so any value round-tripped as 200 OK - a client
could resend against an unrelated domain and get success back.

Domain must now match the certificate's DomainName or one of its
SubjectAlternativeNames, and ValidationDomain must equal Domain or
be one of its superdomains, matching botocore's
InvalidDomainValidationOptionsException semantics for this
operation. Also drops the now-unneeded manual UTF-8 byte encoding
in the resend test now that RestAssuredJsonUtils configures the AWS
content types.

* fix(acm): require Options.Export=ENABLED to revoke a certificate

revokeCertificate gated on Certificate.canExport(), which returns
true for any PRIVATE or IMPORTED certificate regardless of its
Export option - so an imported certificate with Export left at the
default DISABLED could still be revoked, bypassing the
export-enabled guard the operation is meant to enforce.

Check Options.Export directly instead.

* fix(acm): use ValidationException for a not-export-enabled revoke

RevokeCertificate's own modeled Errors list is
AccessDeniedException, ConflictException, InvalidArnException,
ResourceInUseException, ResourceNotFoundException,
ThrottlingException, and ValidationException.
InvalidStateException isn't among them - it's modeled on
UpdateCertificateOptions instead, which is likely where it got
picked up from.

ValidationException is the operation's own general "input failed
to satisfy constraints" code, and the better fit here.
2026-08-28 16:14:16 -04:00
Kurt McAlpineandkurtmc 97ff0bc3e9 feat(elasticache): support cluster-mode replication groups (#2633)
* feat(elasticache): support cluster-mode replication groups

CreateReplicationGroup now provisions a real sharded Valkey cluster when
the request asks for one (NumNodeGroups > 1, a cluster.on parameter
group, or ClusterMode=enabled): one cluster-enabled container per node,
formed via config epochs, MEET, slot assignment and replica attachment,
each fronted by its own auth-proxy port announced to clients via
cluster-announce-client-ipv4/cluster-announce-port so CLUSTER SLOTS and
MOVED redirects point at reachable addresses.

DescribeReplicationGroups reports the topology honestly (ClusterEnabled,
NodeGroups with Slots, MemberClusters, Engine, ARN, AutomaticFailover),
and replication-group members answer DescribeCacheClusters, which is
where terraform-provider-aws reads node type, engine version and port
from.

Adds a terraform compatibility test that applies an
aws_elasticache_replication_group with num_node_groups and
replicas_per_node_group, asserts the data plane is a formed cluster
running in cluster mode (INFO cluster / CLUSTER INFO over RESP through
the proxy), and that a re-plan straight after apply is clean.

* fix(elasticache): address cluster-mode review feedback and compat CI failure

- bump compat-terraform aws-cli image to 2.34.32 so botocore models
  include ReplicationGroup.Engine (old pin silently dropped the field)
- restore cluster-mode runtime state (ports, containers, proxies,
  cluster formation) after restart; mark groups create-failed on error
- announce configured hostname to Valkey nodes so MOVED redirects and
  CLUSTER SLOTS return client-reachable endpoints
- log swallowed socket-close failures in cluster formation

* fix(elasticache): report restore-failed members and modeled node-group quota fault

Review follow-up for cluster-mode support:

- Member cache clusters mirror their group's status instead of a
  hardcoded "available", so a group marked create-failed by a failed
  restore no longer contradicts its own members in
  DescribeCacheClusters. CacheClusterStatus has no create-failed value,
  so failed members report the documented restore-failed.
- NumNodeGroups above the 500 ceiling surfaces the modeled
  NodeGroupsPerReplicationGroupQuotaExceeded fault instead of a generic
  InvalidParameterValue.
- Javadoc names ClusterMode=compatible handling and the
  cluster-mode-only restore scope as deliberate.

* fix(elasticache): announce a client-resolvable hostname for cluster mode

Cluster-mode nodes announced FLOCI_HOSTNAME verbatim, so the shipped
Docker Compose deployment baked the Compose-only name 'floci' into
MOVED/ASK redirects and topology responses, breaking cluster-aware
clients connecting from outside the Compose network.

Add FLOCI_SERVICES_ELASTICACHE_CLUSTER_ANNOUNCE_HOSTNAME (default:
FLOCI_HOSTNAME) used for the announced name and the reported
ConfigurationEndpoint, and set it to localhost.floci.io in
docker-compose.yml — public DNS resolves it to 127.0.0.1 on the host
while the network alias and Floci's embedded DNS resolve it to the
Floci container from inside Docker.

* fix(elasticache): restore cluster-mode groups without blocking startup

Restoring persisted cluster-mode groups ran serially in the synchronous
startup path, so a slow or unavailable Docker daemon could hold up
emulator readiness by a container-readiness plus cluster-formation
timeout per group, timing out readiness-dependent clients such as
Testcontainers.

restorePersistedRuntime now reserves each node's proxy port and marks
groups creating synchronously - so no request can claim a persisted
port or see a stale available status - then brings containers, cluster
formation and proxies back in the background, flipping each group to
available or create-failed as its restore finishes.

---------

Co-authored-by: kurtmc <2661907+kurtmc@users.noreply.github.com>
2026-08-28 16:00:33 -04:00
Facundo ParedesandFacundo Paredes eb5134da2d feat(stepfunctions): add the JSONata functions of the Step Functions dialect (#2676)
Step Functions extends JSONata with $parse, $partition, $range, $hash,
$random and $uuid. None of them exist in the JSONata language, so an
expression calling one failed with "Attempted to invoke a non-function"
and the execution failed with States.QueryEvaluationError.

Bind the six on the evaluation frame next to $states and the workflow
variables. Behaviour follows AWS on the cases a naive reading gets wrong:
a non-integer argument rounds towards zero, several argument combinations
evaluate to undefined instead of failing, $range collapses a
single-element range to a bare number, $parse rejects the JSON AWS
rejects, and $random(seed) reproduces java.util.Random.

Verified with a 65-expression differential against real AWS Step
Functions: 65 match, 0 differ.

Co-authored-by: Facundo Paredes <25681464+facuparedes@users.noreply.github.com>
2026-08-28 15:31:53 -04:00
David cd3f3677f8 fix(lambda): read deployment packages via the zip central directory (#2649)
* fix(lambda): read deployment packages via the zip central directory

ZipExtractor read archives with ZipInputStream, a forward-only reader that
sees only local file headers. A streaming packager (the Serverless
Framework's archiver, for one) cannot seek back to patch an entry's header,
so it sets general-purpose bit 3, zeroes the CRC and sizes in the local
header, and writes the real values in a trailing data descriptor; content
that does not compress is written STORED. ZipInputStream rejects that
pairing with "only DEFLATED entries can have EXT descriptor", because a
STORED entry with deferred sizes has no end marker for a sequential reader
to find. CreateFunction therefore 400d on any Serverless package bundling
node_modules, which real AWS accepts.

Read through the central directory with ZipFile instead, which always
carries the true method, CRC and sizes regardless of the descriptor flag.
The bytes are staged to a temp file because ZipFile needs a seekable
source. The traversal guards, backslash warning and directory handling are
unchanged, as is the method signature.

ZipFile does not verify per-entry CRC while ZipInputStream did, so each
entry is now checked against the CRC recorded for it in the archive. Without
that, a package corrupted in transit would have deployed silently as garbage
rather than being rejected.

Closes #2593

* fix(lambda): stage the deployment package in the code store, not /tmp

Reading the archive through ZipFile needs a seekable file, and the first
version of this change staged it under java.io.tmpdir. That added a new
consumer of the shared temp filesystem where there was none before: the
extractor previously read straight from the in-memory byte[]. Concurrent
deployments of large packages could exhaust that shared space, and doing so
fails unrelated temp-file users, not just Lambda.

Stage beside the extraction target instead. The code store already has to
hold this package's uncompressed contents -- always at least as large as
the archive, usually much larger -- so the volume is already provisioned
for it, and the staged copy is released as soon as extraction ends.

* fix(lambda): read the deployment package without staging a copy on disk

The previous commit staged the archive on disk because java.util.zip.ZipFile
only reads a central directory from a File. Commons Compress reads the same
structure straight off a SeekableInMemoryByteChannel over the bytes already
held, so no second copy of the package is written anywhere: extraction now
costs exactly what the extracted output needs, as it did before this branch.
That removes the staging copy as a resource concern entirely rather than
bounding it. commons-compress is already on the compile classpath via
docker-java-core; it is declared explicitly here because ZipExtractor uses it
directly and must not break if that transitive path changes.

Two behaviours of java.util.zip that Commons Compress does not share are
restored explicitly:

Commons Compress rewrites every '\' to '/' for a FAT-platform entry whose
name contains no '/', which would turn a PowerShell-produced literal filename
into a nested path -- the opposite of what #1215 established, since real AWS
Lambda extracts "wwwroot\app.css" as one flat file. The raw name field is the
bytes as written, so the rewrite is undone when it carries a backslash and no
forward slash, leaving charset handling to Commons Compress.

java.util.zip throws on an unknown compression method, while Commons Compress
reports the entry unreadable and yields an empty stream, which would write a
zero-byte file and deploy a function whose code silently vanished. Entries
that cannot be read are now rejected.

* fix(lambda): read the package with java.util.zip, not Commons Compress

Reverts the in-memory Commons Compress reader from the previous commit. It
removed the staged copy, but it cannot be built into the native image, which
is a shipped artifact of this project.

ZipFile.getInputStream hard-references four codecs, two of which -- xz and
zstandard -- need libraries that are deliberately not on the classpath. The
build uses --link-at-build-time, so every reachable method must resolve, and
native-image fails during analysis:

  Discovered unresolved method during parsing:
    org.apache.commons.compress.compressors.xz.XZCompressorInputStream.<init>
  Error encountered while parsing ZipFile.getInputStream(ZipFile.java:1226)

This is a linking failure rather than a class-initialization one, so
--initialize-at-run-time does not address it; verified by building the image
locally with that option in place. Resolving it properly would mean adding
two compression libraries, one of them shipping JNI natives, purely so
GraalVM can link paths a Lambda package cannot exercise -- AWS deployment
packages are STORED or DEFLATE only.

Back to java.util.zip.ZipFile, staging the archive in the code store. The
staged copy costs at most one archive on the volume that already has to hold
the same package's uncompressed contents, and the native image builds.

Keeps the unknown-compression-method test from the reverted work: the JDK
rejects such an archive when opening it, so the guarantee holds without a
guard, and the test now pins it.
2026-08-28 14:34:16 -04:00
Michal SchreiberandPriamo Germosen f019573bf1 fix(docdb): store and return cluster and instance settings (#2651)
* fix(docdb): store and return cluster and instance settings

CreateDBCluster and ModifyDBCluster dropped DBSubnetGroupName,
DBClusterParameterGroupName, VpcSecurityGroupIds, StorageEncrypted,
KmsKeyId, BackupRetentionPeriod, both windows, DeletionProtection and
tags; instances dropped AutoMinorVersionUpgrade, PreferredMaintenanceWindow,
CopyTagsToSnapshot and PromotionTier. Describe now returns what was given,
or the defaults a live account assigns, and refuses what a live account
refuses before any container is started: an unknown subnet group,
parameter group, security group or KMS key, a KMS key on an unencrypted
cluster, a retention period outside 1..354, malformed or overlapping
windows.

Records persisted before these fields existed are filled in with the
defaults on read. Port is not taken from the request: the port a cluster
reports is the one it is reachable on.

Closes #2614

* fix(docdb): enforce deletion protection, parameter group family and undrivable windows

DeleteDBCluster refuses a cluster with DeletionProtection, before any state
changes. A named parameter group must belong to the family of the engine
version the cluster will run, judged on modify against the requested
version rather than the stored one; a cluster on a default group follows
an engine version change to the new family's default. A window given
without its counterpart that leaves no daily half hour for the derived one
is refused with the live wording instead of a derived window that overlaps.

* fix(docdb): refuse an engine version change that keeps a custom group of the old family

* fix(docdb): judge a retained parameter group by its stored family, not its name

* fix(docdb): classify a retained parameter group through the RDS catalogue, not its name

---------

Co-authored-by: Priamo Germosen <6233424+pgermosen@users.noreply.github.com>
2026-08-28 14:22:23 -04:00
David 231c0972b0 fix(cloudformation): fail the stack when Lambda S3 code cannot be read (#2650)
* fix(cloudformation): fail the stack when Lambda S3 code cannot be read

resolveLambdaCode probed Code.S3Bucket/S3Key only to decide whether to use
it, and treated any failure as "no code available", falling through to the
built-in default handler. A fallback default is sound only when the input
is absent; applying it to an input that is present but unusable turns an
explicit user intent into a silent substitution.

With Handler: index.handler -- the stub's own handler -- the stack reached
CREATE_COMPLETE and the function served the stub's canned 200 for every
request, with nothing in the API surface saying the declared code was never
deployed. With any other handler the resource instead failed with "Handler
file '<x>' not found in deployment package", naming a handler that is
correct in the template and present in the package that was never fetched.

Throw ValidationError naming the bucket, the key and the underlying S3
error, so the resource fails and the stack rolls back as real
CloudFormation does. The default handler is kept for its legitimate case, a
template that supplies no Code block at all.

Note this changes outcomes: stacks that previously completed against
unreadable code now fail.

Closes #2648

* fix(cloudformation): allow opting back in to the Lambda stub fallback

Adds floci.services.cloudformation.allow-stub-lambda-code, defaulting to
false, so failing the stack on unreadable Lambda code stays the default
while a stack that deliberately leaves its packages unbuilt can opt back
in to the previous stub handler rather than break on upgrade. Requested
during review of the parent change.

The knob lives on EmulatorConfig.CloudFormationServiceConfig and in both
the main and test application.yml. Its javadoc records what enabling it
costs: the stack reports CREATE_COMPLETE while serving a placeholder that
returns a canned 200, so it cannot be used to verify the real function.

Reading the flag means the provisioner needs EmulatorConfig, and that
constructor parameter reaches 13 unit tests that build it positionally.
Those pass null, so the read is null safe: a provisioner built without
config gets the documented default, which is the strict behaviour.

The opt in path is covered by its own top level test class rather than a
nested one. A nested class carrying @TestProfile compiles and passes when
targeted directly, but Surefire discovers test classes by file name and
skips it in a full run.
2026-08-28 13:24:53 -04:00
Sam Fakhreddine 1b3417a7a3 feat(config): compliance evaluation loop, retention, pagination (#2642)
* feat(config): add compliance evaluation loop, retention, and pagination

Replace the hardcoded INSUFFICIENT_DATA compliance with real aggregation
over evaluations reported via PutEvaluations / PutExternalEvaluation:

- New actions (13): PutEvaluations, PutExternalEvaluation,
  DeleteEvaluationResults, DescribeComplianceByResource,
  GetComplianceDetailsByConfigRule, GetComplianceDetailsByResource,
  GetComplianceSummaryByConfigRule, GetComplianceSummaryByResourceType,
  DeleteConfigurationRecorder, DeleteDeliveryChannel,
  PutRetentionConfiguration, DescribeRetentionConfigurations,
  DeleteRetentionConfiguration
- PutConfigRule now round-trips the full AWS rule shape (Description,
  Scope, SourceDetails, InputParameters, MaximumExecutionFrequency,
  EvaluationModes) instead of silently dropping fields
- Evaluations persist to config-evaluations.json and are cascade-deleted
  with their rule; retention persists to config-retention.json
- NextToken/Limit pagination on describe/get operations with AWS page
  sizes and InvalidNextTokenException/InvalidLimitException validation
- DescribeConfigRules with an unknown name now fails with
  NoSuchConfigRuleException, matching AWS
- boto3 compatibility suite: tests/test_config.py

Since Floci performs no Lambda invocation, PutEvaluations accepts the
config rule name as the ResultToken; documented in the service doc's
deviations section.

* fix: honor Limit field in Config pagination requests

* fix(config): enforce the modeled rule enums and the ComplianceTypes filter shape

PutConfigRule now deserializes the whole modeled ConfigRule and stores it, so
Source.Owner, MaximumExecutionFrequency, ConfigRuleState and
EvaluationModes[].Mode were persisted and echoed back verbatim — a rule AWS
would have rejected with InvalidParameterValueException read back as a valid
one.

The ComplianceTypes filter on the four compliance reads was likewise unchecked:
an unmodeled value or a list longer than the shape's max of 3 simply matched
nothing, which a caller reads as an empty result rather than as a rejection.

* fix(config): validate the nested SourceDetails enums and Scope cardinality

The stored ConfigRule carries SourceDetails, whose EventSource (aws.config only),
MessageType and MaximumExecutionFrequency are all enum-typed, and a Scope whose
ComplianceResourceTypes list is capped at 100. All four were persisted and echoed
back by DescribeConfigRules verbatim, one level below the members the previous
commit checked.

* fix(config): reject a missing ConfigRuleName on DeleteConfigRule

store.remove(ruleName) throws NullPointerException on the backing
ConcurrentHashMap when ruleName is null (the handler passes null when
ConfigRuleName is absent from the request), producing a 500 instead of
the modeled NoSuchConfigRuleException. Guard on isBlank(ruleName)
first, matching the existing requireRule() idiom used by the sibling
evaluation operations for the same field.

* fix(config): keep the newest evaluation when PutEvaluations reorders

storeEvaluations() unconditionally overwrote the stored compliance
result for a resource/rule pair, so an older evaluation arriving after
a newer one (e.g. an out-of-order Lambda invocation) regressed
compliance details, aggregates, and summaries back to the stale value.
Compare against the stored OrderingTimestamp and skip the incoming
evaluation when it is older than what is already recorded.

* fix(config): make PutEvaluations atomic per resource/rule key

storeEvaluations() read the current evaluation with a plain get() and
wrote the new one with a separate put(), so two concurrent
PutEvaluations calls for the same resource could both read the old
value before either wrote, letting an older OrderingTimestamp win the
race regardless of arrival order. Replace the read-then-write with
ConcurrentHashMap.compute(), which is atomic per key.

Added a stress test exercising 16 concurrent writers per resource key
across 100 attempts; it passes reliably under the fix. The race window
in the prior get/put shape is narrow enough (a handful of nanoseconds
between the two calls) that it did not reproduce deterministically
under test scheduling even with that much contention -- the fix is
justified by the non-atomic read-then-write shape itself, not by a
forced failure.

* fix(config): enforce DescribeConfigRules' 25-name limit

ConfigRuleNames is modeled with Maximum 25 items (confirmed against
botocore's config service-2.json) but describeConfigRules had no size
check, so 26+ names were processed instead of rejected with
InvalidParameterValueException like every other array-size limit this
PR already enforces.

* fix(config): close the DeleteConfigRule/PutEvaluations deletion race

PutEvaluations (and PutExternalEvaluation, DeleteEvaluationResults)
checked a rule's existence via requireRule and then wrote to the
evaluations map as two separate steps. If DeleteConfigRule ran in
between -- removing the rule and its evaluation bucket -- the pending
PutEvaluations call would recreate the bucket via computeIfAbsent
after the delete, orphaning evaluations under the deleted rule's name.
A later rule created with that same name would then inherit the
deleted rule's compliance details and evaluation status.

Guard the check-then-act with a per-rule monitor (ruleKey(region,
ruleName)), matching the lockFor()-keyed-monitor idiom already used by
DocDbService for the identical class of race between a tag update and
a delete.

Added a stress test racing PutEvaluations against DeleteConfigRule
across 200 attempts, then recreating the rule under the same name and
asserting a clean (INSUFFICIENT_DATA) evaluation state. It passes
under the fix; as with the earlier PutEvaluations-ordering race, it
did not reproduce RED against the pre-fix code even under that much
contention -- the race window between the existence check and the map
write is too narrow to hit deterministically without injecting an
artificial delay into production code. The fix is justified by the
non-atomic check-then-act shape itself, confirmed by reading the code.
2026-08-28 11:58:39 -04:00
Allen Sanborn 41b5148824 fix(ec2): report a reachable EIP address, and run gzipped user-data (#2621)
* fix(ec2): report an address that actually answers, and run gzipped user-data

Two independent bugs, both of which end a Terratest suite the moment it tries
to SSH into an instance.

1. The address the API reports was never an address that works. Launch set
   PublicIpAddress to 127.0.0.1 on the strength of a comment calling it
   "host-reachable", but Docker publishes the guest's SSH on a high host port,
   so :22 there is nothing. AllocateAddress then invents a 54.x.x.x that routes
   nowhere, and that is the value Terraform surfaces as aws_eip.x.public_ip and
   test suites dial. The invariant now is that whatever DescribeInstances and
   DescribeAddresses report accepts a connection on the service's real port.

   Where the container network is routable from Floci's API clients — native
   Linux Docker, OrbStack — that address is the container's own IP: port 22 is
   really port 22 there, with no published mapping to translate, and so is every
   other port the guest listens on. Where it is not — Docker Desktop, whose
   containers sit behind a VM — nothing changes and 127.0.0.1 plus published
   ports remains. Which case applies is detected, never assumed, by a throwaway
   TCP connect towards the container network: a refusal is proof of a route,
   since only the container's network stack could have sent the RST. The one
   case a probe cannot settle is Floci running inside a container itself, where
   it measures container-to-container reachability while the clients that will
   use the answer are on the host; there the Docker backend arbitrates and
   FLOCI_SERVICES_EC2_CONTAINER_IPS_ROUTABLE overrides either way.

   AssociateAddress re-points the EIP at that reachable address rather than
   leaving the fictional one. Aliasing instead would need Floci to own routing
   or DNS on the client's machine, and clients that read the address out of the
   API and dial it — Terratest does exactly this — would still get something
   dead. Association is also the first moment the answer is knowable. The cost
   is one deliberate deviation from AWS, an EIP whose public IP changes when it
   is associated; the AllocationId, AssociationId and domain are untouched, and
   disassociation restores the allocated address.

2. Gzipped cloud-init user-data was skipped in silence. The launch path
   recognised a literal "#!" or a plaintext MIME boundary and nothing else, so
   data.cloudinit_config { gzip = true } — the documented way to pass multipart
   user-data — was dropped whole. The instance booted fine and was simply
   missing everything it was supposed to install, which is what made this
   expensive to find. UserData is now unwrapped through gzip, base64, and
   base64-of-gzip before the existing shellscript/MIME handling, and the "no
   executable parts" line is a WARN that says what the consequence is.

* fix(ec2): re-resolve an associated EIP's address on DescribeAddresses

Association can happen before the instance has a container, and Docker hands out
a different bridge IP after a stop/start; either leaves the association naming an
address that no longer answers. DescribeAddresses is the call Terraform refreshes
public_ip from, so it is the last chance to be right.

* test(ec2): cover EIP re-pointing on associate, describe and disassociate

The address rewrite had no test of its own: reverting pointAddressAtInstance
left every existing test green, so nothing was holding the behaviour in place.
These three assert the claim directly — association reports the reachable
address rather than the invented 54.x.x.x one, DescribeAddresses re-resolves it
after the container IP moves, and disassociation hands the allocation back.

* docs(ec2): document container-IP routability and the EIP address rewrite

FLOCI_SERVICES_EC2_CONTAINER_IPS_ROUTABLE was undocumented, and the IMDS table
still promised public-ipv4 always returns 127.0.0.1. The Elastic IP section now
states the one deliberate deviation from AWS — an associated EIP's public IP is
rewritten to something reachable — so it is not discovered by surprise.

* fix(ec2): bound gzipped UserData decompression to stop a heap-exhaustion DoS

GZIPInputStream#readAllBytes() materialized the full decompressed
UserData with no size limit, so a caller-controlled gzip stream (e.g.
via CreateLaunchConfiguration) could expand to gigabytes in the shared
emulator JVM. Bounds it the same way AwsJsonCborController.decodeBody
already does: read in chunks, discard and warn past 10 MB decompressed.

Also documents the container-ips-routable override in both the main
and test application.yml templates, alongside the other ec2 keys.

* fix(ec2): bound aggregate concurrent UserData gzip decompression

The per-payload 10MB decompression cap runs independently per launch
on the unbounded cached launch executor, so it only bounds what a
single launch can allocate. N concurrent RunInstances/
CreateLaunchConfiguration calls, each smuggling a near-cap gzip
payload, could together decompress N * 10MB at once with no aggregate
ceiling.

Add a shared Semaphore(4) that gunzip must acquire before
decompressing and release afterward, budgeting ~40MB of decompressed
UserData in flight at a time - a few multiples of the per-payload cap
rather than 1, so an ordinary burst of legitimate concurrent launches
isn't serialized to one at a time. A launch that can't acquire the
budget blocks briefly rather than failing, mirroring the existing
ContainerLauncher.POPULATE_SEMAPHORE pattern for capping concurrent
code-volume populates.

Adds a concurrency test that drives 12 real concurrent launches with
near-cap gzip UserData through a fixed thread pool and asserts, via a
test-only hook, that peak concurrent decompressions never exceeds 4.
Verified the test fails (peak of 12) when the budget is disabled.
2026-08-28 11:35:06 -04:00
Sam Fakhreddine c96dc98065 feat(s3): opt-in global bucket namespace and replication config (#2640)
* feat(s3): bucket replication configuration round-trip

PUT/GET/DELETE ?replication store the replication configuration verbatim
(validated for a Role and at least one Rule with a Destination/Bucket)
instead of falling through to CreateBucket. Storage-only fidelity — floci
performs no actual replication. Split from a cross-service commit; the IAM
password-policy and CloudFormation SSM-parameter changes ship separately.

* fix(s3): resolve buckets cross-account under a global bucket namespace

S3 bucket names are globally unique in AWS: a bucket lives in one account but is
legitimately reachable cross-account. floci's per-account isolation broke LZA,
which has member accounts read/write a management-owned shared assets bucket and
runs cross-account custom resources (e.g. Custom::S3PutBucketReplication) whose
Lambda calls back under a different account context than the bucket's owner.

Add an opt-in globalBucketNamespace mode (default off, preserving isolation):
bucket/object existence RESOLUTION spans every account's partition while LISTING
stays owner-scoped. Reads route through resolveBucket/resolveObject; bucket-config
MUTATIONS route through a new owner-aware mutateBucket helper that resolves the
owning account via AccountAwareStorageBackend.findAnyAccountEntry and writes back
to the owner's partition (putForAccount) rather than forking a phantom bucket into
the caller's partition. Applied to put/deleteBucketReplication — the path LZA's
Logging stage exercises cross-account.

* test(s3): guard getObject against torn reads under concurrent overwrite

LZA's Bootstrap stage fans out ~15 CodeBuild actions that redundantly re-upload
the same artifact keys (Source.zip/Config.zip) while other builds concurrently
download them. A non-atomic truncate-then-write would let a reader observe an
empty/partial object — which surfaced as an empty src-Config secondary source and
ENOENT: global-config.yaml. Add a stress test (4 writers / 4 readers) asserting
getObject never returns a torn view of a constant-size key.

* docs(s3): document the global bucket namespace flag

Describe FLOCI_SERVICES_S3_GLOBAL_BUCKET_NAMESPACE in s3.md, the
multi-account isolation exception, and the environment-variable reference.

* feat(s3): account-level Block Public Access (s3control PublicAccessBlock)

Add account-scoped PUT/GET/DELETE PublicAccessBlock to the s3control
controller, keyed by the x-amz-account-id header and stored separately
from the bucket-level configuration. LZA's Custom::PutPublicAccessBlock
custom resource calls this account-level op while building the
LoggingStack; without a route the resource reported FAILED and the
stack rolled back (NoStack on CDK readback).

(cherry picked from commit a1cdf186ac7909647350ced455c4e0ba5d2d26a0)

* fix(s3): persist account-level Block Public Access

The account-level (s3control) PublicAccessBlock configuration was held in a
plain ConcurrentHashMap, bypassing StorageFactory while every other piece of
S3 state goes through it. Block Public Access is a security control, and LZA's
Custom::PutPublicAccessBlock runs once per governed account during the
LoggingStack deploy — it does not re-run on a resumed pipeline. A restart
therefore dropped the control silently and every governed account started
reporting NoSuchPublicAccessBlockConfiguration.

Move it to a StorageFactory-backed store (s3-account-public-access-block.json)
addressed through the explicit *ForAccount overloads, so the account comes from
the validated x-amz-account-id header and globalBucketNamespace never widens it.
The s3 descriptor already declares storageKey/storageMode, so no catalog change
is needed and PersistentPathValidator now covers this state.

clear() no longer wipes the config: like the bucket and object stores, its
lifecycle belongs to StorageFactory.clearAll().

* fix(s3): check x-amz-account-id against the caller on Block Public Access

The account-level PublicAccessBlock operations took the account solely from the
x-amz-account-id header, which was only checked for being non-blank. Any caller
could read, overwrite or delete any account's Block Public Access configuration
by setting one header — and Block Public Access is a security control.

AWS s3control answers AccessDenied when the header does not name the caller's
own account: there a cross-account call carries credentials assumed into the
target account, so header and caller always agree. Compare the header against
the caller's resolved account and return the same AWS-shaped AccessDenied (403)
on a mismatch, resolving the caller exactly as AccountAwareStorageBackend does
so the check and the storage partition can never disagree.

One exception is kept deliberately: the configured default (management) account
may act on any account, because Floci's launched Lambdas run on placeholder
credentials that resolve to the management account instead of assuming a role in
the target account. Without it LZA's Custom::PutPublicAccessBlock — the reason
these operations exist — would be denied for every governed account. This is the
same allowance S3Service.mutateBucket already makes for
Custom::S3PutBucketReplication.

Enforcement is scoped to the three PublicAccessBlock routes; the tag routes on
this controller accept and ignore the header as before.

* docs(s3): state the global bucket namespace trade-off explicitly

No behaviour change. The flag widens bucket resolution across accounts, which
reads as an account-isolation violation to a reviewer working from a checklist.
Say the intent in place, on the config option and in the S3 guide: S3 bucket
names are globally unique in AWS, a bucket lives in one owning account, and
cross-account access is a policy decision — so a hard per-account partition
models a state AWS cannot reach and fails legitimate cross-account calls with
NoSuchBucket. Record what it costs too: with the flag on, only IAM and bucket
policy stand between a caller and another account's object. Mutations still
write back to the owning account and listing stays owner-scoped, and the flag
is off by default.

* fix(s3): keep the account-aware bucket replication over the upstream #2519 duplicate

Upstream landed its own Put/Get/DeleteBucketReplication (ce4f6d1c4), which
duplicated the branch implementation. The branch copy stays because it goes
through mutateBucket (the caller-scoped mutation the LZA
Custom::S3PutBucketReplication path requires) and validates Role, Rule and
Destination/Bucket; upstream's root-element MalformedXML check is folded
into it so nothing upstream tested is lost. Duplicate Bucket field and
accessors removed.

* fix(s3): enforce the modeled AccountId pattern and ReplicationRule status enum

Account-level Block Public Access took x-amz-account-id as its storage
partition key after only a blank check, so a value outside the s3control
AccountId shape (^\d{12}$) filed a security configuration under a partition
no account could address again.

PutBucketReplication stored the document after checking only that a Role, a
Rule and a Destination/Bucket were present, so a rule with a missing or
out-of-enum Status round-tripped through GetBucketReplication as a document
AWS would have rejected. Both now answer the error the operation already
uses for its other input guards.

* fix(s3): resolve GetBucketReplication cross-account under the global bucket namespace

putBucketReplication and every other bucket-config mutation resolve cross-account
through mutateBucket/resolveBucket when globalBucketNamespace is enabled, but
getBucketReplication still called bucketStore.get(bucketName) directly. A
management-account caller could write a bucket's replication configuration
cross-account (mirroring LZA's Custom::S3PutBucketReplication path) but a
follow-up GetBucketReplication under the same caller saw NoSuchBucket instead of
the configuration it just stored.

RED test: getBucketReplicationResolvesCrossAccount in
S3GlobalBucketNamespaceTest failed with NoSuchBucket before this change.

* fix(s3): validate each replication rule's own destination bucket

PutBucketReplication checked that at least one Bucket appeared anywhere in the
document, then validated only Status per rule. A multi-rule document where only
one rule carried a Destination/Bucket satisfied that document-wide check and
round-tripped through GetBucketReplication as a configuration AWS would have
rejected as MalformedXML.

Destination elements appear in the same document order as their owning Rule
(extractGroupsMulti can't see nested Destination/Bucket as a Rule leaf), so
pairing the Destination list position-for-position with the Rule list and
requiring an equal count plus a non-blank Bucket in each enforces that every
rule carries its own destination.

RED test: putReplicationRejectsARuleWithoutItsOwnDestinationBucket in
S3ReplicationConfigurationIntegrationTest got 200 instead of 400 before this
change.

* fix(s3): remove unreachable duplicate ?replication dispatch

The PUT and GET handlers each had two identical `if (hasQueryParam(uriInfo,
"replication"))` branches — a rebase artifact. The earlier branch in each
method always returns first, so the second was dead code that risked a future
routing change updating only one copy.

* docs(s3): expose global-bucket-namespace in the canonical application.yml

globalBucketNamespace() was documented in EmulatorConfig and in
docs/services/s3.md but absent from the s3 block in both application.yml
files, leaving the runtime configuration surface out of sync with what the
code and docs describe.

* test(s3): assert torn-read stress threads actually finish

The writer/reader threads were joined with a 30s timeout but never checked for
liveness afterward. A thread still running past the timeout could leak past
the test (hanging the suite) or let the assertions pass vacuously without that
thread's reads or writes having completed.

* fix(s3): reject malformed PutPublicAccessBlock bodies

s3control's PutPublicAccessBlockRequest requires PublicAccessBlockConfiguration,
but the controller normalized any body — null, empty, unparseable, or a
different root element entirely — into a valid configuration with every flag
defaulted to false via canonicalPublicAccessBlockXml. For an account-level
Block Public Access control, that silently disabled every protection on a bad
request instead of failing it.

Reject a body whose root element is not PublicAccessBlockConfiguration with
the same MalformedXML the bucket-level replication path already uses for this
class of error, before normalization runs.

RED test: putRejectsAMalformedOrWrongRootBody in
S3ControlAccountIdEnforcementTest got 200 instead of 400 before this change.

* fix(s3): validate replication destinations against their own rule, not the document total

Counting Rule and Destination elements document-wide and requiring the totals to match let a
rule with two Destinations balance a rule with none, satisfying the check while storing a
configuration AWS would reject as MalformedXML. Destination is Required: Yes directly on Rule, so
PutBucketReplication now walks the parsed element tree and requires each Rule to have exactly one
Destination of its own with a non-blank Bucket, instead of comparing counts across the whole
document.

* fix(s3): reject a replication destination with multiple Bucket elements

Destination.Bucket is a required scalar member (botocore
s3/2006-03-01/service-2.json: "Bucket":{"shape":"BucketName"}), not a list.
child("Bucket") returns only the first match, so a Destination with two Bucket
children silently accepted the first and stored a document AWS would reject
as MalformedXML.

Count the Bucket children explicitly and require exactly one, instead of
taking child("Bucket")'s single match unconditionally.

RED test: putReplicationRejectsADestinationWithMultipleBucketElements in
S3ReplicationConfigurationIntegrationTest got 200 instead of 400 before this
change.

* fix(s3): wire bucket-policy operations through cross-account resolution

getBucketPolicy/putBucketPolicy/deleteBucketPolicy still resolved via
bucketStore directly, unlike object read/write and replication, so a
management-account caller got NoSuchBucket on a member-owned bucket's
policy even with the global bucket namespace enabled. Route them
through resolveBucket/mutateBucket like the rest of the cross-account
paths, and document the IAM-enforcement dependency and the same-name
non-determinism case in the trade-off writeup.

* docs(s3): name the flag that actually gates bucket-policy evaluation

The trade-off write-up said global-bucket-namespace's IAM/bucket-policy
protection depends on FLOCI_SERVICES_IAM_ENFORCEMENT_ENABLED, but that flag
only gates identity-policy checks in IamEnforcementFilter before a request
reaches S3 — bucket-policy evaluation itself (S3Service.authorizeS3Read/
authorizeS3Write, which reads the stored bucket policy) is gated separately
by FLOCI_SERVICES_S3_ENFORCE_AUTH, which also defaults false. Name both
flags and make explicit that the S3-specific one is what actually turns
bucket-policy evaluation on or off.
2026-08-28 11:24:47 -04:00
Allen Sanborn f1ad306599 fix(ec2): round-trip launch template data instead of discarding it (#2595)
* fix(ec2): round-trip launch template data instead of discarding it

CreateLaunchTemplate returned 200 and kept only ImageId, InstanceType,
KeyName, UserData, IamInstanceProfile, SecurityGroupIds and
TagSpecifications. Every other member of RequestLaunchTemplateData was
dropped without a word, so Terraform read back its own input missing and
reported "Provider produced inconsistent result after apply", or diffed
forever. MetadataOptions with HttpTokens=required (IMDSv2) and
BlockDeviceMappings appear in most Gruntwork ASG and ECS modules.

The AWS EC2 service model is the reference for what is stored and for the
element names it is read back under: request parameter names are the ones
botocore's EC2 serializer emits (note the singular BlockDeviceMapping.N
and NetworkInterface.N list prefixes, taken from each list member's
locationName), and response elements use ResponseLaunchTemplateData's
locationNames.

Stored and read back unchanged: ImageId, InstanceType, KeyName, UserData,
KernelId, RamDiskId, SecurityGroupIds, IamInstanceProfile,
BlockDeviceMappings, NetworkInterfaces, TagSpecifications, MetadataOptions,
Monitoring, Placement, CpuOptions, CreditSpecification, EnclaveOptions,
HibernationOptions, MaintenanceOptions, PrivateDnsNameOptions,
CapacityReservationSpecification, EbsOptimized, DisableApiTermination,
DisableApiStop, InstanceInitiatedShutdownBehavior.

Two further contradictions in the same call, both fixed:

- IamInstanceProfile keeps the form it was given. A profile submitted as
  Name reads back as Name rather than being rewritten to an Arn, so
  aws_launch_template.iam_instance_profile.name converges. The
  instance-profile ARN is derived at launch time instead.
- NetworkInterfaces survives as a NetworkInterfaces block. Its Groups are
  no longer hoisted into top-level SecurityGroupIds; on AWS the two are
  mutually exclusive, and the promotion made the block vanish from state.
  A launch resolves security groups from whichever of the two is set.

Deliberately out of scope, accepted and ignored rather than rejected:
InstanceMarketOptions, InstanceRequirements, LicenseSpecifications,
ElasticGpuSpecifications, ElasticInferenceAccelerators,
NetworkPerformanceOptions, Operator, SecondaryInterfaces, and
SecurityGroups (groups by name). Within NetworkInterfaces the IPv4/IPv6
address and prefix lists, EnaSrdSpecification,
ConnectionTrackingSpecification, PrimaryIpv6 and EnaQueueCount are also
ignored. A focused subset that round-trips beats a broad partial one.

LaunchTemplate no longer mirrors launch data in flat fields alongside its
version map; it holds one LaunchTemplateData, which removes the
dataFrom/applyData sync and collapses two 11-argument service methods into
a parameter object with explicit merge semantics for version creation.

Fixes a compatibility defect this collapse introduced (flagged by review):
a template persisted before this change stored the IAM instance profile as
a bare iamInstanceProfileArn string and instance tags as a flat
instanceTags list, both directly on LaunchTemplate and, separately, inside
each entry of its versions map. Neither key exists on the new model, so
ignoreUnknown silently dropped both on load - an upgrade would launch from
an existing template with no IAM profile and no instance tags, with
nothing in the logs to say so.

Legacy @JsonSetters on LaunchTemplateData and LaunchTemplate map both old
keys onto the new shape at load time, covering the versions-map entry (the
path DescribeLaunchTemplateVersions and AutoScaling actually read) and the
top-level fields (the path a template with no versions map falls back to).
Deserialize-only, so a file saved by the current code never regains the
old shape. Ec2ServicePersistenceTest#legacyIamProfileAndInstanceTagsSurviveRestart
seeds a hand-built pre-migration ec2-launch-templates.json and asserts both
paths survive a restart; reverting the two model changes alone fails it.

* fix(ec2): correct SourceVersion inheritance and round-trip VersionDescription

Addresses review feedback on the prior commit:

- CreateLaunchTemplateVersion with SourceVersion omitted merged onto the
  latest version instead of following the AWS-documented "no source
  specified, no inheritance" behavior. A version created without
  SourceVersion now starts from an empty LaunchTemplateData, populated
  only by whatever fields the request itself supplies.
- VersionDescription was accepted and silently dropped. It is a
  version-level field on LaunchTemplateVersion, not a member of
  RequestLaunchTemplateData, so it is tracked in a parallel per-version
  map on LaunchTemplate (alongside VersionNumber, CreateTime) rather than
  inside LaunchTemplateData, and round-trips through
  DescribeLaunchTemplateVersions. CreateLaunchTemplate accepts the same
  field for the initial version.
- SecurityGroups (security groups by name) stays out of scope: resolving
  names to IDs would need lookup machinery - store scan, not-found
  handling, ambiguity across VPCs - that no other EC2 action here has
  either (RunInstances itself only accepts SecurityGroupId). Documented
  the reasoning in both the code and docs/services/ec2.md so the ignored
  list stays accurate now that SourceVersion and VersionDescription are
  handled correctly.
2026-08-28 11:08:52 -04:00
Kenshin Okinaka 2963601f69 feat(ses): support v2 tenant CRUD (CreateTenant/GetTenant/ListTenants/DeleteTenant) (#2644)
* feat(ses): support v2 tenant CRUD (CreateTenant/GetTenant/ListTenants/DeleteTenant)

Add the first phase of SES v2 multi-tenancy: tenant create/get/list/delete via the
RPC-style POST routes under /v2/email/tenants. A new SesTenantService owns the tenant
store, id/ARN generation (tn-<hex>, arn:aws:ses:<region>:<account>:tenant/<name>/<id>),
the ENABLED sending status, and the TenantName validation (1-64 chars [A-Za-z0-9_-],
duplicate -> AlreadyExistsException, unknown -> NotFoundException); the facade delegates
and the controller only parses/renders. Resource associations, tenant suppression, and
tenant-scoped sending are follow-ups.

* docs(ses): correct account-scoping description in SesTenantService Javadoc
2026-08-28 11:03:12 -04:00
Sam Fakhreddine c90c5adfcb feat(lambda): code-signing endpoints and account settings (#2646)
* feat(lambda): GetAccountSettings with usage-derived account limits

Adds the Lambda GetAccountSettings operation. AccountUsage (total code
size and function count) is derived from the caller's stored $LATEST
functions in the region; AccountLimit reports the configured regional
concurrency limit and its unreserved share after per-function reserved
concurrency.

* fix(lambda): widen the default Runtime API port pool to 12000-12499

One Runtime API port is held for the lifetime of each running Lambda
container, so the width of the range is a hard ceiling on concurrent
Lambda executions. The old default of 9200-9299 gave 100, which a
multi-account AWS Landing Zone Accelerator deployment exhausts: it fans
out several custom-resource Lambdas per account and can want well over
a hundred at once.

Exhaustion did not announce itself as a capacity limit either. The
custom resource reported FAILED and CloudFormation rolled the stack
back, so an operator saw an apparently unrelated CloudFormation error
with no hint that a port pool was the cause.

12000 rather than a widened 9200 because the old range's tail collides
with ports floci and its sidecars already use: 9200 is OpenSearch's own
REST port, 9400-9499 is the OpenSearch host-binding pool, 9092 is Kafka
and 9644 Redpanda's admin port.

Both application.yml and the @WithDefault annotation are updated.
application.yml is a config source, not a set of defaults, so a value
set there wins over the annotation; changing only the annotation would
have been a silent no-op (issue #2225). The new test asserts the two
agree, so they cannot drift apart again.

Refs #2206

* fix(lambda): make the Runtime API port-pool exhaustion error self-describing

The old message did not name the pool, its width, or the property that
widens it. It also rarely reaches an operator directly: the Lambda
failure surfaces as a custom resource reporting FAILED and
CloudFormation rolling the stack back, so this text is buried in
floci's own log alongside a CloudFormation error that looks unrelated.

The message now carries its own diagnosis — which pool ran dry, how
many ports it had, that one port is held per running container so this
is the concurrent-execution ceiling, and the two properties that widen
it. Previously the only way to learn those knobs existed was to find
this class in the source.

Refs #2206

* feat(lambda): add ListFunctionsByCodeSigningConfig

Net-new endpoint, GET /2020-04-22/code-signing-configs/{arn}/functions,
always returns an empty FunctionArns list since this codebase has no
CodeSigningConfig management (no Create/PutFunctionCodeSigningConfig),
so no function can ever actually have one attached.

Implemented as its own controller class with its own class-level
@Path("/2020-04-22") rather than folding it into the existing
LambdaCodeSigningController (/2020-06-30): a JAX-RS class-level @Path
is load-bearing for route-matching priority, and stripping it to share
one class across two API-version prefixes causes both endpoints to
fall through to a more general catch-all route elsewhere in the app.

* fix(lambda): scope code storage, publish-version counters, and S3 sync-reload to the owning account

CodeStore resolved extracted code to baseDir/<functionName> with no account
segment, so two accounts' same-named functions in one region shared a single
on-disk directory and overwrote each other's package -- while codeObjectKey
already wrote the same package to an account-prefixed S3 key. Cross-account
invoke resolves a function by the ARN's own account, so a collision here
silently serves one account's code under the other's ARN.

The PublishVersion counter was keyed region+"::"+functionName and the delete
path removed that same unscoped key; both now key on the owning account, via
the shared ownerAccount() helper the S3 key already used.

onS3ObjectUpdated runs on the CDI event thread with no RequestContext, so its
ambient scan only ever saw the default account's partition and its save wrote
back into that partition. It now lists across every account (keeping the region
and $LATEST filters) and saves into the function's own account. listAll(), whose
only caller is the startup concurrency rehydration, is broadened the same way so
a restart no longer drops non-default accounts' reserved concurrency.

Recovered from 613db7bd1, re-derived onto upstream's current shape: CodeStore's
methods are re-signed rather than overloaded (the unscoped forms had no
remaining consumer), and the sync-reload uses a new region-filtered
listAllAccounts() instead of widening listAll() at that call site.

* fix(lambda): carry persisted version counters across the account-scoped key change

The counter map is persisted precisely so a restart cannot re-issue a version
number that already names a snapshot. Re-keying it on the owning account made
every pre-existing entry unreachable, so the next PublishVersion on an upgraded
deployment would have started again at 1 and overwritten the live :1 snapshot.
The counter now adopts and clears the pre-account key on a miss, and deleting a
function clears both forms.

Also covers the widened listAll(): the reserved-concurrency pool is per region
and shared across accounts, so the startup rehydration that feeds it has to see
every account or a restart silently frees capacity that steady-state
PutFunctionConcurrency had already accounted for.

* fix(lambda): validate CodeSigningConfigArn on ListFunctionsByCodeSigningConfig

The handler took @PathParam("codeSigningConfigArn") and never read it, so any
input — including "not-an-arn" — got a 200 with an empty FunctionArns array.
It also dropped the modeled Marker/MaxItems query parameters.

Botocore models InvalidParameterValueException (400) and
ResourceNotFoundException (404) for this operation, and carries a pattern on the
CodeSigningConfigArn shape:

  arn:(aws[a-zA-Z-]*)?:lambda:[a-z]{2}((-gov)|(-iso(b?)))?-[a-z]+-\d{1}
  :\d{12}:code-signing-config:csc-[a-z0-9]{17}

(max 200 chars). That pattern is now applied verbatim, whole-string.

The 404 for a well-formed ARN is a derivation, not an observation against real
AWS: ResourceNotFoundException is modeled for this operation, the only resource
the path parameter can name is a code-signing config, and Floci implements no
CreateCodeSigningConfig / PutFunctionCodeSigningConfig — therefore every
well-formed ARN necessarily names a config that does not exist. The previous
always-empty 200 asserted the opposite (config exists, has no functions), which
is the stronger and false claim.

Validation order matches AWS: ARN shape, then MaxItems range (botocore
MaxListItems: min 1, max 10000), then resource resolution — so a bad MaxItems is
reported as such instead of being masked by the not-found. Marker is accepted
and stateless: the result set is always empty, so no NextMarker is ever emitted.

The pre-existing test asserted the 200-empty behaviour using an ARN whose csc-
suffix was 9 characters, which the model's pattern rejects; it is replaced by six
cases covering the two error classes and both MaxItems bounds.

docs/services/lambda.md's two "always empty" claims are corrected to match.

* docs(lambda): derive the operation count from the routed operations

The branch adds two operations (GetAccountSettings and
ListFunctionsByCodeSigningConfig) but bumped docs/services/index.md by one,
30 -> 31. Rather than hand-correcting to 32, the count was re-derived from the
routes, because 30 could not be reconstructed from anything in the tree.

index.md's own preamble states the rule for REST services: "the count reflects
distinct AWS SDK operations, collapsing routes where one JAX-RS handler fans out
via query-string or header markers". Counting JAX-RS methods across the Lambda
controllers on upstream/main gives:

  LambdaController              24
  LambdaConcurrencyController    3
  LambdaEventInvokeController    5
  LambdaLayerController          5
  LambdaTagController            3
  LambdaUrlController            4
                                --
                                44

Two collapses applied. LambdaCodeSigningController's /2020-06-30 route and
LambdaController's /2015-03-31 route are the same SDK operation
(GetFunctionCodeSigningConfig) and count once. LambdaUrlInvocationController (5)
and the lambda-package ApiGatewayController (5) are data-plane proxies with
{proxy: .*} catch-alls, not Lambda SDK operations, so they are excluded.

44 + GetAccountSettings + ListFunctionsByCodeSigningConfig = 46.

Corroboration that 44 is the real base and 30 is drift: docs/services/lambda.md's
Supported Operations table lists 34 rows on upstream/main and omits exactly the
5 layer and 5 event-invoke operations — 34 + 10 = 44. Those 10 missing table rows
are pre-existing and left alone here; only the count is in scope.

* fix(lambda): match the current CodeSigningConfigArn pattern for isolated partitions

The inlined regex predated the model's (eusc-)? prefix and widened -iso(b?)
alternation, so a well-formed ARN in aws-iso-e/iso-f or the European sovereign
cloud was rejected as malformed instead of reaching the modeled 404.

* fix(lambda): validate FunctionName length, Role ARN, and Handler on config paths

botocore models FunctionName up to 256 chars with dots allowed in the name
segment; LambdaArnUtils rejected dots and never bounded length. Also close
the gap where UpdateFunctionConfiguration accepted a malformed Role ARN or a
whitespace-containing/oversized Handler and stored it verbatim.

* fix(lambda): close leaked directory-listing streams and block dot-segment traversal in CodeStore

Files.walk/Files.list returned streams that were never closed, leaking file
descriptors and making delete() flaky on platforms that refuse to remove an
open file. Separately, sanitizeName replaced disallowed characters but let a
segment consisting entirely of dots (".", "..") pass through untouched, so an
account or function name of exactly ".." resolved outside baseDir via
Path.resolve instead of being rejected.

* fix(lambda): reclaim pre-account-scoped code directories on delete and update

A function created before code storage was account-scoped left its extracted
code at <codePath>/<functionName>. DeleteFunction only ever targeted the new
<codePath>/<accountId>/<functionName> path, and UpdateFunctionCode re-extracted
to the new path without touching the old one, so the legacy directory (and its
disk usage) lingered indefinitely after either operation. CodeStore now also
clears the legacy path on delete, and re-extraction reclaims it on success.

* fix(lambda): reject an explicit null Handler on UpdateFunctionConfiguration

validateHandler treated null as "clear the handler", matching how Description
is handled, but null is not a string at all -- and unlike Description, Handler
names the file AWS invokes. A request with "Handler": null silently cleared it
instead of failing with a 400, which would have broken every subsequent
invocation of the function instead of the one bad request that caused it.

* fix(lambda): do not reclaim a legacy code directory another account's function still uses

The pre-account-scoped layout gave every account's same-named function the
exact same on-disk directory. CodeStore.delete() and code re-extraction both
reclaimed that legacy directory unconditionally once a function migrated to
the account-scoped path, so a delete or code update in one account could
destroy the legacy directory while another account's never-migrated $LATEST
still served invocations from it -- its next cold start would then fail with
a missing code directory.

CodeStore.delete() no longer touches the legacy path at all; only
LambdaService calls deleteLegacy() explicitly, after checking every account's
$LATEST functions (via the existing cross-account listAllAccounts) for one
still pointing its codeLocalPath at that directory.

* fix(lambda): check published versions, not just $LATEST, before reclaiming a legacy code directory

publishVersion snapshots codeLocalPath verbatim (required so a version-qualified
invoke doesn't launch a container with no code, #1987), so a version published
while $LATEST was still on the pre-account-scoped legacy path keeps that
directory alive on its own after $LATEST migrates. The unused-check only
scanned $LATEST records via listAllAccounts(region), so a later delete or code
update reclaimed the directory out from under that published version's own
future invokes. Switched to functionStore.listAll(), which has no $LATEST or
region filter, matching the fact that the legacy path itself carries neither.

* fix(lambda): close a publish-vs-legacy-cleanup race on the code directory

publishVersion read codeLocalPath and persisted a snapshot of it with no
synchronization against extractZipCodeBytes's/deleteFunction's decision to
reclaim the pre-account-scoped legacy code directory (added in bede98fc1 and
f3837be32). A version could be published in the narrow window between that
decision (finding no live reference) and the actual delete, persisting a
snapshot whose codeLocalPath names a directory that is about to be removed --
its own future invocation would then fail with "Code directory not found".

publishVersion and the reclaim call in extractZipCodeBytes now both take the
same per-function lock deleteFunction already used for this. Proven with a
test that holds the lock externally and asserts publishVersion blocks until
it is released, rather than relying on timing to catch the race in the act.
2026-08-28 10:52:53 -04:00
takahiro 64c38c77b9 feat(s3): apply VersioningConfiguration in CloudFormation S3 bucket provisioning (#2626) 2026-08-28 10:36:25 -04:00
Matan Baruch 277809fb41 feat(aps): add Amazon Managed Service for Prometheus workspaces (#2604)
* feat(aps): add Amazon Managed Service for Prometheus workspaces

Implements the AMP workspace lifecycle (CreateWorkspace,
DescribeWorkspace, ListWorkspaces, UpdateWorkspaceAlias,
DeleteWorkspace) plus tagging through the shared /tags/{resourceArn}
dispatcher via a TagHandler with service key aps. Previously the aps
service did not exist, so aws_prometheus_workspace could not be created
through Terraform or Pulumi at all.

Workspaces are ACTIVE from birth so the provider's create waiter
(CREATING to ACTIVE) completes on its first DescribeWorkspace poll, and
a deleted workspace answers DescribeWorkspace with the typed
ResourceNotFoundException its delete waiter matches. createdAt is
serialized as restJson1 epoch-seconds; the ListWorkspaces alias
parameter is a prefix filter, matching the provider's alias_prefix.

clientToken is accepted and ignored, kmsKeyArn is stored and echoed,
and no alertmanager/rulegroups/scraper/logging operations are included.

* refactor(aps): build ARNs via RegionResolver and parse tag ARNs with AwsArnUtils

Replaces the inlined AwsArnUtils.Arn.of + config.defaultRegion pair with
regionResolver.getRegion()/buildArn so a request signed for another
region gets an ARN and endpoint in that region, and drops the
EmulatorConfig dependency that existed only for that getter. The tag
dispatcher path now parses ARNs with AwsArnUtils.parse plus an explicit
workspace/ prefix check (the SchedulerTagHandler idiom), so a
non-workspace aps ARN fails with ValidationException instead of a
misleading workspace ResourceNotFoundException. Also makes the delete
and alias mutators void (their returns were unused) and removes a dead
DELETING status mutation.

* docs(aps): map the aps service key to managed-prometheus.md in the service matrix

The docs-check gate matches ResolvedServiceCatalog external keys against
docs/services/index.md rows by filename; aps is documented at
managed-prometheus.md, so it needs the same alias treatment as
kafka -> msk.

* fix(aps): partition workspaces by request region and align minor wire details

Review follow-ups from #2604:

- Key the workspace store by region (region::workspaceId, like
  CloudWatchLogsService's groupKey), and thread the SigV4-resolved request
  region through every lifecycle and TagHandler operation, so workspaces
  created in one region are invisible to describe/list/delete/tag calls
  served in another. Covered by unit and HTTP region-isolation tests.
- Default ListWorkspaces to pages of 100 (AWS's documented default) while
  keeping the 1000 ceiling, via Pagination's seven-argument overload.
- Strip leading/trailing blanks from aliases at create, alias update, and
  the list prefix filter, per the documented normalisation.
- Return DeleteWorkspace's 202 with an empty body instead of {}.
- Reject tag keys beginning with the reserved aws: prefix in TagResource
  with a ValidationException.

* refactor(aps): align the reserved tag-key check with sibling services

- Match the aws: prefix case-insensitively as a plain loop, the same idiom
  as FisService and BatchService, instead of a case-sensitive stream chain.
- Derive key() from keyPrefix() so the :: separator lives in one place, and
  hoist the region prefix out of the scan predicate.
- Replace the two near-identical SigV4 Authorization literals in the
  integration test with an auth(region) helper.
2026-08-28 10:05:42 -04:00
武田隆志 29325006bb fix(appsync): use ApiKey.id as the API key value (#2645)
CreateApiKey returned a short random id and kept the value the execute
endpoint validates in a non-model apiKey field, which the AWS CLI and SDKs
drop. On AWS the id itself is the da2- key value sent as x-api-key, so make
id that value, validate against it, and drop the extra field. Keys persisted
by earlier builds keep their short id, stay listable and deletable, and never
authenticate (as before).
2026-08-28 09:59:42 -04:00
Michal SchreiberandPriamo Germosen 3b0e31b888 fix(rds,docdb): list DocumentDB clusters and instances in the RDS-family list form (#2623)
* fix(rds,docdb): list DocumentDB clusters and instances in the RDS-family list form

The list form of DescribeDBClusters and DescribeDBInstances answered from
one store: on the rds scope from RDS, on the docdb scope from DocumentDB,
so a DocumentDB cluster was invisible to every list while its identifier
form worked. A live account lists the whole family from either endpoint.
RdsQueryHandler now assembles the list from both stores, honouring the
db-cluster-id / db-instance-id filters in each and an engine filter across
them (case-insensitive, OR over values, refused for a name outside the
family's engine list as on AWS), and the controller sends the docdb-scope
list form there too. The identifier form keeps routing to the store that
owns the identifier. Both halves list the region the request is signed
for.

Closes #2613

* fix(rds): report and filter an Aurora member instance by its Aurora engine name

DbInstance collapsed aurora-postgresql and aurora-mysql onto the community
engine enum, so a cluster member reported Engine postgres and the engine
filter matched it as postgres, where a live account says and matches
aurora-postgresql. Keep the engine name the request gave (or the
cluster's, for a member created without one) on the instance, and read it
for both the Engine element and the filter; a record persisted before the
field existed falls back to the enum.

* fix(rds): give a persisted instance its engine name on restore

An instance written before engineIdentifier existed deserializes with it
null, and a runtime fallback to the enum would keep reporting an Aurora
member as postgres. Backfill it in restorePersistedRuntime from the state
that knows: the member's cluster for a member, the enum for a standalone
instance.

* fix(rds): never persist a guessed engine name for a member of a nameless cluster

A cluster persisted before its own engineIdentifier existed (#1829) has
none to hand down, and writing the member's enum in that case would store
postgres for what may be an Aurora member — a guess that outlives the
code able to tell. The backfill writes only what is certain: the
cluster's stored name for a member, the enum for a standalone instance;
a member of a nameless cluster is left unset.

* fix(rds,neptune): list Neptune clusters and instances in the RDS-family list form too

A live account lists a Neptune cluster from the rds, docdb and neptune
endpoints alike and selects it with engine=neptune. The list form now
merges Neptune rows the way it merges DocumentDB ones, and the neptune
scope's list form goes to the same assembly. The Neptune store is not
keyed by region, so its rows are scoped to the request's region by ARN.

* fix(rds): close the subnet-group tags test in rds.bats

---------

Co-authored-by: Priamo Germosen <6233424+pgermosen@users.noreply.github.com>
2026-08-28 09:37:29 -04:00
Sam Fakhreddine 7188b3ec9d feat(iam): enforce SCPs and populate aws:PrincipalArn during policy evaluation (#2637)
* feat(iam): enforce service control policies during policy evaluation

Service control policies from the caller's organization now gate IAM
policy evaluation. CallerContext carries an optional list of SCP levels
(root, each OU on the account's path, then the account); the evaluator
requires an explicit allow and no explicit deny at every level before
identity policies are consulted. SCPs never grant permissions on their
own.

The ceiling applies to evaluate() only. IamEnforcementFilter is the
single producer of SCP levels, so simulatePrincipalPolicy and the
AppSync GraphQL IAM-auth path (IamAuthValidator) evaluate without one.
Both are explicit non-goals rather than oversights: giving them a
ceiling would require IAM to resolve the principal's organization,
which is the dependency ScpProvider exists to avoid. The coarse AppSync
request is still bounded by the filter ahead of the resource; only the
field-level check runs outside it.

The new ScpProvider interface keeps the dependency direction clean:
OrganizationsService implements it and IamEnforcementFilter resolves it
lazily via Instance, so IAM never depends on Organizations while
Organizations keeps using IamService for role provisioning.

Enforcement is doubly opt-in — FLOCI_SERVICES_IAM_ENFORCEMENT_ENABLED
plus FLOCI_SERVICES_ORGANIZATIONS_SCP_ENFORCEMENT_ENABLED — and the
management account is exempt, matching AWS.

* fix(iam): apply service control policies to the account-root principal

floci's account-root principal is a bare 12-digit account-id access key
(LocalStack multi-account convention). IamService.resolveCallerContext
returns null for it, so IamEnforcementFilter took the unknown-key bypass
and returned before SCP levels were ever consulted. Effect: a
DenyLeaveOrganization SCP attached to a workload OU did not stop a member
account from leaving — SCPs never applied to floci's primary
multi-account principal, unlike the AWS account root which is fully
bounded by SCPs.

Fix: when the caller has no registered identity but the account actually
has an effective SCP ceiling and the access key is the account root
(akid == accountId), synthesize an implicit full-access identity
(ROOT_ALLOW_ALL) and evaluate it against the SCP levels. Accounts with no
effective SCPs, and unknown AKIA keys, keep the historical bypass.

Strictly more enforcement, gated behind two opt-in flags
(iam.enforcement-enabled + organizations.scp-enforcement-enabled, both
default off), so the LZA campaign and existing bare-account behavior are
unaffected.

Known flag-flip caveats (both are correct SCP semantics, documented here
for operators enabling enforcement):
- A level that carries SCPs but no FullAWSAccess denies everything for
  the account root, since scpAllows requires an explicit allow at each
  non-empty level. Auto-attached FullAWSAccess covers the normal path.
- Condition-scoped guardrails keyed on aws:PrincipalArn (e.g. a
  DenyRootUser "Deny * when aws:PrincipalArn like *:root") are inert:
  IamConditionContextResolver never populates aws:PrincipalArn, so a
  plain StringLike on that absent key fails the condition block and the
  statement does not apply. A regression test locks this in.

Tests: unit coverage in IamEnforcementFilterTest (bare-account deny,
non-denied allow proven via arnBuilder invocation, and the realistic
two-statement workload-guardrails doc) plus an end-to-end
ScpEnforcementLeaveOrganizationIntegrationTest driving the Organizations
control plane over HTTP.

* feat(iam): populate aws:PrincipalArn for real identities in policy conditions

IamEnforcementFilter built the condition context only from
IamConditionContextResolver, which populates s3:prefix/delimiter/max-keys
and nothing else. aws:PrincipalArn was therefore never set, so every
policy condition keyed on it was inert across all policy layers (SCPs,
identity, session, permissions boundary): a principal-scoped Deny never
fired and a principal-scoped Allow never matched.

Fix: after resolving the condition context, look up the caller's ARN via
IamService.resolveCallerArn(akid) and, when present, set aws:PrincipalArn.
The lookup returns the user ARN for IAM-user access keys and the
assumed-role ARN for STS sessions, and Optional.empty() for the bare
account-id key (floci's account root) and unknown keys. So the key is
populated for real, identifiable principals and stays absent for the
account root — which is exactly why a DenyRootUser guardrail keyed on
aws:PrincipalArn continues not to fire against the account root, per the
account-root SCP change in the preceding commit.

Effect is bidirectional and applies to every policy layer that
evaluate() consults: a principal-scoped Deny can now deny, and a
principal-scoped Allow can now grant. Both remain gated behind the two
opt-in enforcement flags (iam.enforcement-enabled +
organizations.scp-enforcement-enabled, both default off).

IamEnforcementFilter is the sole caller of the condition-aware
IamPolicyEvaluator.evaluate overload and the sole user of
IamConditionContextResolver, so there is no second evaluation path where
the key would be absent and the same policy would behave differently.

Known caveat (pre-existing, surfaced here for operators): resolveCallerArn
hardcodes the assumed-role session name as "floci-session", so
aws:PrincipalArn for assumed-role callers will not match a condition that
pins a specific session name. This matches what STS GetCallerIdentity
already reports.

Tests: two conditional cases in IamEnforcementFilterTest exercise both
directions against a real IamPolicyEvaluator — a principal-scoped SCP
Deny that fires for an IAM user, and an identity-policy Allow gated on an
IAM-user principal that grants access. Both were confirmed RED with the
population disabled.

* docs(iam,organizations): document account-root SCP handling and condition keys

Clarify how SCP enforcement treats the bare account-id key (subject to the
SCP chain as the account root, but carrying no identity policy), the
condition keys floci populates (s3:prefix/delimiter/max-keys,
aws:PrincipalArn), and the absent-key rule that keeps aws:PrincipalArn
guardrails inert against the account root.

* feat(iam): organization support ops for LZA bootstrap

Add ListOrganizationsFeatures and the root-credentials-management and
root-sessions enable/disable pairs, backed by OrganizationRootFeatures.
LZA custom resources call these during the Prepare/Accounts stages
(EnableAllFeatures), alongside CreateServiceLinkedRole for the Access
Analyzer role, which the emulator already implements — the tests here
cover the service-linked role names those stages depend on.

* fix(iam): register OrganizationRootFeatures for reflection

PersistedModelReflectionTest asserts every type reachable from persisted
storage carries @RegisterForReflection -- without it, native-image
persistence breaks on restart. OrganizationRootFeatures was added in
e60e8abd (organization support ops) without the annotation, so the test
has been red since.

Adds @RegisterForReflection plus @JsonIgnoreProperties(ignoreUnknown =
true), matching the convention of every sibling model in the package
(InstanceProfile, IamPolicy, IamGroup).

* feat(iam): tag and untag instance profiles

Adds a tags map to InstanceProfile and wires TagInstanceProfile /
UntagInstanceProfile through the query handler, with an integration test
covering the tag round trip.

* feat(iam): add UpdateGroup

Net-new operation modeled on the existing updateUser: rename and/or
change a group's path, with the ARN and stored users moving with it.
Same EntityAlreadyExists/NoSuchEntity exception shape as updateUser.

* docs(iam): document SCP enforcement where it is implemented

The Organizations page described SCP participation in policy evaluation and
linked to iam.md#service-control-policies-scps and iam.md#bypass-rules, neither
of which existed anywhere. The behaviour belongs to the IAM enforcement layer —
IamEnforcementFilter resolves the chain via effectiveScpLevels — so document it
there, including the account-root and bypass cases, and restore the
cross-reference now that both anchors resolve.

* fix: use canonical IAM service-linked role names

* feat(iam): seed AWS Backup service-role managed policies

LZA's OperationsStack attaches AWSBackupServiceRolePolicyForBackup and
AWSBackupServiceRolePolicyForRestores to its backup service roles; without
catalog entries AttachRolePolicy fails with NoSuchEntity and the stack
rolls back.

* feat(iam): seed AWS Backup S3 service-role managed policies

LZA's OperationsStack backup role also references
AWSBackupServiceRolePolicyForS3Backup / ForS3Restore, which live at the
root path in real AWS rather than /service-role/. Without them the role
create fails with NoSuchEntity and the stack rolls back.

* fix(iam): deny when a service control policy fails to parse

The SCP ceiling skipped any document it could not parse and evaluated
whatever else the level held. Since FullAWSAccess is attached to every
target, a level almost always carries it alongside the customer's
guardrail: a malformed guardrail dropped out, FullAWSAccess supplied the
required explicit allow, and the restriction vanished with only a WARN
line to show for it. A security control must not fail open.

parseAll now reports whether any document failed, and a level holding an
unparseable document denies. Only SCP evaluation reads that signal —
identity, resource, session and boundary policies keep skipping bad
documents as before.

* perf(organizations): scan the policy store once per SCP resolution

effectiveScpLevels called policiesIn(organization) inside the loop over
the account's ancestry, and policiesIn scans every account's policy
store. A root -> OU -> account chain therefore did three full scans on
an authenticated request path. Hoist the scan above the loop and keep
the per-node target filter inside it.

Also record why the SCP levels are resolved before resolveCallerContext
in IamEnforcementFilter: the account-root branch needs to know whether a
ceiling exists before it can choose between enforcing and bypassing.

* test(organizations): cover each reason effectiveScpLevels returns null

The management-account exemption, the account-outside-any-organization
case, and the SCP-policy-type-disabled case were only asserted as three
lines inside the walk-the-chain test, where a name never says what broke
and an earlier failure hides them. Give each its own test, and assert a
member account does get a ceiling in the same setup so the exemption
cases cannot pass for the trivial reason that no SCPs exist at all.

* fix(iam): never reissue deleted policy version ids

CreatePolicyVersion derived the next version id from the version count,
so deleting a non-default version and creating a new one silently
rewrote the highest surviving version. AWS ids are monotonic; derive
the next id from the highest existing one and cap on the live count.

* fix(iam): resolve principal policies in the account the ARN names

collectUserPolicies, collectRolePolicies, resolveUserBoundaryDocument
and resolveRoleBoundaryDocument stripped a bare name out of the given
principal ARN and looked it up in ambient request-context storage. When
two accounts each hold a same-named user or role, presenting account
A's ARN resolved whichever account the request happened to run as — a
cross-account authorization bypass in either direction, and one that
also silently applied the wrong permissions boundary.

Each lookup now scopes to the account segment of the ARN it was given,
via the existing findRole(accountId, roleName) and a new symmetric
findUser(accountId, userName). resolvePrincipalContext passes the full
ARN to the user-side helpers instead of pre-stripping it to a name.

Callers that legitimately have no ARN — resolveCallerContext, reached
from a long-term access key — still resolve through the ambient account,
so account-routed access keys keep working.

* fix(iam): enforce the modeled password-policy bounds and instance-profile tag limits

UpdateAccountPasswordPolicy stored whatever numbers arrived, so a policy with
MinimumPasswordLength outside 6-128, MaxPasswordAge outside 1-1095 or
PasswordReusePrevention outside 1-24 persisted and was read straight back by
GetAccountPasswordPolicy as if AWS had accepted it. Reject with ValidationError,
the code the service already raises for shape-constraint failures.

TagInstanceProfile merged the tag map with no cardinality check and
UntagInstanceProfile accepted an unbounded TagKeys list, though both shapes are
max 50. Tagging past the quota now raises LimitExceeded, matching the other
per-resource quota guards; an over-long TagKeys request raises ValidationError.

* fix(iam): check the instance-profile tag list shape before resolving the profile

Separates the two constraints the previous commit conflated: a request carrying
more than 50 tags fails the tagListType shape and is now rejected with
ValidationError before the profile lookup, matching untagInstanceProfile's order
and AWS's; exceeding the 50-tag per-resource quota across requests stays
LimitExceeded.

* fix(iam): validate GroupName/NewPath and InstanceProfileName shape before mutation

UpdateGroup read GroupName and NewPath with getParam and passed them straight
into IamService.updateGroup with no pattern/length check, and TagInstanceProfile
did the same for InstanceProfileName before reaching IamService.tagInstanceProfile.
botocore's iam/2010-05-08 model constrains groupNameType/instanceProfileNameType
to [\w+=,.@-]{1,128} and pathType to 512 chars matching a bare slash or a
slash-delimited run of !-~; a malformed value previously surfaced as
NoSuchEntity/200 instead of the ValidationError AWS returns.

* fix(iam): never reissue a policy version id after deleting the highest surviving version

CreatePolicyVersion derived the next id from the max of the currently-live version keys, so
deleting the highest-numbered surviving version (as opposed to an older one) and creating a
new one silently reissued the deleted id — e.g. deleting v5 while v4 survives makes the next
version v5 again, violating IAM's monotonic version-id contract. IamPolicy now tracks a
persisted next-version high-water mark, taken as the max of itself and the live-key floor so a
policy rehydrated from before this field existed is never regressed below what it already has
on disk.

* fix(iam): defensively copy InstanceProfile tags and reject a null map

setTags assigned the incoming map directly and allowed null. A persisted "tags": null on
rehydration, or a caller mutating the map it passed in after the call, could NPE at
new LinkedHashMap<>(profile.getTags()) in tagInstanceProfile or silently mutate the profile's
stored tags out from under it. Now defensively copies into a fresh ConcurrentHashMap, or an
empty one for null, matching how getTags()/setTags() are used elsewhere on this model.

* fix(iam): validate UpdateGroup's NewGroupName and keep member policies resolving across a rename

NewGroupName reached storage with no pattern/length check (the same groupNameType gap already
closed on GroupName/NewPath), and UntagInstanceProfile's InstanceProfileName had the same gap
UpdateGroup's tag-sibling TagInstanceProfile already closed. Also: renaming a group rekeyed
only the group record, leaving each member's own groupNames list pointing at the deleted old
name, so ListGroupsForUser dropped the renamed group and collectUserPolicies silently stopped
resolving its inline/attached policies for those members. updateGroup now updates every
member's groupNames symmetrically with addUserToGroup/removeUserFromGroup.

* fix(iam): guard against reissuing a version id deleted before nextVersionNumber existed

nextVersionNumber previously defaulted to 2 in its field initializer, so a policy persisted by a
pre-migration Floci version rehydrated with the same value a genuinely fresh policy would have,
regardless of how many versions it actually held historically. If such a policy's then-highest
version had been deleted (e.g. v1-v4 live after a pre-migration DeletePolicyVersion("v5")), the
live-key floor alone could not reveal that v5 was already used, and CreatePolicyVersion reissued
it. The field is now left null (unset) unless a policy explicitly sets it, so Jackson leaves a
legacy record's value null instead of masquerading as fresh; CreatePolicyVersion treats null as
"true history unknown" and jumps the counter past the live-key max by 5 (a policy can never hold
more than 5 concurrent versions, so no more than 5 stacked deletions could sit above the live max
between two persists).

* fix(iam): populate aws:PrincipalArn as the account root for the synthesized root principal

Maintainer review on #2637 (pgermosen): SCPs already treat floci's bare account-id key as the
account root (enforced), but aws:PrincipalArn was left absent for it, so a common DenyRootUser
guardrail keyed on aws:PrincipalArn (StringLike arn:aws:iam::*:root) could never fire against it
even though the same principal is otherwise bounded as root — an internal inconsistency between
the two forms of root enforcement. IamEnforcementFilter now populates aws:PrincipalArn as
arn:aws:iam::<account>:root right where the root identity is synthesized, matching AWS's own
root ARN shape. Inverts the IamEnforcementFilterTest that pinned the old inert behavior (a
DenyRootUser guardrail now correctly denies the account root's other actions too, not just the
one an accompanying statement explicitly targets) and adds a direct assertion that the exact
root ARN is what's populated. Docs updated to match.
2026-08-28 08:55:50 -04:00
Ricky Rattlesnake 066e6c904b fix(s3): return x-amz-version-id from presigned POST (#2608)
A presigned POST to a versioning-enabled bucket creates a new version but the
response omits x-amz-version-id, so the caller cannot discover it. A browser
upload has no other channel — there is no SDK response to read — which breaks
the common direct-to-S3 pattern where the browser uploads, reads the version
from the response, and reports it back to the application.

The handler already has the S3Object returned by putObject; it simply never
read getVersionId(). Every other write path in S3Controller sets the header
behind the same null guard.

Fixes #2607
2026-08-28 08:55:07 -04:00
Sam Fakhreddine e471946f44 feat(route53): VPC association lifecycle actions (#2638)
* feat(route53): add VPC association lifecycle actions

Zone creation already persists VPC associations, but the lifecycle
operations that manage them afterwards were missing. Adds, on top of the
existing VpcAssociation model:

- AssociateVPCWithHostedZone   POST /hostedzone/{Id}/associatevpc
- DisassociateVPCFromHostedZone POST /hostedzone/{Id}/disassociatevpc
- CreateVPCAssociationAuthorization POST /hostedzone/{Id}/authorizevpcassociation
- DeleteVPCAssociationAuthorization POST /hostedzone/{Id}/deauthorizevpcassociation
- ListHostedZonesByVPC          GET  /hostedzonesbyvpc

Request paths, XML element names and response shapes follow the Route 53
2013-04-01 rest-xml model, including HostedZoneSummary's HostedZoneId and
Owner members, and ListHostedZonesByVPC honours maxitems/nexttoken.
Associate is idempotent; disassociate raises VPCAssociationNotFound for
an unknown VPC and LastVPCAssociation when it would remove the only
remaining association, and associating a public zone raises
PublicZoneVPCAssociation.

VpcAssociation has no value equality, so associations are matched on VPC
ID and region rather than object identity.

The two authorization endpoints are shape-only: hosted zones are not
account-scoped here, so an authorization cannot gate a later associate
call. They validate the request and echo the VPC back.

* fix(route53): enforce the VPCRegion enum on the VPC association actions

AssociateVPCWithHostedZone, DisassociateVPCFromHostedZone, the two
authorization actions and ListHostedZonesByVPC all read VPCRegion and
stored or matched on it verbatim. A region outside the modelled enum was
accepted, so the association was written under a region that could never
be matched again: the associate reported INSYNC while the later
disassociate answered VPCAssociationNotFound and ListHostedZonesByVPC
silently omitted the zone.

Reject an unmodelled VPCRegion with InvalidInput, which the model lists
for every one of these operations. The check carries the enum from the
model rather than reusing AwsRegions.KNOWN_IDS, because the enum admits
the ISO and European Sovereign partitions the emulator never advertises.

* fix(route53): reject unmodelled VPC regions on create and fix VPC-list pagination

CreateHostedZone stored a VPC association's region without checking it
against the modelled VPCRegion enum, so an association created that way
could never be found again by the later disassociate/list lifecycle
actions, which do check it. ListHostedZonesByVPC also silently restarted
pagination on an unrecognized NextToken and ignored a non-positive
MaxItems instead of rejecting both with InvalidInput.

* fix(route53): don't strand legacy VPC regions, and stabilize equal-name pagination

Two review findings from the latest re-review:
- ListHostedZonesByVPC and DisassociateVPCFromHostedZone rejected any VPCRegion outside the
  modelled enum before ever touching storage, so an association persisted under a region since
  retired from the enum (or from before this check existed) could never be listed or removed —
  only a full hosted-zone deletion could get rid of it. The enum check now applies only to the
  paths that create a new association (AssociateVPCWithHostedZone, CreateHostedZone,
  CreateVPCAssociationAuthorization); lookups and removal accept whatever region is on record.
- ListHostedZonesByVPC sorted matches by name only, so two zones with the same name were ordered
  however the backing store happened to iterate them, which can differ between the page-1 and
  page-2 scans and desync the id-based NextToken continuation point. The sort now tie-breaks by
  id so the total order is fixed regardless of iteration order.

* fix(route53): use the modeled InvalidPaginationToken and ConflictingDomainExists errors

ListHostedZonesByVPC returned the generic InvalidInput for an
unrecognized NextToken instead of the purpose-built
InvalidPaginationToken the model declares for exactly this operation.
AssociateVPCWithHostedZone also let the same VPC attach to two
different hosted zones sharing a name, something the model documents
as ConflictingDomainExists; the existing listHostedZonesByVpc lookup
now scans for that conflict before storing a new association.
2026-08-28 08:19:14 -04:00
Matheus Oliveira c4050936a8 feat(ecs): rewrite ECR image URIs on RunTask like Lambda already does (#2641)
Extracts the AWS-ECR-URI rewrite out of Lambda's ContainerLauncher into
EcrRegistryManager.rewriteImageUri(), now shared by Lambda and ECS so
RunTask images resolve through Floci's emulated registry instead of the
real amazonaws.com host.

Closes #2568

Signed-off-by: Matheus Oliveira <matheus.6148@gmail.com>
2026-08-27 22:33:30 -04:00
Sam Fakhreddine 149ac635f2 fix(ssm): validate SettingValue and require an account list on ModifyDocumentPermission (#2635)
* fix(ssm): validate SettingValue and require an account list on ModifyDocumentPermission

UpdateServiceSetting.SettingValue was read with plain asText(), so an absent
or blank value silently stored an empty customized setting, and botocore's
ServiceSettingValue max (4096) was never enforced. ModifyDocumentPermission
accepted a request with neither AccountIdsToAdd nor AccountIdsToRemove and
returned success having shared/unshared nothing, when botocore documents at
least one of the two as required.

* fix(ssm): review comments — whitespace SettingValue, non-list AccountIds, message format

Greptile: isBlank() rejected a whitespace-only SettingValue even though
botocore's ServiceSettingValue constraint is length-only (min 1); switched to
isEmpty().

Copilot: a non-list AccountIdsToAdd/AccountIdsToRemove payload was silently
treated as an empty list because forEach() on a scalar/object node yields no
elements, so the new "neither list specified" guard could pass a malformed
request. Reject a present-but-non-array field explicitly, and reworded that
guard's message to match this file's "1 validation error detected:" prefix.
2026-08-27 22:26:30 -04:00
Sam Fakhreddine 5400204563 fix(kms): grant fidelity (#2639)
* fix: preserve KMS grant metadata

* fix(kms): reject GrantOperation values outside the modeled enum

CreateGrant stored the Operations list verbatim, so a grant could be
persisted and echoed back with an operation name AWS would have refused.
Validate each element against the GrantOperation enum and raise
ValidationException, matching the other CreateGrant input guards.

* fix(kms): validate CreateGrant Name against GrantNameType constraint

Real AWS enforces GrantNameType's pattern (^[a-zA-Z0-9:/_-]+$) and
256-char max length on CreateGrant's Name field. Add the same
validation so malformed names are rejected the way AWS rejects them.

* fix(kms): validate CreateGrant Constraints and fix name-length error message

Two review findings on CreateGrant:
- Constraints previously passed through unvalidated: an unknown member,
  a non-map EncryptionContextSubset/EncryptionContextEquals, or a
  malformed SourceArn would be persisted and echoed back on ListGrants
  even though real KMS rejects the request. Validate against the
  modeled GrantConstraints shape (kms/2014-11-01/service-2.json).
- Name's length check used the max-length message for both the empty
  and over-256 cases; an empty name now cites the min-length-1
  constraint instead.

* fix(kms): reject non-object CreateGrant Constraints instead of silently dropping it

The handler converted Constraints to null whenever it wasn't a JSON object, so a raw string or
array value was treated as absent and the grant was created without ever reaching
validateGrantConstraints, instead of rejecting the malformed request as real KMS does.
2026-08-27 21:35:32 -04:00
Stuart Lang bf6c7b001c fix(dynamodb): reject key attribute values whose type does not match the key schema (#2625)
* fix(dynamodb): reject key attribute values whose type does not match the key schema

PutItem/UpdateItem (and Get/Delete/BatchWrite/TransactWrite via the same
path) accepted a NULL-typed partition or sort key, which real DynamoDB
and LocalStack reject with a ValidationException. Worse, non-scalar key
values collapsed to an empty storage key, so all such items collided on
one slot.

buildItemKey now validates each key attribute value against the table's
AttributeDefinitions, using AWS's wording for both flavours: the Key
argument form ("The provided key element does not match the schema")
and the PutItem item form ("One or more parameter values were invalid:
Type mismatch for key <name> expected: <type> actual: <type>").

Fixes #2624

* test(dynamodb): cover NULL-typed key rejection at the HTTP layer

* fix(dynamodb): validate key value shapes and index key types on writes

Review follow-up for #2625, all behaviours verified against real DynamoDB:

- Key attribute values that are empty objects or carry multiple type
  members are rejected with AWS's "Supplied AttributeValue ..."
  messages; non-object values get a SerializationException like AWS's
  protocol layer, instead of aliasing onto another item's storage key.
- GSI/LSI key attributes present in a written item are validated
  against AttributeDefinitions on PutItem and UpdateItem (covering
  batch and transact paths, which reuse them), matching AWS's
  "Type mismatch for Index Key <name> Expected: <T> Actual: <T>
  IndexName: <idx>" wording. Absent attributes stay valid (sparse
  indexes).
- Brace the new single-line conditionals per AGENTS.md.

* fix(dynamodb): apply value shape and empty-string rules to index keys

Review follow-up for #2625. The malformed-shape checks added for base
keys skipped GSI/LSI key attributes: validateIndexKeySchema's guard
stepped over empty, multi-member, and non-object values instead of
rejecting them. The three checks now live in a shared
validateAttributeValueShape helper that both key paths run, so they
cannot drift again.

Empty-string index key values are also rejected now, verified against
real DynamoDB, which uses different wording per operation: PutItem
names the index ("... IndexName: gsi1, IndexKey: gsiKey") while
UpdateItem uses the update-expression form without it.

Number normalization no longer rebuilds a multi-member AttributeValue
around its N member — {"S":"x","N":"1"} was being laundered
into a well-formed {"N":"1"} before validation could see it, which
turned the AWS shape error into a type-mismatch error.
2026-08-27 21:05:52 -04:00
Sam Fakhreddine 7f6b875136 feat(ssm): document lifecycle, share permissions, and account-scoped service settings (#2629)
* feat(ssm): document share permissions for DescribeDocumentPermission and ModifyDocumentPermission

* feat(ssm): model documents with GetDocument, CreateDocument, and UpdateDocument

LZA's session-manager-settings custom resource reads SSM-SessionManagerRunShell
via GetDocument, creates it (DocumentType Session) when the InvalidDocument error
code comes back, and updates it otherwise, tolerating DuplicateDocumentContent.
Model documents region-scoped in a persistent store and serve all three ops with
those exact error codes so the AWS SDK maps them to its typed exceptions.

* feat(ssm): add DescribeDocument and DeleteDocument

Completes the document lifecycle alongside the existing Get/Create/Update
operations. DeleteDocument raises InvalidDocument for a name that was never
stored rather than succeeding silently.

* feat(ssm): account-scoped service settings (Get/Update/ResetServiceSetting)

LZA's ssm-block-public-document-sharing module assumes a role into every member account and reads/updates /ssm/documents/console/public-sharing-permission. Model the ServiceSetting API with per-account per-region state, account defaults (Enable for public sharing), and ServiceSettingNotFound for unknown ids, matching real AWS. Closes the gap reported upstream as floci-io/floci#2235.

* fix(ssm): raise InvalidDocument when a permission op names an unknown document

DescribeDocumentPermission returned an empty list and ModifyDocumentPermission
happily created share state for a document that does not exist. Botocore models
InvalidDocument on both operations, and this branch now has a real documentStore,
so the two halves of the service no longer need to disagree about whether a
document exists: both permission methods resolve the document first.

This also settles the ownership half. Only the document's owner may share a
document in AWS. Ownership here is the storage partition: documentStore is an
AccountAwareStorageBackend keyed by the caller's account from RequestContext,
the same resolution RegionResolver.getAccountId() performs, so getDocument can
only resolve a document in the caller's own partition and a non-owner gets
InvalidDocument. Deriving the guard from the partition rather than a second
stored owner field keeps check and storage scope from ever disagreeing.

* fix(ssm): validate Name and PermissionType on the document operations

Every new document handler read request.path("Name").asText(), which yields ""
— not null — for an absent field, so a request with Name omitted built the key
"<region>|" and surfaced "Document  does not exist." with a blank in the message.
Botocore constrains DocumentName to ^[a-zA-Z0-9_\-.]{3,128}$, making a blank name
a constraint violation, which AWS reports as ValidationException. No per-operation
error fits: InvalidDocument means "does not exist" rather than "malformed", and
CreateDocument does not model it at all — so unlike the ACM guards, a generic
ValidationException here is the modeled shape, not a substitute for one.

PermissionType was accepted and ignored on both document-permission operations.
Botocore models DocumentPermissionType as an enum whose only value is Share and
models InvalidPermissionType on both operations, so a present-but-unsupported
value now raises InvalidPermissionType. PermissionType is a required member, so
an absent one is treated as a missing required member (ValidationException), the
same as an absent Name.

Both guards run before the store lookup. The integration test for the permission
round-trip now creates the document it shares, and a two-account test asserts a
non-owner cannot share another account's document.

* fix(ssm): enforce the modelled DocumentType and AccountIds constraints

Two values the document operations read and store were never checked
against the model.

CreateDocument took DocumentType verbatim. Botocore models it as a
17-value enum; floci stored whatever arrived and echoed it back from
GetDocument, DescribeDocument and the create response, so a document
could sit in the store with a type neither AWS nor the emulator
recognises.

ModifyDocumentPermission wrote AccountIdsToAdd straight into the
document's share list. The model caps each list at 20 members and pins
the member pattern to (?i)all|[0-9]{12}; without either check a share
with "not-an-account" reported success and DescribeDocumentPermission
faithfully echoed it back.

Both are rejected with ValidationException, matching the treatment the
blank Name and the PermissionType enum already get.

* fix(ssm): enforce the DocumentName pattern instead of only rejecting blank names

requireDocumentName rejected an absent or blank Name but let any other
value through unvalidated, so a name violating botocore's
^[a-zA-Z0-9_\-.]{3,128}$ pattern (e.g. containing a slash) was accepted
and persisted instead of raising ValidationException. The lifecycle
integration test's document names started with "/", so they had to be
corrected to comply with the pattern now that it is actually enforced.

* fix(ssm): reject missing or non-string Content on CreateDocument/UpdateDocument

Content was read via JsonNode.asText(), which silently returns "" for
either an absent member or a non-textual node (e.g. a JSON object sent
instead of a JSON/YAML-encoded string). That let CreateDocument store
an empty document, and let UpdateDocument erase existing content while
still incrementing the version. Botocore models DocumentContent as a
required string with min length 1 on both operations, so this now
raises ValidationException before either service call is made.

* fix(ssm): clear share permissions when a document is deleted

deleteDocument removed only the document record, leaving its entry in
documentPermissionStore behind. A document recreated later under the
same account, region, and name inherited the deleted document's
account shares instead of starting unshared.

* fix(ssm): validate SettingId is present on service-setting operations

Get/Update/ResetServiceSetting read SettingId via JsonNode.asText(),
which yields "" for an absent member. That blank id was then treated
as an unknown setting (ServiceSettingNotFound) rather than a missing
required member (ValidationException) — the same distinction already
drawn for the document operations' Name field.

* fix(ssm): reject non-string document Name in CreateDocument

asText() silently coerces a numeric or boolean Name to its string form, so it can satisfy the DocumentName pattern and reach create/lookup instead of raising ValidationException for the wrong-typed member.

* fix(ssm): serialize document create/delete/share against each other

deleteDocument's trailing documentPermissionStore.delete ran unsynchronized against createDocument and modifyDocumentPermission, so a delete overlapping a same-name recreate-and-share could wipe out the recreated document's new shares.

* fix(ssm): widen GetDocument/DescribeDocument Name pattern for ARN reads

Botocore models a wider Name pattern (adds ':' and '/') on GetDocument
and DescribeDocument than on the other five document operations, since
DescribeDocument accepts the document's full ARN when reading a
document shared from another account. The shared DOCUMENT_NAME pattern
rejected that shape on both read operations, so an ARN naming a
caller's own document — an ordinary way to call GetDocument — failed
with ValidationException instead of resolving (or, for an unknown
document, InvalidDocument).
2026-08-27 17:20:56 -04:00
Sam Fakhreddine 9b9e7f56a2 feat(apigateway): API key import/usage-plan fidelity and update-operation fixes (#2631)
* feat(apigateway): complete the REST API resource lifecycle

Adds the missing delete and update operations across authorizers,
integrations, integration responses, methods, method responses, models,
request validators, resources, rest APIs, stages, deployments, domain names
and base path mappings, plus tag/untag, usage plan and usage plan key CRUD,
and ImportApiKeys backed by a new ApiKeyCsvParser.

Each operation has a wire-level integration test.

* feat(apigatewayv2): allow clearing an HTTP API CORS configuration

deleteCorsConfiguration unsets the optional CORS block on a stored API so
the response omits it rather than echoing a stale configuration.

* fix(apigateway): accept the AWS-native ImportApiKeys CSV format

The header validator required exactly `name,value,enabled` in lowercase and
read every row by fixed position. Real AWS ships `Name,Key,Description,
Enabled,UsagePlanIds`, so the CLI, SDKs and Terraform all took a 400 on their
first call. Columns are now resolved case-insensitively by name into an index
map, `value` is kept as an alias for `Key`, a missing or blank `Enabled`
defaults to true as AWS does, and rows shorter than the header no longer throw.

Imported keys are also created with generateDistinctId, because the CSV `Key`
column is the key VALUE and AWS generates the id separately — reusing the value
as the id let one row silently clobber an existing key and detach its usage
plan associations.

ImportApiKeys now reports warnings for real: a row whose key value duplicates an
earlier row in the same import raises one, and `failonwarnings=true` turns those
warnings into a BadRequestException instead of being ignored.

* fix(apigateway): honour the patchOperations envelope on UpdateModel and UpdateUsagePlan

Both handlers parsed the PATCH body as a flat map. Real AWS sends
`{"patchOperations":[{"op":"replace","path":"/description","value":"x"}]}`, so
the flat parse succeeded, matched nothing, and returned the untouched resource
with a 200 — a silent no-op. Both now walk the ops list the way the six sibling
endpoints in this controller already do.

UpdateModel supports /description, /schema and /contentType, and rejects /name
with a BadRequestException: AWS treats a model name as an immutable identifier.
That also removes the delete-then-put rename, which had no existence check on
the target key and so destroyed any model already using the new name.

UpdateUsagePlan supports /name, /description and add/remove of /apiStages as
"apiId:stage", covering what the flat handler could do. UsagePlan carries no
throttle or quota state, so those paths are left unsupported rather than faked.

UpdateAuthorizer now parses /authorizerResultTtlInSeconds before mutating
anything. A non-numeric value used to be written straight to the store, after
which serialisation threw on the PATCH and on every later GetAuthorizer and
GetAuthorizers for that resource — unrecoverable short of delete and recreate.

* fix(apigateway): reject duplicate sibling paths and bad parentId on resources

UpdateResource pointed at an unknown /parentId surfaced getResource's 404
"Invalid resource id specified", which reads as though the resource being
patched is missing; the `parent == null` guard beneath it was unreachable for
the same reason. AWS answers 400, so the lookup failure is now rethrown as a
BadRequestException naming the offending value.

Neither CreateResource nor UpdateResource checked for a sibling collision, so
two children of one parent could end up with the same path and request routing
became order-dependent. Both now go through a shared guard that raises
ConflictException (409) when another child of the effective parent already uses
that pathPart.

UpdateResource also stopped mutating as it goes. The store hands back live
objects, so applying ops in-place meant a later rejected op left the earlier
ones visible in memory; the patch is now resolved into pending parentId and
pathPart values, validated, and only then applied.

* style(apigateway): put HttpHeaders first in deleteAuthorizer

Every other handler in the controller takes @Context HttpHeaders as its first
parameter. No behaviour change.

* fix(apigateway): answer BadRequestException for a malformed patchOperations envelope

The PATCH handlers parsed the envelope with convertValue(node, List.class)
inside a catch that only covered IOException. convertValue throws
IllegalArgumentException, which no mapper handles, so a non-array
patchOperations returned 500 instead of the modelled BadRequestException.
The raw List.class conversion also deferred a structured operation value
into the service layer as a ClassCastException, a second 500.

Extract one parsePatchOperations helper that converts through a
TypeReference<List<Map<String, String>>> and widens the catch, so scalar
values coerce and structured ones are rejected at the boundary.

* fix(apigateway): dispatch ImportApiKeys on mode, not on media type

ImportApiKeys was annotated @Consumes("text/csv"), but botocore sends the
operation with no Content-Type header at all — only Accept: application/json.
A request with no Content-Type is application/octet-stream to JAX-RS, so it
never matched, and fell through to the sibling CreateApiKey handler, which
fed the CSV body to the JSON parser and answered a spurious
BadRequestException. Every existing test hid this by setting text/csv
explicitly, a header no client sends.

Fold both operations into one POST /apikeys handler that consumes any media
type and tells them apart by the mode query parameter, the way AWS does, and
cover it with a raw-client case that sends no Content-Type.

* docs(apigateway): document the operations this branch added

The branch added 13 v1 management operations and DeleteCorsConfiguration on
v2 without touching docs, and the Not Implemented list still named
UpdateAuthorizer, DeleteAuthorizer, ImportApiKeys, GetUsagePlan,
UpdateUsagePlan and UpdateModel as absent. GetDeployment and DeleteDeployment
were already implemented but had never been listed either.

api-gateway.md is hand-maintained — ApiGatewayController is a REST controller
and is not registered in tools/docs/services.yaml — so the tables are updated
by hand and the index counts follow the tables: v1 64 -> 79, v2 48 -> 49.
Also record how CreateApiKey and ImportApiKeys share POST /apikeys.

* fix(apigateway): extend the patchOperations boundary parse to the inherited handlers

Six PATCH handlers predate this branch and still parsed the envelope with
convertValue(node, List.class) inside an IOException-only catch, so
updateRestApi, updateResource, updateMethod, updateIntegration, updateStage
and updateApiKey kept answering 500 for a malformed envelope while the eight
handlers this branch added answered 400. A reviewer would rightly ask why
only some of the surface agrees with AWS.

This is a deliberate scope extension beyond the audit's finding: point all
six at the existing parsePatchOperations helper so every PATCH operation on
the service shares one boundary contract. updateAccount stays as it is — it
validates each operation itself and already raises a modelled 400.

* docs(apigatewayv2): correct the VPC Link operations, which are implemented

The v2 Not Implemented list named all five VPC Link operations as absent, but
CreateVpcLink, GetVpcLink, GetVpcLinks and DeleteVpcLink have been routed on
/v2/vpclinks and backed by ApiGatewayV2Service since before this branch. Only
UpdateVpcLink is genuinely missing — there is no PATCH route for it.

Verified each claimed route against ApiGatewayController before editing. Adds
the VPC Links row the v2 table never had and carries the four operations into
the index count: 49 -> 53.

* fix(apigateway): enforce the modelled op enum on patchOperations

Botocore models PatchOperation.op as an enum of add, remove, replace,
move, copy and test. The boundary parse read the envelope's shape but
never the op value, and the handlers behind it disagree about what to do
with an unrecognised one: UpdateModel throws, UpdateApiKey and UpdateStage
skip it. On the skipping handlers an unmodelled op was answered 200 with
the resource untouched, which reads to the caller as an applied patch.

Check op against the enum in parsePatchOperations, the boundary this
branch already made responsible for the envelope on every PATCH handler.
The set is the model's, not the intersection of what the handlers
implement: whether a handler supports move is its own business, but a
value outside the enum should never reach one.

* fix(apigateway): reject a null element in the patchOperations envelope

parsePatchOperations silently skipped a null element in the patchOperations
array instead of rejecting it. Several handlers that predate the shared
boundary parse (updateRestApi, updateStage, updateApiKey, updateMethod) have
no null guard of their own and call op.get("op") directly, so a null element
reached them as an unhandled NullPointerException -- a 500 instead of AWS's
modelled BadRequestException.

Reject the null at the boundary all handlers already share, the same place
that already validates the op enum.

* fix(apigateway): apply patchOperations atomically instead of partially

updateAuthorizer, updateUsagePlan, updateRequestValidator, updateModel,
updateDomainName and updateBasePathMapping mutated the live stored object as
each op was validated. The store hands back live objects (no defensive
copy), so a valid op followed by an invalid one left the valid op's change
visible even though the request answered 400 -- the same partial-apply bug
already fixed for updateResource in an earlier commit on this branch, which
established the fix: resolve every op into pending local values, validate
the whole list, and only mutate the stored object once the patch is known
to be entirely good.

Each handler also now rejects a null patchOperations element explicitly, on
top of the shared boundary's own rejection, matching the defensive style
already used by updateRequestValidator and updateModel before this change.

* fix(apigateway): translate a malformed ImportApiKeys CSV into BadRequestException

ApiKeyCsvParser.parse throws IllegalArgumentException on an unterminated
quoted field, but only AwsException is registered with an ExceptionMapper.
The unmapped exception escaped as a 500 instead of AWS's modelled 400,
letting a malformed import request past the error boundary entirely.

Catch the parser's IllegalArgumentException at the one call site and
translate it into the same BadRequestException every other CSV validation
failure in this method already raises.

* style(apigateway): brace the new conditionals this branch added

New single-line if statements in the domain-name serialization, CSV import
column/cell handling, and resource sibling-collision check violated the
repository's mandatory conditional-brace convention. No behaviour change.

* fix(apigateway): validate all UpdateIntegration patch ops before applying any

updateIntegration mutated the live stored integration inside the same loop that validated later operations, so a PATCH with a valid op followed by an unsupported path left the earlier op applied even though the request as a whole was rejected with 400.
2026-08-27 16:59:59 -04:00
Michal Schreiber 75f8f42d5f fix(elasticache): keep a replication group's encryption, snapshot settings, tags and ARN (#2632)
* fix(elasticache): keep a replication group's encryption, snapshot settings, tags and ARN

DescribeReplicationGroups wrote AtRestEncryptionEnabled and
SnapshotRetentionLimit as constants and never emitted KmsKeyId,
SnapshotWindow or ARN, so a group created with them drifted on the next
Terraform plan (kms_key_id forces replacement) and its tags, given at
create, could not even be asked for without an ARN. Store the four
settings and the tags on the group, resolve KmsKeyId through the KMS
store in the request's region to the key ARN a live account reports,
apply the snapshot settings from ModifyReplicationGroup, emit them with
the ARN, and answer ListTagsForResource for replicationgroup ARNs — for
the record the ARN names, since the store keys groups by id alone.
Delete and modify of a group now share one monitor, so a modify cannot
write the group back after a delete removed it. Validation and wording
follow a live account.

Closes #2615

* fix(elasticache): refuse a KMS key with encryption at rest omitted, and change nothing on a refused modify

An omitted AtRestEncryptionEnabled is false on a live account and a
KmsKeyId is refused with it the same way as with an explicit false.
ModifyReplicationGroup applied the snapshot settings to the store's own
object before validating the user ids, so a request refused for an
unknown user had already changed the group; every check now runs before
any change.

* fix(elasticache): read AtRestEncryptionEnabled as a live account does, and refuse an empty snapshot window

A live account reads any AtRestEncryptionEnabled value that is not
"false" as true — banana, yes and "TRUE " all created an encrypted
group — so the flag is read the same way rather than parsed strictly.
A snapshot window whose end equals its start was measured as a full day;
a live account refuses it as shorter than an hour.
2026-08-27 16:53:33 -04:00
Sam Fakhreddine 4affa05cea feat(firehose): add StartDeliveryStreamEncryption and StopDeliveryStreamEncryption (#2583)
* feat(firehose): add Start/StopDeliveryStreamEncryption

Models DeliveryStreamEncryptionConfiguration on the stream description so
the encryption state set by Start is visible to Describe and cleared by Stop.
Limitations documented in docs/services/firehose.md.

* fix(firehose): keep the key identity on StopDeliveryStreamEncryption and reject Start without an encryption input

- Stopping customer-managed encryption now preserves KeyType and KeyARN with
  Status DISABLED, matching what DescribeDeliveryStream reports on real AWS.
- Streams persisted before the encryption field existed deserialize to the
  AWS-shaped DISABLED default instead of null via a field-level initializer.
- StartDeliveryStreamEncryption without DeliveryStreamEncryptionConfigurationInput
  is now rejected with InvalidArgumentException instead of silently defaulting.

* fix(firehose): reject a KeyARN that is not a KMS key ARN

StartDeliveryStreamEncryption stored DeliveryStreamEncryptionConfigurationInput's
KeyARN verbatim, so a bare key id or an alias ARN was accepted and then reported
back by DescribeDeliveryStream as the stream's encryption key. botocore pins
AWSKMSKeyARNForSSE to arn:.*:kms:<region>:<12-digit account>:key/<id> with a
512-character cap; anything else is an InvalidArgumentException on real AWS.

* fix(firehose): enforce the modeled input constraints on the pre-existing operations

DeliveryStreamType is now checked against the modeled enum, and Tags,
Records and TagKeys against their modeled list bounds (1-50, 1-500,
1-50), all answering InvalidArgumentException as the operations model.
Previously all four were accepted verbatim. Included here because this
PR already carries wire-shape hardening for the same handler; found by
a model-grounded constraint sweep.

* fix(firehose): treat StartDeliveryStreamEncryption input as optional

DeliveryStreamEncryptionConfigurationInput is Required: No in the model; omitting
it is the documented way to enable SSE with the service-owned key and defaults
KeyType to AWS_OWNED_CMK. The prior null-input rejection regressed that path -
inverted the pinning test to assert the 200/AWS_OWNED_CMK behavior.
2026-08-27 16:48:12 -04:00