mirror of
https://github.com/floci-io/floci.git
synced 2026-11-23 06:00:46 -05:00
9df4ffbfa105473ec0e2ec5e92c65a604fba4880
75
Commits
| Author | SHA1 | Message | Date | |
|---|---|---|---|---|
|
|
255162654f |
fix(lambda): refuse function URLs in GovCloud and China (#5615)
The AWS GovCloud (US) User Guide lists "AWS Lambda Function URLs is not available" (https://docs.aws.amazon.com/govcloud-us/latest/UserGuide/govcloud-lambda.html) and the China guide "Amazon Lambda Function URLs is not available in the China Regions" (https://docs.amazonaws.cn/en_us/aws/latest/userguide/lambda.html), but CreateFunctionUrlConfig created one in every partition, on a host no source publishes for either of them. CreateFunctionUrlConfig now refuses a request whose region is in aws-us-gov or aws-cn with an InvalidParameterValueException, which the lambda model declares for the operation. No source shows AWS's message, so the wording is Floci's own, as for the API Gateway EDGE gate. The AWS::Lambda::Url provisioner creates through the same service method, so a stack in those partitions fails with that error. Get, Update and Delete act on an existing config and are unchanged. The ISO and EUSC partitions are left as they are because no source covers them, and the open question about the function URL host now names only those two. The Java compat suite skips LambdaFunctionUrlTest in those two partitions, so the China partition nightly stays green. Signed-off-by: Hector Ventura <hectorvent@gmail.com> |
||
|
|
c6c2c609c3 |
fix(stepfunctions): authorize a Lambda task as the state machine's execution role (#5554)
Under IAM enforcement, a Lambda task naming a function in another account was refused outright, because Floci evaluated no Lambda function policy when #5079 added the check, and a task on a function in the state machine's own account was not checked at all. Function policies now take part in authorization (#5476), so a task is decided the way Lambda decides the Invoke call the execution role makes (Step Functions Developer Guide, "I can't invoke a Lambda function from another account"): within one account the role's policies or the function's policy can allow it, and across accounts both have to (IAM User Guide, cross-account policy evaluation logic). - LambdaTaskAuthorizer evaluates the role's policies, its permissions boundary and its account's SCPs together with the function policy LambdaResourcePolicyProvider supplies. The role ARN has to name an existing role, path included, matched as STS AssumeRole matches one (IamService.roleArnMatches), and the role is evaluated under the ARN IAM holds for it. - The task is authorized against the function ARN LambdaArnUtils.functionArn gives for its reference: a full ARN as written, a name or partial ARN completed in the state machine's partition, Region and account, with the version or alias it names, as Lambda authorizes an invoke. - A task whose Credentials name a role invokes the function as that role, once the execution role has assumed it (Developer Guide, Task state "Credentials"). The role's trust policy has to allow the execution role, with the state machine's ARN as sts:ExternalId, which the cross-account tutorial's trust policy checks. The execution role's own policies have to allow sts:AssumeRole on the role too when it is in another account, or when the trust policy names only the execution role's account, since an account principal delegates to the account (IAM User Guide, "AWS account principals"); AssumeRolePolicyEvaluator.decide tells the two grants apart. RoleArn is read the way the task's Parameters or Arguments are. A role the execution role cannot assume fails the task with States.Permissions, the Developer Guide's error for a task without the privileges to run. - A refusal to invoke fails the task with Lambda.AccessDeniedException. The cause names the role's session as the Step Functions Developer Guide shows it (arn:aws:sts::<account>:assumed-role/<role>) and ends in the IAM User Guide's context for the policy type that refused it, explicit denials first, each in AWS's evaluation order: service control policies, the resource-based policy or role trust policy, identity-based policies, the permissions boundary. |
||
|
|
0d71894153 |
docs(partition): bring the partition pages up to date with the smoke coverage and EDGE rules (#5489)
* docs(partition): bring the partition pages up to date with the smoke coverage and EDGE rules partitions.md still listed the eleven services the smoke test started with and said Step Functions runs in all eight partitions through the emulator, which only IAM does. It now states the rule (every minting service has a case or a listed exemption), names EUSC among the partitions without CloudFront, and replaces the sign-in client id open question, which the model answers, with the one that is open: the cross-device redirect host. lambda.md said a layer ARN outside the aws partition is refused; the check is against the caller's partition. appsync.md implied the AppSync service principal varies by partition; it does not. Signed-off-by: Hector Ventura <hectorvent@gmail.com> * docs(partition): note the endpoint's own origin in the cross-device redirect question Since #5552 the cross-device redirect is also accepted on the endpoint the authorize request arrived on, so the open question is only about which AWS host is accepted outside the commercial partition. Signed-off-by: Hector Ventura <hectorvent@gmail.com> --------- Signed-off-by: Hector Ventura <hectorvent@gmail.com> |
||
|
|
aff6f0eec4 |
fix(cloudformation): expand a SAM function's EventInvokeConfig (#5524)
* fix(cloudformation): expand a SAM function's EventInvokeConfig SAM's EventInvokeConfig was dropped, so a function declaring retries, a maximum event age or invoke destinations deployed with Lambda's defaults and no destination at all. It now expands as AWS's SAM translator expands it: an AWS::Lambda::EventInvokeConfig on $LATEST or the AutoPublishAlias alias, the inline role policy for each destination, the SQS queue or SNS topic SAM creates for a destination given only its Type, and SAM's conditions and error messages. The function's Condition, DeletionPolicy and UpdateReplacePolicy now reach every resource generated for it, as SAM passes them through. A condition naming another with anything but a string is rejected as CloudFormation rejects it, which also fails the template SAM produces for a conditional function with a conditional destination, as on AWS. * fix(cloudformation): resolve SSM parameters for the SAM transform and omit NoValue destinations CloudFormation resolves an AWS::SSM::Parameter::Value<String> parameter before it runs the SAM transform, so a destination Type taken from one is the stored value. The transform now gets the given parameter values over each Default, with SSM-typed parameters read from Parameter Store, wherever it runs. A Destination of AWS::NoValue passes through SAM unchanged and leaves its side without an ARN, which CloudFormation's validation rejects. The event invoke config provisioner resolved it to an empty string and stored that; it now omits AWS::NoValue, so the destination fails as the schema requires. * refactor: share SHA-1 as Digests.sha1 The SAM transform's generated condition names, EC2 key pair fingerprints and the SAML assertion name qualifier each made their own one-shot SHA-1 digest. They now share Digests.sha1 beside sha256. Also moves samTransformParameters above resolveSsmParameters' Javadoc, which it had been inserted beneath. |
||
|
|
8565ad837a |
fix(lambda): expose the executing version on cold launches (#5523)
* fix(lambda): expose the executing version on cold launches Signed-off-by: Andre Kurait <akurait@amazon.com> * fix(lambda): propagate executing version to Kubernetes pods Signed-off-by: Andre Kurait <akurait@amazon.com> --------- Signed-off-by: Andre Kurait <akurait@amazon.com> |
||
|
|
6d7d85f0f8 |
fix(lambda): enforce function policies on cross-account calls (#5476)
Under IAM enforcement, a caller whose own policy allowed lambda:InvokeFunction could invoke another account's function by ARN even when that function's policy granted nothing, and RotateSecret could be pointed at another account's function the same way. Three things combined: there was no resource-policy provider for Lambda, so the call was judged as same-account; the function name was cut at its first colon, so an ARN was evaluated as function:arn in the caller's account, where no Allow or Deny written for the function could match; and the invoke followed the account in the ARN. - LambdaResourcePolicyProvider supplies a function's policy statements and the account its ARN names, also when the function has no policy, so a call to another account's function needs that function's policy to allow the caller as well as the caller's own policy. It is keyed on the ARN, so RotateSecret's check on its rotation function, made under the secretsmanager scope, sees it too. - ResourceArnBuilder evaluates each call against the function it acts on. An invoke runs in the account and Region a full or partial ARN names, as the version or alias it names in the function name or in Qualifier, since Lambda authorizes a qualified call against the qualified ARN. GetFunction, GetFunctionConfiguration and ListDurableExecutionsByFunction read a qualified full ARN in the account it names, so they are evaluated there too, and a read of another account's function needs its policy as on AWS. Every other route acts on the caller's own function of that name, so it is evaluated against that function, unqualified because not all of their handlers act on the qualifier. - An invoke by partial ARN runs in the account it names, as one by full ARN already did. - RotateSecret looks its function up where the rotation runs it: in the ARN's account, and as the version or alias the ARN names. |
||
|
|
47dae887f9 |
fix(lambda): list $LATEST first, then versions in numeric order (#5376)
Sort stored versions numerically so ListVersionsByFunction is stable and matches AWS. * Fix #5121 Signed-off-by: Matheus Oliveira <matheus.6148@gmail.com> |
||
|
|
ee2d1a68a6 |
feat(cloudformation): pass Lambda DurableConfig through (#5218)
* feat(cloudformation): pass Lambda DurableConfig through AWS::Lambda::Function.DurableConfig reaches CreateFunction and UpdateFunctionConfiguration. As on AWS, a RetentionPeriodInDays the template leaves out is 14 on update too, a durable function created without Timeout gets min(ExecutionTimeout, 900), and adding or removing DurableConfig replaces the function. * test(terraform): cover aws_lambda_function durable_config The provider creates a durable function, reads it back without a diff, updates execution_timeout in place, and before destroy stops a RUNNING durable execution through ListDurableExecutionsByFunction, StopDurableExecution and GetDurableExecution. * fix(cloudformation): honor AWS::NoValue, cleared keys and large numbers in DurableConfig A DurableConfig that Fn::If removes with AWS::NoValue leaves the function plain. A KMSKeyArn the template leaves out or sets to "" clears the key, as CloudFormation does on AWS, since Lambda keeps a stored key when the update omits the member. A number beyond an integer reaches Lambda unchanged, so its range check rejects it. * fix(cloudformation): reject a DurableConfig that is not an object Only an intrinsic that resolves to AWS::NoValue removes DurableConfig. CloudFormation rejects a string, number or list in its schema check before the function is touched, so an update with one no longer replaces and deletes a durable function. * test(cloudformation): cover Lambda DurableConfig with the AWS SDK The CloudFormation and Lambda SDK clients create a durable function, update DurableConfig in place, and remove it by replacing the function. * fix(cloudformation): require ExecutionTimeout and known members in DurableConfig CloudFormation checks DurableConfig against the schema on update too: an update without ExecutionTimeout, or with a member the schema does not list, fails before the function is touched. Floci let such an update through and kept the old timeout. * refactor(cloudformation): look up a Lambda function once per deploy The name choice and the replacement decision now share one lookup and one durable check, so they cannot disagree. |
||
|
|
6e6ce61eea |
feat(lambda): durable function chained invokes (#5164)
* feat(lambda): durable function chained invokes
A CHAINED_INVOKE operation runs another function. A durable target
needs a version or alias and runs as its own durable execution with a
random name; its close completes the operation as SUCCEEDED, FAILED,
TIMED_OUT ("CHAINED_INVOKE timed out after N seconds.") or STOPPED. Any
other function is invoked once, and an output over 1 MB fails the
operation. A missing function or an unqualified durable one fails the
operation at once. Stopping the parent leaves the child running.
A plain chained invoke lost with the process runs again after a restart,
and a durable child that closed before its report reaches the parent
reports then.
* fix(lambda): close the gaps in durable chained invokes
A durable child that closes during a restart reports to its parent
under its own lock, and recovery triggers an execution once. A durable
target invoked without Payload starts its child with no input, while a
plain target gets {}. A target started in the batch that closes the
execution still runs and its result is ignored, as on AWS.
* fix(lambda): reject a chained invoke of another account or region
AWS rejects the checkpoint with InvalidParameterValueException "Cannot
start a CHAINED_INVOKE on a function in another account." or "... in
another region." Cross-account chained invocations are not supported.
* fix(lambda): keep durable chained invokes across a crash
The parent is saved before the child it starts, so a crash in between
leaves no child the parent does not know. On restart a child the parent
recorded but the store lost is started again under the same ARN, and a
plain target started by the checkpoint that closed the execution runs
again until its result is recorded. A child reports only to the
operation that started it.
* fix(lambda): recreate a lost durable child on the version its ARN names
An alias the chained invoke named may point to another version after a
restart, and a child recreated there would not match the ARN the parent
saved.
|
||
|
|
840d1bb6c1 |
fix(sqs): set SenderId from caller principal instead of queue owner (#5066)
* feat(sqs): thread accessKeyId through RequestContext and AccountContextFilter * fix(iam): resolve caller user id and align assumed role id with role id * feat(sqs): stamp senderId on Message model and in SqsService * feat(sqs): return message-specific senderId in SQS query and JSON handlers * test(sqs): add integration tests for SenderId caller principal (#4829) * fix(sqs): guard against unsatisfied CDI instance in resolveCurrentSenderId * fix(sqs): address review findings and fix CI for caller principal SenderId - Catch RuntimeException in SqsService to prevent compiler incompatibility - Fallback SenderId to queue owner account when outside request context - Deliver SNS fanout messages with SNS service principal SenderId - Support presigned requests without X-Amz-Algorithm in AccountContextFilter - Populate assumedRoleId and roleSessionName for ECS, EKS and Lambda sessions * fix(sqs): validate session token for temporary credentials and fix CI regressions - Validate session token matching when resolving caller principal for temporary credentials - Generate unique session names for EKS Pod Identity to avoid sender ID collision - Restore default floci-session session name for Lambda execution role sessions - Align SqsService mock in SnsServiceTest with 9-parameter sendMessage signature * fix(sts,lambda): pass sessionToken to resolveCallerUserId and scope Lambda assumed role IDs * fix(lambda): align execution role session name and assumed role ID with function name * fix(sqs): resolve SenderId caller in SQS handlers, not in sendMessage Internal producers (S3 notifications, EventBridge, SNS) call sendMessage on the thread of the request that triggered them, so SenderId picked up that caller's role session. Resolve the caller in the SQS Query/JSON handlers where a real SendMessage call is known, and pass it down. sendMessage without an explicit senderId now defaults to the queue owner. |
||
|
|
a1ed65c51d |
feat(lambda): durable function callbacks (#5100)
* feat(lambda): durable function callbacks
A CALLBACK operation started at checkpoint gets a callback id that
SendDurableExecutionCallbackSuccess, Failure and Heartbeat complete or
keep alive, after which the function is invoked again to see it.
TimeoutSeconds and HeartbeatTimeoutSeconds time it out with
Callback.Timeout or Callback.Heartbeat. A completed, timed out or
stopped callback answers CallbackTimeoutException, an unreadable id
"Invalid callback id". The callback id carries the execution ARN, which
IAM authorizes the callback actions against.
Option range errors now name the update, as AWS does
("updates.1.member.waitOptions.waitSeconds").
* fix(lambda): name a repeated durable update as AWS does
AWS rejects two updates of one operation in a batch, other than a START
closed by its STEP or CONTEXT action, with "Cannot update the same
operation twice in a single request."
* fix(lambda): leave a durable execution waiting after a body-less callback failure
AWS marks a callback failed with an empty request body as FAILED but does
not invoke the function again, so the execution keeps waiting. The SDKs
send {} when Error is omitted, which does invoke it.
* fix(lambda): bound a durable callback failure's error at 1 MB
AWS rejects an Error over 1048576 bytes, measured as compact JSON, with
InvalidParameterValueException "Error object size must be less than or
equal to 1048576 bytes."
* test(lambda): keep a pending durable callback across a restart
* fix(lambda): reject a durable callback failure body that is not a JSON object
AWS treats only an empty body as a failure with no Error. Whitespace,
null or broken JSON get 400 SerializationException and leave the
callback open.
* docs(lambda): note the durable callback result limit AWS enforces
|
||
|
|
6a3bc12769 |
feat(lambda): run durable functions with checkpoints, waits and step retries (#5047)
* feat(lambda): run durable functions with checkpoints, waits and step retries
Invoking a durable function starts a durable execution, through Invoke or through an ARN (EventBridge, Scheduler, function URLs, destinations). The function checkpoints through CheckpointDurableExecution and GetDurableExecutionState, and Floci re-invokes it when a wait or a step retry comes due. GetDurableExecution, GetDurableExecutionHistory, ListDurableExecutionsByFunction and StopDurableExecution read and stop executions. Timers are persisted deadlines fired by a background sweep, so an execution survives a restart. Callbacks and chained invokes are rejected at checkpoint time.
* fix(iam): authorize durable execution actions against the owning function
A durable execution route has no /functions/ segment, so its resource fell back to *. The function name now comes from the execution ARN in the path.
* fix(lambda): keep durable executions inside their account
The execution APIs took the account from the ARN in the path, so another account could read or stop an execution. An ARN of another account is now ResourceNotFoundException.
* fix(lambda): limit the error size of an EXECUTION checkpoint too
* fix(lambda): reject an EXECUTION close that carries the other result kind
AWS rejects SUCCEED with an Error and FAIL with a Payload on the EXECUTION operation, as it does for steps.
* fix(lambda): spend a durable wake-up when a failed invocation schedules its retry
* fix(lambda): keep a durable crash retry's backoff across a restart
* fix(lambda): bound the durable execution locks
A lock per execution ARN was kept forever, even for an ARN that did not exist. A fixed set of striped locks replaces it. Locks are never nested, so a shared stripe cannot deadlock.
* fix(lambda): accept PAUSED, PAUSING and DELETING as durable status filters
AWS accepts them and answers an empty list, since Floci never puts an execution in those states.
* fix(lambda): reject a non-finite durable list timestamp
* test(lambda): resume a durable execution from its JSON file after a restart
* fix(lambda): keep durable executions inside their region
An execution ARN of another region now answers ResourceNotFoundException "Function not found", as AWS does, instead of reaching the execution past the IAM check of the request region.
* fix(lambda): validate durable list parameters before an empty status filter answers
Statuses of only PAUSED, PAUSING or DELETING still checks MaxItems and Marker, as AWS does. The bad Marker message is "Invalid Marker".
* perf(lambda): skip the execution scan for a status filter that matches nothing
Statuses of only PAUSED, PAUSING or DELETING now checks MaxItems and Marker without listing the account's executions.
* test(lambda): drop durable tests that repeat other coverage
The in-memory restart test repeats the persistence test, and the Docker success case repeats the compat suite's checkpoint loop. The Docker test keeps the failure case.
* fix(lambda): re-attach a durable execution name only on the same version
AWS keeps execution names unique per function across versions. A sync Invoke of another version with the same name and payload is DurableExecutionAlreadyStartedException, not the existing execution.
* chore(lambda): simplify the durable execution engine
Drop stored fields nothing reads, share the unseen-operations and
page-cursor helpers, skip the name scan for a generated name, and save
an execution once per invocation instead of twice.
* fix(lambda): reject a non-integer durable MaxItems as AWS does
AWS answers MaxItems=x on the durable execution APIs with
SerializationException "'x' can not be converted to Integer".
* docs(lambda): list the durable execution size limits as not emulated
* fix(iam): authorize durable execution actions against the execution ARN
The durable execution actions take the durable execution resource,
function:name:version/durable-execution/name/id. A role allowed on
function:name:* may checkpoint, one allowed only on the unqualified
function ARN is denied.
* fix(lambda): answer an unknown durable execution on checkpoint as a bad token
CheckpointDurableExecution and GetDurableExecutionState do not model
ResourceNotFoundException. AWS answers InvalidParameterValueException:
"Checkpoint token is not valid for the durable execution ARN" for a
token minted for another execution, "Invalid checkpoint token" otherwise.
* fix(lambda): replay a durable checkpoint retried with the same ClientToken
AWS answers a retry of the last checkpoint with the same ClientToken
with the same state and a usable next token, even though the request
token is spent. A different ClientToken, a retry after the next
checkpoint, or a retry of the checkpoint that closed the execution is
still an invalid checkpoint token.
* fix(lambda): validate durable list filters as AWS does
ListDurableExecutionsByFunction takes one status at most and answers
more with InvalidParameterValueException "Cannot filter by more than one
status". An unreadable StartedAfter or StartedBefore is
SerializationException "'<value>' can not be converted to Date", and a
plain date is accepted. Type errors come first, then MaxItems and status
values, then the single-status rule, then the function lookup.
* docs(lambda): note the history IncludeExecutionData default
* fix(lambda): report durable MaxItems and Statuses errors as AWS does
AWS puts an invalid MaxItems and an invalid Statuses into one
ValidationException ("2 validation errors detected: ...; ..."), MaxItems
first. A negative MaxItems must be greater than or equal to 0. MaxItems
is checked before the execution or function is looked up.
* refactor(lambda): share one durable execution ARN pattern with IAM
IAM and the durable execution service now recognize an execution ARN
with the same pattern, the one AWS validates it with.
* fix(lambda): replay a durable checkpoint answer as it was sent
On AWS a retry with the same ClientToken returns the operations as the
first answer had them: a WAIT stays STARTED in the retry even after it
has elapsed, while a fresh checkpoint reports it SUCCEEDED.
|
||
|
|
f074dd3c40 |
feat(lambda): allow per-runtime image reference overrides (#4552)
* feat(lambda): allow per-runtime image reference overrides * test(lambda): cover runtime image YAML configuration * docs(lambda): show quoted runtime image env key * test(lambda): verify quoted runtime image env key --------- Co-authored-by: Vamsi Akavarapu <16164447+vamsiak@users.noreply.github.com> |
||
|
|
823f8751de |
feat(lambda): store DurableConfig on functions (execution later) (#5007)
* feat(lambda): accept and echo DurableConfig on functions CreateFunction and UpdateFunctionConfiguration take DurableConfig, PublishVersion snapshots it, and every read echoes it. ExecutionTimeout is required on create, RetentionPeriodInDays defaults to 14, a durable function's Timeout defaults to min(ExecutionTimeout, 900) and its logging to JSON. Update merges the members, and a function created without DurableConfig cannot gain one. KMSKeyArn is validated against its pattern and stored, the key itself is not looked up. * chore(lambda): trim the DurableConfig tests to one case per rule * feat(lambda): durable functions log in JSON format only A durable function rejects LogFormat Text on create and update, and a LoggingConfig without LogFormat reads back as JSON. An empty KMSKeyArn means no key. * chore(lambda): let the logging helpers own the durable JSON rule validateLoggingConfig and applyLoggingConfig take the durable flag, so a durable function's default format and the Text rejection live in one place and a LoggingConfig without LogFormat keeps its log levels. applyDurableConfig sets the retention default and merges, and the test uses chainable helpers. * chore(lambda): say why the durable compat test ignores a failed cleanup |
||
|
|
73b8c6124c |
feat(lambda): bound the warm pool globally with LRU eviction (#4683)
* feat(lambda): bound the warm pool globally with LRU eviction Adds warm-pool-max-per-function (replaces the hardcoded max(4, cpus)) and warm-pool-max-total (0 = unbounded). When the total would be exceeded, the least-recently-used idle container of any function is stopped before the released one is pooled, so the function that just ran keeps its container. Busy containers are not counted; their ceiling is region-concurrency-limit. WarmPool now takes a Clock so LRU order and the idle sweep are testable without sleeping. Closes #4682 * fix(lambda): warn when warm-pool-max-total is negative instead of treating it as unbounded Math.max(0, value) turned -1 into 0, the documented opt-out, so a mistyped cap silently restored the unbounded pool. Resolve it like warm-pool-max-per-function: a negative value is logged and the total stays unbounded. * docs(lambda): state the warm-pool peak bound per region region-concurrency-limit applies independently in each region while warm-pool-max-total is emulator-wide, so a single sum understated peak container count with more than one active region. Describe the cap as an idle-only, emulator-wide bound and the peak as the cap plus in-flight invocations across every active region. Also document that a negative value is ignored with a warning. * fix(lambda): do not stop a drained container again from the global cap eviction evictIdleBeyond snapshots each idle deque, then removes the chosen handles under the pool lock. drainEnvironment and drainFunction detach the deque from the pool and stop its contents themselves, so a drain between the snapshot and the removal left the eviction holding the orphaned deque: remove(handle) still returned true and the container was stopped a second time. Check the deque is still the live one for its environment before removing from it. |
||
|
|
3b1ac49f4f |
docs(lambda): correct CloudFormation and SAM event source mapping notes (#4739)
* test(lambda): qualify CloudFormation mapping execution A stack-created SQS mapping now has a compatibility test that sends messages through it: the filter drops and deletes a nonmatching message, the batching window holds a batch open until a later message joins it, and a partial batch response retries only the reported message. The Lambda docs no longer claim CloudFormation drops FilterCriteria, and they describe SQS failure and partial batch handling. * test(lambda): widen the mapping window margin and read every log page The third message must join the batch while the window is still open, so a 10 second window leaves room for a stalled runner. FilterLogEvents can return a partial page with a token, so the batch log is read through the paginator. * test(lambda): drop the stack-created SQS delivery test SqsEventSourcePollerTest already pins the batching window, the filter and partial batch responses with an injected clock, so the wall-clock delivery test only added a race and long polls. The stored-property checks stay. |
||
|
|
2170c89d88 |
fix(lambda): include the resource namespace in code volume names (#4872)
* fix(lambda): include the resource namespace in code volume names Code volumes, their completion markers and the populate helper container are named through prefixedDockerName, so FLOCI_DOCKER_RESOURCE_NAMESPACE follows the container name prefix as it already does for Lambda containers. Two namespaced instances on one daemon no longer share a code volume, and one's superseded-volume cleanup can no longer remove the other's. Names are unchanged without a namespace. * fix(lambda): keep two resource namespaces from sharing a code volume Greptile and pgermosen on #4872: a namespace and a function name may both contain dashes, so namespace ci with function foo-code-bar and namespace ci-code-foo with function bar spelled the same volume name for the same code, and the superseded sweep, which works from a per-process map of names, could remove the other instance's volume. A namespaced code volume name now ends with a short hash of the namespace (names without a namespace are unchanged), and the sweep checks the volume's floci_namespace label before deleting, so a volume of another namespace is left alone however its name parses. Also imports the Mockito types in ContainerLauncherCodeVolumeReuseTest instead of qualifying them inline. |
||
|
|
fa4d4663a2 |
feat(lambda): honour the Invoke Qualifier and wait between asynchronous retries as AWS does (#4733)
* feat(lambda): honour the Invoke Qualifier query parameter * feat(lambda): wait between asynchronous retries as AWS does A failed Event invocation now waits floci.services.lambda.async-retry-delay-seconds before its first retry and twice that before its second (default 60, matching AWS), capped at the event's remaining maximum age. The concurrency permit is held only for each attempt, and an emulator reset drops retries still waiting. * test(lambda): prove asynchronous retries end to end * docs(lambda): document asynchronous retry timing and the Invoke Qualifier * fix(lambda): drop retries of deleted functions and tighten async retry edges - Drop a pending asynchronous retry when its function (or version) was deleted. - Decide expiry once, on the injected clock, when a retry is scheduled. - Check the reset generation at routing, so no stale outcome is delivered. - Restore upstream behavior when an attempt throws: stop retrying and route the previous result, or UnknownError when there is none. - Harden tests: in-order permit release, deterministic reset, error types and an unqualified-ARN Qualifier case for Invoke. * fix(lambda): drop a deleted function's pending events on every path Replace the store lookup with a per-function deletion counter, captured when the event is invoked and checked wherever an event is attempted or routed. This covers the expiry path, which bypassed the old check, and a delete-and-recreate of the same name during the wait, which the lookup could not see. Verified against AWS that DeleteFunction drops pending retries without delivering a record. * fix(lambda): clear deletion counts before bumping the reset generation An invoke between the two statements of clear() captured the new generation with a stale deletion count and its event was dropped. The expiry-path deletion test now drops inside the first attempt, so it no longer races the one-second maximum event age. * fix(lambda): keep deletion counts across a reset Clearing them while the old generation was still current let a deleted function's pending event see a zero count and be routed. A reset now only bumps the generation, in one atomic step. * fix(lambda): drop an Event invoke that races DeleteFunction An Event invoke that resolved the function just before a concurrent DeleteFunction could take its deletion-count snapshot after the delete had already moved the count. The event then never looked stale, so the deleted function could still be started and a failure record could still reach its destination. DeleteFunction now moves the deletion count only after the function has left the store, and an Event invoke checks that the function is still in the store after it takes its snapshot and before it queues the event. Either the check sees the function gone and the invoke answers 202 without queueing anything, or the snapshot predates the count change and the event is dropped as stale later. * fix(lambda): validate the Invoke Qualifier query parameter Invoke treated an empty or blank Qualifier as if none had been given and ran $LATEST, and it passed a qualifier longer than 128 characters on to the lookup, which answered 404. AWS rejects both with a 400. A supplied Qualifier must now be 1 to 128 characters of letters, digits, $, _ and -, or Invoke fails with ValidationException. The controller reads the parameter from the raw query, because @QueryParam reports a present but empty value as null and the check could not see it. * fix(lambda): stop pending events before a delete or reset removes state DeleteFunction moved a function's deletion count only after it had removed the function's code and store entry. A retry whose timer fired in that gap still passed the staleness check, tried to start a function with no code, and could deliver a failure record to its destination. An attempt that finished in that gap could deliver its OnFailure record. DeleteFunction now moves the count before it deletes anything, which stops every queued or running event, and again after the store entry is gone, which stops an Event invoke that read the count in between. An emulator reset wiped storage before the executor's clear() moved the reset generation, so a retry firing during the wipe could run or deliver against half-cleared state. The executor now also moves the generation in beforeReset(), which runs before the wipe. clear() still moves it, to drop events accepted between the two. * test(lambda): fix a doc comment and name the tolerated Docker ping failure The class comment now reads "wait as they do on AWS". The Docker ping check names its caught exception "expected" and says why returning false is safe: the test is then skipped rather than failed. * fix(lambda): count version and alias invokes against the function's reservation Routing the Invoke Qualifier to a published version meant a qualified invoke took its permit against the version's snapshot, which carries no reservation, so a reserved concurrency of 0 on the function no longer throttled it and a positive one stopped counting those invokes. The name-qualified path (fn:1, fn:alias) already had the same gap. Reserved concurrency is function-wide in AWS, so the executor now takes the permit against the function's $LATEST record, which holds the reservation. That covers direct Invoke with a Qualifier, qualified names and ARNs, aliases, event source mappings and asynchronous retries alike. It reads the stored record rather than the limiter's region registry because event source pollers can invoke before LambdaService has rehydrated that registry after a restart. * fix(lambda): drop a deleted function's pending events before draining its containers DeleteFunction drained the warm pool before fencing pending asynchronous events, and draining blocks while idle containers stop. A retry whose timer fired in that window still passed the staleness check and could cold-start a container after the drain, leaving it warm for a function that no longer exists. The fence now goes up first. |
||
|
|
894f20bb81 |
fix(lambda): reject invalid configuration numbers before mutation (#4726)
* fix(lambda): reject invalid configuration numbers before mutation * fix(lambda): validate configuration ARN types and memory limit |
||
|
|
e8b768382a |
fix(lambda): apply FunctionResponseTypes on UpdateEventSourceMapping (#4584)
* fix(lambda): apply FunctionResponseTypes on UpdateEventSourceMapping UpdateEventSourceMapping ignored FunctionResponseTypes, so turning ReportBatchItemFailures on or off for an existing mapping succeeded but changed nothing: GetEventSourceMapping kept the old list and the pollers kept retrying whole batches. Apply the member when present, sharing the create path's parsing; an empty list clears it. * fix(lambda): validate FunctionResponseTypes on event source mappings AWS accepts at most one FunctionResponseTypes entry, and only ReportBatchItemFailures. Reject anything else with InvalidParameterValueException on both CreateEventSourceMapping and UpdateEventSourceMapping instead of storing it. * fix(lambda): validate every UpdateEventSourceMapping member before applying any A request that failed on a later member (FunctionName in another region, empty Topics) still changed the members parsed before it on the stored mapping, which the pollers share. A JSON null FunctionResponseTypes is now an absent member, and a non-array value is a SerializationException rather than silently clearing ReportBatchItemFailures. * fix(lambda): honour ReportBatchItemFailures on Kinesis event source mappings The Kinesis poller checkpointed the whole batch after a successful invoke, so records the function reported in batchItemFailures were never retried. It now checkpoints just before the lowest reported record and retries the whole batch on a malformed response, matching the DynamoDB Streams poller. |
||
|
|
071a170ce9 |
fix(lambda): return current reserved concurrency in GetFunction (#4592)
* fix(lambda): return current reserved concurrency in GetFunction * fix(lambda): omit concurrency for qualified GetFunction reads |
||
|
|
0a786207d6 |
fix(lambda): return event source mapping ARN and support tagging mappings (#4587)
* fix(lambda): return event source mapping ARN and support tagging mappings CreateEventSourceMapping now stores Tags, every mapping response carries EventSourceMappingArn, and TagResource/ListTags/UntagResource route event-source-mapping ARNs to the mapping instead of rejecting them as non-function ARNs. * fix(lambda): address review on event source mapping ARN and tags - CloudFormation builds EventSourceMappingArn from the region and account the mapping is stored in, not the stack's, so it matches Lambda's ARN. - TagResource rejects a non-object Tags or a non-string tag value with SerializationException instead of persisting it. - The tag APIs match a mapping ARN exactly, so an ARN in another partition is reported as ResourceNotFoundException. - Explain the tolerated teardown failures in LambdaEsmTagsTest. |
||
|
|
76f8c09341 |
fix(docker): make the Docker client pool size configurable, default 1024 (#4276)
The shared DockerClient's connection pool was hard-coded to 100. Each live Lambda container holds two of those connections for its whole lifetime (the followed log stream and the exit watcher), so about 50 warm containers exhaust the pool. Create, start, stop and remove then wait for a free connection, including the idle-container stop that would release one, and the emulator stalls. Expose the size as floci.docker.max-connections (FLOCI_DOCKER_MAX_CONNECTIONS), reject values below 1, and default it to 1024 so that the 500-port Lambda runtime API range, not the Docker pool, is the ceiling on concurrent Lambda containers. Refs #2219, #2224 Co-authored-by: Goooooooooody <205637002+Goooooooooody@users.noreply.github.com> |
||
|
|
2df052181d |
fix(dynamodb): route stream consumers through one account-scoped reader (#4394)
* refactor(dynamodb): add a stream reader and key native streams by table ARN DynamoDbStreamReader is the engine-neutral way to read DynamoDB Streams. DynamoDbApiStreamReader implements it over the selected DynamoDbOperations using the Streams wire API. Native streams were keyed by region and table name, so same-named tables in two accounts shared one stream. They are now keyed by table ARN, and ListStreams returns only the caller's account and region. Streams of every account are restored from persisted tables at startup. * refactor(dynamodb): move stream consumers onto the stream reader The Lambda DynamoDB Streams poller reads through DynamoDbStreamReader: each tick renews iterators from committed progress for every readable shard, and reads a child shard only after its parent was read to its end. It discards restart checkpoints only for a process-lifetime engine, and pins LATEST per shard via newestSequenceNumbers, replacing DynamoDbStreamService.latestSequenceNumber. A read fills a batch from as many GetRecords calls as it needs, so a batch is not cut at the 1000 record GetRecords maximum. EventBridge Pipes reads DynamoDB streams the same way, committing a batch only once it is delivered or sent to the DLQ, delivers the AWS stream record shape with eventSourceARN, and honors LATEST. The Redshift zero-ETL consumer reads the same way, keeping per-shard progress in the integration (legacy checkpointSequenceNumber is ignored on load) and committing a batch only after it is written to the landing table. It discards that progress at startup for a process-lifetime engine, and the writer now takes AWS stream records, so Redshift no longer uses DynamoDbStreamService or DynamoDbStreamRecord, whose SHARD_ID is now package-private. |
||
|
|
c3c5c16c81 |
fix(lambda): support async retries and dead-letter queue (DLQ) for asynchronous invocations (#4251)
* fix(lambda): support async retries and dead-letter queue (DLQ) - Add retry loop honoring MaximumRetryAttempts and MaximumEventAgeInSeconds in LambdaExecutorService - Deliver original payload and message attributes (RequestID, ErrorCode, ErrorMessage) to SQS/SNS DLQ in AsyncInvokeDestinationRouter - Give precedence to OnFailure destination over DeadLetterConfig - Wrap EventInvokeConfig queries in RequestScopes.callAs for correct account partitioning - Add comprehensive unit and integration tests covering retries and DLQ delivery Closes #4194 * test(lambda): cover cross-account DLQ delivery * fix(lambda): add missing async destination test helper * test(lambda): allow async retry attempts in chain guard test * fix(lambda): preserve async result on age expiry |
||
|
|
7334cac52b |
fix(lambda): honor LATEST and stop deleted DynamoDB stream mappings writing back (#4318)
A DynamoDB Streams mapping created with StartingPosition LATEST is now pinned after the stream's newest record at creation, so only later writes are delivered. Previously every mapping without a checkpoint started from TRIM_HORIZON. The poll worker now re-reads the stored mapping after its fetch and skips the batch when the mapping was deleted or disabled meanwhile. An invocation still running when the mapping is deleted completes, but its result is dropped: no retry state, no OnFailure destination send, and no checkpoint write that would re-insert the mapping into the store. This also covers a state reset racing an in-flight poll. Refs #4311 |
||
|
|
09276c75dc |
fix(lambda): honor alias async destination configuration (#4348)
* fix: route Lambda async destinations by invoked alias * test: verify qualified Lambda ARN executor calls * test: cover real alias destination routing |
||
|
|
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. |
||
|
|
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.
|
||
|
|
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.
|
||
|
|
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.
|
||
|
|
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. |
||
|
|
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. |
||
|
|
75d1c2ae62 | feat(lambda): support custom Docker flags (#3751) | ||
|
|
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. |
||
|
|
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. |
||
|
|
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. |
||
|
|
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. |
||
|
|
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. |
||
|
|
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 (
|
||
|
|
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 |
||
|
|
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.
|
||
|
|
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. |
||
|
|
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. |
||
|
|
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 |
||
|
|
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. |
||
|
|
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. |
||
|
|
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. |
||
|
|
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 |
||
|
|
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 |