Skip to content

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

fix: inject standard Lambda env vars in warm-worker execution path (#482)

Michael Smithe3afc2a3af72
diff --git a/ministack/core/lambda_runtime.py b/ministack/core/lambda_runtime.py
index 7b0b1fd9..cedb3f3d 100644
--- a/ministack/core/lambda_runtime.py
+++ b/ministack/core/lambda_runtime.py
@@ -422,16 +422,36 @@ class Worker:
module_name = module_name.replace("/", ".")
env_vars = self.config.get("Environment", {}).get("Variables", {})
spawn_env = {**os.environ, **env_vars}
- # Restore the internal endpoint URL so Lambda SDK calls reach
- # this MiniStack instance, not a host-mapped port that may be
- # unreachable from inside the container.
- for key in ("AWS_ENDPOINT_URL", "LOCALSTACK_HOSTNAME"):
- if key in os.environ:
- spawn_env[key] = os.environ[key]
+ # Inject standard Lambda runtime env vars to match the Docker and
+ # provided-runtime execution paths in lambda_svc.py. Real AWS
+ # Lambda always injects these; the warm-worker path was missing them.
+ # Per AWS docs:
+ # https://docs.aws.amazon.com/lambda/latest/dg/configuration-envvars.html
+ from ministack.core.responses import get_region, new_uuid
+ spawn_env.setdefault("AWS_REGION", get_region())
+ spawn_env.setdefault("AWS_DEFAULT_REGION", get_region())
+ spawn_env.setdefault("AWS_ACCESS_KEY_ID", os.environ.get("AWS_ACCESS_KEY_ID", "test"))
+ spawn_env.setdefault("AWS_SECRET_ACCESS_KEY", os.environ.get("AWS_SECRET_ACCESS_KEY", "test"))
+ spawn_env.setdefault("AWS_SESSION_TOKEN", os.environ.get("AWS_SESSION_TOKEN", ""))
+ # AWS_ENDPOINT_URL precedence matches real AWS: function
+ # Environment.Variables wins, then host env, then the internal
+ # default that points at this MiniStack instance. Real AWS Lambda
+ # does not inject AWS_ENDPOINT_URL — it is an SDK/testing convention
+ # — so function-level values must be respected. spawn_env was built
+ # as {**os.environ, **env_vars}, so any function-level value is
+ # already present; setdefault only fills in the default when neither
+ # the function nor the host set one.
+ port = os.environ.get("GATEWAY_PORT", os.environ.get("EDGE_PORT", "4566"))
+ spawn_env.setdefault("AWS_ENDPOINT_URL", f"http://127.0.0.1:{port}")
+ if "LOCALSTACK_HOSTNAME" in os.environ:
+ spawn_env["LOCALSTACK_HOSTNAME"] = os.environ["LOCALSTACK_HOSTNAME"]
spawn_env.setdefault("LAMBDA_TASK_ROOT", code_dir)
spawn_env.setdefault("AWS_LAMBDA_FUNCTION_NAME", self.config.get("FunctionName", ""))
spawn_env.setdefault("AWS_LAMBDA_FUNCTION_MEMORY_SIZE", str(self.config.get("MemorySize", 128)))
+ spawn_env.setdefault("AWS_LAMBDA_FUNCTION_VERSION", self.config.get("Version", "$LATEST"))
+ spawn_env.setdefault("AWS_LAMBDA_LOG_STREAM_NAME", new_uuid())
spawn_env.setdefault("_LAMBDA_FUNCTION_ARN", self.config.get("FunctionArn", ""))
+ spawn_env.setdefault("_LAMBDA_TIMEOUT", str(self.config.get("Timeout", 30)))
# Set layer paths so worker runtimes can find packages from extracted layers.
# _LAMBDA_LAYERS_DIRS is consumed by the Python worker; Node.js layer resolution
diff --git a/tests/test_lambda.py b/tests/test_lambda.py
index 4314d136..fd6288a6 100644
--- a/tests/test_lambda.py
+++ b/tests/test_lambda.py
@@ -772,45 +772,95 @@ def test_lambda_python_env_vars_at_spawn(lam):
payload = json.loads(resp["Payload"].read())
assert payload["myVar"] == "from-spawn-py"
-def test_lambda_endpoint_url_not_overridden_by_function_env(lam):
- """AWS_ENDPOINT_URL from function env vars must not override the
- process-level value. When MiniStack runs in Docker, the host-mapped
- port (e.g. 4568) is unreachable from inside the container — the
- Lambda binary must always use MiniStack's internal endpoint.
-
- This test verifies that the MiniStack server's AWS_ENDPOINT_URL takes
- precedence over function-level env vars. It requires the server to
- have AWS_ENDPOINT_URL set (as it does when running via docker-compose).
+def test_lambda_standard_runtime_env_vars_injected(lam):
+ """Warm-worker Lambdas must inject the same env vars as the Docker
+ execution path (lambda_svc.py:_execute_function_docker), which in turn
+ matches the standard AWS Lambda runtime environment per AWS docs:
+ https://docs.aws.amazon.com/lambda/latest/dg/configuration-envvars.html
+
+ This is the regression test for the warm-worker env var gap. The vars
+ asserted below are the full set the Docker path injects — any var the
+ Docker path sets but the warm-worker doesn't is a divergence bug.
"""
- # Verify the MiniStack server has AWS_ENDPOINT_URL set by checking
- # a baseline Lambda. If the server doesn't have it, the override
- # logic has nothing to restore and this test is not meaningful.
- probe_code = (
+ code = (
"import os\n"
"def handler(event, context):\n"
- " return {'endpoint': os.environ.get('AWS_ENDPOINT_URL', '')}\n"
- )
- probe_name = f"lam-endpoint-probe-{_uuid_mod.uuid4().hex[:8]}"
+ " keys = [\n"
+ " 'AWS_REGION', 'AWS_DEFAULT_REGION',\n"
+ " 'AWS_ACCESS_KEY_ID', 'AWS_SECRET_ACCESS_KEY', 'AWS_SESSION_TOKEN',\n"
+ " 'AWS_LAMBDA_FUNCTION_NAME', 'AWS_LAMBDA_FUNCTION_MEMORY_SIZE',\n"
+ " 'AWS_LAMBDA_FUNCTION_VERSION', 'AWS_LAMBDA_LOG_STREAM_NAME',\n"
+ " 'AWS_ENDPOINT_URL',\n"
+ " ]\n"
+ " return {k: os.environ.get(k, '<UNSET>') for k in keys}\n"
+ )
+ name = f"lam-runtime-env-{_uuid_mod.uuid4().hex[:8]}"
lam.create_function(
- FunctionName=probe_name,
+ FunctionName=name,
Runtime="python3.11",
Role=_LAMBDA_ROLE,
Handler="index.handler",
- Code={"ZipFile": _make_zip(probe_code)},
+ Code={"ZipFile": _make_zip(code)},
)
- resp = lam.invoke(FunctionName=probe_name, Payload=b"{}")
- server_endpoint = json.loads(resp["Payload"].read()).get("endpoint", "")
- if not server_endpoint:
- pytest.skip("MiniStack server does not have AWS_ENDPOINT_URL set "
- "(run with docker-compose to test endpoint override)")
+ resp = lam.invoke(FunctionName=name, Payload=b"{}")
+ payload = json.loads(resp["Payload"].read())
- # Now test with a function that sets a conflicting AWS_ENDPOINT_URL.
+ # Vars that must be non-empty (AWS spec requires a value).
+ must_be_nonempty = [
+ "AWS_REGION",
+ "AWS_DEFAULT_REGION",
+ "AWS_ACCESS_KEY_ID",
+ "AWS_SECRET_ACCESS_KEY",
+ "AWS_LAMBDA_FUNCTION_NAME",
+ "AWS_LAMBDA_FUNCTION_MEMORY_SIZE",
+ "AWS_LAMBDA_FUNCTION_VERSION",
+ "AWS_LAMBDA_LOG_STREAM_NAME",
+ "AWS_ENDPOINT_URL",
+ ]
+ for key in must_be_nonempty:
+ val = payload.get(key, "<UNSET>")
+ assert val and val != "<UNSET>", (
+ f"{key} must be set and non-empty (got {val!r}). "
+ f"The Docker execution path sets this; warm-worker must too."
+ )
+
+ # AWS_SESSION_TOKEN must be PRESENT (set in the env) but may be empty
+ # when no session creds are configured. Real AWS sets it to the role
+ # session token; Ministack mirrors what the host process has, defaulting
+ # to "". The key matters because boto3's credential chain checks for
+ # its presence.
+ assert payload.get("AWS_SESSION_TOKEN", "<UNSET>") != "<UNSET>", (
+ "AWS_SESSION_TOKEN must be present in the env (may be empty string). "
+ "boto3's credential chain looks for this key explicitly."
+ )
+
+ # Function-identity vars must match the configured function.
+ assert payload["AWS_LAMBDA_FUNCTION_NAME"] == name, (
+ f"AWS_LAMBDA_FUNCTION_NAME must equal the function name "
+ f"(got {payload['AWS_LAMBDA_FUNCTION_NAME']!r}, expected {name!r})"
+ )
+ # MEMORY_SIZE defaults to 128 in CreateFunction when unspecified.
+ assert payload["AWS_LAMBDA_FUNCTION_MEMORY_SIZE"] == "128"
+ # VERSION defaults to $LATEST for unpublished functions.
+ assert payload["AWS_LAMBDA_FUNCTION_VERSION"] == "$LATEST"
+
+def test_lambda_function_env_overrides_endpoint_url(lam):
+ """Function ``Environment.Variables.AWS_ENDPOINT_URL`` wins over the
+ host process value, matching real AWS Lambda behavior.
+
+ Real AWS does not inject ``AWS_ENDPOINT_URL`` — it is an SDK/testing
+ convention — so a function-level value is the user's authoritative
+ configuration and must not be silently overridden by MiniStack.
+ Precedence is: function Environment.Variables → host AWS_ENDPOINT_URL
+ → MiniStack's internal default.
+ """
code = (
"import os\n"
"def handler(event, context):\n"
" return {'endpoint': os.environ.get('AWS_ENDPOINT_URL', 'unset')}\n"
)
fname = f"lam-endpoint-override-{_uuid_mod.uuid4().hex[:8]}"
+ function_endpoint = "http://function-scoped-endpoint:9999"
lam.create_function(
FunctionName=fname,
Runtime="python3.11",
@@ -818,16 +868,14 @@ def test_lambda_endpoint_url_not_overridden_by_function_env(lam):
Handler="index.handler",
Code={"ZipFile": _make_zip(code)},
Environment={"Variables": {
- "AWS_ENDPOINT_URL": "http://should-be-overridden:9999",
+ "AWS_ENDPOINT_URL": function_endpoint,
}},
)
resp = lam.invoke(FunctionName=fname, Payload=b"{}")
payload = json.loads(resp["Payload"].read())
- # The Lambda must see the server's endpoint, not the function env var.
- assert payload["endpoint"] != "http://should-be-overridden:9999", (
- "Function-level AWS_ENDPOINT_URL must not override internal endpoint"
+ assert payload["endpoint"] == function_endpoint, (
+ "Function-level AWS_ENDPOINT_URL must win over host/internal default"
)
- assert payload["endpoint"] == server_endpoint
def test_lambda_dynamodb_stream_esm(lam, ddb):