Skip to content

Ministack: Free, open-source local AWS emulator - 60+ services, Terraform compatible, real databases. Free forever. MIT licensed.

fix(lambda): retain invocation alias in context (#2021)

Jay Janssencc6671e28111
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 4e6ccf26..9a205ac0 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -8,6 +8,7 @@ Versioning follows [Semantic Versioning](https://semver.org/).
## [Unreleased]
### Fixed
+- **Lambda — preserve invocation aliases in runtime context** — `Invoke` retains the requested alias or version in `invoked_function_arn`, while `function_version` remains the resolved published version. Warm workers receive invocation identity per request.
- **IoT — `https://<endpointAddress>` verifies under `USE_SSL=1`** — `DescribeEndpoint` hands out `<prefix>-ats.iot.<region>.<MINISTACK_HOST>` and `<prefix>.credentials.iot.<region>.<MINISTACK_HOST>`, which SDKs dial over HTTPS as on AWS, but the generated gateway certificate did not name them, so the handshake failed hostname verification. The certificate now carries `*.iot.<region>.<MINISTACK_HOST>` and `*.credentials.iot.<region>.<MINISTACK_HOST>` for every region, and a cached certificate without them is regenerated. Contributed by @iot-rocket.
### Added
diff --git a/ministack/core/lambda_runtime.py b/ministack/core/lambda_runtime.py
index cb2153f5..6c645c65 100644
--- a/ministack/core/lambda_runtime.py
+++ b/ministack/core/lambda_runtime.py
@@ -307,7 +307,7 @@ def run():
"function_name": init.get("function_name", ""),
"function_version": os.environ.get("AWS_LAMBDA_FUNCTION_VERSION", "$LATEST"),
"memory_limit_in_mb": init.get("memory", 128),
- "invoked_function_arn": init.get("arn", ""),
+ "invoked_function_arn": _ms_ctx.get("invoked_function_arn", init.get("arn", "")),
"aws_request_id": _ms_ctx.get("request_id", ""),
"log_group_name": os.environ.get("AWS_LAMBDA_LOG_GROUP_NAME", "/aws/lambda/" + _function_name),
"log_stream_name": os.environ.get("AWS_LAMBDA_LOG_STREAM_NAME", ""),
@@ -951,7 +951,7 @@ rl.on("line", async (line) => {
functionName: process.env.AWS_LAMBDA_FUNCTION_NAME || "",
functionVersion: process.env.AWS_LAMBDA_FUNCTION_VERSION || "$LATEST",
memoryLimitInMB: process.env.AWS_LAMBDA_FUNCTION_MEMORY_SIZE || "128",
- invokedFunctionArn: process.env._LAMBDA_FUNCTION_ARN || "",
+ invokedFunctionArn: ctx.invoked_function_arn || process.env._LAMBDA_FUNCTION_ARN || "",
awsRequestId: ctx.request_id || "",
logGroupName: process.env.AWS_LAMBDA_LOG_GROUP_NAME
|| ("/aws/lambda/" + (process.env.AWS_LAMBDA_FUNCTION_NAME || "")),
@@ -1335,7 +1335,7 @@ class Worker:
return "\n".join(lines)
def invoke(self, event, request_id: str, *, trace_id: str | None = None,
- depth=None, durable: dict | None = None) -> dict:
+ depth=None, durable: dict | None = None, invoked_function_arn: str | None = None) -> dict:
"""Run one invocation on this worker.
The per-invocation values travel beside the payload, not inside it:
@@ -1355,13 +1355,14 @@ class Worker:
timeout = self.config.get("Timeout", 30)
# Only what genuinely differs per invocation. The function's own
- # identity (name, version, memory, ARN, log group and stream) is
+ # identity (name, version, memory, log group and stream) is
# already in the worker's environment, where AWS puts it, and both
# bootstraps build their context object from there.
envelope = {
"event": event,
"ctx": {
"request_id": request_id,
+ "invoked_function_arn": invoked_function_arn if invoked_function_arn is not None else self.config.get("FunctionArn", ""),
"timeout_ms": int(float(timeout) * 1000),
"trace_id": trace_id,
"depth": depth,
@@ -1869,7 +1870,7 @@ class ProvidedWorker(Worker):
self._stopped()
return
try:
- request_id, event, deadline_ms, trace_id = pending.get(
+ request_id, event, deadline_ms, trace_id, invoked_function_arn = pending.get(
timeout=0.1)
break
except queue.Empty:
@@ -1880,7 +1881,7 @@ class ProvidedWorker(Worker):
self.send_header("Lambda-Runtime-Deadline-Ms", str(deadline_ms))
self.send_header(
"Lambda-Runtime-Invoked-Function-Arn",
- worker.config.get("FunctionArn", ""),
+ invoked_function_arn,
)
if trace_id:
# The Runtime API header is how AWS hands X-Ray context to
@@ -2091,7 +2092,7 @@ class ProvidedWorker(Worker):
log = self._drain_stderr_bounded(first_line_wait=0.1)
return f": {log}" if log else ""
- def invoke(self, event: dict, request_id: str, *, trace_id: str = None) -> dict:
+ def invoke(self, event: dict, request_id: str, *, trace_id: str = None, invoked_function_arn: str | None = None) -> dict:
"""Run one invocation on this environment.
``trace_id`` is per-invocation X-Ray context, passed separately rather
@@ -2126,7 +2127,8 @@ class ProvidedWorker(Worker):
self._current_request_id = request_id
pending = self._pending
deadline_ms = int((time.time() + timeout) * 1000)
- pending.put((request_id, event, deadline_ms, trace_id))
+ pending.put((request_id, event, deadline_ms, trace_id,
+ invoked_function_arn if invoked_function_arn is not None else self.config.get("FunctionArn", "")))
deadline = time.monotonic() + timeout
failure = None
diff --git a/ministack/services/lambda_svc.py b/ministack/services/lambda_svc.py
index ac91c6e8..9bcb6ba7 100644
--- a/ministack/services/lambda_svc.py
+++ b/ministack/services/lambda_svc.py
@@ -2989,6 +2989,11 @@ async def _invoke(name: str, event: dict, headers: dict, path_qualifier: str | N
409,
)
+ # Keep caller identity separate from the resolved version's stored config.
+ exec_record = dict(exec_record)
+ exec_record["config"] = dict(exec_record.get("config") or exec_record)
+ exec_record["config"]["FunctionArn"] = _func_arn(name) + (f":{qualifier}" if qualifier else "")
+
if invocation_type == "DryRun":
return 204, {"X-Amz-Executed-Version": executed_version}, b""
@@ -5270,6 +5275,7 @@ def _execute_function_warm(func: dict, event: dict) -> dict:
event,
new_uuid(),
trace_id=_xray_trace_id_for_invocation(config),
+ invoked_function_arn=config.get("FunctionArn", ""),
depth=_invoke_depth.get(),
durable=_durable_env_overlay(),
)
@@ -5363,6 +5369,7 @@ def _execute_function_provided_warm(func: dict, event: dict,
result = worker.invoke(
event, request_id or new_uuid(),
trace_id=_xray_trace_id_for_invocation(config),
+ invoked_function_arn=config.get("FunctionArn", ""),
)
if result.get("status") == "ok":
return {"body": result.get("result"), "log": result.get("log", "")}
diff --git a/tests/test_lambda.py b/tests/test_lambda.py
index 4f5a1ec0..d0048f4e 100644
--- a/tests/test_lambda.py
+++ b/tests/test_lambda.py
@@ -4892,7 +4892,7 @@ def test_lambda_cross_account_layer_under_auth_names_the_calling_user(monkeypatc
from ministack.services import iam as iam_svc
monkeypatch.setattr(app_mod, "AUTH", True)
- key, user = "AKIALAYERCONSUMER001", "layer-consumer"
+ key, user = "test-layer-consumer-key", "layer-consumer"
user_arn = f"arn:aws:iam::{_CALLER_ACCOUNT}:user/{user}"
seeded = [
(iam_svc._users, user, {"UserName": user, "Arn": user_arn, "UserId": "AIDALAYER", "AttachedPolicies": []}),
@@ -13724,7 +13724,10 @@ def test_provided_metadata_does_not_mutate_payload(monkeypatch, event):
result = lambda_svc._execute_function_provided_warm(
{"config": _provided_dispatch_config(), "code_zip": b"zip"}, event, "request-1",
)
- worker.invoke.assert_called_once_with(event, "request-1", trace_id="trace-1")
+ worker.invoke.assert_called_once_with(
+ event, "request-1", trace_id="trace-1",
+ invoked_function_arn=_provided_dispatch_config()["FunctionArn"],
+ )
release.assert_called_once_with(worker)
assert result == {"body": event, "log": "handler log"}
if isinstance(event, dict):
@@ -14262,3 +14265,17 @@ def test_classify_function_error_bare_timeout_string_is_unhandled():
assert lsvc._classify_function_error("Task timed out after 300.00 seconds", "") == "Unhandled"
# Only the exact runtime message counts; other handler strings stay successes.
assert lsvc._classify_function_error("the Task timed out after 3.00 seconds today", "") is None
+
+
+def test_provided_invocation_arn_is_per_request(worker_factory):
+ worker = worker_factory(_bootstrap('''
+while True:
+ headers, event = next_invocation()
+ post_response(headers["Lambda-Runtime-Aws-Request-Id"],
+ headers["Lambda-Runtime-Invoked-Function-Arn"])
+'''))
+ for qualifier in ("worker", "other", "1", "worker"):
+ arn = worker.config["FunctionArn"] + ":" + qualifier
+ result = worker.invoke({}, "request-" + qualifier, invoked_function_arn=arn)
+ assert result["status"] == "ok", result
+ assert result["result"] == arn
diff --git a/tests/test_lambda_invocation_identity.py b/tests/test_lambda_invocation_identity.py
new file mode 100644
index 00000000..b8b06761
--- /dev/null
+++ b/tests/test_lambda_invocation_identity.py
@@ -0,0 +1,52 @@
+"""Invoke identity follows the caller's qualifier, not alias resolution.
+
+AWS contract: https://docs.aws.amazon.com/lambda/latest/dg/python-context.html
+"""
+import asyncio
+import io
+import json
+import uuid
+import zipfile
+from copy import deepcopy
+
+import pytest
+
+from ministack.core.lambda_runtime import invalidate_worker
+from ministack.services import lambda_svc as svc
+
+
[email protected]("runtime", ["python3.12", "nodejs20.x"])
[email protected]("asynchronous", [False, True])
+def test_invocation_retains_alias_without_mutating_version(monkeypatch, asynchronous, runtime):
+ name = "identity-" + uuid.uuid4().hex
+ arn = svc._func_arn(name)
+ config = {"FunctionName": name, "FunctionArn": arn, "Runtime": runtime,
+ "Handler": "index.handler", "Timeout": 10, "Version": "$LATEST"}
+ buf = io.BytesIO()
+ with zipfile.ZipFile(buf, "w") as archive:
+ archive.writestr("index.py", "def handler(event, context):\n"
+ " return [context.invoked_function_arn, context.function_version, event]\n")
+ archive.writestr("index.js", "exports.handler = async (event, context) => [context.invokedFunctionArn, context.functionVersion, event];")
+ version = {"config": {**config, "FunctionArn": arn + ":1", "Version": "1"},
+ "code_zip": buf.getvalue()}
+ function = {"config": config, "code_zip": buf.getvalue(), "versions": {"1": version},
+ "aliases": {"worker": {"FunctionVersion": "1"}, "other": {"FunctionVersion": "1"}}}
+ original = deepcopy(function)
+ monkeypatch.setitem(svc._functions, name, function)
+ monkeypatch.setattr(svc, "_emit_lambda_metrics", lambda *args, **kwargs: None)
+ monkeypatch.setattr(svc, "_execute_function_with_config_scope", svc._execute_function_warm)
+ captured = []
+ monkeypatch.setattr(svc, "invoke_async_with_retry", lambda f, e: captured.append(svc._execute_function_warm(f, e)))
+ try:
+ # Alternate aliases sharing one published version, including warm reuse.
+ for qualifier in ["worker", "other", "1", "worker", None, "$LATEST"]:
+ headers = {"x-amz-invocation-type": "Event"} if asynchronous else {}
+ status, response_headers, body = asyncio.run(svc._invoke(name, {"value": 1}, headers, qualifier))
+ expected_version = "1" if qualifier in ("worker", "other", "1") else "$LATEST"
+ assert response_headers["X-Amz-Executed-Version"] == expected_version
+ assert status == (202 if asynchronous else 200)
+ result = captured[-1]["body"] if asynchronous else json.loads(body)
+ assert result == [arn + (":" + qualifier if qualifier else ""), expected_version, {"value": 1}]
+ assert function == original
+ finally:
+ invalidate_worker(name)