Commit Graph
48 Commits
Author SHA1 Message Date
Mario Toffia 88a992757e feat(lambda): bisect failing DynamoDB stream batches and keep refused failures (#4337)
BisectBatchOnFunctionError now splits a batch that fails with a function
error in half, keyed by checkpoint, until the poison record is isolated.
Splits do not consume the retry quota; throttles and partial batch
responses do not split.

A discarded batch whose OnFailure destination refuses the send is parked
at the persisted checkpoint and only the send is retried with backoff,
instead of checkpointing past a batch that was never delivered.
2026-09-24 21:18:00 -04:00
lex00 41ceed4dba feat(lambda): manage code signing configurations (#4286)
* feat(lambda): manage code signing configurations

CreateCodeSigningConfig and its Get, Update, Delete and List siblings were
missing, so aws_lambda_code_signing_config and anything else that manages the
resource had nothing to call.

Adds the five, backed by a store. Constraints come from the model: an id of
csc- plus 17 characters, AllowedPublishers required with one to twenty signing
profile ARNs, a Description of at most 256 characters, and Warn as the default
UntrustedArtifactOnDeployment.

ListFunctionsByCodeSigningConfig now resolves the configuration instead of
answering every well-formed ARN with a 404. That answer was correct only while
no configuration could exist. A known one reports no functions, since
PutFunctionCodeSigningConfig is still not wired.

Nothing verifies a signature, so a configuration never gates a deployment. The
docs say so.

* fix(lambda): register the code signing config model for reflection

PersistedModelReflectionTest flagged it: a type reachable from persisted
storage needs @RegisterForReflection or native-image persistence breaks on
restart. The two nested shapes need it too.

* docs(lambda): name the ARN pattern as the reason the id alphabet is lowercase

The comment credited the id pattern, which is the looser of the two.
CodeSigningConfigId allows csc-[a-zA-Z0-9-_\.]{17} and CodeSigningConfigArn
ends in csc-[a-z0-9]{17}, so the ARN is what binds the alphabet. Anyone
reconciling the code against the old comment could widen it, still satisfy the
id pattern, and start emitting ARNs that do not conform.

Also imports List in the new test instead of writing java.util.List.of inline.

* fix(lambda): mint the code signing config ARN through AwsArnUtils

The ARN was assembled from a hardcoded arn:aws: prefix, so it named the
commercial partition whatever region the request carried. AwsArnUtils resolves
the partition from the region, which is what the partition-literals gate asks
for.

* fix(lambda): validate every member of an update before applying any

The store hands back the live instance, so validating and setting in turn left
an earlier member written when a later one was rejected. An update carrying a
valid Description and an empty AllowedPublishers answered 400 with the
description already changed, visible to the next GetCodeSigningConfig and
saved by the persistent and hybrid stores on their next write.

aRejectedUpdateChangesNothing sends that combination, and the same shape with
the policy as the rejected member, and asserts the description is unchanged
after each. It fails without the reordering.
2026-09-24 12:05:29 -04:00
stodan 34f4f72e82 fix(cloudformation): pass Lambda hot-reload code through to the Lambda service (#4093)
* fix(cloudformation): pass Lambda hot-reload code through to the Lambda service

AWS::Lambda::Function code of {S3Bucket: hot-reload, S3Key: /host/path} is
Lambda's bind-mount hot-reload convention: the bucket is a marker and the key
is a directory on the Docker host. The provisioner probed S3 for the pair
before calling CreateFunction, so no such object existed and the stack failed
with a ValidationError (or, with allow-stub-lambda-code on, quietly deployed
the stub handler).

Skip the S3 probe for the hot-reload bucket and hand the Code map to
LambdaService unchanged, which keeps enforcing hot-reload enablement, the
absolute-path rule and the allow-list, and reports its own error as the
resource status reason. Record a hot-reload code identity so a redeploy with
the same path is a no-op, and compare adopted functions by host path since a
hot-reload function carries no S3 bucket or key.

* fix(cloudformation): canonicalise the hot-reload code identity

LambdaService stores a hot-reload host path normalised (#4053), while the
provisioner recorded the raw template key as the code identity and compared
adopted functions against it. A template that spelled the same directory with
a trailing slash or a ".." segment, or a function adopted from a direct
CreateFunction, therefore looked like a code change and triggered an
UpdateFunctionCode that mounted the same directory again.

Build the identity from, and compare against, the normalised path. The raw key
still goes to Lambda so its validation and error messages are unchanged. Also
cover the documented SAM CodeUri form, s3://hot-reload//abs/path, through the
transform.
2026-09-23 18:03:35 -05:00
Allen Sanborn 97a2a08e1f feat(lambda): deliver asynchronous invocation results to configured destinations (#4247)
* feat(lambda): deliver asynchronous invocation results to configured destinations

An event invoke configuration was stored and returned faithfully but never
applied, so a function with an OnSuccess or OnFailure destination computed its
result and the emulator dropped it. A CDK application that carries a function's
output on to a bus, as the Loan Broker sample does with an EventBridge
destination, saw nothing arrive.

An Event invocation now hands its result to AsyncInvokeDestinationRouter, which
delivers the invocation record AWS sends to all four destination kinds, routed
by the service in the destination ARN: an EventBridge event bus, an SQS queue,
an SNS topic, and another Lambda function. On a bus the record is the event
detail, under the source "lambda" and the detail type "Lambda Function
Invocation Result - Success" or "... - Failure", so a rule matching
detail.responsePayload.<field> sees the function's own response where AWS puts
it. A function error routes to OnFailure with a condition of RetriesExhausted, a
responseContext.functionError, and the error as the responsePayload.

The router is its own bean and reaches its collaborators through Instance
lookups because the dependency graph runs the other way: SnsService invokes its
Lambda subscribers and EventBridgeInvoker its Lambda targets, so injecting
those services into LambdaExecutorService eagerly would close a CDI cycle. The
lookup happens per delivery, which is also when a destination is first known to
exist, so a function without one costs a single map read. Delivery runs on the
invocation's pool thread under the destination account's request scope, and a
destination that rejects the record is logged: the caller was answered with 202
long before, and has nowhere to receive a late failure.

Retries and event age are still not applied, so a failure reaches its
destination once and approximateInvokeCount is always 1. The docs say so.

* fix(lambda): read an event invoke configuration as the function's own account

The configuration store is account-aware: PutFunctionEventInvokeConfig writes
into the caller's partition, keyed by that account. findEventInvokeConfig is
called from the asynchronous invoke pool, which carries no request context, so
the read fell back to the default account. A function in any other account
therefore looked as though it had no configuration and its destination was
silently skipped, with nothing logged, because having no destination is the
ordinary case this path is built to return quickly.

The read now runs under the function's owning account, taken from the function
itself and falling back to the account in its ARN, the same way the other
background workers re-establish an account before touching an account-aware
store.

* fix(lambda): bound a Lambda destination chain that leads back into itself

A function whose OnSuccess or OnFailure destination is a Lambda function, and
whose chain of those leads back to a function already in it, invoked forever.
Real AWS is not unbounded here either: recursive loop detection halts such a
chain after about sixteen invocations, so looping without end was a deviation
and not merely a hazard, and on a laptop it is a worse one than on AWS.

The number of destination hops that reached an invocation is now carried with
it, from the router through invokeArnFromDestination and into the executor, and
a Lambda destination at the sixteenth hop is dropped with a warning naming the
function the chain started from. A ThreadLocal, which is how the EventBridge
invoker bounds bus-to-bus forwarding, cannot serve here: every hop is an Event
invocation and so runs on a different pool thread.

The bound applies to Lambda destinations alone, the only kind that re-enters
this path. A queue, topic or bus at the last hop is still delivered, since it
ends the chain rather than extending it.

* docs(lambda): state the destination limits in the service docs

The alias constraint was recorded only in findEventInvokeConfig's javadoc, which
serves a maintainer reading the code and not a user reading the service docs,
and AGENTS.md asks for an intentional deviation to be documented. A destination
configured on an alias is not found, because the lookup matches the version the
invocation ran; $LATEST and an explicit version both work, and the CDK onSuccess
and onFailure properties store theirs under $LATEST.

Records the Lambda destination chain bound alongside it, so both limits of this
feature are in one place.

* refactor(lambda): make the destination routing switch an expression

AGENTS.md asks for switch expressions over switch statements without
qualification. The routing switch was a statement whose arms fell through to a
shared log line, with two of them returning early to skip it. Each arm now
yields whether the record was delivered and the log line is guarded on that,
which also removes the two returns hidden inside the arms.

The Lambda arm moves into its own method so its chain-bound check reads as a
condition on delivery rather than a second exit from the switch. No behaviour
changes: a record dropped for an unsupported ARN or for reaching the chain bound
is still logged at warn and still leaves the debug line unwritten.

* fix(lambda): carry the function and destination as event resources, and say S3 is not delivered

Two parity gaps against the capturing-records page, both found in review.

putOnEventBus set no Resources. AWS fills the event's resource field with the
invoked function and the destination, and EventBridgeService already emits the
member and matches rules against it (buildEventEnvelope reads entry Resources at
:1041 and writes `resources` at :1064; matchesPattern reads it at :894). Without
it a rule whose pattern matches on `resources` never fires -- the field arrives
empty rather than absent, so the pattern does not match and the record is dropped
at the bus rather than at the destination. Rules matching on `detail`, which is
the case the tests cover, are unaffected, which is why it stayed invisible.

The docs claimed all four destination kinds are supported. AWS has five: an S3
bucket, on failure only. The router keys on the service in the destination ARN
and has no s3 arm, so such a record reaches the default arm and is dropped with a
warning. That is the deploys-green-nothing-arrives shape this branch exists to
remove, so it is now a third bullet in the limits list rather than an omission,
and the opening sentence says four of five instead of all four.

The Resources test is measured killing a mutant: with the entry.put removed it
fails with "was: null", which is the defect verbatim.

* docs(lambda): correct the pre-fix mechanism, and scope the hop bound honestly

Two corrections from review, both to things this branch asserted.

The Resources javadoc and its test comment said the member "arrives empty
rather than absent, so the pattern simply does not match". It was absent, and
the route is worse than a mismatch: matchesPattern casts event.get("Resources")
to an ArrayNode unconditionally (EventBridgeService.java:894), so an absent
member throws NPE, the surrounding catch swallows it, and it is logged as
"Failed to parse event pattern" and reported as no-match. The record is dropped
at the bus and the log blames the caller's pattern. SesEventPublisher.java:215
already documents the same shape in almost the same words.

The limits list said a chain "stops at 16 hops" without qualification. The bound
is keyed on the destination being a Lambda ARN, so a cycle that leaves and
re-enters Lambda another way is not bounded at all: SnsService.java:1688 and
EventBridgeInvoker.java:109 each start a fresh chain at zero, so a topic that
fans back to the function, or a bus rule targeting it, loops forever. With
CallerRunsPolicy on the async executor that grows the stack once the queue
saturates rather than just spinning.

The code fix needs the depth threaded through both re-entry points, so it is
filed rather than done inline. The docs no longer claim what the code does not
do, which is the half that must not wait.

* fix(lambda): always emit millisecond precision in the record timestamp

Instant.toString() emits micro or nanosecond precision on JDK 9+, and emits no
fractional part at all when the nanos are zero. AWS always emits milliseconds
(2019-11-14T18:16:05.568Z), so a consumer parsing the record with a fixed .SSS
pattern breaks on the whole-second case. Same formatter shape as
ElasticBeanstalkQueryHandler, which already had this problem.

The test is deterministic on purpose. An assertion that only formats now() is
passed by truncatedTo(MILLIS).toString() about 999 runs in 1000, since that
differs only on an exact second -- I measured exactly that: the first version of
this test let the near-miss through, 16/16 green. formatRecordTimestamp is
package-private so the deciding input can be pinned, and the mutant now fails
with "expected 2019-11-14T18:16:05.000Z but was 2019-11-14T18:16:05Z".

LambdaEventInvokeConfigAccountScopeTest becomes an IntegrationTest. The earlier
round dismissed the conformance warning as a rule the repo ignores; review
counted it, and it does not: 778 of 922 @QuarkusTest classes follow the naming,
and 26 of 29 within services/lambda. The dismissal was wrong.
2026-09-23 18:32:06 -04:00
Priamo Germosen 83ae2b4697 fix(lambda): mount hot-reload read-only and refuse Docker socket directories (#4154)
Bind-mount the hot-reload host directory at /var/task read-only, as /var/task is in AWS Lambda, and, when no allow-list is set, refuse the host root, /var, /proc, and anything under /run or /var/run, where the Docker socket lives or can be reached. Move the no-allow-list warning onto StartupEvent, beside NetworkExposureGuard, so it reaches an operator who has not called Lambda yet.
2026-09-22 07:38:20 -05:00
Priamo Germosen 847ad256f2 fix(lambda): resolve hot-reload paths before checking the allow-list (#4053)
Normalize the hot-reload S3Key and compare it against the allow-list by directory instead of by string prefix, so dot-dot segments and sibling directories no longer pass. Store the normalized path, reject a colon in it, and warn at startup when hot-reload runs without an allow-list.
2026-09-21 07:53:07 -05:00
Vũ Thế Huy 75d1c2ae62 feat(lambda): support custom Docker flags (#3751) 2026-09-17 10:57:42 -04:00
Chris Jovanovski 86072aaa84 fix(lambda): back off DynamoDB Streams retries and expire aged records (#3613)
* fix(lambda): back off DynamoDB Streams ESM retries and enforce MaximumRecordAgeInSeconds

* fix(lambda): treat unset MaximumRecordAgeInSeconds as no age cutoff

Keep expired records retrying when no finite Lambda age limit is configured.
2026-09-15 21:46:27 -04:00
Brian Taylor 24a8c8440b fix(lambda): resolve layer version ARNs by account (#2948)
* fix(lambda): resolve layer version ARNs by account

Layer resolution dropped the ARN's account segment, so an ARN naming another
account resolved inside the caller's own partition. Two consequences, filed
separately as #2813 and #2809.

A foreign ARN whose layer name and version happened to match one of the
caller's own resolved to that layer: the function recorded an ARN it was not
using, and the launcher mounted different content at /opt than
GetFunctionConfiguration reported. resolveLayerByArn now scopes the lookup to
the caller's account and partition, so a foreign ARN is a miss.

A foreign ARN that matched nothing was rejected outright, which no AWS-managed
public layer can ever satisfy: Powertools, the AppConfig extension and
Datadog-published layers all live in AWS-owned accounts, and every Terraform
stack attaching one failed at CreateFunction. Validation now applies the
eager existence check only to the caller's own account and records a foreign
ARN unresolved, warning that its content is not mounted.

Measured against the live service in ap-southeast-1:

  CreateFunction, foreign ARN matching an own layer name/version
    -> AccessDeniedException, not a substitution
  CreateFunction, AWS-managed Powertools layer
    -> 201, ARN echoed verbatim on GetFunctionConfiguration
  CreateFunction, missing layer in the caller's own account
    -> InvalidParameterValueException: Layer version ... does not exist.

The own-account message and status are unchanged, matching that third case
exactly. The AccessDenied case is a known divergence: Floci implements no
layer permissions, so it cannot tell a public layer from one the caller has no
policy for, and accepts both.

Closes #2813
Closes #2809

* fix(lambda): reject foreign-partition layer ARNs when attaching them

GetLayerVersionByArn already answers a non-aws partition with
InvalidParameterValueException, but CreateFunction and
UpdateFunctionConfiguration accepted the same ARN and persisted it, so a
function could carry a layer Floci's own lookup path calls invalid.

Partitions are isolated, so no resource policy can ever make a cn or
gov layer readable from the aws partition. That is what separates it
from a foreign account, where a policy can, and where AWS-managed public
layers live. Foreign accounts stay accepted; foreign partitions now
reject with the message GetLayerVersionByArn already uses.

Measured on CreateFunction in ap-southeast-1: a cross-partition layer
ARN and a foreign-account layer ARN both fail with AccessDeniedException,
so the live service does not distinguish them at this call. The split
here is Floci's, on reachability grounds, and is documented as such.

* fix(lambda): gate foreign-account layer ARNs behind a config flag

Review asked for the accept-foreign-ARN behaviour to be opt-in rather than the
default, on both PRs' reasoning that it broadens what CreateFunction accepts
beyond AWS. It is now floci.services.lambda.accept-external-layer-arns, default
false, env FLOCI_SERVICES_LAMBDA_ACCEPT_EXTERNAL_LAYER_ARNS.

Off, a layer ARN naming another account is refused. On, it is recorded on the
function verbatim and its content is not mounted, which is what a stack
attaching Powertools or the AppConfig extension needs. A same-account ARN is
unaffected either way: a missing layer is still the eager
InvalidParameterValueException.

The refusal is AccessDeniedException, 403, not the InvalidParameterValueException
this branch previously used for the partition case. That was the second review
finding: the live probe in this PR measured CreateFunction returning
AccessDeniedException for a cross-partition ARN and the identical
AccessDeniedException for a same-partition foreign account, so reporting a
different error class than what was measured was an observable divergence
presented as parity. Both now report what AWS reported.

Cross-partition stays refused with the flag on. Partitions are isolated, so no
resource policy can make an aws-cn layer readable from aws, and
GetLayerVersionByArn already calls such an ARN invalid.

Negative control, with the default flipped to true and the tests kept:

  LambdaLayerArnAccountIntegrationTest
    foreignAccountArnIsDeniedByDefaultAndTheFunctionIsNotCreated
    updateFunctionConfigurationIsDeniedAndLeavesTheExistingLayerInPlace
  Tests run: 7, Failures: 2

Also moves the two generic ARN ownership checks this branch was adding into
AwsArnUtils as isForeignPartition and isForeignAccount, so the layer code keeps
only the layer-shaped part. Review noted RdsService.targetGroupBelongsTo already
carries its own copy and asked not to land a further one. The existing RDS, EKS
and EC2 copies are deliberately left alone; this only avoids adding another.
2026-09-13 00:19:37 -04:00
Allen Sanborn 83b010e6c3 docs(lambda,s3): mark two leniencies as Floci's call, not observed AWS (#3270)
* docs(lambda,s3): mark two leniencies as Floci's call, not observed AWS

Both lines read as parity claims for behaviour nobody probed against
AWS, which is the failure mode of keeping measured and inferred apart:
a later reader can cite either one as a probed result.

lambda.md: accepting ApplicationLogLevel and SystemLogLevel alongside
LogFormat=Text is justified in the text by Floci's own response shape,
which never surfaces those levels for Text. Request behaviour and
response behaviour are both our choice, so say so.

s3.md: log-delivery-write really does match AWS on PutBucketAcl, but
AWS documents that canned ACL as bucket-only and the SDK's
ObjectCannedACL enum omits it, so accepting it on PutObjectAcl is a
Floci leniency rather than parity. Both paths share one canned-ACL
helper, which is also why aws-exec-read, an object-only canned ACL in
the SDK model, is accepted on buckets. Name that mirror-image case so
the next reader sees the pattern instead of filing it again.

No behaviour change: both entries describe code that stays as it is.

* docs(s3): attribute the aws-exec-read narrowing to the SDK model, not to AWS

The sentence said aws-exec-read is one "which AWS lists only for objects". That is
the same mistake this PR exists to correct, made inside the correction: AWS's canned
ACL reference lists it under "Bucket and object". What is narrower is botocore's
BucketCannedACL enum, which omits it while ObjectCannedACL includes it, so the
client-side validation on PutBucketAcl is an SDK artefact rather than documented AWS
behaviour.

Verified against the shipped model: BucketCannedACL is private, public-read,
public-read-write, authenticated-read; ObjectCannedACL adds aws-exec-read,
bucket-owner-read and bucket-owner-full-control.

The log-delivery-write half of the sentence was accurate and is unchanged.
2026-09-09 15:21:04 -04:00
Mario Toffia af42564cb3 feat(lambda): provision AWS::Lambda::EventInvokeConfig (#3230)
* feat(lambda): provision AWS::Lambda::EventInvokeConfig

The physical id is the registry schema's composite FunctionName|Qualifier
identifier. A create puts the configuration, an update with the same identity
applies the template's settings through the merge-style update call, and a
changed function or qualifier is a replacement whose displaced configuration
the ReplacementCleanup record deletes once the update commits or restores on
rollback. The schema's MaximumRetryAttempts and MaximumEventAgeInSeconds
bounds are checked before any call, as CloudFormation validates them before
the handler runs.

The Lambda docs now list the five event invoke config operations, which the
page wrongly called not implemented, and say that asynchronous invocations do
not yet apply the settings.

* fix(lambda): update the event invoke config in place for equivalent names and roll back in-place changes

A short name and the function's ARN address one configuration, so an update
that changes between them updates in place under the prior physical id
instead of recording a replacement whose cleanup would delete that one
configuration. An in-place update keeps the settings it replaces on the
resource, and a failed stack update puts them back in full. DestinationConfig
is resolved before it is looked at, so a conditional that resolves to
AWS::NoValue is omitted rather than sent as an empty destination set. The
integration test reads stack events with XmlParser.

* fix(lambda): keep the event invoke config rollback snapshot until the restore succeeds

A restore that throws left no snapshot behind, so the next rollback attempt
reported success without restoring anything. The snapshot is now spent only
after the settings are back.
2026-09-08 07:34:52 -04:00
Vũ Thế Huy ec2d678e6d fix(lambda): honor MaximumBatchingWindowInSeconds on SQS event source mappings (#3203)
* fix(lambda): honor MaximumBatchingWindowInSeconds on SQS event source mappings

CreateEventSourceMapping, GetEventSourceMapping and UpdateEventSourceMapping now
parse, validate (0 to 300), persist and return MaximumBatchingWindowInSeconds
instead of silently dropping it.

When the window is greater than 0 the SQS poller holds an underfilled batch open,
accumulating messages across polls, and invokes the function once the batch
reaches BatchSize or the window elapses since the first buffered message. A window
of 0 or unset keeps the previous invoke-on-first-receive behavior.

Closes #3155

* fix(lambda): cover the batching window in SQS message visibility and window-off transitions

Address review feedback on the batching-window poller:

- Visibility timeout is now fn.timeout + window + 30 instead of the max of the two,
  so a message buffered for the full window and then processed for the full
  function timeout stays invisible for the whole span. Otherwise a long invoke
  could outlive the visibility and another consumer would receive a duplicate
  with a stale receipt handle.
- When the window is changed from positive to zero (or unset) on a live mapping,
  the poller now drains and delivers any already-buffered batch on the next tick
  instead of ignoring it, so those messages are not stranded until their
  visibility expires and cannot be replayed alongside fresh copies if a positive
  window is later restored.
2026-09-07 21:43:06 -05:00
Mario Toffia 024bfa0a5c feat(docker): containers Floci launches trust the Floci CA (#3091)
* feat(tls): write a CA bundle for launched containers at boot

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

#3079's docs commit (dc3e9ee6a) was written against a tls.md that predated
#3086 and, once squashed onto main, removed the "Custom Domains Learned at
Runtime" section #3086 had added and reworded the intro to place ACM
certificates "in a later release", although AcmService has issued them from
the local CA since #3086. Both are restored here, next to the new section,
because a separate PR would conflict with this one on the same lines.
2026-09-06 14:57:08 -05:00
Vũ Thế Huy ee5c87d6d6 feat(lambda): support self-managed Apache Kafka event source mappings (#3062) (#3082)
* feat(lambda): support self-managed Apache Kafka event source mappings (#3062)

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

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

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

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

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

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

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

* test(cloudformation): assert exact Fn::GetAtt attributes for Lambda ESM
2026-09-05 23:41:44 -04:00
Guilherme Scaranse 5512db0e05 fix(lambda): persist, validate and enforce event source mapping FilterCriteria (#3060)
* fix(lambda): persist and validate event source mapping FilterCriteria

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

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

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

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

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

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

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

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

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

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

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

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

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

Stricter than AWS for cidr, wildcard and boolean literals, all of which AWS
accepts. Docs record the deviation and the reason.
2026-09-05 10:32:42 -04:00
Priamo Germosen 252bfe85a2 feat(lambda): mint EKS bearer tokens natively for the kubernetes executor (#2981)
* docs(lambda): qualify which kubeconfig auth methods the Kubernetes executor supports

#2919 replaced the Fabric8 Kubernetes client with a plain REST client that
only understands static-token and client-certificate kubeconfig auth. The
Kubernetes executor section still said Floci "uses your local kubeconfig"
without qualification, which reads as full kubectl parity. exec and
auth-provider credential plugins (aws eks get-token, gcloud) fail with a
named error instead, so an EKS or GKE user following the doc as-is would
be surprised.

Follow-up noted on hectorvent's approval of #2919.

* feat(lambda): mint EKS bearer tokens natively for the kubernetes executor

#2919 dropped the Fabric8 Kubernetes client, whose kubeconfig handling
covered exec-credential plugins like `aws eks get-token` as a side effect
of shelling out to them via client-go. The replacement REST client
rejected that shape outright, so kubeconfigs generated by
`aws eks update-kubeconfig` (the common case for a real EKS cluster)
stopped working.

Adds EksTokenMinter, which recognizes the `aws eks get-token
--cluster-name <name>` exec shape and mints the bearer token itself:
a presigned sts:GetCallerIdentity URL with x-k8s-aws-id bound into the
signature, base64url-encoded and prefixed with k8s-aws-v1., matching
what aws-iam-authenticator's webhook expects and what the AWS CLI's
own `aws eks get-token` produces. No subprocess is spawned and no SDK
dependency is added, keeping KubernetesApiClient as it was after #2919.

Recognition scans for "eks", "get-token" as a consecutive pair
anywhere in the exec args, rather than requiring them first: confirmed
against the AWS CLI's own update_kubeconfig.py, a generated kubeconfig
always puts the global --region ahead of the subcommand and --output
json after it, so a strictly-positional check would have rejected
every kubeconfig that tool actually produces.

Credentials are resolved from AWS_ACCESS_KEY_ID/AWS_SECRET_ACCESS_KEY/
AWS_SESSION_TOKEN, falling back to the shared credentials file
(AWS_PROFILE, default ~/.aws/credentials). Both are read from the
kubeconfig exec block's own `env` entries first: `aws eks
update-kubeconfig --profile <p>` threads the profile through exec.env
precisely because the plugin has no other reason to see it. An
AWS_PROFILE the exec block names explicitly is honored ahead of static
keys that merely happen to be ambient in Floci's own process, rather
than falling out of plain env-var-beats-profile precedence: those
ambient keys weren't necessarily meant for this resolution, so letting
them silently outrank a profile the kubeconfig specifically asked for
would authenticate as the wrong principal. A lone access key or secret
key, at either the exec.env or ambient-env tier, is rejected outright
rather than silently falling through to the next source, matching
botocore's own PartialCredentialsError instead of quietly picking a
different identity than whatever was actually intended. A session
token is only ever combined with the access/secret key pair from the
same source (exec.env or ambient) it came from, never mixed across
the two, since a session token is only valid for the specific key
pair STS issued it alongside.

STS is signed against the region's actual partition suffix, sourced
from the AWS SDKs' own public partition metadata (botocore's
partitions.json): amazonaws.com for the commercial aws partition and
aws-us-gov, amazonaws.com.cn for aws-cn, and the classified
ISO/ISOB/ISOE/ISOF partitions each under their own distinct domain.
Previously this always assumed the commercial partition, so a
non-standard-partition cluster would get a token signed for a host
that isn't its real STS endpoint.

Role assumption is rejected explicitly, in every form get-token's own
--role-arn flag can actually reach this code as: not just the long
form and the abbreviated --role that update_kubeconfig.py writes when
--role-arn was passed to update-kubeconfig, but every unambiguous
prefix in between (--role-a, --role-ar) that AWS CLI's own argument
parser equally accepts, since role-arn is the only get-token option
starting with "role", plus all of those flags' --flag=value spellings.
Missing any of these would silently mint a token under ambient or
profile credentials instead of the identity the kubeconfig asked for.
Any other exec command or an auth-provider plugin still fails with a
named error rather than being silently mishandled;
SSO/IMDS/container-credentials/IRSA are not implemented.

mint's signing timestamp now takes an injectable Clock (defaulting to
Clock.systemUTC() for every existing caller) instead of calling
Instant.now() directly, so a test can pin it and assert on the exact
resulting signature. Added such a test: the signature for fixed
credentials, cluster, region and timestamp is checked against a value
computed by a from-scratch Python re-implementation of the SigV4 spec,
not ported from this code, so the two can't share a bug. Every other
test up to now only checked the token's shape (right host, right
query keys, a signature that looks like a signature); this is the
first one that proves the actual bytes are what the spec says they
should be.

Also updates docs/services/lambda.md's Kubernetes executor section,
which still said the aws eks get-token exec plugin was unsupported.
2026-09-04 18:05:00 -05:00
Kurt McAlpine 23728e0b75 feat(ecr): prefer locally present images over the loopback registry rewrite (#3022)
* feat(ecr): prefer locally present images over the loopback registry rewrite

EcrRegistryManager.rewriteImageUri rewrote every AWS-shaped
<account>.dkr.ecr.<region>.amazonaws.com/<repo>:<tag> URI to Floci's
loopback registry unconditionally, so a container image Lambda function
(or ECS task) whose image was built locally and tagged with its real ECR
URI could never run: the launcher started the registry:2 sidecar and
tried to pull from it, failing with "failed to resolve reference ..."
(Lambda.InitError) even though the daemon already held the image.

The rewrite now first asks the Docker daemon whether the image exists
under the URI as given; if it does, the URI is used unchanged and the
registry container is not started. Images the daemon does not have keep
the existing rewrite-and-pull path, so CDK DockerImageFunction flows are
unaffected. floci.services.ecr.prefer-local-images
(FLOCI_SERVICES_ECR_PREFER_LOCAL_IMAGES, default true) restores the old
behaviour when set to false.

Verified with a provided.al2023 Go image tagged
000000000000.dkr.ecr.ap-southeast-2.amazonaws.com/e2e/hello-image:local:
Invoke fails on 2.0.1 and succeeds with this change, both with Floci as
a host process and inside a container sharing the host's docker.sock; an
image absent from the daemon still takes the rewrite path.

* fix(ecr): inspect the image reference ContainerBuilder launches when preferring local images

With floci.docker.image-registry-base set, rewriteImageUri inspected the bare
AWS-shaped URI while ContainerBuilder later prefixed it, so a locally present
image was reported as found and then missed at launch. Resolve the image
through ContainerBuilder before asking the daemon so both paths agree.
2026-09-04 10:59:51 -04:00
Niels Kootstra 7fdd145c0c fix(lambda): honor configured function architecture (#2994)
* fix(lambda): honor configured function architecture

* fix(lambda): isolate Docker images by platform

* fix(lambda): reject unsupported architectures early

* fix(lambda): require one function architecture

Note: pre-existing full-suite flakes in EC2, Kinesis Analytics, and RDS Data passed in isolated reruns.

* fix(lambda): preserve legacy architecture fallback

* fix(lambda): reject malformed architecture fields

* fix(lambda): reject invalid persisted architectures
2026-09-04 09:22:23 -04:00
Priamo Germosen 2b531dad3a docs(lambda): qualify which kubeconfig auth methods the Kubernetes executor supports (#2978)
#2919 replaced the Fabric8 Kubernetes client with a plain REST client that
only understands static-token and client-certificate kubeconfig auth. The
Kubernetes executor section still said Floci "uses your local kubeconfig"
without qualification, which reads as full kubectl parity. exec and
auth-provider credential plugins (aws eks get-token, gcloud) fail with a
named error instead, so an EKS or GKE user following the doc as-is would
be surprised.

Follow-up noted on hectorvent's approval of #2919.
2026-09-02 23:17:06 -05:00
Brian Taylor ca4c84c9e0 fix(lambda): delete only the named version when DeleteFunction has a Qualifier (#2824)
* fix(lambda): delete only the named version when DeleteFunction has a Qualifier

DeleteFunction accepted a Qualifier and dropped it: the controller never
bound the query parameter, so every call took the unqualified path and
removed the function, $LATEST and every other version. A caller pruning
one old version silently lost the whole function, with a success
response and no warning.

The qualified path now removes that version alone. Error behaviour
follows the live service rather than the reference, which documents none
of it: deleting $LATEST by qualifier and naming an alias are both
InvalidParameterValueException, a version an alias references is a
ResourceConflictException, and a version that does not exist is a silent
success rather than a 404.

Closes #2819

* test(lambda): cover qualified DeleteFunction through the AWS SDK

The integration test drives the endpoint over raw HTTP, so nothing
exercised the qualified delete through a real SDK client. Adds SDK
coverage for the four cases: deleting one version leaves the function
and its other versions, $LATEST cannot be deleted by qualifier, a
version an alias references is refused, and an absent version is a
no-op.

* fix(lambda): pattern-validate the DeleteFunction qualifier

Character.isDigit accepts non-ASCII decimal digits, so a full-width or
Arabic-Indic digit was read as a version number and answered with a
silent 204 instead of being rejected. The live service pattern-validates
the qualifier before anything else and its constraint is ASCII-only;
that check now runs first, and the digit test no longer relies on
Character.isDigit.
2026-08-31 22:01:34 -04:00
Brian Taylor 44629631ca fix(lambda): honour ListLayers and ListLayerVersions query parameters (#2817)
* fix(lambda): honour ListLayers and ListLayerVersions query parameters

CompatibleRuntime, CompatibleArchitecture, MaxItems and Marker were
accepted and ignored, and NextMarker was never emitted, so a client
paginating with MaxItems saw a single page and silently got the whole
list, while a runtime or architecture filter returned layers that do
not match it.

Both actions now filter, paginate and emit NextMarker. Validation
follows the live service rather than the API reference: range and enum
failures accumulate into one ValidationException in a fixed member
order, a non-integer MaxItems is a SerializationException that
short-circuits validation, and a Marker the service did not issue is
InvalidParameterValueException "Invalid pagination key.".

Under a filter, LatestMatchingVersion is the newest version that
matches rather than the newest overall, so ListLayers needs every
version of each layer rather than the latest of each.

Closes #2808

* fix(lambda): sign layer pagination markers

The tag identifying a Marker as Floci's was a fixed string, so a caller
could base64 a cursor of their own with the same prefix and have it
accepted. That cursor was then applied to the page, silently skipping
results or emptying the list where AWS rejects an unissued token.

Markers now carry an HMAC over the cursor, keyed per process, so a
fabricated or edited token fails the check. A marker from an earlier run
is stale for the same reason, which is what AWS does with an expired one.

* test(lambda): cover layer listing parameters through the AWS SDK

AGENTS.md prefers SDK clients over raw HTTP for management-plane
validation. The integration test covers the parameters through the wire
protocol; this adds the same filtering, pagination and enum rejection
through @aws-sdk/client-lambda, so a marshalling regression that only
the SDK would notice does not pass unseen.
2026-08-31 19:38:30 -04:00
Brian Taylor a7b2b79492 fix(lambda): honour Publish on CreateFunction and UpdateFunctionCode (#2825)
The Publish flag was never read on either path, so no version was ever
created unless the caller made a separate PublishVersion call, and both
actions reported Version as $LATEST. Terraform reads Version and
qualified_arn straight from that response, so every aws_lambda_function
with publish = true recorded $LATEST — which Lambda@Edge cannot use.

Both actions now publish and report the new version. The ARN they return
differs, following the live service rather than the reference, which does
not distinguish them: CreateFunction keeps the unqualified FunctionArn
while UpdateFunctionCode returns the qualified one, as PublishVersion
does.

Closes #2820
2026-08-31 14:52:19 -04:00
Brian Taylor 968ff78e25 fix(lambda): make the code-volume populate concurrency configurable (#2830)
Concurrent first-time code-volume populates are capped by a semaphore sized
Math.max(2, availableProcessors() / 2). The JVM honours the container's cgroup
CPU quota, so a CPU-constrained Floci container derives 2 permits and concurrent
cold starts of *distinct* large functions complete in waves of two instead of in
parallel.

Measured on main, six distinct functions with 41MB packages, all cold, fired
concurrently, varying only the quota on Floci's own container:

  unlimited (16 cpu)  ->  8 permits  ->  one wave of 6   ->   8.3s
  --cpus=8            ->  4 permits  ->  waves of 4, 2   ->  13.2s
  --cpus=4            ->  2 permits  ->  waves of 2,2,2  ->  19.2s

The wave sizes track the formula exactly, which rules out generic CPU starvation
- that would slow all six uniformly rather than produce discrete equal-size waves.

The populate is IO-bound (creating a helper container and streaming a tar into
it), so CPU count is a weak proxy for how many the Docker daemon can absorb. The
cap itself is still worth having: the daemon overload it was added to prevent is
real. What was missing is a way to decouple it from the CPU allocation, so this
adds floci.services.lambda.code-volume-populate-concurrency
(FLOCI_SERVICES_LAMBDA_CODE_VOLUME_POPULATE_CONCURRENCY) and leaves the derived
default untouched.

Values below 1 fall back to the derived default with a warning: zero permits
would deadlock every populate, and a negative Semaphore count would make
acquire() block until that many releases arrived.

The semaphore becomes an instance field so the permit count can come from
config. Floci runs a single @ApplicationScoped launcher, so it is still one gate
for the whole emulator.

Refs #2050
2026-08-31 11:14:29 -04:00
Brian Taylor 5b363ffa2d fix(lambda): implement GetLayerVersionByArn (#2812)
* fix(lambda): implement GetLayerVersionByArn

GET /2018-10-31/layers?find=LayerVersion&Arn={arn} is GetLayerVersionByArn,
but only ListLayers was bound to that path and it ignored both query
parameters. A GetLayerVersionByArn call was therefore answered with a
ListLayers body and HTTP 200: an SDK deserialises that against the
GetLayerVersionByArn output shape, finds none of its members, and hands the
caller an empty result instead of the layer version or a
ResourceNotFoundException.

AWS gives the two actions the same method and path, discriminated only by
`find`, and JAX-RS cannot route on a query parameter, so the branch lives in
the handler.

The semantics below were measured against the live service rather than
inferred from the reference:

  find=LayerVersion&Arn=<present>  200 + LayerVersion object
  find=LayerVersion&Arn=<absent>   404 ResourceNotFoundException
  find=LayerVersion, no Arn        400 ValidationException, must not be null
  find=LayerVersion&Arn=junk       400 ValidationException, pattern in message
  find=Nonsense                    200 + ListLayers body
  find=layerversion                200 + ListLayers body (match is case-sensitive)

The Arn pattern enforced here is the one the live service reports in its own
ValidationException, not the one the API reference publishes: it constrains
the region segment more tightly and additionally accepts the AWS-managed
arn:<partition>:lambda:::awslayer:<name> form, which the reference omits.

The response reuses the builder GetLayerVersion already returns, and resolves
Content.Location against the layer's own region rather than the caller's,
matching the lookup resolveLayerByArn already keys on.

* fix(lambda): scope GetLayerVersionByArn to the caller's account

resolveLayerByArn keys on region, layer name and version. Storage is already
partitioned per account, so that lookup runs inside the caller's own partition
— an ARN naming a different account did not reach that account's layers, but it
did resolve to the caller's own same-named layer and return it.

Measured on main, without this action: account B publishes
arn:...:111111111111:layer:acct-probe:1, then calls CreateFunction with
Layers=[arn:...:000000000000:layer:acct-probe:1]. The call succeeds and the
function records account A's ARN while B's own layer is what resolves. Account
B never sees account A's layer — GetLayerVersion by name and ListLayers both
return nothing for it — so this is a wrong-resource answer, not a cross-account
read.

GetLayerVersionByArn is the one layer action that takes an account explicitly,
so it honours it: an ARN outside the caller's account is a 404, which is what
the caller already gets from GetLayerVersion for a layer it cannot see. No
layer can be shared cross-account here — layer permissions are unimplemented —
so a foreign account is always a miss, and the check is the place sharing would
hook in if that changes.

The same account-blindness reaches CreateFunction and UpdateFunctionConfiguration
through validateLayersResolvable, and the container launcher through the same
resolver. Those are pre-existing on main and change behaviour for existing
actions, so they are left for a separate change rather than folded in here.

* fix(lambda): reject a layer ARN naming another partition

The account guard compared only the account, and resolveLayerByArn drops
the partition as well as the account, so an ARN in another accepted
partition with the same account, region, name and version resolved to
the caller's local layer and was returned under the foreign-partition
ARN. The live service rejects those outright with
InvalidParameterValueException.
2026-08-31 09:10:49 -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
Allen Sanborn 94795dd67b fix(lambda): return VpcConfig, SnapStart and LoggingConfig from every read path (#2527)
* fix(lambda): return VpcConfig, SnapStart and LoggingConfig

CreateFunction and UpdateFunctionConfiguration accepted all three with a 200
and then omitted them from every read path, so a VPC-attached function read
back unattached. Terraform refreshes aws_lambda_function.vpc_config,
snap_start and logging_config on every plan, which made the resource
permanently non-converging rather than cosmetically incomplete.

VpcConfig was already stored but never serialised; SnapStart and LoggingConfig
were dropped on the floor entirely.

The response shapes are not the request shapes, per the AWS service model:

- VpcConfigResponse adds VpcId, which VpcConfig has no member for. Resolved
  from the first subnet through Ec2Service, and left off when EC2 does not
  know the subnet — Lambda still accepts unmanaged subnet ids.
- SnapStartResponse adds OptimizationStatus, which SnapStart has no member
  for. On only for a published version with ApplyOn=PublishedVersions.

SnapStart and LoggingConfig are always present in a response, as on AWS: unset
reads back as ApplyOn=None/OptimizationStatus=Off and LogFormat=Text with the
default /aws/lambda/<name> log group. LogFormat=JSON additionally returns both
log levels, defaulting to INFO. RuntimeVersionConfig is returned for managed
runtimes. All of it is carried into PublishVersion snapshots.

LoggingConfig is replaced wholesale on update rather than merged, matching AWS.
Both enums are validated against the model's enum sets before any field is
mutated, alongside the existing Layers and EFS pre-checks — updateFunction-
Configuration mutates the live store object, so a late throw would leave a
rejected update half-applied.

* fix(lambda): validate LogGroup and stop storing Text-format log levels

pgermosen's review on #2527 flagged two loose ends in LoggingConfig
handling. LogGroup accepted any non-blank string instead of AWS's
documented 1-512 character, [.\-_/#A-Za-z0-9]+ constraint. Separately,
ApplicationLogLevel and SystemLogLevel were stored regardless of
LogFormat but only ever surfaced by putLoggingConfig when the format
is JSON, so a Text-format function could accept a log level, persist
it, and never show it on any read path — the same accepted-then-
forgotten shape this PR exists to remove. applyLoggingConfig now only
keeps the levels when the resolved format is JSON, so nothing is
stored that isn't observable.

Also switches the two SnapStart integration tests off nodejs20.x,
which AWS's SnapStart guide does not support, onto java21, and adds
coverage for the LogGroup constraint, the JSON-only log level
validation errors, the VpcConfig detach path, and the parity error
wording pgermosen's review called out as unasserted.

docs/services/lambda.md is updated to describe the LogGroup
constraint and the Text-format no-op behavior.
2026-08-26 21:03:05 -04:00
TATSUNO “Taz” Yasuhiro bc13801121 feat(lambda): support kubernetes as the lambda runner (#1941)
* feat(lambda): support kubernetes as the lambda runner

* fix(lambda): keep the port reserved when a failed launch cannot confirm pod deletion

* fix(lambda): carry the owning account in the layer Content.Location URL

The URL is fetched unsigned. Without an X-Amz-Credential query the
account filter falls back to the default account, so a layer published
under another account resolves the wrong bucket namespace and 404s.
Mirror the credential query the kubernetes executor already appends to
its download URLs.

* chore(build): raise the surefire heap to 6g

The suite outgrew the 4g default heap of 16g CI runners. At OOM a full
GC reclaims almost nothing, so the live set is real. The heap dump
shows 192 surviving QuarkusClassLoader instances, each pinned test app
keeping its own copy of the Jandex index. This PR widens the classpath
with the kubernetes client, which made each pinned copy heavier and
tipped CI over the edge. Verified locally that the full suite passes
with 6g and fails with 4g. Unpinning the leaked classloaders remains
follow-up work on main.
2026-08-20 12:52:32 -04:00
floverfelt f8b07a78ff feat(lambda): add the ability to name and label lambda containers, code volumes (#2409) 2026-08-19 14:21:47 -04:00
sheldon-nadarajah-sft 2f0ef45978 fix(lambda): validate Layers ARNs eagerly on CreateFunction/UpdateFunctionConfiguration (#2282)
* fix(appconfig): add DeleteConfigurationProfile/DeleteHostedConfigurationVersion/ListDeploymentStrategies/DeleteDeploymentStrategy

These four operations had no route at all, so a request fell through
to S3's generic path-style catch-all (GET/DELETE /{bucket}[/{key}])
and returned a misleading NoSuchBucket 404 instead of a real AppConfig
response - confirmed via both raw HTTP and the real AWS SDK for Java.

Adds the missing routes + AppConfigService methods, mirroring existing
precedent (DeleteConfigurationProfile/DeleteHostedConfigurationVersion/
DeleteDeploymentStrategy follow DeleteApplication's idempotent-delete
convention - no upfront existence check; ListDeploymentStrategies
includes the three predefined strategies alongside custom ones,
verified against the API reference's own sample response).

DeleteDeploymentStrategy's real path is /deployementstrategies/{id}
(extra "e" - a genuine, documented quirk in AWS's own API model; every
other deployment-strategy operation correctly uses
/deploymentstrategies). Confirmed against the API reference and
reproduced against the real SDK, which sends the misspelled path
literally - matched it rather than "fixing" it, since wire-protocol
fidelity to what AWS actually does is the point.

Regenerated docs/services/appconfig.md's Supported Operations list
(hand-maintained for REST controllers - not yet covered by
tools/docs/regen_action_docs.py, confirmed via services.yaml's own
Phase-1 scope comment).

Tests: AppConfigIntegrationTest (+4), compatibility-tests/sdk-test-java
AppConfigTest (+1, covering all four operations via the real SDK).
Ran locally (JDK 25):

AppConfigIntegrationTest (unit):        29/29 passed
AppConfigTest (SDK compat, live):       16/16 passed

* fix(appconfig): scope profile deletion to its application, reject deleting predefined strategies

Review feedback on #2280 (Copilot + Greptile, both independently):

- deleteConfigurationProfile ignored appId entirely and deleted by the
  bare, globally-keyed profileId - a caller could delete another
  application's profile just by guessing/reusing its ID, since
  sibling reads (getConfigurationProfile) already enforce this
  ownership check but the new delete route didn't. Now rejects with
  the same ResourceNotFoundException as a mismatched get; a profileId
  that doesn't exist anywhere is still an idempotent no-op, matching
  deleteApplication's existing convention - only an existing-but-
  wrongly-scoped one is rejected.
- Same method also now cascades the delete to that profile's hosted
  configuration versions - they aren't independently addressable
  outside a profile's lifecycle, so leaving them in versionStore after
  the profile was "deleted" let a caller keep fetching versions for a
  profile that supposedly no longer exists.
- deleteDeploymentStrategy silently reported success (204) for a
  predefined strategy (e.g. AppConfig.AllAtOnce) without doing
  anything, since builtins were never in strategyStore in the first
  place - the strategy would still exist and still show up in every
  subsequent Get/List call despite the "successful" delete. Now
  rejects with BadRequestException.

Also applied this project's own established cleanup-logging
convention (System.err.println on a best-effort catch, matching
several other compatibility-tests/sdk-test-java files) to the one new
try/finally block flagged by Greptile, rather than swallowing the
exception silently.

Tests: 2 new AppConfigIntegrationTest cases (cross-application delete
rejected + original untouched, predefined-strategy delete rejected +
still resolvable) and 2 new SDK compatibility tests using the real
AWS SDK for Java v2's exception types.

AppConfigIntegrationTest:                31/31 passed
AppConfigTest (SDK compat, live):        18/18 passed

* fix(lambda): validate Layers ARNs eagerly on CreateFunction/UpdateFunctionConfiguration

Real AWS rejects an unresolvable layer ARN at attach time with
InvalidParameterValueException. Floci accepted any ARN unconditionally
- CreateFunction/UpdateFunctionConfiguration never validated it at
all, so the only signal was a silent WARN log from ContainerLauncher
when it tried (and failed) to mount the layer's content at container-
launch time, well after the caller had already moved on believing the
attach succeeded.

Adds LambdaLayerService as a LambdaService dependency and validates
each Layers ARN via the existing resolveLayerByArn before setting it
on the function, on both CreateFunction and UpdateFunctionConfiguration.
Left ContainerLauncher's existing warn-and-continue behavior alone for
the one case it still legitimately covers: a layer deleted *after*
being attached (real AWS doesn't re-validate layers on invoke either).

The three package-private test-only constructors (predating layer
support) now assign the new field null and validateLayersResolvable
short-circuits on it, following this class's own existing convention
for optional test-nulled dependencies (see the s3Service/aliasStore/
esmStore null-guards already throughout this file) - existing tests
using those constructors are unaffected.

Also fixes docs/services/lambda.md, which still described layer
support as entirely stubbed/unimplemented (PublishLayerVersion,
GetLayerVersion, ListLayerVersions, ListLayers, and DeleteLayerVersion
were all actually implemented already, just never documented as such).

This intentionally does NOT add real cross-account layer content
fetching (e.g. resolving the actual AWS-owned AppConfig Extension or a
Datadog-published layer) - there is no AWS-SDK/credential-handling
infrastructure anywhere in Floci for that, and it's a materially
larger feature (new dependency, credential trust boundary into
Floci's own control-plane process, cache/failure-semantics design)
than this fix. Documented as a known limitation instead.

Tests: LambdaLayerIntegrationTest (+2, covering both CreateFunction
and UpdateFunctionConfiguration rejecting an unresolvable layer and
leaving existing state unchanged). Ran locally (JDK 25):

LambdaLayerIntegrationTest:                  21/21 passed
LambdaServiceTest/PersistenceTest/
  ImageConfigTest/EventInvokeConfigTest/
  ContainerLauncherTest (constructor-affected): 114/114 passed

* fix(lambda): validate UpdateFunctionConfiguration's Layers before any field mutation

Review feedback on #2282 (Greptile): InMemoryStorage#get returns the
live object backing the store entry, not a copy, and this method
mutates that object's fields one by one with a single save() at the
end - validating Layers where it's applied (after Description,
Timeout, and several other fields are already set) meant a rejected
update could leave those earlier fields live on the stored function
even though the whole call returned 400.

Moves the Layers extraction + validateLayersResolvable call to the
very top of the method, before any field mutation, so a rejected
Layers ARN no longer has that side effect. CreateFunction didn't need
the same fix - its function object is newly constructed and never
touches the store until the very end, so a validation failure there
was already side-effect-free (confirmed by checking where zip
extraction happens relative to the existing Layers check - after it).

This is a narrow fix for the field this PR touches - the same
mutate-then-single-save pattern already existed for other fields
(e.g. the RevisionId check happens after Description/Handler/
MemorySize/Role/Runtime/Timeout/Environment are already mutated), so
it's a pre-existing gap for those, not something this PR introduces or
attempts to fix wholesale.

Strengthened the existing update-rejection test to bundle a Description
change into the same rejected request and assert it was NOT applied -
this is the actual regression check for the ordering fix, not just
that Layers itself was left alone.

LambdaLayerIntegrationTest: 21/21 passed.
2026-08-17 15:23:13 -04:00
TiM 573d4bdaff fix(lambda,iam): assume execution role for in-function SDK calls (#1909)
* fix(lambda,iam): assume execution role for in-function SDK calls

- Run Lambda SDK calls as known execution roles so IAM policies and caller identity match AWS behavior.
- Preserve unknown-role and mounted-credential fallbacks while leaving ECS behavior unchanged.
- Revoke container-bound sessions on cleanup and sweep orphaned sessions after restart.
- Resolve the session account from the function ARN when the model carries no account, so a
  published version enforces its execution role instead of dropping to the placeholder
  credentials, and revokes under the account it registered with. PublishVersion builds its
  snapshot field by field and leaves accountId unset (#2040), so the account has to come off
  the version ARN; routing every read through one helper keeps register and revoke in step.
- Add unit, enforcement, lifecycle, and real Docker coverage, plus updated documentation.

* fix(lambda): mint execution-role sessions from a CSPRNG and flag credential passthrough

The session key and secret are what IamEnforcementFilter authorizes a caller
against, so mint them from SecureRandom rather than ThreadLocalRandom, matching
how CertificateGenerator already sources security-relevant values. Register the
class for native-image run-time initialization so the static instance is not
captured, frozen-seed, into the image heap.

Credential passthrough (Floci's own AWS_ACCESS_KEY_ID/AWS_SECRET_ACCESS_KEY/
AWS_SESSION_TOKEN forwarded into a launched container) applies whenever those
variables are set, so a Floci started from a shell that exports real credentials
hands them to every workload whose role it cannot resolve. Log a WARN carrying
the access-key prefix the first time the fallback forwards host credentials, and
say so in the docs, so the accidental case is visible instead of looking
identical to the deliberate one.
2026-08-15 20:59:05 -05:00
Alex BannaandAlexander Banna e1f389f61b feat(lambda): support EFS file system configs (#2053)
* feat(lambda): support EFS file system configs

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

* fix(lambda): isolate warm pools by version

* test(dynamodb): retain Quarkus port for cleanup

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

---------

Co-authored-by: Alexander Banna <abanna@users.noreply.github.com>
2026-08-12 16:12:39 -04:00
floverfeltandFlorian Overfelt b543aa4baa feat(lambda): support extra /etc/hosts entries on Lambda launch (#2073)
* feat(lambda): support extra /etc/hosts entries via FLOCI_SERVICES_LAMBDA_EXTRA_HOSTS

* feat(lambda): support ipv6 addresses.

---------

Co-authored-by: Florian Overfelt <joverfelt@meso-scale.com>
2026-08-04 21:50:25 -05:00
Hector Ventura 3b4e73ca5a docs(lambda): document Podman rootless support and Runtime API host override (#1340)
Adds a 'Running on Podman (rootless)' section to the Docker configuration
docs with the known-working container config, and documents the existing
FLOCI_SERVICES_LAMBDA_DOCKER_HOST_OVERRIDE escape hatch for when Runtime
API host auto-detection picks an unreachable address.

Closes #876
2026-06-14 20:34:43 -05:00
Hector Ventura 2d30641479 fix(dns): resolve public hostnames from spawned containers (#1168)
Lambda/CodeBuild containers get Floci's IP as their only DNS, so all
public-name resolution flows through Floci's embedded UDP/53 forwarder.
The forwarder read responses into a hardcoded 512-byte buffer, silently
truncating larger EDNS0 responses (e.g. CDN-backed hosts), so public
lookups failed inside Lambda with ENOTFOUND/EBUSY.

- Enlarge the forwarder receive buffer to 4096 bytes (EDNS0).
- Forward across an ordered upstream list (resolv.conf + configurable
  public fallbacks), returning the first valid response; warn when all
  upstreams fail instead of dropping the response silently.
- Append configurable fallback resolvers (default 8.8.8.8, 8.8.4.4)
  after Floci's IP on spawned containers' HostConfig.Dns, controllable
  via floci.dns.container-fallback-* / FLOCI_DNS_CONTAINER_FALLBACK_*.

Closes #1110
2026-06-04 00:42:38 -05:00
Fred Peña ded329beac fix Lambda container networking when Floci runs in Docker (#765)
Automatically detect the Docker network of the running Floci container and use it for spawned containers when no explicit Docker network is configured. This lets Lambda containers reach Floci’s Runtime API in Docker Compose setups without requiring users to manually set FLOCI_SERVICES_LAMBDA_DOCKER_NETWORK.

Also update Lambda/Docker docs to clarify the automatic network inheritance behavior.

Tested with:

./mvnw -q -Dtest=ContainerBuilderTest,CurrentContainerNetworkResolverTest,DockerHostResolverTest,ContainerLauncherTest test
2026-05-10 13:54:23 -05:00
Hector Ventura 9e35046647 Docs/enviroment instead yml (#764)
* docs: moving all config to env instead of yml
* docs: sync with main and new features
* docs: reverting docker-compose.yml
2026-05-10 11:53:31 -05:00
Roméo 3ef99bc5e6 docs(lambda): update description to clarify Docker container usage (#720) 2026-05-06 18:05:37 -05:00
Taewoo Ryu aee46fe2da feat(lambda): mount host AWS config for real credential discovery (#703)
When FLOCI_SERVICES_LAMBDA_AWS_CONFIG_PATH is set, bind-mount the host
path read-only into Lambda containers at /opt/aws-config and set
AWS_SHARED_CREDENTIALS_FILE and AWS_CONFIG_FILE env vars so the SDK
discovers credentials regardless of container HOME directory.

When unset, credentials are read from Floci's own environment with a
fallback to test/test/test. Blank values are treated as absent.

Closes #686
2026-05-05 18:22:12 -05:00
Chris Wright f9d4da69d2 docs(lambda): clarify compose hostname for containers (#688) 2026-05-02 16:50:50 -05:00
Hector Ventura 404b42bdc0 feat(lambda): bind-mount hot-reload via S3Bucket=hot-reload (#601)
* feat(lambda): add bind-mount hot-reload mode via S3Bucket=hot-reload

Functions created with S3Bucket=hot-reload and S3Key=/absolute/path
have their host directory bind-mounted into /var/task rather than
packaged as a ZIP. Each invocation runs an ephemeral container so
file changes on disk are picked up immediately without calling
UpdateFunctionCode or re-uploading code.

Feature is disabled by default; opt in with:
  FLOCI_SERVICES_LAMBDA_HOT_RELOAD_ENABLED=true

An optional path allowlist (FLOCI_SERVICES_LAMBDA_HOT_RELOAD_ALLOWED_PATHS)
restricts which host directories may be bind-mounted.

* fix: missing hot reload enable env
2026-04-25 19:38:03 -05:00
Hector Ventura e023936a81 feat(lambda): embedded DNS server for virtual-hosted S3 resolution (#585)
* feat(lambda): embedded DNS server for virtual-hosted S3 resolution

  Lambda containers cannot resolve virtual-hosted S3 URLs
  (my-bucket.floci:4566) because Docker DNS has no wildcard support —
  queries for *.floci fall through to public DNS and hit real AWS.

  Adds a Vert.x UDP/53 DNS server that binds automatically when Floci
  runs inside Docker. It resolves any *.{floci.hostname} query to
  Floci's container IP and forwards everything else upstream. Lambda
  containers receive Floci's IP as their DNS server via HostConfig.withDns().

  An optional floci.dns.extra-suffixes config allows LocalStack migrants
  to route *.localhost.localstack.cloud without changing Lambda code.

  Netty NioDatagramChannel was tried first but silently dropped IPv4
  UDP packets due to AF_INET6 socket defaults — Vert.x DatagramSocket
  with setIpV6(false) resolves this.

* fix: adding missing dns class
2026-04-25 09:33:00 -05:00
Hector Ventura 4f0150870a feat(docker): centralize Docker config and add private registry authentication (#549) 2026-04-21 08:45:37 -05:00
Hector Ventura 114fade129 feat(lambda): implement reactive S3-to-Lambda sync for hot-reloading (#509)
* feat(lambda): implement reactive S3-to-Lambda sync for hot-reloading
* fix: clean unused hotreload properties
2026-04-17 19:04:47 -05:00
Kenshin Okinaka d8243b8803 feat(lambda): support ScalingConfig.MaximumConcurrency on SQS event source mappings (#490)
* feat(lambda): support ScalingConfig.MaximumConcurrency on SQS event source mappings

Wire-level support for ScalingConfig on CreateEventSourceMapping,
UpdateEventSourceMapping, GetEventSourceMapping, and
ListEventSourceMappings:

- New ScalingConfig model carrying MaximumConcurrency (Integer, nullable).
- Create and Update parse ScalingConfig from the request, validate range
  (2-1000), reject non-SQS event sources with InvalidParameterValueException.
- Response includes ScalingConfig only when a cap is set; omitted when
  null, matching AWS behavior.
- Update with an empty ScalingConfig clears the cap (AWS reset semantics).

The value is persisted on the EventSourceMapping but not yet enforced at
invocation time — the SQS poller today serializes to one concurrent
invocation per ESM regardless. Real parallel dispatch capped by
MaximumConcurrency is a follow-up (Scope B).

Tests:
- EsmIntegrationTest: 6 new cases covering round-trip, below/above range
  rejection, non-SQS rejection, omission when unset, add-then-clear via
  update.
- LambdaEsmScalingConfigTest (SDK compat): 5 cases verifying SDK typed
  ScalingConfig round-trips, InvalidParameterValueException on range
  violations, and add/clear lifecycle via update.

* fix(lambda): reject non-integer MaximumConcurrency and ScalingConfig on non-SQS sources

- parseScalingConfig now detects fractional values (e.g. 2.5) and
  returns InvalidParameterValueException instead of silently truncating.
- Empty ScalingConfig ({}) on a non-SQS event source is now rejected.
  Previously the non-SQS check only fired when MaximumConcurrency was
  non-null, so an empty ScalingConfig on Kinesis / DynamoDB Streams
  slipped through.
- Two new integration tests cover both cases.

* fix(lambda): tighten ScalingConfig input validation

- Reject non-object ScalingConfig (e.g. "foo", []) with 400 instead of
  silently treating it as absent. In update paths this previously cleared
  an existing cap unintentionally.
- Reject non-numeric MaximumConcurrency (e.g. string "7"). AWS expects a
  JSON number on the wire; the previous toString + parseInt path accepted
  strings that real AWS would reject.
- Use longValue() before range-checking to avoid intValue() overflow on
  large inputs (e.g. 5000000000) that would produce a negative value and
  a misleading error message.
- Two new integration tests: string MaximumConcurrency and non-object
  ScalingConfig.

* fix(lambda): add NaN/Infinity guard and expand ScalingConfig test coverage

- parseScalingConfig now explicitly rejects NaN and Infinity rather than
  letting them fall through to longValue() with a misleading error.
- The post-range non-SQS guard was flagged as dead code by the reviewer
  but is in fact reachable (non-SQS + valid numeric MaximumConcurrency).
  Retained and confirmed by the existing @Order(43) test.
- New tests: update range validation (below/above on PUT), and list
  with mixed ScalingConfig presence across ESMs.
2026-04-17 00:16:55 -05:00
Kenshin Okinaka fb26731131 feat(lambda): enforce reserved and per-region concurrency (#424)
* feat(lambda): enforce reserved concurrency at invocation time

Introduce LambdaConcurrencyLimiter using AtomicInteger + CAS. Acquire a
permit before invoke and release in finally for both sync and async
paths. DryRun skips enforcement. Functions without a reserved value are
not enforced in this step (account-pool enforcement will follow).

Reset inflight counters when a function is deleted to prevent leaks.

* test(lambda): use JUnit Assertions in LambdaConcurrencyLimiterTest

AssertJ is not on the unit-test classpath; switch to the Jupiter
assertions already used by sibling tests.

* feat(lambda): enforce account-wide concurrency pool and validate Put

Extend LambdaConcurrencyLimiter with an account-shared unreserved pool
sized as accountLimit - Σreserved. Functions without a reserved value
now share this pool; exhaustion returns TooManyRequestsException.

PutFunctionConcurrency rejects values that would leave less than
unreserved-concurrency-min (AWS default: 100) available, matching AWS's
LimitExceededException behavior.

Config: floci.services.lambda.account-concurrency-limit (default 1000)
and floci.services.lambda.unreserved-concurrency-min (default 100).
Docs and controller javadoc updated accordingly.

* feat(lambda): rehydrate reserved concurrency and handle throttle in pollers

On startup, LambdaService walks functionStore.listAll() and re-registers
reserved values with the limiter so validatePut and the unreserved pool
see the correct totals before the first Put of the session.

SQS/Kinesis/DynamoDB Streams pollers now catch TooManyRequestsException
explicitly. SQS lets messages return via visibility timeout; Kinesis and
DynamoDB Streams skip advancing the shard iterator, so records are
redelivered on the next poll.

* test(lambda): add SDK compatibility tests for concurrency enforcement

Verify end-to-end wire behavior: LimitExceededException on Put that
violates unreserved-min, TooManyRequestsException on Event invoke when
reserved=0, and DryRun bypassing the concurrency gate.

* fix(lambda): close concurrency races in limiter and rehydrate

- Recompute cap inside the unreserved CAS loop so concurrent setReserved
  does not leave permits granted above the live pool.
- Replace validatePut + setReserved with a single validateAndSetReserved
  guarded by a reservedLock; concurrent Puts for different functions
  can no longer each pass validation against stale totals.
- Rehydrate only $LATEST entries so published versions do not
  double-count into totalReserved().

* fix(lambda): address PR review feedback

- Partition limiter state by region. AWS Lambda concurrency is per
  account-per-region; functions in different regions no longer share
  the same reserved totals or unreserved pool.
- PutFunctionConcurrency and DeleteFunctionConcurrency now roll back
  the limiter update if functionStore.save() fails, so limiter and
  persisted state stay consistent.
- Replace the awkward (InvokeResult) null cast in the DynamoDB Streams
  poller with a plain forward declaration.

* refactor(lambda): rename account-concurrency-limit to region-concurrency-limit

The limit applies per-region (AWS Lambda's "account-level" quota is
actually per-account-per-region). Rename the config key, field, and
accessor to match what the value controls, and clarify the doc note.

No functional change.

* fix(lambda): O(1) region total and compare-and-rollback on save failure

- Maintain per-region AtomicInteger running total of reserved values,
  updated under reservedLock on every mutation. acquireUnreserved reads
  the cap in O(1) without iterating the map, eliminating the weakly-
  consistent partial-sum window that existed when reads happened off
  the lock while writes were serialized.
- Replace unconditional rollback with rollbackReservedIfExpected: the
  limiter only restores the previous value if the current entry still
  matches what the caller wrote, so a concurrent successful Put cannot
  be clobbered by an earlier request's rollback after its save fails.

* docs(lambda): scrub remaining account-wide wording and document drain semantics

Replace lingering "account-wide" / "account pool" phrasing with
per-region terminology in the controller javadoc and unit-test comment.
Two references remain by design: EmulatorConfig and the lambda service
doc quote AWS's own "account-level" label to explain the renamed key.

Also fold two follow-up review items into this change:
- Replace fully-qualified AwsException / InvokeResult references in the
  SQS, Kinesis, and DynamoDB Streams pollers with normal imports.
- Document that reducing or clearing a reserved value does not kill
  already-inflight invocations, mirroring AWS behavior and causing a
  brief drain window where total inflight may exceed the region limit.

* fix(lambda): serialize Put/Delete per function and preserve busy inflight

- Wrap PutFunctionConcurrency and DeleteFunctionConcurrency in a
  per-function lock so concurrent requests for the same ARN can't
  interleave the limiter update and the store save in a way that
  leaves them out of sync.
- Retain the inflight counter on reset when permits are still open,
  so an ARN recreated under load sees the remaining inflight rather
  than starting fresh and briefly allowing more than reserved capacity.
  Idle counters (value 0) are still dropped to prevent leaks.
- Tests now close acquired permits via try-with-resources and cover
  both the retain-while-busy and drop-when-idle reset behaviors.

* test(lambda): close all permits via try-with-resources

Close the acquire() result in regions_areIndependent so the test leaves
no inflight state behind and accurately asserts both the exhausted and
recovered cases.

* perf(lambda): avoid regex split in regionOf on the invoke hot path

regionOf() runs on every acquire/release. Replace String.split(":"),
which uses regex and allocates an array, with a single pass that finds
the fourth ':' segment and returns a substring — same semantics, no
allocation beyond the returned region string.

* fix(lambda): keep per-function lock map and tighten compat assertion

- deleteFunction no longer removes the per-function entry from
  concurrencyOpLocks. Removing it could race with a concurrent
  Put/Delete still synchronized on the old lock object, letting the
  next request create a fresh lock and run in parallel — defeating
  the very serialization the map provides. The map grows by one
  Object per deleted function, acceptable for a local emulator.
- LambdaConcurrencyTest now asserts the wire-level error identity
  (400 status + "LimitExceededException" errorCode) for the Put
  rejection. The Lambda SDK v2 model does not declare a typed
  LimitExceededException class, so wire-level assertions catch
  protocol-fidelity regressions more precisely than the previous
  generic LambdaException check.

* fix(lambda): retain inflight counter on reset and allow over-committed reductions

- reset() no longer drops idle inflight counters. The previous
  counter.get()==0 + remove pattern races with a concurrent
  acquireReserved that has already obtained the AtomicInteger
  reference and is about to increment it: a successful remove
  between those two moments would leave the next acquire to
  allocate a fresh counter and silently undercount inflight,
  permitting reserved over-subscription.
- validateAndSetReserved now allows any value <= the function's
  current reservation unconditionally. Reductions cannot worsen
  unreserved capacity, so blocking them in an already over-committed
  state (e.g. after lowering region-concurrency-limit at runtime)
  prevented operators from recovering. Increases still go through
  the unreserved-min check.

* fix(lambda): take per-function lock in deleteFunction

A concurrent deleteFunction + Put/DeleteFunctionConcurrency for the
same ARN could interleave the limiter reset and the store delete,
leaving the limiter holding (or clearing) state for a function the
store no longer knows about. Wrap the limiter+store mutations in the
same lockForConcurrencyOp(arn) used by the concurrency endpoints.

Tighten the surrounding comment so it describes the current code
rather than the lock-removal call that earlier revisions used to have.

* test(lambda): wire a real concurrency limiter into the test constructor

The package-private LambdaService constructor used by unit tests passed
null for concurrencyLimiter, so the null-guards in
putFunctionConcurrency / deleteFunctionConcurrency / deleteFunction made
those paths silently skip validation and limiter bookkeeping under tests.
That hid divergence from production behavior.

Construct a default LambdaConcurrencyLimiter (AWS defaults: 1000 / 100)
in the test ctor so the same enforcement runs in unit tests.

* test(lambda): cover concurrent PutFunctionConcurrency for the same ARN

Verify that the per-function lock in LambdaService serializes racing
Puts so the limiter and the functionStore always agree on whichever
write landed last. 50 iterations across two threads against the same
function exercise the lock discipline and assert store/limiter
consistency on every iteration.

* docs: document reserved concurrency config keys

- docs/services/lambda.md: drop redundant "(enforced at invocation)"
  from the PutFunctionConcurrency table entry (the admonition below
  already explains enforcement); add region-concurrency-limit and
  unreserved-concurrency-min to the Configuration YAML sample.
- docs/configuration/application-yml.md: mirror the two new keys in
  the top-level reference sample so every known lambda setting is
  discoverable in one place.

* refactor(lambda): address review feedback (A)

- LambdaServiceTest.concurrentPutFunctionConcurrency now asserts against
  limiter.totalReserved(region) instead of getFunctionConcurrency(), which
  read the same field as the value under test. The new assertion actually
  proves the limiter and the persisted store stayed in agreement.
- Expose a package-private concurrencyLimiter() accessor on LambdaService
  so tests can inspect limiter state without reflection.
- Drop unused Permit.NOOP: the reserved=null path now runs through
  acquireUnreserved and always returns a real decrement closure.
- Document the intentional unbounded growth of the inflight counter map
  (race avoidance on reset) and concurrencyOpLocks (race avoidance on
  deleteFunction). Both are acceptable for a local emulator workload.

* test(lambda): add rehydrate, multi-ARN race, and qualified-invoke coverage

- LambdaServiceTest.rehydrateConcurrency_restoresReservedFromStore
  prepopulates a LambdaFunctionStore with reserved values, builds a
  fresh LambdaService over it, and verifies totalReserved(region) goes
  from 0 to the expected sum after the @PostConstruct hook runs.
- LambdaServiceTest.multiArnPutFunctionConcurrency_respectsRegionTotalUnderContention
  races two Puts on different ARNs that would together push the region
  below unreserved-min. reservedLock must let exactly one win; the
  other must fail with LimitExceededException and the limiter's total
  must reflect only the winning reservation.
- Compat LambdaConcurrencyTest.invoke_withVersionQualifier_stillHonorsReservedOnLatest
  publishes a version, sets reserved=0, and invokes with the qualifier
  set. Today Floci drops the qualifier and routes to $LATEST, so the
  reservation throttles the call. This test locks the behavior in: a
  future qualifier-routing change must either copy the reservation onto
  the snapshot or key the limiter off the base ARN to keep it green.

* refactor(lambda): idempotent permits, warn on malformed ARN, more tests

- Wrap acquire()/release() counter closures in an AtomicBoolean guard so
  a double-close of a Permit can never drive the inflight counter
  negative. Future callers that mix try-with-resources with explicit
  close, or that add retry logic around invoke, stay safe by default.
- regionOf() now warns once per unique malformed input instead of
  silently coalescing everything into "unknown". The first occurrence
  is logged so a bug that passes a bare function name into the limiter
  is debuggable without spamming the log.
- New LambdaServiceTest.putFunctionConcurrency_rollsBackLimiterIfSaveFails
  injects a failing LambdaFunctionStore and verifies the limiter total
  is restored when functionStore.save throws.
- New LambdaServiceTest.deleteFunction_preservesInflightPermitUntilItCloses
  holds a permit through a deleteFunction call and asserts the inflight
  counter stays live until the permit is closed.
- New LambdaConcurrencyLimiterTest.permit_closeIsIdempotent locks in the
  double-close guarantee.
2026-04-14 01:09:22 -05:00
Kenshin Okinaka 3b6b5fb687 feat(lambda): add PutFunctionConcurrency stub (#325)
* feat(lambda): add PutFunctionConcurrency stub

Add PutFunctionConcurrency, GetFunctionConcurrency, and
DeleteFunctionConcurrency endpoints:

  PUT    /2017-10-31/functions/{FunctionName}/concurrency
  DELETE /2017-10-31/functions/{FunctionName}/concurrency
  GET    /2019-09-30/functions/{FunctionName}/concurrency

The stored ReservedConcurrentExecutions value is persisted on
LambdaFunction and echoed back, but it is not enforced at invocation
time — invocation slots in LambdaExecutorService / WarmPool are not
bounded, and the account-level concurrent execution limit is not
validated.

* fix(lambda): tighten PutFunctionConcurrency validation
2026-04-11 09:40:12 -05:00
TiM a32b7f1f3b docs: comprehensive audit sweep + CHANGELOG backfill (1.1.0-1.5.2) (#326)
CHANGELOG.md was empty for the 1.1.0-1.5.2 release cycle and service docs
had drifted from code behaviour. This sweep reconciles docs against the
current codebase on upstream/main.

- Backfill CHANGELOG.md for 1.1.0 through 1.5.2 from git history
- Correct exact operation counts in docs/services/index.md: S3 (~30 -> 58),
  Lambda (~25 -> 30), API Gateway v1 (~24 -> 62). Counts now come from the
  actual dispatch handlers rather than @Path annotation counts.
- Rewrite README "Supported Services" table to drop per-service op counts
  (they drift too fast); point readers at docs/services/index.md
- Update 24 service docs for accuracy, add "Not Implemented" sections
  where relevant (s3.md, lambda.md, api-gateway.md)
- Refresh configuration and getting-started docs
- Add EventBridge Scheduler and AppConfig to mkdocs nav
- Add AppConfig / AppConfigData rows to README and services index
  following the 1.5.2 upstream release
2026-04-10 10:52:34 -05:00
Hector Ventura 61433f59ab firt commit 2026-03-15 17:43:56 -05:00