Skip to content

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

fix(lambda): honor cross-account layer grants and retain attached content (#1712)

iot-rockete5a4464f5732
diff --git a/CHANGELOG.md b/CHANGELOG.md
index f5b81ee4..3496703a 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]
+
+### Fixed
+- **Lambda — a layer shared through `AddLayerVersionPermission` attaches** — every layer ARN from another account was refused before the stored policy was read. Attachment, from the API and from a CloudFormation function, and `GetLayerVersionByArn` now evaluate it for account, root, public and organization grants, and an attached function keeps the content after the grant is revoked or the version is deleted. Contributed by @iot-rocket.
+
## [1.5.12] — 2026-09-15
### Added
diff --git a/ministack/core/iam_evaluator.py b/ministack/core/iam_evaluator.py
index c65ced6c..9df6e297 100644
--- a/ministack/core/iam_evaluator.py
+++ b/ministack/core/iam_evaluator.py
@@ -152,6 +152,20 @@ def _account_from_arn(arn: str) -> str | None:
return parts[4] if _ACCOUNT_ID_RE.fullmatch(parts[4]) else None
+def _principal_org_id(account_id: str) -> str | None:
+ """aws:PrincipalOrgID, the Organization the calling account belongs to.
+ In this emulator every account is the master of its own org the moment it
+ calls Organizations and member accounts are not modelled, so the id
+ resolves from that account's own scope, and an account that never called
+ Organizations has none."""
+ try:
+ from ministack.services import organizations as org_svc
+ org = org_svc._orgs.get_scoped(account_id, None, "self")
+ except Exception:
+ return None
+ return org.get("Id") if isinstance(org, dict) else None
+
+
def _resolve_condition_key(key: str, ctx: EvalContext) -> Any:
"""Resolve a global condition context key to its value."""
k = key.lower()
@@ -186,6 +200,8 @@ def _resolve_condition_key(key: str, ctx: EvalContext) -> Any:
return _account_from_arn(ctx.resource_arn) or ctx.principal_account
if k in ctx.service_context:
return ctx.service_context[k]
+ if k == "aws:principalorgid":
+ return _principal_org_id(ctx.principal_account)
return None # key not present
@@ -541,6 +557,35 @@ def evaluate(ctx: EvalContext,
"No matching Allow statement")
+def evaluate_resource_policy(doc: str | dict | None, ctx: EvalContext) -> EvalResult:
+ """Evaluate a Lambda layer-version policy for the account principal in *ctx*.
+
+ Such a document names the principals it applies to, so a statement counts
+ only when its ``AWS`` principal (or ``*``) matches the caller; action,
+ resource, conditions and deny-before-allow are then the ordinary
+ evaluation. ``Service`` principals are ignored, since the trust-policy
+ matcher lets them match any account root. A statement carrying only
+ ``NotPrincipal`` never matches, leaving that unsupported form closed."""
+ if isinstance(doc, str):
+ try:
+ doc = json.loads(doc)
+ except (json.JSONDecodeError, TypeError):
+ doc = None
+ statements = doc.get("Statement", []) if isinstance(doc, dict) else []
+ if isinstance(statements, dict):
+ statements = [statements]
+ applicable = []
+ for stmt in statements if isinstance(statements, list) else []:
+ if not isinstance(stmt, dict):
+ continue
+ principal = stmt.get("Principal", {})
+ if isinstance(principal, dict):
+ principal = {"AWS": principal.get("AWS", [])}
+ if _principal_matches(principal, ctx.principal_arn):
+ applicable.append(stmt)
+ return evaluate(ctx, [parse_policy_document({"Statement": applicable})])
+
+
# ---------------------------------------------------------------------------
# Principal resolution
# ---------------------------------------------------------------------------
@@ -937,25 +982,13 @@ def resolve_caller_identity(access_key_id: str) -> dict | None:
return None
account_id = get_account_id()
- def _principal_org_id():
- # aws:PrincipalOrgID — the caller account's Organization, when it has
- # one. In this emulator's model every account is the master of its own
- # org the moment it calls Organizations, so the id resolves from the
- # caller's own scope.
- try:
- from ministack.services import organizations as org_svc
- org = org_svc._orgs.get("self")
- return org.get("Id") if org else None
- except Exception:
- return None
-
if _is_root_key(access_key_id):
return {
"accessKey": access_key_id,
"accountId": account_id,
"userArn": f"arn:aws:iam::{account_id}:root",
"userId": account_id,
- "principalOrgId": _principal_org_id(),
+ "principalOrgId": _principal_org_id(account_id),
"session": None,
}
session = sts_svc._sessions.get(access_key_id)
@@ -965,7 +998,7 @@ def resolve_caller_identity(access_key_id: str) -> dict | None:
"accountId": account_id,
"userArn": session.get("Arn", ""),
"userId": session.get("UserId", ""),
- "principalOrgId": _principal_org_id(),
+ "principalOrgId": _principal_org_id(account_id),
"session": session,
}
key_record = iam_svc._access_keys.get_scoped(account_id, None, access_key_id)
@@ -977,7 +1010,7 @@ def resolve_caller_identity(access_key_id: str) -> dict | None:
"accountId": account_id,
"userArn": user.get("Arn") or f"arn:aws:iam::{account_id}:user/{user_name}",
"userId": user.get("UserId", ""),
- "principalOrgId": _principal_org_id(),
+ "principalOrgId": _principal_org_id(account_id),
"session": None,
}
return None
diff --git a/ministack/core/lambda_runtime.py b/ministack/core/lambda_runtime.py
index 5c6ac83e..57a36345 100644
--- a/ministack/core/lambda_runtime.py
+++ b/ministack/core/lambda_runtime.py
@@ -1109,7 +1109,7 @@ class Worker:
if not layer_arn:
continue
try:
- layer_data = _resolve_layer_zip(layer_arn)
+ layer_data = _resolve_layer_zip(layer_ref)
if layer_data:
layer_dir = os.path.join(self._tmpdir, f"layer_{len(layers_dirs)}")
os.makedirs(layer_dir)
diff --git a/ministack/services/cloudformation/provisioners.py b/ministack/services/cloudformation/provisioners.py
index ee5b8439..14ca112b 100644
--- a/ministack/services/cloudformation/provisioners.py
+++ b/ministack/services/cloudformation/provisioners.py
@@ -1810,7 +1810,11 @@ def _lambda_create(logical_id, props, stack_name):
memory = int(props.get("MemorySize", 128))
env_vars = props.get("Environment", {}).get("Variables", {})
description = props.get("Description", "")
- layers = props.get("Layers", [])
+ # The Lambda API's own resolution, so a template cannot attach a foreign
+ # layer the API would refuse.
+ layers, err = _lambda_svc._normalize_layer_attachments(props.get("Layers"))
+ if err:
+ raise ValueError(f"AWS::Lambda::Function layer attachment failed: {err[2]!r}")
# Resolve the actual code bytes:
# - inline ZipFile is wrapped to a real zip archive
@@ -1847,7 +1851,7 @@ def _lambda_create(logical_id, props, stack_name):
"CodeSha256": code_sha,
"Version": "$LATEST",
"Environment": {"Variables": env_vars},
- "Layers": [{"Arn": l} if isinstance(l, str) else l for l in layers],
+ "Layers": layers,
"State": "Active",
"LastUpdateStatus": "Successful",
"PackageType": "Image" if is_image else "Zip",
@@ -1879,12 +1883,15 @@ def _lambda_create(logical_id, props, stack_name):
func["config"]["ImageUri"] = image_uri
if props.get("ImageConfig"):
func["config"]["ImageConfigResponse"] = {"ImageConfig": props["ImageConfig"]}
+ replaced = name in _lambda_svc._functions
_lambda_svc._functions[name] = func
# On a stack UPDATE this re-provisions over an existing function; recycle the
# warm worker + docker pool so the new code/config load on the next invoke
# (#897). No-op on first create (no worker spawned yet).
_lambda_svc.invalidate_worker(name)
_lambda_svc._pool_kill_function(get_account_id(), name)
+ if replaced:
+ _lambda_svc._sweep_extract_cache()
return name, {"Arn": arn}
@@ -1978,6 +1985,8 @@ def _lambda_update(physical_id, old_props, new_props, stack_name, logical_id=Non
def _lambda_delete(physical_id, props):
_lambda_svc._functions.pop(physical_id, None)
+ # The function may have held the last reference to a deleted layer version.
+ _lambda_svc._sweep_extract_cache()
def _lambda_url_target(props):
@@ -7044,7 +7053,12 @@ def _lambda_layer_delete(physical_id, props):
layer_name = parts[-2].split("layer:")[-1] if "layer:" in physical_id else ""
layer = _lambda_svc._layers.get(layer_name)
if layer:
- layer["versions"] = [v for v in layer["versions"] if v["LayerVersionArn"] != physical_id]
+ # Tombstoned like DeleteLayerVersion: attached functions keep the
+ # content until the sweep finds no reference left.
+ for v in layer["versions"]:
+ if v["LayerVersionArn"] == physical_id:
+ v["_deleted"] = True
+ _lambda_svc._sweep_extract_cache()
# ---------------------------------------------------------------------------
diff --git a/ministack/services/lambda_svc.py b/ministack/services/lambda_svc.py
index 15655421..907881da 100644
--- a/ministack/services/lambda_svc.py
+++ b/ministack/services/lambda_svc.py
@@ -78,6 +78,7 @@ from ministack.core.responses import (
json_response,
new_uuid,
)
+from ministack.core.router import extract_access_key_id
logger = logging.getLogger("lambda")
@@ -178,6 +179,13 @@ _invoke_depth: contextvars.ContextVar[int] = contextvars.ContextVar(
)
+# The caller's access key, set per request so a layer-policy denial can name
+# the calling identity the way AWS does.
+_request_access_key: contextvars.ContextVar[str] = contextvars.ContextVar(
+ "ministack_lambda_request_access_key", default=""
+)
+
+
def _inbound_invoke_depth(headers: dict) -> int:
"""How many Lambda hops the incoming request has already been through."""
raw = headers.get(_INVOKE_DEPTH_HEADER)
@@ -445,21 +453,34 @@ def _b64_sha_to_hex(b64_sha: str) -> str | None:
def _sweep_extract_cache() -> None:
"""Drop cached extraction trees whose blob no longer backs any function,
- function version, or layer version — the same reference-based policy the
- lambda-blob persistence sweep uses. Called when references disappear
- (function delete, code update, layer-version delete); reset() still
- clears everything wholesale. Runs on stored CodeSha256 values only, so a
- sweep never hashes a byte."""
+ function version, or layer version, and reap deleted layer versions once
+ no function references them. Called when references disappear (function
+ delete, code update, layer detach, layer-version delete, CloudFormation
+ deletes) and after a state restore; reset() still clears everything
+ wholesale. Runs on stored CodeSha256 values only, so a sweep never hashes
+ a byte."""
live_code: set[str] = set()
live_layer: set[str] = set()
+ attached_layers: set[str] = set()
for func in _functions._data.values():
for cfg in [func.get("config") or {}] + [
(v or {}).get("config") or {} for v in (func.get("versions") or {}).values()]:
sha = _b64_sha_to_hex(cfg.get("CodeSha256", ""))
if sha:
live_code.add(sha)
+ for ref in cfg.get("Layers") or []:
+ if isinstance(ref, dict) and ref.get("CodeSize") == 0:
+ continue
+ attached_layers.add(ref if isinstance(ref, str) else ref.get("Arn", ""))
for layer in _layers._data.values():
- for ver in layer.get("versions", []):
+ versions = layer.get("versions") or []
+ # A deleted version survives only while an attached function still
+ # needs its bytes. Removed in place, one atomic list.remove at a time,
+ # so a version a concurrent publish appends is never lost.
+ for ver in [v for v in versions if v.get("_deleted")
+ and v.get("LayerVersionArn") not in attached_layers]:
+ versions.remove(ver)
+ for ver in versions:
sha = _b64_sha_to_hex((ver.get("Content") or {}).get("CodeSha256", ""))
if sha:
live_layer.add(sha)
@@ -649,6 +670,9 @@ def restore_state(data):
region = _region_from_function_record(func)
_functions._data[(get_account_id(), region, name)] = func
_layers.update(data.get("layers", {}))
+ # A snapshot may carry a deleted layer version whose last reference
+ # did not survive the restore.
+ _sweep_extract_cache()
_restore_esms(data.get("esms", {}))
_function_urls.update(data.get("function_urls", {}))
_restore_esm_positions(_kinesis_positions, data.get("kinesis_positions", {}))
@@ -1264,15 +1288,12 @@ def _validate_unzipped_size(zip_data: bytes | None):
return None
-def _layer_unzipped_size(layer_arn: str) -> int:
+def _layer_unzipped_size(attachment: str | dict) -> int:
"""Unzipped size of an attached layer version's content. A layer we don't
hold the bytes for (an external ARN, or content that failed to fetch)
contributes 0 — it can't be measured, so it isn't counted rather than
guessed at (never over-rejecting a function that AWS would accept)."""
- version_config, err = _resolve_layer_version_for_attachment(layer_arn)
- if err or not version_config:
- return 0
- return _unzipped_size(version_config.get("_zip_data"))
+ return _unzipped_size(_resolve_layer_zip(attachment))
def _validate_total_unzipped_size(code_zip: bytes | None, layers):
@@ -1282,9 +1303,8 @@ def _validate_total_unzipped_size(code_zip: bytes | None, layers):
layers and custom runtimes" (unzipped)."""
total = _unzipped_size(code_zip)
for layer in layers or []:
- arn = layer.get("Arn") if isinstance(layer, dict) else layer
- if arn:
- total += _layer_unzipped_size(arn)
+ if layer:
+ total += _layer_unzipped_size(layer)
if total > _UNZIPPED_LIMIT_BYTES:
return error_response_json(
"InvalidParameterValueException",
@@ -1655,6 +1675,38 @@ def _invalid_layer_version_arn(layer_arn: str):
)
+def _layer_access_denied(layer_arn: str):
+ """The denial AWS returns for a foreign layer, naming the calling identity."""
+ from ministack.core.iam_evaluator import resolve_caller_identity
+
+ identity = resolve_caller_identity(_request_access_key.get()) or {}
+ caller = identity.get("userArn") or f"arn:aws:iam::{get_account_id()}:root"
+ return None, error_response_json(
+ "AccessDeniedException",
+ f"User: {caller} is not authorized to perform: lambda:GetLayerVersion on "
+ f"resource: {layer_arn} because no resource-based policy allows the "
+ "lambda:GetLayerVersion action",
+ 403,
+ )
+
+
+def _resolve_cross_account_layer(layer_arn: str, spec, name_and_version, *, allow_opaque=False):
+ """Check stored grants; allow opaque references only for unknown layer names."""
+ if spec.region != get_region():
+ return _layer_access_denied(layer_arn)
+ layer_name, version = name_and_version
+ vc, _ = _find_layer_version(layer_name, version, spec.account_id, spec.region)
+ if vc is not None:
+ if _layer_policy_allows(vc, get_account_id()):
+ return vc, None
+ return _layer_access_denied(layer_arn)
+ if not allow_opaque or _layers.contains_scoped(spec.account_id, spec.region, layer_name):
+ # A known layer's missing/deleted version cannot become an opaque grant.
+ return _layer_access_denied(layer_arn)
+ logger.debug("Attaching unknown external layer %s without content", layer_arn)
+ return {"Version": version, "Content": {"CodeSize": 0}}, None
+
+
def _resolve_layer_version_for_attachment(layer_arn: str):
try:
spec = parse_arn(layer_arn)
@@ -1666,30 +1718,19 @@ def _resolve_layer_version_for_attachment(layer_arn: str):
return None, _invalid_layer_version_arn(layer_arn)
if spec.account_id != get_account_id():
- return None, error_response_json(
- "AccessDeniedException",
- "User is not authorized to access this resource.",
- 403,
- )
+ return _resolve_cross_account_layer(layer_arn, spec, layer_ref, allow_opaque=True)
if spec.region != get_region():
return None, error_response_json(
"InvalidParameterValueException",
- f"Layer version ARN {layer_arn} is in region {spec.region}; "
- f"function region is {get_region()}",
+ "Layers are not in the same region as the function. "
+ f"Layers are expected to be in region {get_region()}.",
400,
)
layer_name, version = layer_ref
- layer = _layers.get_scoped(spec.account_id, spec.region, layer_name)
- if not layer:
- return None, error_response_json(
- "InvalidParameterValueException",
- f"Layer version {layer_arn} does not exist.",
- 400,
- )
- for version_config in layer["versions"]:
- if version_config["Version"] == version:
- return version_config, None
+ version_config, _ = _find_layer_version(layer_name, version, spec.account_id, spec.region)
+ if version_config is not None:
+ return version_config, None
return None, error_response_json(
"InvalidParameterValueException",
f"Layer version {layer_arn} does not exist.",
@@ -1929,6 +1970,7 @@ async def handle_request(method: str, path: str, headers: dict, body: bytes, que
path = unquote(path)
parts = path.rstrip("/").split("/")
+ _request_access_key.set(extract_access_key_id(headers, query_params))
# --- Durable Execution surface (preview, API version 2025-12-01) ---
# Routed first because some paths embed the function ARN as a path segment
@@ -2228,10 +2270,6 @@ def _create_function(data: dict):
version_id=code_data.get("S3ObjectVersion"),
)
- err = _validate_total_unzipped_size(code_zip, data.get("Layers"))
- if err is not None:
- return err
-
if image_uri:
data.setdefault("PackageType", "Image")
@@ -2247,6 +2285,9 @@ def _create_function(data: dict):
if err:
return err
layers_cfg, err = _normalize_layer_attachments(data.get("Layers"))
+ if err:
+ return err
+ err = _validate_total_unzipped_size(code_zip, layers_cfg)
if err:
return err
if data.get("Layers") is not None:
@@ -2761,6 +2802,9 @@ def _update_config(name: str, data: dict):
return err
if "Layers" in data:
layers_cfg, err = _normalize_layer_attachments(data.get("Layers"))
+ if err:
+ return err
+ err = _validate_total_unzipped_size(_functions[name].get("code_zip"), layers_cfg)
if err:
return err
data = dict(data)
@@ -2855,6 +2899,8 @@ def _update_config(name: str, data: dict):
# in-process warm worker recycle solved for Python/Node.
_pool_kill_function(get_account_id(), name)
_schedule_state_transition(name, _LAMBDA_STATE_TRANSITION_DELAY)
+ if "Layers" in data:
+ _sweep_extract_cache()
return json_response(config)
@@ -4266,8 +4312,7 @@ def _spawn_lambda_container_impl(config: dict, code_zip: bytes | None,
raise ValueError("Zip PackageType requires code_zip bytes")
code_dir = _docker_extracted_dir(code_zip, "code")
for layer_ref in layers_list:
- layer_arn_str = layer_ref if isinstance(layer_ref, str) else layer_ref.get("Arn", "")
- layer_zip = _resolve_layer_zip(layer_arn_str)
+ layer_zip = _resolve_layer_zip(layer_ref)
if not layer_zip:
continue
layers_dirs.append(_docker_extracted_dir(layer_zip, "layer"))
@@ -5425,8 +5470,7 @@ def _execute_function_local(func: dict, event: dict) -> dict:
layers_dirs: list[str] = []
for layer_ref in config.get("Layers", []):
- layer_arn_str = layer_ref if isinstance(layer_ref, str) else layer_ref.get("Arn", "")
- layer_zip = _resolve_layer_zip(layer_arn_str)
+ layer_zip = _resolve_layer_zip(layer_ref)
if layer_zip:
layer_dir = os.path.join(tmpdir, f"layer_{len(layers_dirs)}")
os.makedirs(layer_dir)
@@ -5574,33 +5618,26 @@ def _execute_function_local(func: dict, event: dict) -> dict:
}
-def _resolve_layer_zip(layer_arn_str: str) -> bytes | None:
- """Given a layer version ARN return the stored zip bytes, or None."""
+def _resolve_layer_zip(attachment: str | dict) -> bytes | None:
+ """Return attached content, including versions deleted since attachment."""
+ if isinstance(attachment, dict):
+ # An opaque attachment must not acquire content from a layer published
+ # later without a grant. Every stored ZIP has a nonzero compressed size.
+ if attachment.get("CodeSize") == 0:
+ return None
+ attachment = attachment.get("Arn", "")
try:
- spec = parse_arn(layer_arn_str)
+ spec = parse_arn(attachment)
except ArnParseError:
return None
- if spec.service != "lambda":
+ ref = _lambda_layer_version_name_and_number_from_arn_spec(spec)
+ if ref is None or spec.region != get_region():
return None
- if spec.account_id != get_account_id():
- return None
- if spec.region != get_region():
- return None
- parts = spec.resource.split(":", 2)
- if len(parts) != 3 or parts[0] != "layer":
- return None
- layer_name = parts[1]
- try:
- version = int(parts[2])
- except ValueError:
- return None
- layer = _layers.get_scoped(spec.account_id, spec.region, layer_name)
- if not layer:
- return None
- for v in layer["versions"]:
- if v["Version"] == version:
- return v.get("_zip_data")
- return None
+ # Attachment checks permission. Cold starts must still work after revocation.
+ vc, _ = _find_layer_version(
+ *ref, spec.account_id, spec.region, include_deleted=True
+ )
+ return vc.get("_zip_data") if vc else None
def _layer_codesize_for_arn(layer_arn_str: str) -> int:
@@ -6151,7 +6188,7 @@ def _list_layer_versions(layer_name: str, query_params: dict):
all_versions = [
{k: v for k, v in vc.items() if not k.startswith("_")}
for vc in layer["versions"]
- if _match_layer_version(vc, runtime, arch)
+ if not vc.get("_deleted") and _match_layer_version(vc, runtime, arch)
]
all_versions.sort(key=lambda v: v["Version"], reverse=True)
@@ -6178,6 +6215,8 @@ def _get_layer_version(layer_name: str, version: int):
"Layer Version Cannot be less than 1.",
400,
)
+ if layer_name.startswith("arn:"):
+ return _get_layer_version_by_arn(f"{layer_name}:{version}")
layer = _layers.get(layer_name)
if not layer:
return error_response_json(
@@ -6186,7 +6225,7 @@ def _get_layer_version(layer_name: str, version: int):
404,
)
for vc in layer["versions"]:
- if vc["Version"] == version:
+ if vc["Version"] == version and not vc.get("_deleted"):
out = {k: v for k, v in vc.items() if not k.startswith("_")}
return json_response(out)
return error_response_json(
@@ -6213,20 +6252,19 @@ def _get_layer_version_by_arn(arn: str):
"arn:(aws[a-zA-Z-]*)?:lambda:[a-z]{2}((-gov)|(-iso([a-z]?)))?-[a-z]+-\\d{{1}}:\\d{{12}}:layer:[a-zA-Z0-9-_]+:[0-9]+",
400,
)
+ layer_name = parts[1]
+ version = int(parts[2])
if spec.account_id != get_account_id():
- return error_response_json(
- "AccessDeniedException",
- "User is not authorized to access this resource.",
- 403,
- )
+ vc, err = _resolve_cross_account_layer(arn, spec, (layer_name, version))
+ if err:
+ return err
+ return json_response({k: v for k, v in vc.items() if not k.startswith("_")})
if spec.region != get_region():
return error_response_json(
"ResourceNotFoundException",
"The resource you requested does not exist.",
404,
)
- layer_name = parts[1]
- version = int(parts[2])
return _get_layer_version(layer_name, version)
@@ -6240,7 +6278,9 @@ def _delete_layer_version(layer_name: str, version: int):
layer = _layers.get(layer_name)
if not layer:
return 204, {}, b""
- layer["versions"] = [vc for vc in layer["versions"] if vc["Version"] != version]
+ for vc in layer["versions"]:
+ if vc["Version"] == version:
+ vc["_deleted"] = True
# The removed version may have been the last reference to its extracted
# layer tree in the docker executor cache.
_sweep_extract_cache()
@@ -6253,7 +6293,8 @@ def _list_layers(query_params: dict):
result = []
for name, layer in _layers.items():
- matching = [vc for vc in layer["versions"] if _match_layer_version(vc, runtime, arch)]
+ matching = [vc for vc in layer["versions"]
+ if not vc.get("_deleted") and _match_layer_version(vc, runtime, arch)]
if matching:
latest = matching[-1]
result.append(
@@ -6290,6 +6331,8 @@ def _find_layer_version(
version: int,
account_id: str | None = None,
region: str | None = None,
+ *,
+ include_deleted: bool = False,
):
"""Return (layer_version_config, error_response) — one will be None."""
if account_id and region:
@@ -6304,7 +6347,7 @@ def _find_layer_version(
404,
)
for vc in layer["versions"]:
- if vc["Version"] == version:
+ if vc["Version"] == version and (include_deleted or not vc.get("_deleted")):
return vc, None
return None, error_response_json(
"ResourceNotFoundException",
@@ -6356,6 +6399,25 @@ def _layer_statement_principal(principal: str):
return {"AWS": principal}
+def _layer_policy_allows(version_config: dict, account_id: str) -> bool:
+ """Whether the layer version's resource policy grants the calling account
+ lambda:GetLayerVersion. The caller is the account root, the way an
+ AddLayerVersionPermission grant names it; aws:PrincipalOrgID and every
+ other condition key resolve inside the evaluator."""
+ from ministack.core.iam_evaluator import EvalContext, evaluate_resource_policy
+
+ ctx = EvalContext(
+ principal_arn=f"arn:aws:iam::{account_id}:root",
+ principal_type="Root",
+ principal_account=account_id,
+ action="lambda:GetLayerVersion",
+ resource_arn=version_config["LayerVersionArn"],
+ region=get_region(),
+ )
+ result = evaluate_resource_policy(version_config.get("_policy"), ctx)
+ return result.decision == "Allow"
+
+
def _add_layer_version_permission(
layer_name: str,
version: int,
diff --git a/tests/test_cfn.py b/tests/test_cfn.py
index ffa3a9ab..005f2116 100644
--- a/tests/test_cfn.py
+++ b/tests/test_cfn.py
@@ -12927,6 +12927,63 @@ def test_cfn_lambda_layer_packages_importable(cfn, s3, lam):
cfn.delete_stack(StackName=stack_name)
[email protected]("granted", [False, True], ids=["ungranted", "granted"])
+def test_cfn_lambda_function_foreign_layer_follows_the_layer_policy(granted):
+ """A template resolves its layers the way CreateFunction does, so a stack
+ cannot attach, and later load, another account's layer without a grant."""
+ owner_id = str(100000000000 + _uuid_mod.uuid4().int % 400000000000)
+ consumer_id = str(int(owner_id) + 400000000000)
+
+ def client(service, account):
+ return boto3.client(
+ service, endpoint_url=os.environ.get("MINISTACK_ENDPOINT", "http://localhost:4566"),
+ region_name="us-east-1", aws_access_key_id=account, aws_secret_access_key="test",
+ )
+
+ owner, lam, cfn = client("lambda", owner_id), client("lambda", consumer_id), client(
+ "cloudformation", consumer_id)
+ buf = io.BytesIO()
+ with zipfile.ZipFile(buf, "w") as z:
+ z.writestr("python/foreign.py", "VALUE = 1\n")
+ published = owner.publish_layer_version(LayerName="foreign", Content={"ZipFile": buf.getvalue()})
+ arn = published["LayerVersionArn"]
+ if granted:
+ owner.add_layer_version_permission(
+ LayerName="foreign", VersionNumber=published["Version"], StatementId="shared",
+ Action="lambda:GetLayerVersion", Principal=consumer_id,
+ )
+ stack_name = "cfn-foreign-layer"
+ cfn.create_stack(StackName=stack_name, TemplateBody=json.dumps({"Resources": {"Fn": {
+ "Type": "AWS::Lambda::Function",
+ "Properties": {
+ "FunctionName": "foreign-layer-fn", "Runtime": "python3.12",
+ "Handler": "index.handler", "Role": f"arn:aws:iam::{consumer_id}:role/cfn-role",
+ "Code": {"ZipFile": "def handler(event, context):\n return {}\n"},
+ "Layers": [arn],
+ },
+ }}}))
+ try:
+ stack = _wait_stack(cfn, stack_name)
+ if granted:
+ assert stack["StackStatus"] == "CREATE_COMPLETE", stack.get("StackStatusReason")
+ assert lam.get_function_configuration(FunctionName="foreign-layer-fn")["Layers"] == [
+ {"Arn": arn, "CodeSize": published["Content"]["CodeSize"]}]
+ else:
+ assert stack["StackStatus"] == "ROLLBACK_COMPLETE"
+ reasons = [e.get("ResourceStatusReason", "") for e in cfn.describe_stack_events(
+ StackName=stack_name)["StackEvents"] if e["ResourceStatus"] == "CREATE_FAILED"]
+ assert any(
+ f"User: arn:aws:iam::{consumer_id}:root is not authorized to perform: "
+ f"lambda:GetLayerVersion on resource: {arn} because no resource-based "
+ "policy allows the lambda:GetLayerVersion action" in reason
+ for reason in reasons
+ ), reasons
+ finally:
+ cfn.delete_stack(StackName=stack_name)
+ _wait_stack(cfn, stack_name)
+ owner.delete_layer_version(LayerName="foreign", VersionNumber=published["Version"])
+
+
def test_cfn_lambda_layer_version_permission(cfn, s3, lam):
"""A layer plus the permission resource that grants another account access
to it — the shape serverless-python-requirements emits for a layer with
diff --git a/tests/test_lambda.py b/tests/test_lambda.py
index 83e34608..9fc6491a 100644
--- a/tests/test_lambda.py
+++ b/tests/test_lambda.py
@@ -2984,11 +2984,23 @@ def test_lambda_rejects_cross_region_layers_on_create_and_update():
with pytest.raises(ClientError) as update_exc:
east.update_function_configuration(FunctionName=update_name, Layers=[layer_arn])
assert update_exc.value.response["Error"]["Code"] == "InvalidParameterValueException"
+ assert update_exc.value.response["Error"]["Message"] == (
+ "Layers are not in the same region as the function. "
+ "Layers are expected to be in region us-east-1."
+ )
finally:
east.delete_function(FunctionName=update_name)
-def test_lambda_rejects_wrong_account_layers_on_create_and_update(lam):
+def test_lambda_wrong_account_layer_arn_does_not_resolve_to_the_local_layer(lam):
+ """A foreign-account ARN is opaque, never the local layer of the same name.
+
+ The layer store is keyed by account and region, so rewriting the account
+ field of an ARN this account published must not hand back that layer's
+ content. Since an unregistered cross-account layer is accepted as an opaque
+ reference, the visible proof is the code size: the real layer has one, the
+ opaque reference reports zero.
+ """
suffix = _uuid_mod.uuid4().hex[:8]
layer_buf = io.BytesIO()
@@ -3005,16 +3017,17 @@ def test_lambda_rejects_wrong_account_layers_on_create_and_update(lam):
create_name = f"wrong-account-layer-create-{suffix}"
update_name = f"wrong-account-layer-update-{suffix}"
try:
- with pytest.raises(ClientError) as create_exc:
- lam.create_function(
- FunctionName=create_name,
- Runtime="python3.12",
- Role=_LAMBDA_ROLE,
- Handler="index.handler",
- Code={"ZipFile": _make_zip(_LAMBDA_CODE)},
- Layers=[wrong_account_arn],
- )
- assert create_exc.value.response["Error"]["Code"] == "AccessDeniedException"
+ lam.create_function(
+ FunctionName=create_name,
+ Runtime="python3.12",
+ Role=_LAMBDA_ROLE,
+ Handler="index.handler",
+ Code={"ZipFile": _make_zip(_LAMBDA_CODE)},
+ Layers=[wrong_account_arn],
+ )
+ assert lam.get_function_configuration(FunctionName=create_name)["Layers"] == [
+ {"Arn": wrong_account_arn, "CodeSize": 0}
+ ]
lam.create_function(
FunctionName=update_name,
@@ -3023,11 +3036,16 @@ def test_lambda_rejects_wrong_account_layers_on_create_and_update(lam):
Handler="index.handler",
Code={"ZipFile": _make_zip(_LAMBDA_CODE)},
)
- with pytest.raises(ClientError) as update_exc:
- lam.update_function_configuration(FunctionName=update_name, Layers=[wrong_account_arn])
- assert update_exc.value.response["Error"]["Code"] == "AccessDeniedException"
- cfg = lam.get_function_configuration(FunctionName=update_name)
- assert cfg["Layers"] == []
+ lam.update_function_configuration(FunctionName=update_name, Layers=[wrong_account_arn])
+ assert lam.get_function_configuration(FunctionName=update_name)["Layers"] == [
+ {"Arn": wrong_account_arn, "CodeSize": 0}
+ ]
+
+ # The layer this account really published still resolves to its bytes.
+ lam.update_function_configuration(FunctionName=update_name, Layers=[layer_arn])
+ own = lam.get_function_configuration(FunctionName=update_name)
+ assert own["Layers"][0]["Arn"] == layer_arn
+ assert own["Layers"][0]["CodeSize"] > 0
finally:
for name in (create_name, update_name):
try:
@@ -4676,6 +4694,427 @@ def test_esm_response_no_function_name_field(lam, sqs):
sqs.delete_queue(QueueUrl=q_url)
+# CloudWatch Lambda Insights, the layer people reference cross-account; nothing resolves the version locally.
+_AWS_MANAGED_LAYER = "arn:aws:lambda:us-east-1:580247275435:layer:LambdaInsightsExtension:38"
+_OTHER_REGION_LAYER = "arn:aws:lambda:eu-central-1:580247275435:layer:LambdaInsightsExtension:38"
+_FOREIGN_ACCOUNT = "580247275435"
+_FOREIGN_REGION = "us-east-1"
+_FOREIGN_CODE_SIZE = 4198176
+_CALLER_ACCOUNT = "000000000000"
+
+
+def _via_endpoint(url):
+ """Content.Location names MINISTACK_HOST/GATEWAY_PORT; aim it at MINISTACK_ENDPOINT."""
+ endpoint = urlparse(_endpoint)
+ return urlparse(url)._replace(scheme=endpoint.scheme, netloc=endpoint.netloc).geturl()
+
+
+def _foreign_arn(layer_name, version=7, account=_FOREIGN_ACCOUNT):
+ return f"arn:aws:lambda:{_FOREIGN_REGION}:{account}:layer:{layer_name}:{version}"
+
+
+def _layer_access_denied(arn, caller=f"arn:aws:iam::{_CALLER_ACCOUNT}:root"):
+ return (f"User: {caller} is not authorized to perform: lambda:GetLayerVersion on resource: {arn} "
+ "because no resource-based policy allows the lambda:GetLayerVersion action")
+
+
+def _import_handler(module):
+ """Handler code reporting whether a layer module imports, and its VALUE."""
+ return _make_zip(
+ "def handler(e, c):\n try:\n"
+ f" import {module}\n return {{'value': getattr({module}, 'VALUE', True)}}\n"
+ " except ImportError:\n return {'value': None}\n"
+ )
+
+
+def _layer_verdicts(arn):
+ """(attach config, attach error, GetLayerVersionByArn payload, read error), in process;
+ an error is (code, message) or None."""
+ import ministack.services.lambda_svc as _lsvc
+
+ version_config, err = _lsvc._resolve_layer_version_for_attachment(arn)
+ status, _headers, body = _lsvc._get_layer_version_by_arn(arn)
+ payload = json.loads(body)
+
+ def error(response_body):
+ parsed = json.loads(response_body)
+ return parsed["__type"], parsed.get("message", "")
+ return (version_config, err and error(err[2]),
+ None if status >= 400 else payload, error(body) if status >= 400 else None)
+
+
+def _foreign_layer(layer_name, version=7, granted_to=None, org_id=None, owner=_FOREIGN_ACCOUNT):
+ """Seed one layer version in *owner*'s scope, grant it through the real
+ AddLayerVersionPermission, and run the block as the consumer account."""
+ import ministack.services.lambda_svc as _lsvc
+ from ministack.core.responses import request_scope
+
+ version_config = None
+ if layer_name is not None:
+ arn = _foreign_arn(layer_name, version, owner)
+ version_config = {"LayerArn": arn.rsplit(":", 1)[0], "LayerVersionArn": arn, "Version": version,
+ "Content": {"CodeSize": _FOREIGN_CODE_SIZE}}
+ _lsvc._layers.set_scoped(owner, _FOREIGN_REGION, layer_name,
+ {"versions": [version_config], "next_version": version + 1})
+ try:
+ if granted_to is not None:
+ grant = {"StatementId": "shared", "Action": "lambda:GetLayerVersion", "Principal": granted_to}
+ if org_id:
+ grant["OrganizationId"] = org_id
+ with request_scope(owner, _FOREIGN_REGION):
+ status, _headers, body = _lsvc._add_layer_version_permission(layer_name, version, grant)
+ assert status == 201, body
+ with request_scope(_CALLER_ACCOUNT, _FOREIGN_REGION):
+ yield version_config
+ finally:
+ if layer_name is not None:
+ _lsvc._layers.pop_scoped(owner, _FOREIGN_REGION, layer_name, None)
+
+
+_DENIED = "AccessDeniedException"
+
+
+# (seeded layer name, grant principal, explicit ARN, attachment error code, GetLayerVersionByArn error code)
[email protected](("layer_name", "granted_to", "arn", "attach_error", "read_error"), [
+ pytest.param("owner-granted", _CALLER_ACCOUNT, None, None, None, id="account-grant"),
+ pytest.param("root-granted", f"arn:aws:iam::{_CALLER_ACCOUNT}:root", None, None, None,
+ id="account-root-arn-grant"),
+ pytest.param("everyone-granted", "*", None, None, None, id="wildcard-grant"),
+ pytest.param("ungranted", None, None, _DENIED, _DENIED, id="no-grant"),
+ pytest.param("granted-elsewhere", "111111111111", None, _DENIED, _DENIED, id="grant-to-another-account"),
+ pytest.param("partly-seeded", "*", _foreign_arn("partly-seeded", 35), _DENIED, _DENIED,
+ id="missing-version-of-known-layer"),
+ pytest.param(None, None, _AWS_MANAGED_LAYER, None, _DENIED, id="unknown-layer-is-opaque"),
+ pytest.param(None, None, _OTHER_REGION_LAYER, _DENIED, _DENIED, id="another-region"),
+ pytest.param(None, None, _foreign_arn("nope-not-here", 1, _CALLER_ACCOUNT),
+ "InvalidParameterValueException", "ResourceNotFoundException", id="own-account-layer-missing"),
+])
+def test_lambda_cross_account_layer_verdicts(layer_name, granted_to, arn, attach_error, read_error):
+ """A grant makes stored foreign content attachable and readable. An unknown
+ foreign layer name attaches as metadata only; a missing layer of this
+ account never does. The resolver does not read AUTH (see the next test)."""
+ arn = arn or _foreign_arn(layer_name)
+ with _foreign_layer(layer_name, granted_to=granted_to):
+ version_config, attach, payload, read = _layer_verdicts(arn)
+ assert ((attach or [None])[0], (read or [None])[0]) == (attach_error, read_error)
+ messages = {"InvalidParameterValueException": f"Layer version {arn} does not exist.",
+ "ResourceNotFoundException": "The resource you requested does not exist."}
+ for error in filter(None, (attach, read)):
+ assert error[1] == messages.get(error[0], _layer_access_denied(arn))
+ if attach_error is None:
+ assert version_config["Content"]["CodeSize"] == (_FOREIGN_CODE_SIZE if layer_name else 0)
+ if read_error is None:
+ assert (payload["LayerVersionArn"], payload["Content"]["CodeSize"]) == (arn, _FOREIGN_CODE_SIZE)
+ assert not [key for key in payload if key.startswith("_")]
+
+
+def test_lambda_cross_account_layer_under_auth_names_the_calling_user(monkeypatch):
+ """Through the app with AUTH=true as an IAM user of the consuming account: the
+ layer policy decides, and a denial names that user the way AWS does."""
+ import ministack.app as app_mod
+ from ministack.services import iam as iam_svc
+
+ monkeypatch.setattr(app_mod, "AUTH", True)
+ key, user = "AKIALAYERCONSUMER001", "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": []}),
+ (iam_svc._user_inline_policies, user,
+ {"lambda": {"Statement": [{"Effect": "Allow", "Action": "lambda:*", "Resource": "*"}]}}),
+ (iam_svc._access_keys, key, {"AccessKeyId": key, "SecretAccessKey": "s", "Status": "Active", "UserName": user}),
+ ]
+ for store, name, record in seeded:
+ store.set_scoped(_CALLER_ACCOUNT, None, name, record)
+ sent = []
+
+ async def receive():
+ return {"type": "http.request", "body": b"", "more_body": False}
+
+ async def send(message):
+ sent.append(message)
+
+ try:
+ for granted_to in ("*", None):
+ sent.clear()
+ arn = _foreign_arn("auth-layer")
+ with _foreign_layer("auth-layer", granted_to=granted_to):
+ asyncio.run(app_mod.app({
+ "type": "http", "method": "GET", "path": "/2018-10-31/layers",
+ "query_string": f"find=LayerVersion&Arn={arn}".encode(),
+ "headers": [(b"host", b"lambda.localhost"), (b"authorization", (
+ f"AWS4-HMAC-SHA256 Credential={key}/20260915/{_FOREIGN_REGION}/lambda/aws4_request, "
+ "SignedHeaders=host, Signature=0").encode())],
+ }, receive, send))
+ status, body = sent[0]["status"], json.loads(sent[1]["body"])
+ if granted_to:
+ assert (status, body["Content"]["CodeSize"]) == (200, _FOREIGN_CODE_SIZE)
+ else:
+ assert (status, body["message"]) == (403, _layer_access_denied(arn, user_arn))
+ finally:
+ for store, name, _record in seeded:
+ store.pop_scoped(_CALLER_ACCOUNT, None, name, None)
+
+
+def shared_layer():
+ """Publish real layer bytes and provision the consumer's execution role."""
+ owner_id = str(100000000000 + _uuid_mod.uuid4().int % 400000000000)
+ caller_id = str(int(owner_id) + 400000000000)
+ owner = _account_context_client("lambda", owner_id)
+ caller = _account_context_client("lambda", caller_id)
+ iam = _account_context_client("iam", caller_id)
+ name = f"shared-layer-{_uuid_mod.uuid4().hex[:8]}"
+ role = iam.create_role(RoleName=name, AssumeRolePolicyDocument=json.dumps({"Statement": [{
+ "Effect": "Allow", "Principal": {"Service": "lambda.amazonaws.com"}, "Action": "sts:AssumeRole"}]}),
+ )["Role"]["Arn"]
+ published = owner.publish_layer_version(
+ LayerName=name, Content={"ZipFile": _make_zip_js("VALUE = 'shared bytes'\n", "python/shared_module.py")})
+ try:
+ yield owner, caller, published, role
+ finally:
+ # Functions first: a deleted layer version is retained while one is still attached.
+ for fn in caller.list_functions()["Functions"]:
+ caller.delete_function(FunctionName=fn["FunctionName"])
+ owner.delete_layer_version(LayerName=name, VersionNumber=published["Version"])
+ iam.delete_role(RoleName=name)
+
+
+def test_lambda_shared_layer_execution_and_lifecycle(shared_layer):
+ owner, caller, published, role = shared_layer
+ arn, layer_arn, version = published["LayerVersionArn"], published["LayerArn"], published["Version"]
+ layer_name = arn.split(":")[-2]
+ owner.add_layer_version_permission(LayerName=layer_name, VersionNumber=version, StatementId="shared",
+ Action="lambda:GetLayerVersion", Principal=role.split(":")[4])
+ for result in [caller.get_layer_version_by_arn(Arn=arn),
+ caller.get_layer_version(LayerName=layer_arn, VersionNumber=version)]:
+ assert (result["LayerVersionArn"], result["Content"]["CodeSize"]) == (arn, published["Content"]["CodeSize"])
+ assert not any(key.startswith("_") for key in result)
+ with _urlreq.urlopen(_via_endpoint(result["Content"]["Location"])) as response:
+ assert len(response.read()) == published["Content"]["CodeSize"]
+
+ code = _import_handler("shared_module")
+ for name, layers in [("created", [arn]), ("updated", [])]:
+ caller.create_function(FunctionName=name, Runtime="python3.13", Handler="index.handler",
+ Role=role, Code={"ZipFile": code}, Layers=layers)
+ assert _invoke_lambda_payload(caller, "created")[1] == {"value": "shared bytes"}
+ assert _invoke_lambda_payload(caller, "updated")[1] == {"value": None}
+ caller.update_function_configuration(FunctionName="updated", Layers=[arn])
+ assert _invoke_lambda_payload(caller, "updated")[1] == {"value": "shared bytes"}
+ fn_version = caller.publish_version(FunctionName="updated")["Version"]
+
+ owner.remove_layer_version_permission(LayerName=layer_name, VersionNumber=version, StatementId="shared")
+ for deleted in [False, True]:
+ if deleted:
+ owner.delete_layer_version(LayerName=layer_name, VersionNumber=version)
+ assert owner.list_layer_versions(LayerName=layer_name)["LayerVersions"] == []
+ assert owner.list_layers()["Layers"] == []
+ with pytest.raises(ClientError) as missing:
+ owner.get_layer_version(LayerName=layer_name, VersionNumber=version)
+ assert missing.value.response["Error"]["Code"] == "ResourceNotFoundException"
+ for call in [
+ lambda: caller.create_function(FunctionName="denied", Runtime="python3.13", Handler="index.handler",
+ Role=role, Code={"ZipFile": code}, Layers=[arn]),
+ lambda: caller.update_function_configuration(FunctionName="updated", Layers=[arn]),
+ lambda: caller.get_layer_version_by_arn(Arn=arn),
+ lambda: caller.get_layer_version(LayerName=layer_arn, VersionNumber=version),
+ ]:
+ with pytest.raises(ClientError) as denied:
+ call()
+ assert denied.value.response["Error"]["Code"] == _DENIED
+ # Force a cold start after revocation/deletion without reattaching the layer.
+ caller.update_function_configuration(FunctionName="updated", Environment={"Variables": {"D": str(deleted)}})
+ assert _invoke_lambda_payload(caller, "updated")[1] == {"value": "shared bytes"}
+ assert caller.get_function_configuration(FunctionName="updated")["Layers"] == [
+ {"Arn": arn, "CodeSize": published["Content"]["CodeSize"]}]
+
+ caller.update_function_configuration(FunctionName="updated", Layers=[])
+ caller.delete_function(FunctionName="created")
+ assert _invoke_lambda_payload(caller, "updated")[1] == {"value": None}
+ # First invocation of the published version is cold, after deletion and detach.
+ assert _invoke_lambda_payload(caller, "updated", Qualifier=fn_version)[1] == {"value": "shared bytes"}
+
+
[email protected](("membership", "allowed"), [("matching", True), ("different", False), ("absent", False)])
+def test_lambda_shared_layer_organization_condition(monkeypatch, membership, allowed):
+ """A wildcard grant carrying OrganizationId reaches org members only, and
+ asking the question must not enrol the caller in an organization."""
+ from ministack.core.responses import AccountScopedDict
+ from ministack.services import lambda_svc, organizations
+
+ orgs = AccountScopedDict()
+ monkeypatch.setattr(organizations, "_orgs", orgs)
+ if membership != "absent":
+ orgs.set_scoped(_CALLER_ACCOUNT, None, "self",
+ {"Id": "o-0123456789" if membership == "matching" else "o-9876543210"})
+ with _foreign_layer("org-layer", granted_to="*", org_id="o-0123456789"):
+ arn = _foreign_arn("org-layer")
+ assert (_layer_verdicts(arn)[1] is None) is allowed
+ for response in [lambda_svc._get_layer_version_by_arn(arn),
+ lambda_svc._get_layer_version(arn.rsplit(":", 1)[0], 7)]:
+ assert response[0] == (200 if allowed else 403)
+ assert len(orgs._data) == (0 if membership == "absent" else 1)
+
+
+def test_lambda_opaque_layer_does_not_load_later_private_content(shared_layer):
+ """A metadata-only attachment must not pick up content the owner publishes
+ afterwards at the same ARN, at a cold start or on reattachment."""
+ owner, caller, published, role = shared_layer
+ name = published["LayerArn"].split(":")[-1] + "-later"
+ arn = published["LayerVersionArn"].replace(published["LayerArn"].split(":")[-1], name)
+ fname = f"opaque-{_uuid_mod.uuid4().hex[:8]}"
+ later = None
+ try:
+ caller.create_function(FunctionName=fname, Runtime="python3.13", Handler="index.handler", Role=role,
+ Code={"ZipFile": _import_handler("private_layer_module")}, Layers=[arn])
+ later = owner.publish_layer_version(
+ LayerName=name, Content={"ZipFile": _make_zip_js("SECRET = 123\n", "python/private_layer_module.py")})
+ assert later["LayerVersionArn"] == arn
+ # No invocation before publication, so this is a cold start.
+ assert _invoke_lambda_payload(caller, fname)[1] == {"value": None}
+ assert caller.get_function_configuration(FunctionName=fname)["Layers"] == [{"Arn": arn, "CodeSize": 0}]
+ with pytest.raises(ClientError) as denied:
+ caller.update_function_configuration(FunctionName=fname, Layers=[arn])
+ assert denied.value.response["Error"]["Code"] == _DENIED
+ finally:
+ with contextlib.suppress(ClientError):
+ caller.delete_function(FunctionName=fname)
+ if later is not None:
+ owner.delete_layer_version(LayerName=name, VersionNumber=later["Version"])
+
+
+def isolated_layers(lambda_svc_isolated, monkeypatch):
+ """lambda_svc with an empty layer store and extraction cache."""
+ from ministack.core.responses import AccountRegionScopedDict
+
+ svc, _ = lambda_svc_isolated
+ monkeypatch.setattr(svc, "_layers", AccountRegionScopedDict())
+ monkeypatch.setattr(svc, "_docker_extract_dirs", {})
+ return svc
+
+
+def test_lambda_deleted_shared_layer_retention_and_restore(isolated_layers):
+ """A deleted version keeps serving the functions attached to it, survives a
+ state round trip while one still is, and is reaped when the last goes."""
+ import base64
+
+ from ministack.core.responses import request_scope
+
+ svc = isolated_layers
+ layer_zip = _make_zip("retained bytes")
+ with request_scope(_FOREIGN_ACCOUNT, _FOREIGN_REGION):
+ _, _, body = svc._publish_layer_version("retained", {"Content": {"ZipFile": base64.b64encode(layer_zip).decode()}})
+ arn = json.loads(body)["LayerVersionArn"]
+ svc._add_layer_version_permission(
+ "retained", 1, {"StatementId": "shared", "Action": "lambda:GetLayerVersion", "Principal": "*"})
+ with request_scope(_CALLER_ACCOUNT, _FOREIGN_REGION):
+ svc._functions["retains-version"] = {
+ "config": {"FunctionName": "retains-version", "Layers": []},
+ "versions": {"1": {"config": {"Layers": [{"Arn": arn, "CodeSize": len(layer_zip)}]}}},
+ }
+ with request_scope(_FOREIGN_ACCOUNT, _FOREIGN_REGION):
+ svc._delete_layer_version("retained", 1)
+ # A deleted version reads back the way AWS reports it; the two APIs word it differently.
+ status, _, body = svc._get_layer_version("retained", 1)
+ assert (status, json.loads(body)["message"]) == (404, "The resource you requested does not exist.")
+ status, _, body = svc._get_layer_version_policy("retained", 1)
+ assert (status, json.loads(body)["message"]) == (404, f"Layer version {arn} does not exist.")
+ assert svc.serve_layer_content("retained", 1)[0] == 404
+ assert [vc["Version"] for vc in svc._layers["retained"]["versions"]] == [1]
+
+ state = svc.get_state()
+ svc._layers.clear()
+ svc._functions.clear()
+ svc.restore_state(state)
+ with request_scope(_CALLER_ACCOUNT, _FOREIGN_REGION):
+ assert svc._resolve_layer_zip(arn) == layer_zip
+ assert svc._layer_unzipped_size(arn) == len("retained bytes")
+ assert _layer_verdicts(arn)[1][0] == _DENIED
+ svc._delete_function("retains-version", {}, path_qualifier="1")
+ assert svc._resolve_layer_zip(arn) is None
+ assert _layer_verdicts(arn)[1][0] == _DENIED
+ with request_scope(_FOREIGN_ACCOUNT, _FOREIGN_REGION):
+ assert svc._layers["retained"]["versions"] == []
+ assert not [vc for layer in svc.get_state()["layers"]._data.values() for vc in layer["versions"]]
+
+
+def _seed_attached_layer(svc, name, attached_code_size, deleted):
+ from ministack.core.responses import request_scope
+
+ arn = _foreign_arn(name, 1)
+ with request_scope(_FOREIGN_ACCOUNT, _FOREIGN_REGION):
+ svc._layers[name] = {"versions": [{"Version": 1, "LayerVersionArn": arn, "Content": {"CodeSize": 4096},
+ "_zip_data": _make_zip("x"), "_deleted": deleted}], "next_version": 2}
+ with request_scope(_CALLER_ACCOUNT, _FOREIGN_REGION):
+ svc._functions["attached"] = {"config": {"FunctionName": "attached",
+ "Layers": [{"Arn": arn, "CodeSize": attached_code_size}]}}
+ return arn
+
+
[email protected](("attached_code_size", "reaped"), [
+ pytest.param(4096, False, id="attached-with-content-retained"),
+ pytest.param(0, True, id="opaque-attachment-does-not-retain"),
+])
+def test_lambda_deleted_layer_version_reaping(isolated_layers, attached_code_size, reaped):
+ """Only an attachment that carries the bytes keeps a deleted version alive."""
+ from ministack.core.responses import request_scope
+
+ _seed_attached_layer(isolated_layers, "reaped-layer", attached_code_size, deleted=True)
+ isolated_layers._sweep_extract_cache()
+ with request_scope(_FOREIGN_ACCOUNT, _FOREIGN_REGION):
+ assert (isolated_layers._layers["reaped-layer"]["versions"] == []) is reaped
+
+
+def test_lambda_cfn_deletes_and_restore_reap_unreferenced_layer_versions(isolated_layers):
+ """CloudFormation deletes tombstone and sweep like the Lambda API, and a
+ restored snapshot drops a tombstone nothing references."""
+ from ministack.core.responses import AccountRegionScopedDict, request_scope
+ from ministack.services.cloudformation import provisioners
+
+ svc = isolated_layers
+ arn = _seed_attached_layer(svc, "cfn-layer", 4096, deleted=False)
+ with request_scope(_FOREIGN_ACCOUNT, _FOREIGN_REGION):
+ provisioners._lambda_layer_delete(arn, {})
+ assert svc._layers["cfn-layer"]["versions"][0]["_deleted"]
+ state = svc.get_state()
+ with request_scope(_CALLER_ACCOUNT, _FOREIGN_REGION):
+ provisioners._lambda_delete("attached", {})
+ state["functions"] = AccountRegionScopedDict()
+ with request_scope(_FOREIGN_ACCOUNT, _FOREIGN_REGION):
+ assert svc._layers["cfn-layer"]["versions"] == []
+ svc._layers.clear()
+ svc.restore_state(state)
+ assert svc._layers["cfn-layer"]["versions"] == []
+
+
[email protected]("owner", [_FOREIGN_ACCOUNT, _CALLER_ACCOUNT], ids=["shared-layer", "own-layer"])
+def test_lambda_layer_attachment_checks_total_unzipped_size(monkeypatch, owner):
+ """The function-plus-layers unzipped limit covers create and update, for a
+ granted foreign layer and an own one; a rejected update changes nothing."""
+ import base64
+
+ from ministack.core.responses import AccountRegionScopedDict
+ from ministack.services import lambda_svc
+
+ monkeypatch.setattr(lambda_svc, "_functions", AccountRegionScopedDict())
+ monkeypatch.setattr(lambda_svc, "_UNZIPPED_LIMIT_BYTES", 30)
+ with _foreign_layer("quota-layer", granted_to="*" if owner != _CALLER_ACCOUNT else None, owner=owner) as vc:
+ vc["_zip_data"] = _make_zip("x" * 20)
+ arn = _foreign_arn("quota-layer", account=owner)
+ fname = f"quota-{_uuid_mod.uuid4().hex[:8]}"
+ original = {"FunctionName": fname, "Layers": [], "Description": "before"}
+ lambda_svc._functions[fname] = {"config": original.copy(), "code_zip": _make_zip("x" * 20)}
+ response = lambda_svc._update_config(fname, {"Layers": [arn], "Description": "after"})
+ assert (response[0], json.loads(response[2])["__type"]) == (400, "InvalidParameterValueException")
+ assert lambda_svc._functions[fname]["config"] == original
+ response = lambda_svc._create_function({
+ "FunctionName": "too-large", "Runtime": "python3.13", "Role": _LAMBDA_ROLE, "Handler": "index.handler",
+ "Code": {"ZipFile": base64.b64encode(_make_zip("x" * 20)).decode()}, "Layers": [arn]})
+ assert response[0] == 400
+ assert "too-large" not in lambda_svc._functions
+
+
def test_lambda_update_function_configuration_layers(lam):
"""Attaching a layer via update-function-configuration should normalize ARN strings
to {Arn, CodeSize} dicts — regression test for 'str' object has no attribute 'get'."""