Ministack: Free, open-source local AWS emulator - 60+ services, Terraform compatible, real databases. Free forever. MIT licensed.
Python awsaws-emulatoraws-localaws-sdkdevtoolsdockerdynamodbec2emulatorlambdalocalstacklocalstack-alternativeministackmock-awsopen-sourcepythons3sqsterraform
fix(lambda): resolve layers from other accounts that MiniStack doesn't hold (#2384)
Kacper Harabasz3866f3f17f11
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 3f39209c..1807edc9 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -13,6 +13,7 @@ Versioning follows [Semantic Versioning](https://semver.org/).- **IoT — thing-group membership authorized on the group and the thing** — with `AUTH=true`, `AddThingToThingGroup` and `RemoveThingFromThingGroup` were authorized on `thinggroup/addThingToThingGroup` (the request path), so a policy granting exactly the thing group and the thing was denied; both calls are now checked on the thing group and then the thing named in the body (by name or ARN), and a denial names the resource that failed. Contributed by @iot-rocket.- **API Gateway — `AWS_IAM` methods refuse an `Authorization` header that is not SigV4** — under `AUTH=true` a REST API method with `AWS_IAM` authorization served a bearer token or an algorithm in lower case, and answered the SigV4a algorithm name without a signed `x-amz-region-set` or an unknown `AWS4-` algorithm with `UnrecognizedClientException`; it now answers 403 `IncompleteSignatureException` with API Gateway's message for each, while a method without `AWS_IAM` still serves such calls. Contributed by @iot-rocket.- **S3 — access point policies and unsigned requests** — an access point policy was stored but never applied, and an unsigned request through an access point was served. With `AUTH=true` a request through an access point alias or ARN is allowed on the access point by an identity policy or the access point policy (a Deny in either refuses it), and an unsigned one gets 400 `InvalidRequest`; S3 Control calls on the access point are unaffected. Contributed by @iot-rocket.+- **Lambda — layers from other accounts that MiniStack doesn't hold** — a function attaching a third-party public layer, such as Datadog's `arn:aws:lambda:<region>:464622532012:layer:Datadog-Extension-ARM:<n>`, was refused with `AccessDeniedException`, where AWS attaches it. A layer version from another account that MiniStack does not hold now resolves as an empty layer with a warning in the log: `CreateFunction` and `UpdateFunctionConfiguration` attach it as `Arn` and `CodeSize` 0, `GetLayerVersionByArn` and `GetLayerVersion` by ARN return `LayerArn`, `LayerVersionArn`, `Version` and `Content.CodeSize` 0, and the layer does not run, even if a version is published under that ARN later. This replaces the name list for AWS-published extensions. A made-up ARN looks like a real one offline, so any 12-digit account, layer name and version that could exist on AWS resolve, where AWS answers `AccessDeniedException` for one that does not exist. A version of 0, a version with a leading zero and a name longer than 140 characters can't exist, and `CreateFunction`, `UpdateFunctionConfiguration` and `GetLayerVersionByArn` refuse them with that `AccessDeniedException`, as on AWS. A layer MiniStack holds still needs its grant, so a version it does not hold or grant is refused, and a layer from another region is still refused. `GetLayerVersion` now refuses a `LayerName` longer than 140 characters, a layer ARN included, with AWS's `ValidationException` before checking the version; `GetLayerVersionByArn` has no such limit, as on AWS. Contributed by @kharabasz.- **CloudFront — `CreateFunction` tags** — the request's `Tags` were dropped, so `ListTagsForResource` on the new function's ARN was empty and Terraform re-planned `tags_all` on `aws_cloudfront_function`; they are now stored, a tag without `Value` is listed with an empty one, a refused create stores none, and `DeleteFunction` removes them so a function created again under the same name starts without them. `CreateFunction` and `UpdateFunction` answer invalid base64 code with `MalformedInput` "Invalid Base64 encoding", and `CreateFunction` now refuses what AWS refuses, before the name lookup: a missing or empty `FunctionCode`, a missing `FunctionConfig` or `Runtime`, an unknown runtime, a missing or empty `Name`, and a tag key that is missing, empty, over 128 characters or outside letters, numbers, spaces and `_ . : / = + - @` (values over 256 characters or outside the same set), listed together (at most ten) in one `MalformedXML`; and after it, `InvalidTagging` for a repeated key, an `aws:` key or more than 50 tags. Contributed by @kharabasz.- **CloudWatch — `PutMetricAlarm` and `PutCompositeAlarm` tags on create** — `Tags` were dropped when either call created an alarm, so Terraform re-planned `tags_all` on `aws_cloudwatch_metric_alarm` and `aws_cloudwatch_composite_alarm`; they are now stored over CBOR, JSON 1.0 and Query, keeping empty values and the last value of a repeated key, and they are still ignored when the call updates an existing alarm, as on AWS (use `TagResource` / `UntagResource`). Both calls now refuse what AWS refuses, before anything is stored (`PutCompositeAlarm` before its `AlarmRule` checks): a wrong JSON type in `Tags` (`MalformedInput`), a missing or empty `Key`, a missing `Value`, a key over 128 or a value over 256 characters, or a `DatapointsToAlarm` below 1, listed together (at most ten) in one `ValidationError`, on create a key or value with characters outside letters, numbers, spaces and `_ . : / = + - @` or too long in UTF-16 units, an `aws:` key on create (`PutMetricAlarm` 403 `AccessDenied`, `PutCompositeAlarm` `ValidationError` "Invalid System Tag"), and more than 50 tags on create. Query error messages are now XML-escaped. Contributed by @kharabasz.- **CloudWatch — `DatapointsToAlarm` only when set** — an alarm created by `PutMetricAlarm` or `AWS::CloudWatch::Alarm` without `DatapointsToAlarm` reported it as `EvaluationPeriods`, so Terraform planned `datapoints_to_alarm = 3 -> null`; `DescribeAlarms` now leaves it out unless the request or template sets it, the Query response includes it when set, and an update that omits it clears it. Contributed by @kharabasz.diff --git a/ministack/services/lambda_svc.py b/ministack/services/lambda_svc.pyindex 1c202ad7..3a1d4533 100644--- a/ministack/services/lambda_svc.py+++ b/ministack/services/lambda_svc.py@@ -1731,45 +1731,42 @@ def _layer_access_denied(layer_arn: str):)-# The extensions AWS publishes from its own accounts and grants-# lambda:GetLayerVersion on to everyone. Keyed by LAYER NAME, not by publisher-# account: the name is stable while the account differs in every region, so one-# short list replaces ~190 account ids that go stale as regions are added.-_AWS_PUBLISHED_LAYER_PREFIXES = (- "LambdaInsightsExtension",- "AWS-Parameters-and-Secrets-Lambda-Extension",- "AWS-AppConfig-Extension",- "AWSOpenTelemetryDistro",- "aws-otel-",- "AWSSDKPandas-",+# The shape of a layer version ARN that can exist on AWS: a 12-digit account, a+# name of at most 140 of [a-zA-Z0-9-_], and a version from 1 with no leading zero.+_POSSIBLE_LAYER_VERSION_ARN_RE = re.compile(+ r"arn:aws:lambda:[a-z0-9-]+:[0-9]{12}:layer:[a-zA-Z0-9-_]{1,140}:[1-9][0-9]*")-def _is_aws_published_layer(layer_name: str) -> bool:- return layer_name.startswith(_AWS_PUBLISHED_LAYER_PREFIXES)--def _resolve_cross_account_layer(layer_arn: str, spec, name_and_version):- """Another account's layer through its grant; an unknown account passes by- name, and the bytes are not available offline (CodeSize 0, does not run)."""+ """Another account's layer. A layer MiniStack holds answers through its grant,+ so a version it does not hold or does not grant is denied, as on AWS. A layer+ it does not hold resolves as an empty version: on AWS it may be a public+ vendor or AWS extension, and offline a real ARN looks like a made-up one, so+ any account and version that could exist resolve. Its bytes are not+ available, so it has CodeSize 0, leaves out what only the publisher knows,+ and does not run. An ARN that cannot name a layer version on AWS is denied."""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 and _layer_policy_allows(vc, get_account_id()):- return vc, None- if vc is None and _is_aws_published_layer(layer_name):- logger.warning(- "Layer %s is an AWS-published extension: the reference resolves so "- "the stack deploys, but the bytes are not available offline and the "- "extension will not run", layer_arn,- )- return {- "LayerVersionArn": layer_arn,- "Version": version,- "Content": {"CodeSize": 0},- }, None- return _layer_access_denied(layer_arn)+ if not _POSSIBLE_LAYER_VERSION_ARN_RE.fullmatch(layer_arn):+ return _layer_access_denied(layer_arn)+ if _layers.get_scoped(spec.account_id, spec.region, layer_name) is not None:+ vc, _ = _find_layer_version(layer_name, version, spec.account_id, spec.region)+ if vc is not None and _layer_policy_allows(vc, get_account_id()):+ return vc, None+ return _layer_access_denied(layer_arn)+ logger.warning(+ "Layer %s is not held by MiniStack: the reference resolves so the stack "+ "deploys, but the bytes are not available offline and the layer will not run",+ layer_arn,+ )+ return {+ "LayerArn": layer_arn.rsplit(":", 1)[0],+ "LayerVersionArn": layer_arn,+ "Version": version,+ "Content": {"CodeSize": 0},+ }, Nonedef _resolve_layer_version_for_attachment(layer_arn: str):@@ -2112,7 +2109,7 @@ async def handle_request(method: str, path: str, headers: dict, body: bytes, quelayer_name, ver_num, policy_sid, query_params)if method == "GET":- return _get_layer_version(layer_name, ver_num)+ return _layer_name_too_long(layer_name) or _get_layer_version(layer_name, ver_num)if method == "DELETE":return _delete_layer_version(layer_name, ver_num)@@ -5868,6 +5865,10 @@ def _execute_function_local(func: dict, event: dict, request_id: str) -> dict:def _resolve_layer_zip(attachment: str | dict) -> bytes | None:"""Return attached content, including versions deleted since attachment."""if isinstance(attachment, dict):+ if attachment.get("CodeSize") == 0:+ # Attached as an empty layer MiniStack did not hold; a version+ # published under that ARN later must not load without its grant.+ return Noneattachment = attachment.get("Arn", "")try:spec = parse_arn(attachment)@@ -6475,6 +6476,20 @@ def _list_layer_versions(layer_name: str, query_params: dict):return json_response(result)+def _layer_name_too_long(layer_name: str):+ """GetLayerVersion's LayerName limit. It covers the whole value, a layer ARN+ included, and is checked before the version. GetLayerVersionByArn has no+ LayerName member and no such limit."""+ if len(layer_name) <= 140:+ return None+ return error_response_json(+ "ValidationException",+ f"1 validation error detected: Value '{layer_name}' at 'layerName' failed to "+ "satisfy constraint: Member must have length less than or equal to 140",+ 400,+ )++def _get_layer_version(layer_name: str, version: int):if version < 1:return error_response_json(diff --git a/tests/test_cfn.py b/tests/test_cfn.pyindex 91b4cfc8..142a6252 100644--- a/tests/test_cfn.py+++ b/tests/test_cfn.py@@ -17947,6 +17947,40 @@ def test_cfn_lambda_function_foreign_layer_follows_the_layer_policy(granted):owner.delete_layer_version(LayerName="foreign", VersionNumber=published["Version"])+def test_cfn_lambda_function_unheld_foreign_layer_attaches_empty():+ """A template attaching a public vendor layer MiniStack does not hold deploys, as+ on AWS (#2313 C7), with the layer reported as {Arn, CodeSize: 0} (#2313+ maintainer (3)), the same as CreateFunction."""+ consumer_id = str(100000000000 + _uuid_mod.uuid4().int % 800000000000)++ def client(service):+ return boto3.client(+ service, endpoint_url=os.environ.get("MINISTACK_ENDPOINT", "http://localhost:4566"),+ region_name="us-east-1", aws_access_key_id=consumer_id, aws_secret_access_key="test",+ )++ lam, cfn = client("lambda"), client("cloudformation")+ arn = "arn:aws:lambda:us-east-1:464622532012:layer:Datadog-Extension-ARM:101"+ stack_name = "cfn-unheld-layer"+ cfn.create_stack(StackName=stack_name, TemplateBody=json.dumps({"Resources": {"Fn": {+ "Type": "AWS::Lambda::Function",+ "Properties": {+ "FunctionName": "unheld-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)+ assert stack["StackStatus"] == "CREATE_COMPLETE", stack.get("StackStatusReason")+ assert lam.get_function_configuration(FunctionName="unheld-layer-fn")["Layers"] == [+ {"Arn": arn, "CodeSize": 0}]+ finally:+ cfn.delete_stack(StackName=stack_name)+ _wait_stack(cfn, stack_name)++def test_cfn_lambda_layer_version_permission(cfn, s3, lam):"""A layer plus the permission resource that grants another account accessto it — the shape serverless-python-requirements emits for a layer withdiff --git a/tests/test_lambda.py b/tests/test_lambda.pyindex 6a9a9b5d..3a73a00c 100644--- a/tests/test_lambda.py+++ b/tests/test_lambda.py@@ -3127,13 +3127,12 @@ def test_lambda_rejects_cross_region_layers_on_create_and_update():east.delete_function(FunctionName=update_name)-def test_lambda_rejects_wrong_account_layers_on_create_and_update(lam):- """A foreign-account ARN with no grant behind it is refused.-- 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 — and with no AddLayerVersionPermission statement naming the- caller, the attachment is denied on create and on update alike.+def test_lambda_wrong_account_layer_attaches_empty_not_local_content(lam):+ """Rewriting the account field of an ARN this account published must not hand+ back that layer's content. The store is keyed by account and region, and+ MiniStack holds no layer of that name in the other account, so the ARN+ attaches as an empty layer, {Arn, CodeSize: 0}, on create and on update alike+ (#2313 maintainer (3) and (4); the key set AWS gives an unsigned layer, C12)."""suffix = _uuid_mod.uuid4().hex[:8]@@ -3150,17 +3149,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}"+ empty = [{"Arn": wrong_account_arn, "CodeSize": 0}]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"+ created = 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 created["Layers"] == emptylam.create_function(FunctionName=update_name,@@ -3169,9 +3168,8 @@ 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"+ updated = lam.update_function_configuration(FunctionName=update_name, Layers=[wrong_account_arn])+ assert updated["Layers"] == empty# The layer this account really published still resolves to its bytes.lam.update_function_configuration(FunctionName=update_name, Layers=[layer_arn])@@ -3512,7 +3510,6 @@ def test_lambda_layer_version_arn_errors_do_not_fallback_to_local_layer(lam):bad_refs = [(wrong_region, "ResourceNotFoundException"),- (wrong_account, "AccessDeniedException"),(wrong_service, "ValidationException"),(missing_version, "ValidationException"),]@@ -3521,6 +3518,13 @@ def test_lambda_layer_version_arn_errors_do_not_fallback_to_local_layer(lam):lam.get_layer_version_by_arn(Arn=layer_ref)assert exc.value.response["Error"]["Code"] == expected_code+ # The same name in another account is a layer MiniStack does not hold: it reads+ # as an empty version, never as this account's content (#2313 maintainer (3)).+ other = lam.get_layer_version_by_arn(Arn=wrong_account)+ other.pop("ResponseMetadata")+ assert other == {"LayerArn": wrong_account.rsplit(":", 1)[0], "LayerVersionArn": wrong_account,+ "Version": pub["Version"], "Content": {"CodeSize": 0}}+same_layer = lam.get_layer_version_by_arn(Arn=arn)assert same_layer["LayerVersionArn"] == arn@@ -4828,6 +4832,10 @@ def test_esm_response_no_function_name_field(lam, sqs):sqs.delete_queue(QueueUrl=q_url)+# Cross-account layers (#2313). Capture keys refer to the AWS captures listed in the issue's+# evidence comment: "C.." (lambda-public-layer-accounts), "U.." (2313-uncertainties, -2),+# "X:.." (2313-uncertainties-4) and "Y:.." (2313-uncertainties-5). "Maintainer (n)" is a+# decision on the issue for what MiniStack cannot know offline.# 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"@@ -4915,27 +4923,52 @@ _DENIED = "AccessDeniedException"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("ungranted", None, None, _DENIED, _DENIED, id="no-grant"), # C11pytest.param("granted-elsewhere", "111111111111", None, _DENIED, _DENIED, id="grant-to-another-account"),+ # A layer MiniStack holds refuses a version it does not hold, as AWS refuses a+ # version that does not exist (C5, U10) (maintainer (1)).pytest.param("partly-seeded", "*", _foreign_arn("partly-seeded", 35), _DENIED, _DENIED,- id="missing-version-of-known-layer"),- # A name AWS does not publish, under the same account: the gate is the layer- # NAME, so this is still denied.- pytest.param(None, None, _foreign_arn("not-an-aws-extension", 38), _DENIED, _DENIED,- id="unknown-foreign-layer"),- # An extension AWS publishes itself carries a public grant on AWS, so a- # template referencing it deploys there. It resolves here too; the bytes are- # not available offline, so CodeSize is 0 and the extension does not run.+ id="missing-version-of-held-layer"),+ # A layer MiniStack does not hold resolves as an empty version (maintainer (4)):+ # a public vendor layer (Datadog, C1) or an AWS extension (C3) answers 200 on+ # AWS, and offline a made-up ARN looks the same as a real one, though AWS+ # refuses the made-up one (C5, C6). CodeSize is 0 and the layer does not run.+ pytest.param(None, None, _foreign_arn("Datadog-Extension-ARM", 101, "464622532012"), None, None,+ id="unheld-vendor-layer"),+ pytest.param(None, None, _foreign_arn("example-missing", 99999, "111111111111"), None, None,+ id="unheld-made-up-layer"),+ # C3 captured :68 on AWS (200); any version resolves here (maintainer (4)).pytest.param(None, None, _AWS_MANAGED_LAYER, None, None, id="aws-published-extension"),+ # Another region is refused with the same denial on read and attach (C13, U6:cross-region).pytest.param(None, None, _OTHER_REGION_LAYER, _DENIED, _DENIED, id="another-region"),+ # Versions and names that cannot exist on AWS are refused with the same denial,+ # on read and attach (X:version-0, X:version-leading-zero, X:name-141-chars).+ pytest.param(None, None, _foreign_arn("Datadog-Extension-ARM", 0, "464622532012"), _DENIED, _DENIED,+ id="version-0"),+ pytest.param(None, None, _foreign_arn("Datadog-Extension-ARM", "0101", "464622532012"), _DENIED, _DENIED,+ id="version-leading-zero"),+ pytest.param(None, None, _foreign_arn("a" * 141, 1, "464622532012"), _DENIED, _DENIED, id="name-141-chars"),+ # An ARN AWS rejects on shape (X:account-11-digits: 400 ValidationException) is not+ # resolved empty; it keeps the denial it had before #2313.+ pytest.param(None, None, _foreign_arn("Datadog-Extension-ARM", 101, "46462253201"), _DENIED, _DENIED,+ id="malformed-account-keeps-denial"),+ # 12 non-ASCII digits: AWS's \d is ASCII, so presumably 400 there too (inferred from X:account-letters).+ pytest.param(None, None, _foreign_arn("Datadog-Extension-ARM", 101, "\u0664" * 12), _DENIED, _DENIED,+ id="non-ascii-digit-account-keeps-denial"),+ pytest.param(None, None, _foreign_arn("Datadog.Extension", 101, "464622532012"), _DENIED, _DENIED,+ id="name-with-dot-keeps-denial"), # X:name-with-dot (AWS: 400 ValidationException)+ pytest.param(None, None, _foreign_arn("Datadog-Extension-ARM", 101, "464622532012").replace("arn:aws:", "arn:aws-cn:"),+ _DENIED, _DENIED, id="partition-cn-keeps-denial"), # X:partition-cn (AWS: 400 / 500)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. Without- one — no statement, a statement naming another account, or no layer of that- name at all — the attachment and the read are denied. The resolver does not- read AUTH (see the next test)."""+ """A held foreign layer answers through its grant: AWS resolves a `*` grant (C12)+ and denies an unshared layer (C11); account and root-ARN grants and a grant to+ another account follow the policy evaluator. Denials carry AWS's+ AccessDeniedException message (C11, C5, C13). A layer MiniStack does not hold+ resolves empty (maintainer (4)). The resolver does not read AUTH (see the next+ tests)."""arn = arn or _foreign_arn(layer_name)with _foreign_layer(layer_name, granted_to=granted_to):version_config, attach, payload, read = _layer_verdicts(arn)@@ -4952,6 +4985,133 @@ def test_lambda_cross_account_layer_verdicts(layer_name, granted_to, arn, attachassert not [key for key in payload if key.startswith("_")]+_UNHELD_LAYER = "arn:aws:lambda:us-east-1:464622532012:layer:Datadog-Extension-ARM:101"+++def test_lambda_unheld_cross_account_layer_reads_as_empty_version(caplog):+ """GetLayerVersionByArn, and GetLayerVersion with the layer ARN as LayerName,+ answer the same body, as on AWS (C14 calls[0] equals C1 calls[0]; maintainer (2)).+ The body is the maintainer's empty layer (maintainer (3)): LayerArn derived from+ the ARN as AWS derives it (C1), LayerVersionArn, Version, and Content.CodeSize 0+ where AWS reports the real size. What only the publisher knows (C1: CodeSha256,+ Location, CreatedDate, Description, CompatibleArchitectures, signing ARNs) is+ left out. The log says the layer will not run."""+ import ministack.services.lambda_svc as _lsvc+ from ministack.core.responses import request_scope++ expected = {"LayerArn": _UNHELD_LAYER.rsplit(":", 1)[0], "LayerVersionArn": _UNHELD_LAYER,+ "Version": 101, "Content": {"CodeSize": 0}}+ with request_scope(_CALLER_ACCOUNT, _FOREIGN_REGION), caplog.at_level("WARNING", logger="lambda"):+ by_arn = _lsvc._get_layer_version_by_arn(_UNHELD_LAYER)+ by_name = _lsvc._get_layer_version(_UNHELD_LAYER.rsplit(":", 1)[0], 101)+ for status, _headers, body in (by_arn, by_name):+ assert status == 200, body+ assert json.loads(body) == expected+ assert any("is not held by MiniStack" in record.getMessage() and _UNHELD_LAYER in record.getMessage()+ for record in caplog.records)+++def test_lambda_unheld_cross_account_layer_attaches(monkeypatch):+ """CreateFunction, GetFunction, GetFunctionConfiguration and+ UpdateFunctionConfiguration accept an unheld layer, as AWS does (C7 to C10: 201+ and 200). AWS reports its real CodeSize and, for a signed layer, both signing+ ARNs (C7 to C10). MiniStack reports {Arn, CodeSize: 0} (maintainer (3)), the key+ set AWS gives an unsigned layer (C12)."""+ import ministack.app as app_mod+ from ministack.core.responses import request_scope+ from ministack.services import lambda_svc++ # In process, so the execution role is not created; AUTH=true would refuse it.+ monkeypatch.setattr(app_mod, "AUTH", False)+ monkeypatch.setattr(lambda_svc, "_functions", AccountRegionScopedDict())+ x86_layer = "arn:aws:lambda:us-east-1:464622532012:layer:Datadog-Extension:101"+ with request_scope(_CALLER_ACCOUNT, _FOREIGN_REGION):+ status, _headers, body = lambda_svc._create_function({+ "FunctionName": "unheld-layer-fn", "Runtime": "python3.12", "Role": _LAMBDA_ROLE,+ "Handler": "index.handler", "Layers": [_UNHELD_LAYER],+ "Code": {"ZipFile": base64.b64encode(_make_zip("def handler(e, c): return 1")).decode()}})+ assert status == 201, body+ created = json.loads(body)+ assert created["Layers"] == [{"Arn": _UNHELD_LAYER, "CodeSize": 0}]+ _status, _headers, body = lambda_svc._get_function("unheld-layer-fn")+ assert json.loads(body)["Configuration"]["Layers"] == [{"Arn": _UNHELD_LAYER, "CodeSize": 0}]+ status, _headers, body = lambda_svc._update_config(+ "unheld-layer-fn", {"Layers": [x86_layer]})+ assert status == 200, body+ assert json.loads(body)["Layers"] == [{"Arn": x86_layer, "CodeSize": 0}]+ _status, _headers, body = lambda_svc._get_function_config("unheld-layer-fn")+ assert json.loads(body)["Layers"] == [{"Arn": x86_layer, "CodeSize": 0}]+++_LAYER_ARN_PREFIX = "arn:aws:lambda:us-east-1:464622532012:layer:" # 44 characters++[email protected](("layer_name", "version", "expected_status"), [+ pytest.param(_LAYER_ARN_PREFIX + "a" * 96, 1, 200, id="arn-140-chars"), # Y:arn-total-140 (AWS 403; M(4))+ pytest.param(_LAYER_ARN_PREFIX + "a" * 97, 1, 400, id="arn-141-chars"), # Y:arn-total-141+ pytest.param(_LAYER_ARN_PREFIX + "a" * 97, 0, 400, id="arn-141-chars-version-0"), # Y:arn-total-141-version-0+ pytest.param("a" * 141, 1, 400, id="bare-name-141-chars"), # Y:bare-name-141+ pytest.param("a" * 140, 1, 404, id="bare-name-140-chars"), # Y:bare-name-140+])+def test_lambda_get_layer_version_layer_name_length(lam, layer_name, version, expected_status):+ """GetLayerVersion limits the whole LayerName, a layer ARN included, to 140+ characters, before it checks the version (Y:*). A layer ARN of 140 characters+ goes on to the by-ARN path, where an unheld layer resolves empty (maintainer (4);+ AWS answers 403 for this made-up name, Y:arn-total-140)."""+ if expected_status == 200:+ assert lam.get_layer_version(LayerName=layer_name, VersionNumber=version)["Content"] == {"CodeSize": 0}+ return+ with pytest.raises(ClientError) as exc:+ lam.get_layer_version(LayerName=layer_name, VersionNumber=version)+ error = exc.value.response+ assert error["ResponseMetadata"]["HTTPStatusCode"] == expected_status+ if expected_status == 400:+ assert error["Error"]["Code"] == "ValidationException"+ assert error["Error"]["Message"] == (+ f"1 validation error detected: Value '{layer_name}' at 'layerName' failed to satisfy "+ "constraint: Member must have length less than or equal to 140")+ else:+ assert error["Error"]["Message"] == "The resource you requested does not exist."+++def test_lambda_get_layer_version_by_arn_has_no_layer_name_limit(lam):+ """GetLayerVersionByArn has no LayerName member, so a 141-character name in+ this account's ARN keeps the not-found answer it had before. AWS applies no+ length check on the by-ARN path (X:name-141-chars, Y:arn-total-141 by_arn: 403+ for a foreign ARN, past validation); the own-account 404 is main's behavior,+ inferred to match, not captured."""+ arn = f"arn:aws:lambda:us-east-1:{_CALLER_ACCOUNT}:layer:{'a' * 141}:1"+ with pytest.raises(ClientError) as exc:+ lam.get_layer_version_by_arn(Arn=arn)+ assert exc.value.response["Error"]["Code"] == "ResourceNotFoundException"+++def test_lambda_held_cross_account_layer_with_every_version_deleted_is_denied():+ """A layer MiniStack holds whose versions were all deleted is still held, so the+ reference is denied (maintainer (1)), as AWS denies a version that does not+ exist (C5)."""+ arn = _foreign_arn("all-deleted")+ with _foreign_layer("all-deleted", granted_to="*") as version_config:+ version_config["_deleted"] = True+ _config, attach, payload, read = _layer_verdicts(arn)+ assert attach == read == (_DENIED, _layer_access_denied(arn))+ assert payload is None+++def test_lambda_layer_attached_empty_never_loads_content_later():+ """A layer attached while MiniStack did not hold it stays empty at cold start,+ even if a version is published under that ARN afterwards: its content was never+ granted at attach time. MiniStack-only, following maintainer (0) ("not run");+ nothing on AWS corresponds."""+ import ministack.services.lambda_svc as _lsvc++ arn = _foreign_arn("published-later")+ with _foreign_layer("published-later", granted_to="*") as version_config:+ version_config["_zip_data"] = b"layer-bytes"+ assert _lsvc._resolve_layer_zip({"Arn": arn, "CodeSize": 0}) is None+ assert _lsvc._resolve_layer_zip({"Arn": arn, "CodeSize": _FOREIGN_CODE_SIZE}) == b"layer-bytes"++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: thelayer policy decides, and a denial names that user the way AWS does."""