Ministack: Free, open-source local AWS emulator - 60+ services, Terraform compatible, real databases. Free forever. MIT licensed.
Python awsaws-emulatoraws-localaws-sdkdevtoolsdockerdynamodbec2emulatorlambdalocalstacklocalstack-alternativeministackmock-awsopen-sourcepythons3sqsterraform
feat(lambda): enforce RecursiveLoop with a per-request depth counter (#1378)
iot-rocket89f193e38055
diff --git a/ministack/core/lambda_runtime.py b/ministack/core/lambda_runtime.pyindex a5bc0bed..113bb7f0 100644--- a/ministack/core/lambda_runtime.py+++ b/ministack/core/lambda_runtime.py@@ -76,11 +76,66 @@ def _account_region_from_function_config(config: dict) -> tuple[str, str]:_workers: dict = {}_lock = threading.Lock()+# ---------------------------------------------------------------------------+# Recursive-loop lineage (runs inside every ministack-owned Python child)+# ---------------------------------------------------------------------------++# Name of the env var each executor sets to the current invocation's loop+# depth, and of the header the child stamps onto outgoing SDK calls so the+# nested Invoke can be attributed to its caller. Kept here (not in lambda_svc)+# because both the worker script and lambda_svc's one-shot wrappers embed it.+INVOKE_DEPTH_ENV = "_MINISTACK_INVOKE_DEPTH"+INVOKE_DEPTH_HEADER = "X-Ministack-Invoke-Depth"+# The warm worker's env is fixed at spawn time, so its depth rides in the+# event and is popped off before the handler sees it — same trick the X-Ray+# trace header uses.+INVOKE_DEPTH_EVENT_KEY = "_ministack_invoke_depth"+++def _sub_depth_tokens(script: str) -> str:+ """Substitute the invoke-depth carrier names into a bootstrap script."""+ return (+ script.replace("__DEPTH_ENV__", INVOKE_DEPTH_ENV)+ .replace("__DEPTH_HEADER__", INVOKE_DEPTH_HEADER)+ .replace("__DEPTH_EVENT_KEY__", INVOKE_DEPTH_EVENT_KEY)+ )+++# Prepended to the Python bootstraps we own (warm worker + one-shot wrappers),+# which call `_ms_install_invoke_depth()` once sys.path is set up and before+# they import the handler module — botocore copies BUILTIN_HANDLERS into every+# Session it builds, and handlers routinely build their clients at import time.+#+# botocore forwards `_X_AMZN_TRACE_ID` as `X-Amzn-Trace-Id` on every outgoing+# call through its own `add_recursion_detection_header`; this registers a+# handler alongside it for ministack's depth counter.+#+# Importing botocore is what a cold start pays for the counter (~0.15s here),+# once per worker — or once per invocation on the one-shot executor, which+# only durable invocations use. A function whose environment has no botocore+# is not instrumented: it would have to be calling Invoke over raw urllib,+# which never carried lineage anyway.+INVOKE_DEPTH_BOOTSTRAP = _sub_depth_tokens('''+def _ms_install_invoke_depth():+ import os+ try:+ import botocore.handlers+ except ImportError:+ return++ def _ms_add_invoke_depth(params, **kwargs):+ depth = os.environ.get("__DEPTH_ENV__")+ if depth and "__DEPTH_HEADER__" not in params["headers"]:+ params["headers"]["__DEPTH_HEADER__"] = depth++ botocore.handlers.BUILTIN_HANDLERS.append(("before-call", _ms_add_invoke_depth))+''')+# ---------------------------------------------------------------------------# Python worker script (runs inside a persistent subprocess)# ----------------------------------------------------------------------------_PYTHON_WORKER_SCRIPT = '''+_PYTHON_WORKER_SCRIPT = INVOKE_DEPTH_BOOTSTRAP + _sub_depth_tokens('''import sys, json, importlib, traceback, os, timedef run():@@ -110,6 +165,9 @@ def run():if os.path.isdir(_sp):_site.addsitedir(_sp)sys.path.insert(0, _ld)+ # After sys.path is complete (so a function that bundles its own botocore+ # gets that one) and before the handler module builds any client.+ _ms_install_invoke_depth()try:mod = importlib.import_module(module_name)handler_fn = getattr(mod, handler_name)@@ -133,6 +191,13 @@ def run():os.environ["_X_AMZN_TRACE_ID"] = _xray_tidelif "_X_AMZN_TRACE_ID" in os.environ:del os.environ["_X_AMZN_TRACE_ID"]+ # Recursive-loop depth: same per-invocation channel as the trace+ # header, read by the before-call handler when this function calls out.+ _ms_depth = event.pop("__DEPTH_EVENT_KEY__", None)+ if _ms_depth is not None:+ os.environ["__DEPTH_ENV__"] = str(_ms_depth)+ elif "__DEPTH_ENV__" in os.environ:+ del os.environ["__DEPTH_ENV__"]_function_name = init.get("function_name", "")_deadline = time.time() + float(os.environ.get("_LAMBDA_TIMEOUT", "3"))context = type("Context", (), {@@ -155,13 +220,13 @@ def run():_real_stdout.flush()run()-'''+''')# ---------------------------------------------------------------------------# Node.js worker script (runs inside a persistent subprocess)# ----------------------------------------------------------------------------_NODEJS_WORKER_SCRIPT = r'''+_NODEJS_WORKER_SCRIPT = _sub_depth_tokens(r'''const readline = require("readline");const path = require("path");const http = require("http");@@ -206,6 +271,13 @@ fs.write = function(fd, ...args) {const body = params.Payload instanceof Uint8Array? Buffer.from(params.Payload): (params.Payload || "");+ const headers = { "Content-Type": "application/json" };+ // Carry the caller's recursive-loop depth so ministack can attribute this+ // nested Invoke to it (the counterpart of the botocore before-call handler+ // on the Python side).+ if (process.env.__DEPTH_ENV__) {+ headers["__DEPTH_HEADER__"] = process.env.__DEPTH_ENV__;+ }return new Promise((resolve, reject) => {const req = http.request({@@ -213,7 +285,7 @@ fs.write = function(fd, ...args) {port: parseInt(ep.port || "4566", 10),method: "POST",path: "/2015-03-31/functions/" + fn + "/invocations" + qs,- headers: { "Content-Type": "application/json" },+ headers: headers,},(res) => {const chunks = [];@@ -781,6 +853,15 @@ rl.on("line", async (line) => {} else if ("_X_AMZN_TRACE_ID" in process.env) {delete process.env._X_AMZN_TRACE_ID;}+ // Recursive-loop depth rides the same per-invocation channel, and the+ // bundled Lambda stub reads it back off process.env when the handler+ // invokes another function.+ if (event.__DEPTH_EVENT_KEY__ !== undefined) {+ process.env.__DEPTH_ENV__ = String(event.__DEPTH_EVENT_KEY__);+ } else if ("__DEPTH_ENV__" in process.env) {+ delete process.env.__DEPTH_ENV__;+ }+ delete event.__DEPTH_EVENT_KEY__;delete event._x_amzn_trace_id;delete event._request_id;delete event._function_name;@@ -826,7 +907,7 @@ rl.on("line", async (line) => {}) + "\n");}});-'''+''')def _detect_runtime_binary(runtime: str) -> tuple[str, str]:diff --git a/ministack/services/lambda_svc.py b/ministack/services/lambda_svc.pyindex 189c904b..a1f8b02f 100644--- a/ministack/services/lambda_svc.py+++ b/ministack/services/lambda_svc.py@@ -49,7 +49,14 @@ from typing import Anyfrom urllib.parse import quote, unquotefrom ministack.core.arn import ArnParseError, parse_arn-from ministack.core.lambda_runtime import get_or_create_worker, invalidate_worker+from ministack.core.lambda_runtime import (+ INVOKE_DEPTH_BOOTSTRAP,+ INVOKE_DEPTH_ENV,+ INVOKE_DEPTH_EVENT_KEY,+ INVOKE_DEPTH_HEADER,+ get_or_create_worker,+ invalidate_worker,+)from ministack.core.persistence import PERSIST_STATE, STATE_DIR, load_statefrom ministack.core.responses import (_12_DIGIT_RE,@@ -122,6 +129,86 @@ def _xray_trace_id_for_invocation(config: dict, inbound_trace_header: str | Nonereturn f"Root=1-{epoch_hex}-{root_random};Parent={parent};Sampled=1"+# ---------------------------------------------------------------------------+# Recursive-loop detection+# ---------------------------------------------------------------------------+#+# AWS drops an invocation once a request has gone around the same function+# more than 16 times, unless PutFunctionRecursionConfig set RecursiveLoop to+# Allow. It counts *lineage*, not concurrency: the counter rides along with+# the request, so a loop is caught even when every hop finishes before the+# next one starts. That distinction matters here — an async self-invoke+# returns 202 and releases the warm worker immediately, so it loops forever+# with only one execution in flight at a time and no resource ever runs out.+#+# 16 is the number of invocations that *run*: "If your function is invoked+# approximately 16 times in the same chain of requests, then Lambda+# automatically stops the next function invocation in that request chain"+# (Lambda Developer Guide, "Use Lambda recursive loop detection to prevent+# infinite loops"). So hop 17 is the first one dropped, and the depth check+# below is `>`, not `>=`. AWS says "approximately"; ministack counts exactly.+MAX_INVOKE_DEPTH = 16++# Cross-process carrier. The executors put the current depth in the child's+# environment; the bootstrap in ministack's Python children (and the Node+# worker's bundled Lambda stub) stamps it onto outgoing calls, so a nested+# Invoke arrives here carrying its caller's depth. It is a plain request+# header, so a client can forge it: an emulator has no trust boundary to+# defend here, and being able to set the depth by hand is what makes the+# limit testable without running 16 real hops.+_INVOKE_DEPTH_HEADER = INVOKE_DEPTH_HEADER.lower()++# In-process carrier. Set on the request task in `_invoke`; inherited by the+# execution thread and by async-invoke threads (both copy the context), which+# is where the executors read it back to seed the child environment.+_invoke_depth: contextvars.ContextVar[int] = contextvars.ContextVar(+ "ministack_invoke_depth", default=0+)+++def _inbound_invoke_depth(headers: dict) -> int:+ """How many Lambda hops the incoming request has already been through."""+ raw = headers.get(_INVOKE_DEPTH_HEADER)+ if raw is None:+ return 0+ try:+ return max(0, int(raw))+ except (TypeError, ValueError):+ return 0+++def _recursive_loop_drop(name: str, func: dict, depth: int):+ """AWS-shaped drop response when `depth` busts the loop limit, else None.++ `RecursiveLoop: Allow` opts the function out, exactly as on AWS — the+ counter keeps climbing, nothing is dropped.+ """+ if depth <= MAX_INVOKE_DEPTH:+ return None+ if (func.get("recursive_loop") or "Terminate") == "Allow":+ return None+ try:+ from ministack.services import cloudwatch as _cw+ _cw.record_metric(+ "AWS/Lambda", "RecursiveInvocationsDropped", 1, "Count",+ {"FunctionName": name},+ )+ except Exception:+ logger.debug("emit recursive-drop metric failed", exc_info=True)+ logger.warning(+ "Dropped invocation of %s: recursive loop detected at depth %d "+ "(limit %d). Set RecursiveLoop=Allow to opt out.",+ name, depth, MAX_INVOKE_DEPTH,+ )+ return error_response_json(+ "RecursiveInvocationException",+ "Lambda has detected your function being invoked in a recursive loop "+ "with other Amazon Web Services resources and stopped your function's "+ f"invocation: {_func_arn(name)}",+ 400,+ )++def _account_from_arn(arn: str) -> str:"""Extract the 12-digit account ID from a Lambda function ARN.@@ -558,7 +645,7 @@ def _restore_esm_positions(store: AccountRegionScopedDict, positions) -> None:# Wrapper script executed inside the subprocess.# All configuration is passed through env vars; event data arrives on stdin.# ----------------------------------------------------------------------------_WRAPPER_SCRIPT = """\+_WRAPPER_SCRIPT = INVOKE_DEPTH_BOOTSTRAP + """\import sys, os, jsonsys.path.insert(0, os.environ["_LAMBDA_CODE_DIR"])@@ -601,6 +688,10 @@ class LambdaContext:def get_remaining_time_in_millis():return int(float(os.environ.get("_LAMBDA_TIMEOUT", "3")) * 1000)+# After sys.path is complete (so a function that bundles its own botocore gets+# that one) and before the handler module builds any client.+_ms_install_invoke_depth()+_mod = __import__(_mod_path)for _part in _mod_path.split(".")[1:]:_mod = getattr(_mod, _part)@@ -2394,6 +2485,14 @@ async def _invoke(name: str, event: dict, headers: dict, path_qualifier: str | Nif invocation_type == "DryRun":return 204, {"X-Amz-Executed-Version": executed_version}, b""+ # Recursive-loop guard — one counter check before anything executes, and+ # the only place the depth is established for everything downstream.+ depth = _inbound_invoke_depth(headers) + 1+ dropped = _recursive_loop_drop(name, func, depth)+ if dropped is not None:+ return dropped+ _invoke_depth.set(depth)+# If the function has DurableConfig.Enabled, spin up a durable execution# record so the SDK calls (Checkpoint / GetState) inside the function# have a target. The ARN is surfaced back via the X-Amz-Durable-Execution-@@ -3498,6 +3597,14 @@ def _spawn_lambda_container(config: dict, code_zip: bytes | None):# Per-invocation durable-execution overlay (no-op when the call isn't# inside a durable function).container_env.update(_durable_env_overlay())+ # Recursive-loop depth of the invocation that cold-started this container.+ # Same staleness-on-reuse caveat as the durable overlay above: the pool+ # hands the container to later invocations without re-baking its env. And+ # unlike the warm/local executors, nothing inside an RIE container stamps+ # this onto outgoing calls — ministack owns no bootstrap in there — so a+ # docker-executor function's nested Invoke arrives without lineage unless+ # the function forwards the variable itself.+ container_env[INVOKE_DEPTH_ENV] = str(_invoke_depth.get())# NOTE: X-Ray active tracing is NOT supported in the docker RIE# executor. AWS RIE explicitly does not implement X-Ray# (https://github.com/aws/aws-lambda-runtime-interface-emulator —@@ -4094,6 +4201,13 @@ def _execute_function_warm(func: dict, event: dict) -> dict:_xray = _xray_trace_id_for_invocation(config)if _xray:event["_x_amzn_trace_id"] = _xray+ # Same channel for the recursive-loop depth: the worker's env is+ # fixed at spawn time, so it has to ride in the event. Both worker+ # bootstraps move it to the environment and drop the key before the+ # handler runs. Non-dict payloads have nowhere to carry it, and lose+ # the counter.+ if isinstance(event, dict):+ event[INVOKE_DEPTH_EVENT_KEY] = _invoke_depth.get()result = worker.invoke(event, new_uuid())if result.get("status") == "ok":return {"body": result.get("result"), "log": result.get("log", "")}@@ -4257,6 +4371,7 @@ def _execute_function_provided(func: dict, event: dict) -> dict:_xray_trace_id = _xray_trace_id_for_invocation(config)if _xray_trace_id:proc_env["_X_AMZN_TRACE_ID"] = _xray_trace_id+ proc_env[INVOKE_DEPTH_ENV] = str(_invoke_depth.get())# Override AWS_ENDPOINT_URL *after* function env vars so# Lambda binaries always call back to this MiniStack# instance. Function-level env vars may carry the@@ -4426,6 +4541,7 @@ def _execute_function_local(func: dict, event: dict) -> dict:_xray_trace_id = _xray_trace_id_for_invocation(config)if _xray_trace_id:env["_X_AMZN_TRACE_ID"] = _xray_trace_id+ env[INVOKE_DEPTH_ENV] = str(_invoke_depth.get())cmd = ["node", wrapper_path] if is_node else ["python3", wrapper_path]proc = subprocess.run(diff --git a/tests/conftest.py b/tests/conftest.pyindex 3085ea99..b1b0ac6e 100644--- a/tests/conftest.py+++ b/tests/conftest.py@@ -141,6 +141,15 @@ _SERIAL_TESTS = {# Account-global mutations (password policy, alias); must run serially."tests/test_iam.py::test_iam_password_policy_absent_then_set","tests/test_iam.py::test_iam_account_alias_crud",+ # Recursive-loop detection. The two chain tests cold-start 16+ Lambdas+ # each and poll CloudWatch Logs until the chain stops changing; the other+ # two assert on wall clock (a dropped invocation must come back long+ # before the handler's timeout could have elapsed). Both shapes tip over+ # under xdist load, so run them in the serial phase.+ "tests/test_lambda.py::test_lambda_recursive_loop_terminates_self_invoking_chain",+ "tests/test_lambda.py::test_lambda_recursive_loop_allow_lets_the_chain_through",+ "tests/test_lambda.py::test_lambda_recursive_loop_drop_is_recursive_invocation_exception",+ "tests/test_lambda.py::test_lambda_nested_invoke_below_limit_is_unaffected",}diff --git a/tests/test_lambda.py b/tests/test_lambda.pyindex 56ef6668..9a174a8b 100644--- a/tests/test_lambda.py+++ b/tests/test_lambda.py@@ -10090,3 +10090,297 @@ def test_lambda_keepalive_zero_forces_cold_start(monkeypatch):finally:with _svc._warm_pool_lock:_svc._warm_pool.pop(key, None)+++# ---------------------------------------------------------------------------+# Recursive-loop detection — PutFunctionRecursionConfig made real.+#+# AWS drops an invocation once a request has gone around the same function+# more than 16 times, unless RecursiveLoop is set to Allow, and surfaces the+# drop as RecursiveInvocationException. It counts lineage carried on the+# request rather than concurrent executions, which is what catches the loop+# shape that has nothing to exhaust: an async self-invoke returns 202 and+# releases the warm worker immediately, so it recurses forever with a single+# execution in flight. These tests drive that through a real chain, so they+# cover the whole path — depth into the child env, the botocore hook that+# stamps it onto the nested call, and the counter check back on the gateway.+#+# Every test here is bounded in wall clock: a regression that reopens the+# runaway must fail, not hang.+# ---------------------------------------------------------------------------++_RECURSION_LIMIT = 16++# Logs its hop number, then invokes itself asynchronously with the next one.+# `stop` is a backstop so a broken guard ends the chain instead of running+# until the test session is killed.+_LOOP_HANDLER = (+ "import json, os, sys, boto3\n"+ "def handler(event, context):\n"+ " n = int(event.get('n', 0))\n"+ " stop = int(event.get('stop', 40))\n"+ " print('LOOPHOP %d' % n, file=sys.stderr)\n"+ " if n >= stop:\n"+ " return {'done': n}\n"+ " c = boto3.client('lambda', endpoint_url=os.environ['AWS_ENDPOINT_URL'],\n"+ " region_name=os.environ['AWS_REGION'])\n"+ " try:\n"+ " c.invoke(FunctionName=os.environ['AWS_LAMBDA_FUNCTION_NAME'],\n"+ " InvocationType='Event',\n"+ " Payload=json.dumps({'n': n + 1, 'stop': stop}))\n"+ " except Exception as exc:\n"+ " print('LOOPDROP %s' % type(exc).__name__, file=sys.stderr)\n"+ " return {'n': n}\n"+)+++def _create_loop_fn(lam, name: str) -> None:+ lam.create_function(+ FunctionName=name,+ Runtime="python3.12",+ Role=_LAMBDA_ROLE,+ Handler="index.handler",+ Code={"ZipFile": _make_zip(_LOOP_HANDLER)},+ Timeout=10,+ )+++def _drain_loop(logs, name: str, budget_s: float = 60.0, settle_s: float = 4.0):+ """Run the chain to a standstill; return (hops seen, drop markers seen).++ Polls the function's log group until nothing new shows up for `settle_s`,+ so the assertions describe a finished chain rather than a snapshot of one+ still in flight. Gives up at `budget_s` — a chain that never settles is a+ failed guard, and saying so beats hanging the suite.+ """+ hops: set = set()+ drops: set = set()+ started = time.time()+ last_change = started+ while time.time() - started < budget_s:+ time.sleep(0.5)+ try:+ events = logs.filter_log_events(+ logGroupName=f"/aws/lambda/{name}", limit=1000+ ).get("events", [])+ except ClientError:+ continue # log group not created until the first hop runs+ seen_hops, seen_drops = set(), set()+ for ev in events:+ for line in ev["message"].splitlines():+ if line.startswith("LOOPHOP"):+ seen_hops.add(int(line.split()[1]))+ elif line.startswith("LOOPDROP"):+ seen_drops.add(line)+ if (seen_hops, seen_drops) != (hops, drops):+ hops, drops = seen_hops, seen_drops+ last_change = time.time()+ elif hops and time.time() - last_change >= settle_s:+ return hops, drops+ pytest.fail(+ f"recursion chain for {name} never settled within {budget_s}s "+ f"(hops seen: {sorted(hops)})"+ )+++def test_lambda_recursive_loop_terminates_self_invoking_chain(lam, logs):+ """A function that async-invokes itself forever stops at the AWS limit.++ Terminate is the default, so this function never calls+ PutFunctionRecursionConfig — the guard has to apply it on its own.+ """+ name = f"qa-loop-term-{_uuid_mod.uuid4().hex[:8]}"+ _create_loop_fn(lam, name)+ try:+ lam.invoke(FunctionName=name, InvocationType="Event",+ Payload=json.dumps({"n": 0, "stop": 40}).encode())+ hops, drops = _drain_loop(logs, name)+ # Hops are 0-based, so the 16 permitted executions are 0..15 and the+ # 17th request is dropped before the handler ever runs.+ assert max(hops) == _RECURSION_LIMIT - 1, sorted(hops)+ assert hops == set(range(_RECURSION_LIMIT)), sorted(hops)+ # The caller of the dropped invoke sees the AWS error, not a silence.+ assert drops, "no LOOPDROP marker — chain ended without an error"+ finally:+ lam.delete_function(FunctionName=name)+++def test_lambda_recursive_loop_allow_lets_the_chain_through(lam, logs):+ """RecursiveLoop=Allow opts out — the same chain runs past the limit.++ Pins that the limit is driven by the function's config rather than+ hardcoded; the chain ends on its own `stop`, well beyond 16.+ """+ name = f"qa-loop-allow-{_uuid_mod.uuid4().hex[:8]}"+ _create_loop_fn(lam, name)+ try:+ lam.put_function_recursion_config(FunctionName=name, RecursiveLoop="Allow")+ stop = _RECURSION_LIMIT + 5+ lam.invoke(FunctionName=name, InvocationType="Event",+ Payload=json.dumps({"n": 0, "stop": stop}).encode())+ hops, drops = _drain_loop(logs, name)+ assert max(hops) == stop, sorted(hops)+ assert not drops, f"invocation dropped despite RecursiveLoop=Allow: {drops}"+ finally:+ lam.delete_function(FunctionName=name)+++def test_lambda_recursive_loop_drop_is_recursive_invocation_exception(lam):+ """The dropped invocation fails fast with the AWS-modelled error.++ Stamping the depth header directly starts the caller at the limit, so the+ drop is reached in one hop — which also pins the wire contract the child+ processes use to carry lineage back to the gateway.+ """+ name = f"qa-loop-shape-{_uuid_mod.uuid4().hex[:8]}"+ client = _regional_client("lambda", "us-east-1")++ def _stamp_depth(params, **kwargs):+ params["headers"]["X-Ministack-Invoke-Depth"] = str(_RECURSION_LIMIT)++ _create_loop_fn(lam, name)+ try:+ client.meta.events.register("before-call.lambda.Invoke", _stamp_depth)+ started = time.time()+ with pytest.raises(ClientError) as exc:+ client.invoke(FunctionName=name, Payload=b'{"n": 0, "stop": 0}')+ elapsed = time.time() - started+ assert exc.value.response["Error"]["Code"] == "RecursiveInvocationException"+ assert exc.value.response["ResponseMetadata"]["HTTPStatusCode"] == 400+ # Dropped means never executed: the answer comes back immediately+ # rather than after the handler's 10s timeout.+ assert elapsed < 5, f"drop took {elapsed:.1f}s — did the handler run?"+ finally:+ lam.delete_function(FunctionName=name)+++def test_lambda_nested_invoke_below_limit_is_unaffected(lam):+ """A → B stays legal. The guard counts hops, so ordinary nesting — the+ re-entrancy the executor exists to support — must pass straight through."""+ callee = f"qa-nest-callee-{_uuid_mod.uuid4().hex[:8]}"+ caller = f"qa-nest-caller-{_uuid_mod.uuid4().hex[:8]}"+ lam.create_function(+ FunctionName=callee,+ Runtime="python3.12",+ Role=_LAMBDA_ROLE,+ Handler="index.handler",+ Code={"ZipFile": _make_zip("def handler(event, context):\n"+ " return {'from': 'callee'}\n")},+ Timeout=10,+ )+ lam.create_function(+ FunctionName=caller,+ Runtime="python3.12",+ Role=_LAMBDA_ROLE,+ Handler="index.handler",+ Code={"ZipFile": _make_zip(+ "import json, os, boto3\n"+ "def handler(event, context):\n"+ " c = boto3.client('lambda', endpoint_url=os.environ['AWS_ENDPOINT_URL'],\n"+ " region_name=os.environ['AWS_REGION'])\n"+ " r = c.invoke(FunctionName=event['target'],\n"+ " Payload=json.dumps({}))\n"+ " return json.loads(r['Payload'].read())\n"+ )},+ Timeout=10,+ )+ try:+ started = time.time()+ resp = lam.invoke(FunctionName=caller,+ Payload=json.dumps({"target": callee}).encode())+ body = json.loads(resp["Payload"].read())+ assert resp.get("FunctionError") is None, body+ assert body == {"from": "callee"}+ assert time.time() - started < 20+ finally:+ for fn in (caller, callee):+ lam.delete_function(FunctionName=fn)+++def test_lambda_recursive_loop_counts_nodejs_hops(lam):+ """A Node hop carries the counter too, and never sees it in its event.++ The Node worker takes the depth off the event exactly like the Python one,+ and its bundled Lambda client stamps it back onto the nested Invoke.+ Starting the caller one hop below the limit trips the guard on that single+ nested call, so the whole Node path is pinned without chaining 16 hops+ (each of which would cost a cold start).+ """+ callee = f"qa-node-callee-{_uuid_mod.uuid4().hex[:8]}"+ caller = f"qa-node-caller-{_uuid_mod.uuid4().hex[:8]}"+ lam.create_function(+ FunctionName=callee,+ Runtime="python3.12",+ Role=_LAMBDA_ROLE,+ Handler="index.handler",+ Code={"ZipFile": _make_zip("def handler(event, context):\n"+ " return {'from': 'callee'}\n")},+ Timeout=10,+ )+ lam.create_function(+ FunctionName=caller,+ Runtime="nodejs20.x",+ Role=_LAMBDA_ROLE,+ Handler="index.handler",+ Code={"ZipFile": _make_zip_js(+ 'const { Lambda } = require("@aws-sdk/client-lambda");\n'+ "exports.handler = async (event) => {\n"+ " const keys = Object.keys(event);\n"+ " const r = await new Lambda({}).invoke({\n"+ " FunctionName: event.target, Payload: JSON.stringify({}),\n"+ " });\n"+ " return { keys: keys, status: r.StatusCode, body: String(r.Payload) };\n"+ "};\n"+ )},+ Timeout=10,+ )+ client = _regional_client("lambda", "us-east-1")++ def _stamp_depth(params, **kwargs):+ params["headers"]["X-Ministack-Invoke-Depth"] = str(_RECURSION_LIMIT - 1)++ try:+ client.meta.events.register("before-call.lambda.Invoke", _stamp_depth)+ resp = client.invoke(FunctionName=caller,+ Payload=json.dumps({"target": callee}).encode())+ body = json.loads(resp["Payload"].read())+ assert resp.get("FunctionError") is None, body+ # The depth rides in the event, so the handler must never see the key.+ assert body["keys"] == ["target"], body["keys"]+ # The caller is at the limit, so its nested hop is the one over it.+ assert body["status"] == 400, body+ assert "RecursiveInvocationException" in body["body"], body+ finally:+ for fn in (caller, callee):+ lam.delete_function(FunctionName=fn)+++ "headers,expected",+ [+ pytest.param({}, 0, id="absent"),+ pytest.param({"x-ministack-invoke-depth": "3"}, 3, id="normal"),+ pytest.param({"x-ministack-invoke-depth": "16"}, 16, id="at-limit"),+ # Nothing caps the inbound value: a request already past the limit is+ # dropped rather than clamped, so the number has to survive intact.+ pytest.param({"x-ministack-invoke-depth": "999"}, 999, id="over-limit"),+ pytest.param({"x-ministack-invoke-depth": "-5"}, 0, id="negative"),+ pytest.param({"x-ministack-invoke-depth": ""}, 0, id="empty"),+ pytest.param({"x-ministack-invoke-depth": "not-a-number"}, 0, id="garbage"),+ pytest.param({"x-ministack-invoke-depth": "1.5"}, 0, id="float"),+ pytest.param({"x-ministack-invoke-depth": None}, 0, id="none"),+ # ASGI lowercases request headers, and every other header read in+ # ministack assumes it; a capitalised key is simply not there.+ pytest.param({"X-Ministack-Invoke-Depth": "4"}, 0, id="wrong-case"),+ ],+)+def test_lambda_inbound_invoke_depth_parsing(headers, expected):+ """A forged or malformed depth header must never break the invoke path.++ The header is client-supplied, so every shape has to land somewhere sane:+ junk reads as "fresh lineage" (0) rather than raising, and a legitimate+ count passes through unclamped so the limit check can see it.+ """+ from ministack.services.lambda_svc import _inbound_invoke_depth++ assert _inbound_invoke_depth(headers) == expected