Skip to content

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

feat(lambda): serve the Function URL data plane (#1260)

Liam Mizrahi575f496e72f4
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 26fcf137..dc32e151 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -5,6 +5,11 @@ All notable changes to MiniStack will be documented here.
Format follows [Keep a Changelog](https://keepachangelog.com/en/1.0.0/).
Versioning follows [Semantic Versioning](https://semver.org/).
+## [Unreleased]
+
+### Added
+- **Lambda — Function URL data plane** — `CreateFunctionUrlConfig` returned a `{urlId}.lambda-url.{region}.on.aws` URL that nothing served: a request addressed to it matched no route, fell through to S3 virtual-host addressing, and came back as `NoSuchBucket`. Function URLs are now invocable. A request reaching the gateway on a `{urlId}.lambda-url.{region}.*` host — or on the path-based `/_aws/lambda-url/{urlId}/...` form, for clients that can't set `Host` and browsers that won't resolve `*.localhost` — resolves the URL id to its function and invokes it with a payload-format-2.0 event carrying `$default` for `routeKey` and `stage`, `rawPath`/`rawQueryString` percent-encoded as AWS sends them, and `body`/`queryStringParameters` omitted rather than null. `AuthType` is enforced (`AWS_IAM` returns `403 Forbidden` to an unsigned request, header-signed and presigned both pass; `NONE` is open), the `Cors` config drives preflight and response headers with a non-allowed origin getting none, and `InvokeMode: RESPONSE_STREAM` responses are unwrapped from the `HttpResponseStream` framing so the prelude supplies the status and headers instead of leaking into the body. Cookies returned via the format-2.0 `cookies` array become `Set-Cookie` headers. Contributed by @liammizrahi.
+
## [1.4.10] — 2026-08-03
### Added
diff --git a/ministack/app.py b/ministack/app.py
index f254aee8..03ab8f43 100644
--- a/ministack/app.py
+++ b/ministack/app.py
@@ -39,6 +39,11 @@ if _VERSION == "dev":
_EXECUTE_API_RE = re.compile(
r"^([a-f0-9]{8})\.execute-api\." + re.escape(_MINISTACK_HOST) + r"(?::\d+)?$"
)
+# Lambda Function URL: {urlId}.lambda-url.{region}.<anything>[:port]. The stored
+# FunctionUrl carries AWS's own `.on.aws` suffix, so we match any suffix rather
+# than only _MINISTACK_HOST — pointing a proxy or an /etc/hosts entry at the
+# AWS-shaped hostname is the whole point of addressing a function this way.
+_LAMBDA_URL_RE = re.compile(r"^([0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12})\.lambda-url\.[a-z0-9-]+\.")
# AppSync Events realtime WebSocket: {apiId}.appsync-realtime-api.<anything>[:port].
_APPSYNC_REALTIME_RE = re.compile(r"^([a-z0-9]+)\.appsync-realtime-api\.")
# IoT data plane WebSocket: anything containing ".iot." in the host header.
@@ -136,7 +141,9 @@ def _extract_s3_vhost_bucket(host: str):
if first_tail_segment == "s3" or first_tail_segment.startswith(("s3-", "s3express-")):
return candidate
return None
-_S3_VHOST_EXCLUDE_RE = re.compile(r"\.(execute-api|alb|emr|efs|elasticache|s3-control|appsync-api|appsync-realtime-api|iot)\.")
+_S3_VHOST_EXCLUDE_RE = re.compile(
+ r"\.(execute-api|lambda-url|alb|emr|efs|elasticache|s3-control|appsync-api|appsync-realtime-api|iot)\."
+)
_HEALTH_PATHS = ("/_ministack/health", "/_localstack/health", "/health")
_BODY_METHODS = ("POST", "PUT", "PATCH")
_COGNITO_USERINFO_PATHS = ("/oauth2/userInfo", "/oauth2/userinfo")
@@ -865,12 +872,12 @@ async def _handle_sqs_messages_request(method: str, path: str, headers: dict, qu
async def _handle_pre_body_request(method: str, path: str, headers: dict, query_params: dict, request_id: str):
"""Handle fast-path routes that do not require request body parsing."""
# OPTIONS on an execute-api host / path MUST flow through apigateway.handle_execute
- # so the API's own corsConfiguration is applied (#406). Skip the generic wildcard
- # preflight in that case.
+ # so the API's own corsConfiguration is applied (#406). A Function URL owns its
+ # CORS config the same way. Skip the generic wildcard preflight in both cases.
host = headers.get("host", "")
- is_execute_api = _parse_execute_api_url(host, path) is not None
+ owns_cors = _parse_execute_api_url(host, path) is not None or _parse_lambda_url(host, path) is not None
for response in (
- None if is_execute_api else _handle_options_request(method, request_id),
+ None if owns_cors else _handle_options_request(method, request_id),
_handle_health_request(path, request_id),
_handle_ready_request(path, request_id),
_handle_unknown_localstack_request(path, request_id),
@@ -1311,6 +1318,46 @@ def _is_potential_alb_request(host: str, path: str) -> bool:
)
+def _parse_lambda_url(host: str, path: str) -> tuple[str, str] | None:
+ """Resolve a Function URL request into ``(url_id, function_path)``.
+
+ Two addressing modes, mirroring execute-api:
+ 1. Host-based (AWS-native): ``{urlId}.lambda-url.{region}.<host>[:port]/{path}``
+ 2. Path-based: ``<host>[:port]/_aws/lambda-url/{urlId}/{path}``
+
+ The path-based form exists for the same reason as its execute-api
+ counterpart: browsers on macOS don't resolve ``*.localhost``, and many HTTP
+ clients can't override the ``Host`` header.
+ """
+ m = _LAMBDA_URL_RE.match(host)
+ if m:
+ return m.group(1), path or "/"
+
+ if path.startswith("/_aws/lambda-url/"):
+ rest = path[len("/_aws/lambda-url/") :]
+ url_id, _, remainder = rest.partition("/")
+ if url_id:
+ return url_id, "/" + remainder
+ return None
+
+
+async def _handle_lambda_url_request(
+ host: str, path: str, method: str, headers: dict, body: bytes, query_params: dict
+):
+ """Handle Lambda Function URL data plane requests (Host-based + path-based)."""
+ parsed = _parse_lambda_url(host, path)
+ if parsed is None:
+ return None
+ url_id, function_path = parsed
+ try:
+ return await _get_module("lambda_svc").handle_function_url_request(
+ url_id, method, function_path, headers, body, query_params
+ )
+ except Exception as e:
+ logger.exception("Error in Lambda Function URL dispatch: %s", e)
+ return 500, {"Content-Type": "application/json"}, json.dumps({"message": str(e)}).encode()
+
+
async def _handle_alb_request(host: str, path: str, method: str, headers: dict, body: bytes, query_params: dict):
"""Handle ALB data-plane requests for host-based and /_alb-prefixed addressing."""
if not _is_potential_alb_request(host, path):
@@ -1434,6 +1481,8 @@ async def _handle_special_data_plane_request(
host = headers.get("host", "")
if response := await _handle_execute_api_request(host, path, method, headers, body, query_params):
return _with_data_plane_headers(response, request_id, wildcard_cors=False)
+ if response := await _handle_lambda_url_request(host, path, method, headers, body, query_params):
+ return _with_data_plane_headers(response, request_id, wildcard_cors=False)
if response := await _handle_s3_vhost_request(host, path, method, headers, body, query_params):
return _with_data_plane_headers(response, request_id, include_s3_id=True)
if response := await _handle_alb_request(host, path, method, headers, body, query_params):
diff --git a/ministack/services/lambda_svc.py b/ministack/services/lambda_svc.py
index 1ab41c69..165bd2a3 100644
--- a/ministack/services/lambda_svc.py
+++ b/ministack/services/lambda_svc.py
@@ -46,7 +46,7 @@ import urllib.request
import zipfile
from datetime import datetime, timezone
from typing import Any
-from urllib.parse import unquote
+from urllib.parse import quote, unquote
from ministack.core.arn import ArnParseError, parse_arn
from ministack.core.lambda_runtime import get_or_create_worker, invalidate_worker
@@ -6110,6 +6110,258 @@ def _list_function_url_configs(func_name: str, query_params: dict):
return json_response({"FunctionUrlConfigs": configs})
+# ---------------------------------------------------------------------------
+# Function URL data plane
+# ---------------------------------------------------------------------------
+
+# `awslambda.HttpResponseStream.from()` frames a RESPONSE_STREAM reply as the
+# JSON prelude (status + headers), eight NUL bytes, then the body. Real Function
+# URLs consume that framing at the edge; so do we.
+_STREAM_PRELUDE_SEPARATOR = b"\x00" * 8
+
+# Content types a Function URL delivers to the handler as a UTF-8 string rather
+# than base64. Function URLs use payload format 2.0, same rule as HTTP API v2.
+_FUNCTION_URL_TEXT_TYPES = ("application/json", "application/xml", "application/javascript")
+
+
+def _function_url_id(function_url: str) -> str:
+ """Return the URL id (first host label) of a stored ``FunctionUrl``."""
+ return function_url.split("://", 1)[-1].split(".", 1)[0]
+
+
+def resolve_function_url(url_id: str) -> tuple[str, str, str, str | None, dict] | None:
+ """Resolve a Function URL id to ``(account, region, func_name, qualifier, config)``.
+
+ The scan spans every account/region scope: a data-plane request carries no
+ credentials to scope the lookup by, and the URL id is globally unique.
+ """
+ for (account_id, region, key), cfg in _function_urls.all_items():
+ if _function_url_id(cfg.get("FunctionUrl", "")) == url_id:
+ name, _, qualifier = key.partition(":")
+ return account_id, region, name, (qualifier or None), cfg
+ return None
+
+
+def _function_url_cors_headers(cfg: dict, request_headers: dict) -> dict:
+ """Build CORS response headers from a Function URL's ``Cors`` config.
+
+ Returns an empty dict when the URL has no CORS config — real Function URLs
+ send no CORS headers at all in that case, so a browser blocks the response
+ exactly as it would against AWS.
+ """
+ cors = cfg.get("Cors") or {}
+ if not cors:
+ return {}
+ origin = request_headers.get("origin", "")
+ allowed = cors.get("AllowOrigins") or []
+ if "*" in allowed:
+ allow_origin = "*"
+ elif origin and origin in allowed:
+ allow_origin = origin
+ else:
+ return {}
+ cors_headers = {"Access-Control-Allow-Origin": allow_origin}
+ if allow_origin != "*":
+ cors_headers["Vary"] = "Origin"
+ if cors.get("AllowMethods"):
+ cors_headers["Access-Control-Allow-Methods"] = ",".join(cors["AllowMethods"])
+ if cors.get("AllowHeaders"):
+ cors_headers["Access-Control-Allow-Headers"] = ",".join(cors["AllowHeaders"])
+ if cors.get("ExposeHeaders"):
+ cors_headers["Access-Control-Expose-Headers"] = ",".join(cors["ExposeHeaders"])
+ if cors.get("AllowCredentials"):
+ cors_headers["Access-Control-Allow-Credentials"] = "true"
+ if cors.get("MaxAge") is not None:
+ cors_headers["Access-Control-Max-Age"] = str(cors["MaxAge"])
+ return cors_headers
+
+
+def _function_url_is_signed(headers: dict, query_params: dict) -> bool:
+ """Whether a request carries SigV4 material, header-signed or presigned."""
+ auth = headers.get("authorization", "")
+ if auth.startswith("AWS4-HMAC-SHA256"):
+ return True
+ return "X-Amz-Signature" in query_params or "x-amz-signature" in query_params
+
+
+def _split_stream_prelude(payload: bytes) -> tuple[dict | None, bytes]:
+ """Split a RESPONSE_STREAM payload into its prelude and body.
+
+ A handler that writes to the response stream without calling
+ ``HttpResponseStream.from()`` sends no prelude; the whole payload is then
+ the body and the caller falls back to ``200``.
+ """
+ index = payload.find(_STREAM_PRELUDE_SEPARATOR)
+ if index <= 0:
+ return None, payload
+ try:
+ prelude = json.loads(payload[:index])
+ except (json.JSONDecodeError, UnicodeDecodeError):
+ return None, payload
+ if not isinstance(prelude, dict):
+ return None, payload
+ return prelude, payload[index + len(_STREAM_PRELUDE_SEPARATOR) :]
+
+
+def _build_function_url_event(
+ url_id: str,
+ account_id: str,
+ region: str,
+ method: str,
+ path: str,
+ headers: dict,
+ body: bytes,
+ query_params: dict,
+) -> dict:
+ """Build the payload-format-2.0 event a Function URL delivers.
+
+ Differs from the HTTP API v2 event in that ``routeKey`` and ``stage`` are
+ always ``$default`` and there are no ``pathParameters``.
+ """
+ raw_qs = "&".join(
+ f"{quote(k, safe='')}={quote(val, safe='')}" for k, vals in query_params.items() for val in vals
+ )
+ if body:
+ content_type = (headers.get("content-type") or "").split(";", 1)[0].strip().lower()
+ if content_type.startswith("text/") or content_type in _FUNCTION_URL_TEXT_TYPES:
+ req_body, is_base64 = body.decode("utf-8", errors="replace"), False
+ else:
+ req_body, is_base64 = base64.b64encode(body).decode("ascii"), True
+ else:
+ req_body, is_base64 = None, False
+
+ domain_name = f"{url_id}.lambda-url.{region}.on.aws"
+ event = {
+ "version": "2.0",
+ "routeKey": "$default",
+ "rawPath": path,
+ "rawQueryString": raw_qs,
+ "headers": dict(headers),
+ "requestContext": {
+ "accountId": account_id,
+ "apiId": url_id,
+ "domainName": domain_name,
+ "domainPrefix": url_id,
+ "http": {
+ "method": method,
+ "path": path,
+ "protocol": "HTTP/1.1",
+ "sourceIp": "127.0.0.1",
+ "userAgent": headers.get("user-agent", ""),
+ },
+ "requestId": new_uuid(),
+ "routeKey": "$default",
+ "stage": "$default",
+ "time": time.strftime("%d/%b/%Y:%H:%M:%S +0000"),
+ "timeEpoch": int(time.time() * 1000),
+ },
+ "isBase64Encoded": is_base64,
+ }
+ # Real AWS omits these keys entirely rather than sending null; strict event
+ # validators reject a present-but-null value (same reason as apigateway.py).
+ if req_body is not None:
+ event["body"] = req_body
+ if query_params:
+ event["queryStringParameters"] = {k: ",".join(v) for k, v in query_params.items()}
+ return event
+
+
+async def handle_function_url_request(
+ url_id: str, method: str, path: str, headers: dict, body: bytes, query_params: dict
+) -> tuple:
+ """Serve a Lambda Function URL data-plane request."""
+ resolved = resolve_function_url(url_id)
+ if resolved is None:
+ return error_response_json("ResourceNotFoundException", "Not Found", 404)
+ account_id, region, func_name, qualifier, cfg = resolved
+
+ cors_headers = _function_url_cors_headers(cfg, headers)
+ if method == "OPTIONS" and cfg.get("Cors"):
+ return 200, cors_headers, b""
+
+ if cfg.get("AuthType") == "AWS_IAM" and not _function_url_is_signed(headers, query_params):
+ return 403, {"Content-Type": "application/json", **cors_headers}, json.dumps({"Message": "Forbidden"}).encode()
+
+ function_ref = f"{func_name}:{qualifier}" if qualifier else func_name
+ func_data, func_config, _ = _get_func_record_for_ref_in_scope(function_ref, account_id=account_id, region=region)
+ if func_data is None or func_config is None:
+ return error_response_json("ResourceNotFoundException", f"Function not found: {func_name}", 404)
+
+ event = _build_function_url_event(url_id, account_id, region, method, path, headers, body, query_params)
+ exec_record = _execution_record_for_config(func_data, func_config)
+ result = await asyncio.to_thread(_execute_function_with_config_scope, exec_record, event)
+
+ if cfg.get("InvokeMode") == "RESPONSE_STREAM" and not result.get("error") and not result.get("throttle"):
+ return _function_url_stream_response(result, cors_headers)
+
+ proxy_response, _ = lambda_execute_result_to_api_proxy_response(result)
+ return _function_url_proxy_response(proxy_response, cors_headers)
+
+
+def _apply_headers_case_insensitively(base: dict, overrides: dict) -> None:
+ """Merge ``overrides`` into ``base``, replacing any case-insensitive match.
+
+ HTTP field names are case-insensitive (RFC 9110 §5.1), so a lowercase
+ ``content-type`` returned by a handler must replace a seeded
+ ``Content-Type`` rather than ship alongside it — the same handling #750
+ applied to the API Gateway v1 multiValueHeaders merge.
+ """
+ for key, value in overrides.items():
+ lower_key = key.lower()
+ for existing in [header for header in base if header.lower() == lower_key]:
+ del base[existing]
+ base[key] = str(value)
+
+
+def _function_url_stream_response(result: dict, cors_headers: dict) -> tuple:
+ """Shape a RESPONSE_STREAM result by consuming its prelude framing."""
+ payload = result.get("body")
+ if payload is None:
+ payload = b""
+ elif isinstance(payload, str):
+ payload = payload.encode("utf-8")
+ elif not isinstance(payload, bytes):
+ payload = json.dumps(payload, ensure_ascii=False).encode("utf-8")
+
+ prelude, stream_body = _split_stream_prelude(payload)
+ status = int(prelude.get("statusCode", 200)) if prelude else 200
+ # Real Function URLs default a streamed response to application/octet-stream
+ # unless the prelude names a content type.
+ resp_headers = {"Content-Type": "application/octet-stream"}
+ if prelude:
+ _apply_headers_case_insensitively(resp_headers, prelude.get("headers") or {})
+ _apply_headers_case_insensitively(resp_headers, cors_headers)
+ return status, resp_headers, stream_body
+
+
+def _function_url_proxy_response(proxy_response: dict | None, cors_headers: dict) -> tuple:
+ """Shape a BUFFERED result from its AWS_PROXY-style return value."""
+ if proxy_response is None:
+ return 502, {"Content-Type": "application/json", **cors_headers}, b'{"message":"Internal Server Error"}'
+
+ status = int(proxy_response.get("statusCode", 200))
+ resp_headers = {"Content-Type": "application/json"}
+ _apply_headers_case_insensitively(resp_headers, proxy_response.get("headers") or {})
+ _apply_headers_case_insensitively(resp_headers, cors_headers)
+ # Payload format 2.0 delivers cookies via a top-level `cookies` array, which
+ # AWS emits as one Set-Cookie header per entry; _send_response expands a list.
+ cookies = proxy_response.get("cookies")
+ if cookies:
+ for existing in [header for header in resp_headers if header.lower() == "set-cookie"]:
+ del resp_headers[existing]
+ resp_headers["Set-Cookie"] = list(cookies)
+
+ payload = proxy_response.get("body", "")
+ if proxy_response.get("isBase64Encoded"):
+ try:
+ body_bytes = base64.b64decode(payload)
+ except (ValueError, TypeError):
+ body_bytes = b""
+ else:
+ body_bytes = payload.encode("utf-8") if isinstance(payload, str) else bytes(payload or b"")
+ return status, resp_headers, body_bytes
+
+
def reset():
import shutil
diff --git a/tests/test_lambda.py b/tests/test_lambda.py
index 5267de07..0fd5cda9 100644
--- a/tests/test_lambda.py
+++ b/tests/test_lambda.py
@@ -4,6 +4,8 @@ import io
import json
import os
import time
+import urllib.error as _urlerr
+import urllib.request as _urlreq
import uuid as _uuid_mod
import zipfile
from unittest.mock import patch
@@ -8482,3 +8484,275 @@ def test_invoke_rie_rewrites_custom_resource_response_url():
"http://host.docker.internal:4566/_ministack/cfn-response/tok"
# The caller's event dict must not be mutated in place.
assert event["ResponseURL"] == "http://localhost:4566/_ministack/cfn-response/tok"
+
+
+# ---------------------------------------------------------------------------
+# Function URL data plane
+# ---------------------------------------------------------------------------
+
+_FUNCTION_URL_ECHO_JS = """
+exports.handler = async (event) => ({
+ statusCode: 200,
+ headers: { "content-type": "application/json" },
+ body: JSON.stringify({
+ version: event.version,
+ routeKey: event.routeKey,
+ rawPath: event.rawPath,
+ rawQueryString: event.rawQueryString,
+ method: event.requestContext.http.method,
+ stage: event.requestContext.stage,
+ domainName: event.requestContext.domainName,
+ body: event.body ?? null,
+ hasQueryStringParameters: "queryStringParameters" in event,
+ }),
+});
+"""
+
+_FUNCTION_URL_STREAM_JS = """
+exports.handler = awslambda.streamifyResponse(async (event, responseStream) => {
+ const stream = awslambda.HttpResponseStream.from(responseStream, {
+ statusCode: 201,
+ headers: { "content-type": "text/event-stream", "x-from-prelude": "yes" },
+ });
+ stream.write("data: one\\n\\n");
+ stream.write("data: two\\n\\n");
+ stream.end();
+});
+"""
+
+
+def _function_url_id(function_url: str) -> str:
+ """Return the URL id (first host label) of a ``FunctionUrl``."""
+ return function_url.split("://", 1)[-1].split(".", 1)[0]
+
+
+def _function_url_request(url_id: str, path="/", method="GET", data=None, headers=None):
+ """Call a Function URL through the AWS-shaped host, returning the raw response."""
+ host = f"{url_id}.lambda-url.us-east-1.localhost:{_EXECUTE_PORT}"
+ req = _urlreq.Request(f"{_endpoint}{path}", method=method, data=data)
+ req.add_header("Host", host)
+ for name, value in (headers or {}).items():
+ req.add_header(name, value)
+ return req
+
+
+def test_lambda_function_url_data_plane_invokes_with_payload_format_2(lam):
+ with _nodejs_lambda(lam, _FUNCTION_URL_ECHO_JS, prefix="fu-echo") as fname:
+ created = lam.create_function_url_config(FunctionName=fname, AuthType="NONE")
+ url_id = _function_url_id(created["FunctionUrl"])
+ try:
+ req = _function_url_request(url_id, path="/orders/42?q=a%20b")
+ with _urlreq.urlopen(req) as resp:
+ assert resp.status == 200
+ payload = json.loads(resp.read())
+
+ assert payload["version"] == "2.0"
+ # Function URLs always report the $default route and stage.
+ assert payload["routeKey"] == "$default"
+ assert payload["stage"] == "$default"
+ assert payload["rawPath"] == "/orders/42"
+ assert payload["rawQueryString"] == "q=a%20b"
+ assert payload["method"] == "GET"
+ assert payload["domainName"].startswith(f"{url_id}.lambda-url.")
+ # A bodyless request omits `body` rather than sending null.
+ assert payload["body"] is None
+ finally:
+ lam.delete_function_url_config(FunctionName=fname)
+
+
+def test_lambda_function_url_data_plane_omits_query_string_parameters_when_absent(lam):
+ with _nodejs_lambda(lam, _FUNCTION_URL_ECHO_JS, prefix="fu-noqs") as fname:
+ created = lam.create_function_url_config(FunctionName=fname, AuthType="NONE")
+ url_id = _function_url_id(created["FunctionUrl"])
+ try:
+ with _urlreq.urlopen(_function_url_request(url_id)) as resp:
+ payload = json.loads(resp.read())
+ assert payload["hasQueryStringParameters"] is False
+ finally:
+ lam.delete_function_url_config(FunctionName=fname)
+
+
+def test_lambda_function_url_data_plane_forwards_request_body(lam):
+ with _nodejs_lambda(lam, _FUNCTION_URL_ECHO_JS, prefix="fu-post") as fname:
+ created = lam.create_function_url_config(FunctionName=fname, AuthType="NONE")
+ url_id = _function_url_id(created["FunctionUrl"])
+ try:
+ req = _function_url_request(
+ url_id,
+ path="/submit",
+ method="POST",
+ data=b'{"hello":"world"}',
+ headers={"Content-Type": "application/json"},
+ )
+ with _urlreq.urlopen(req) as resp:
+ payload = json.loads(resp.read())
+ assert payload["method"] == "POST"
+ assert payload["body"] == '{"hello":"world"}'
+ finally:
+ lam.delete_function_url_config(FunctionName=fname)
+
+
+def test_lambda_function_url_data_plane_path_based_addressing(lam):
+ """`/_aws/lambda-url/{urlId}/...` works where `*.localhost` won't resolve."""
+ with _nodejs_lambda(lam, _FUNCTION_URL_ECHO_JS, prefix="fu-path") as fname:
+ created = lam.create_function_url_config(FunctionName=fname, AuthType="NONE")
+ url_id = _function_url_id(created["FunctionUrl"])
+ try:
+ req = _urlreq.Request(f"{_endpoint}/_aws/lambda-url/{url_id}/orders/42", method="GET")
+ with _urlreq.urlopen(req) as resp:
+ payload = json.loads(resp.read())
+ assert payload["rawPath"] == "/orders/42"
+ finally:
+ lam.delete_function_url_config(FunctionName=fname)
+
+
+def test_lambda_function_url_data_plane_unknown_url_id_returns_404(lam):
+ unknown = "00000000-0000-0000-0000-000000000000"
+ with pytest.raises(_urlerr.HTTPError) as exc:
+ _urlreq.urlopen(_function_url_request(unknown))
+ assert exc.value.code == 404
+
+
+def test_lambda_function_url_data_plane_aws_iam_rejects_unsigned(lam):
+ with _nodejs_lambda(lam, _FUNCTION_URL_ECHO_JS, prefix="fu-iam") as fname:
+ created = lam.create_function_url_config(FunctionName=fname, AuthType="AWS_IAM")
+ url_id = _function_url_id(created["FunctionUrl"])
+ try:
+ with pytest.raises(_urlerr.HTTPError) as exc:
+ _urlreq.urlopen(_function_url_request(url_id))
+ assert exc.value.code == 403
+
+ signed = _function_url_request(
+ url_id, headers={"Authorization": "AWS4-HMAC-SHA256 Credential=test/20260101/us-east-1/lambda/aws4_request"}
+ )
+ with _urlreq.urlopen(signed) as resp:
+ assert resp.status == 200
+ finally:
+ lam.delete_function_url_config(FunctionName=fname)
+
+
+def test_lambda_function_url_data_plane_applies_cors_config(lam):
+ cors = {
+ "AllowOrigins": ["https://app.example.com"],
+ "AllowMethods": ["GET", "POST"],
+ "AllowHeaders": ["content-type"],
+ "MaxAge": 600,
+ }
+ with _nodejs_lambda(lam, _FUNCTION_URL_ECHO_JS, prefix="fu-cors") as fname:
+ created = lam.create_function_url_config(FunctionName=fname, AuthType="NONE", Cors=cors)
+ url_id = _function_url_id(created["FunctionUrl"])
+ try:
+ preflight = _function_url_request(
+ url_id,
+ method="OPTIONS",
+ headers={"Origin": "https://app.example.com", "Access-Control-Request-Method": "POST"},
+ )
+ with _urlreq.urlopen(preflight) as resp:
+ assert resp.status == 200
+ assert resp.headers["Access-Control-Allow-Origin"] == "https://app.example.com"
+ assert resp.headers["Access-Control-Allow-Methods"] == "GET,POST"
+ assert resp.headers["Access-Control-Max-Age"] == "600"
+
+ # An origin outside AllowOrigins gets no CORS headers, as on AWS.
+ disallowed = _function_url_request(
+ url_id, method="OPTIONS", headers={"Origin": "https://evil.example.com"}
+ )
+ with _urlreq.urlopen(disallowed) as resp:
+ assert resp.headers.get("Access-Control-Allow-Origin") is None
+ finally:
+ lam.delete_function_url_config(FunctionName=fname)
+
+
+def test_lambda_function_url_response_stream_consumes_prelude_without_streamify(lam):
+ """The prelude framing is consumed whatever produced it.
+
+ Runs on every executor: the handler returns the framed payload directly
+ rather than going through `awslambda.streamifyResponse`, which only exists
+ in the real Lambda runtime.
+ """
+ prelude = '{"statusCode":201,"headers":{"content-type":"text/event-stream","x-from-prelude":"yes"}}'
+ code = (
+ "def handler(event, context):\n"
+ f" return {prelude!r} + '\\x00' * 8 + 'data: one\\n\\ndata: two\\n\\n'\n"
+ )
+ fname = f"fu-framed-{_uuid_mod.uuid4().hex[:8]}"
+ lam.create_function(
+ FunctionName=fname,
+ Runtime="python3.12",
+ Role=_LAMBDA_ROLE,
+ Handler="index.handler",
+ Code={"ZipFile": _make_zip(code)},
+ )
+ try:
+ created = lam.create_function_url_config(
+ FunctionName=fname, AuthType="NONE", InvokeMode="RESPONSE_STREAM"
+ )
+ url_id = _function_url_id(created["FunctionUrl"])
+ try:
+ with _urlreq.urlopen(_function_url_request(url_id)) as resp:
+ assert resp.status == 201
+ assert resp.headers["content-type"] == "text/event-stream"
+ assert resp.headers["x-from-prelude"] == "yes"
+ body = resp.read()
+ assert body == b"data: one\n\ndata: two\n\n"
+ assert b"\x00" not in body
+ assert b"statusCode" not in body
+ finally:
+ lam.delete_function_url_config(FunctionName=fname)
+ finally:
+ lam.delete_function(FunctionName=fname)
+
+
+def test_lambda_function_url_response_stream_without_prelude_defaults_to_200(lam):
+ """A stream carrying no prelude is served whole, with a 200."""
+ code = "def handler(event, context):\n return 'raw stream body'\n"
+ fname = f"fu-noprelude-{_uuid_mod.uuid4().hex[:8]}"
+ lam.create_function(
+ FunctionName=fname,
+ Runtime="python3.12",
+ Role=_LAMBDA_ROLE,
+ Handler="index.handler",
+ Code={"ZipFile": _make_zip(code)},
+ )
+ try:
+ created = lam.create_function_url_config(
+ FunctionName=fname, AuthType="NONE", InvokeMode="RESPONSE_STREAM"
+ )
+ url_id = _function_url_id(created["FunctionUrl"])
+ try:
+ with _urlreq.urlopen(_function_url_request(url_id)) as resp:
+ assert resp.status == 200
+ assert resp.read() == b"raw stream body"
+ finally:
+ lam.delete_function_url_config(FunctionName=fname)
+ finally:
+ lam.delete_function(FunctionName=fname)
+
+
+ os.environ.get("LAMBDA_EXECUTOR", "").lower() != "docker",
+ reason="requires LAMBDA_EXECUTOR=docker and Docker daemon",
+)
+def test_lambda_function_url_response_stream_consumes_prelude(lam):
+ """RESPONSE_STREAM status/headers come from the prelude, and it never reaches the body.
+
+ `awslambda.streamifyResponse` is provided by the Lambda runtime interface
+ client, so this end-to-end variant needs the Docker executor.
+ """
+ with _nodejs_lambda(lam, _FUNCTION_URL_STREAM_JS, prefix="fu-stream", runtime="nodejs22.x") as fname:
+ created = lam.create_function_url_config(
+ FunctionName=fname, AuthType="NONE", InvokeMode="RESPONSE_STREAM"
+ )
+ url_id = _function_url_id(created["FunctionUrl"])
+ try:
+ with _urlreq.urlopen(_function_url_request(url_id)) as resp:
+ assert resp.status == 201
+ assert resp.headers["content-type"] == "text/event-stream"
+ assert resp.headers["x-from-prelude"] == "yes"
+ body = resp.read()
+ assert body == b"data: one\n\ndata: two\n\n"
+ # The eight-NUL separator and the JSON prelude must be consumed.
+ assert b"\x00" not in body
+ assert b"statusCode" not in body
+ finally:
+ lam.delete_function_url_config(FunctionName=fname)