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
feat(iam): evaluate resource policies under AUTH=true (SQS, SNS, S3, Lambda, Secrets Manager, ECR, KMS, API Gateway) (#2156)
iot-rocket422103b246a6
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex c9f27e51..1d481997 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -8,6 +8,20 @@ Versioning follows [Semantic Versioning](https://semver.org/).## [Unreleased]### Added+- **Auth — REST API resource policies are evaluated under `AUTH=true`** — an API Gateway resource policy took no part in the decision; for an `execute-api:Invoke` a statement naming the calling user or role now allows the call without an identity policy, a statement naming only the account still needs one, a Deny wins over an identity Allow, and a call without a SigV4 signature (none, or a bearer token) to a method without authorization passes only when the policy, if any, allows everyone, else it answers `ACCESS_DENIED` with API Gateway's message. Contributed by @iot-rocket.+- **Auth — KMS key policies are evaluated under `AUTH=true`** — a key policy took no part in the decision; it now has to allow even in the key's own account: a statement naming the calling user or role allows the call without an identity policy, identity policies count only when the key policy has a statement for the account (the default key policy does), and a Deny wins over an identity Allow. Contributed by @iot-rocket.+- **Auth — ECR repository policies count under `AUTH=true`** — a repository policy took no part in the decision; a statement naming the calling user or role now allows the call without an identity policy, a statement naming only the account still needs one, and a Deny wins over an identity Allow. Contributed by @iot-rocket.+- **Auth — Secrets Manager resource policies count under `AUTH=true`** — a secret's resource policy took no part in the decision; a statement naming the calling user or role now allows the call without an identity policy, a statement naming only the account still needs one, and a Deny wins over an identity Allow. Contributed by @iot-rocket.+- **Auth — Lambda function policies count under `AUTH=true`** — an `AddPermission` statement naming the calling user or role did not let a caller without an identity policy in; it now allows the actions it names (`InvokeFunction`, `GetFunction`, ...), while a statement naming only the account still needs an identity Allow, and a call that names the function by ARN is checked against that ARN. Contributed by @iot-rocket.+- **Auth — bucket policies count under `AUTH=true` in the owner's account** — a bucket policy was consulted only for another account's requests; in the owner's account a statement naming the calling user or role now allows the request without an identity policy, a statement naming only the account still needs one, and a Deny wins over an identity Allow, CDK's `aws:SecureTransport` Deny on the bootstrap bucket included. Contributed by @iot-rocket.+- **Auth — queue and topic policies count under `AUTH=true`** — a queue or topic policy statement naming the calling user or role did not let a caller without an identity policy in; in the owner's account it now allows the call, a statement naming only the account still needs an identity Allow, and across accounts both have to allow. A denial answers `AuthorizationError` on SNS and reports `AccessDenied` to SDKs on SQS, its message says "with an explicit deny in a resource-based policy" when the resource's policy denied, and the check reads the queue of the account the `QueueUrl` names. Contributed by @iot-rocket.+- **Auth — the request time of a header-signed request is checked** — under `AUTH=true` a request signed with an IAM user or STS session key was served whatever its time; one signed more than 15 minutes (STS, IAM, SNS, SQS, DynamoDB, S3, ECR, RDS, ElastiCache) or 5 minutes (the default for other services) from the server clock answers `SignatureDoesNotMatch` / `InvalidSignatureException` with AWS's `Signature expired` or `Signature not yet current` message, `RequestTimeTooSkewed` from S3 and `AuthFailure` from EC2. Contributed by @iot-rocket.+- **Auth — the session token of a header-signed request is checked** — under `AUTH=true` an STS session key sent without its token was accepted and now answers as an unknown key, and a wrong token, or a token with an IAM user key, answers `InvalidClientTokenId` (`UnrecognizedClientException` from JSON services, `InvalidToken` 400 from S3), as on AWS. Contributed by @iot-rocket.+- **Auth — header signatures are verified for IAM user and STS session keys** — under `AUTH=true` a request signed with such a key and the wrong secret, or changed after signing, was served; it now answers `SignatureDoesNotMatch` (or the service's `InvalidSignatureException`), an `Authorization` header without its `Signature` or `SignedHeaders` answers `IncompleteSignature` (Lambda `MissingAuthenticationTokenException`, S3 `AuthorizationHeaderMalformed`) and a credential date other than the request date `SignatureDoesNotMatch` (S3 `AuthorizationHeaderMalformed`), S3 unsigned, streaming and signed-chunk payloads are checked the same way, and the root key still accepts any secret. Contributed by @iot-rocket.++### Fixed+- **S3 — presigned URLs keep AWS's time limits under `AUTH=true`** — an `X-Amz-Expires` over 604800 seconds or not a number, or a malformed `X-Amz-Date`, answers 400 `AuthorizationQueryParametersError`, and a URL dated more than 15 minutes ahead answers 403 `AccessDenied` `Request is not yet valid`, where they were served. Contributed by @iot-rocket.+- **Auth — credential failures in the service's protocol** — under `AUTH=true` an unknown, inactive or expired access key answered `UnrecognizedClientException` 403 from every service; it now gets the code, status and `Content-Type` AWS sends for the service's protocol, for example `InvalidClientTokenId` 403 from IAM and SQS, `UnrecognizedClientException` 400 from DynamoDB, `InvalidAccessKeyId` 403 from S3 and `AuthFailure` 401 from EC2. Contributed by @iot-rocket.- **STS — session policies and `GetFederationToken`** — `AssumeRole` ignored `Policy` and `PolicyArns` and `GetFederationToken` answered `InvalidAction`; under `AUTH=true` a role session now gets only what both the role and its session policies allow, a `Deny` in them denies, and `AssumeRole` rejects a malformed policy with `MalformedPolicyDocument` and an unknown policy ARN with `ValidationError`. `GetFederationToken` is added: its federated user gets the calling user's permissions within the session policies (none without one) and its `Tags`, not the user's tags, as `aws:PrincipalTag/*`; it checks its `Name`, policies and tags, and under `AUTH=true` a temporary caller answers `AccessDenied`. Contributed by @iot-rocket.- **IAM — permissions boundaries are enforced** — the boundaries of users and roles were stored and never applied; under `AUTH=true` a boundary now limits what the identity policies allow and a `Deny` in it denies, a boundary must name a known managed policy (`ValidationError` for a malformed ARN, CloudFormation `AWS::IAM::User` included), deleting an absent boundary answers `NoSuchEntity`, and a policy in use as a boundary cannot be deleted. `ListUsers` and `ListRoles` leave the boundary out, `ListEntitiesForPolicy` lists boundary users and roles and honours `PolicyUsageFilter`, and a managed policy reports `PermissionsBoundaryUsageCount`. Contributed by @iot-rocket.diff --git a/ministack/app.py b/ministack/app.pyindex 0d838520..1c524ad6 100644--- a/ministack/app.py+++ b/ministack/app.py@@ -2235,7 +2235,8 @@ def _enforce_data_plane(response = auth_error_response(denied) if auth_error_response else Nonereturn response or _credential_failure(service, iam_action, request_id, denied, headers)return access_denied_response(service, iam_action, denied.principal_arn, request_id, headers=headers,- explicit_deny=denied.decision == "Deny")+ explicit_deny=denied.decision == "Deny",+ resource_policy_arn=denied.resource_policy_arn)return None@@ -2725,6 +2726,7 @@ async def _dispatch_service_request(return access_denied_response(service, iam_action, denied.principal_arn, request_id, headers=headers,resource_arn=resource_arn, explicit_deny=denied.decision == "Deny",+ resource_policy_arn=denied.resource_policy_arn,)handler = SERVICE_HANDLERS.get(service)diff --git a/ministack/core/iam_actions.py b/ministack/core/iam_actions.pyindex 7fc51690..e70e86a8 100644--- a/ministack/core/iam_actions.py+++ b/ministack/core/iam_actions.py@@ -769,6 +769,9 @@ _SERVICE_PROTOCOL: dict[str, str] = {# Everything else defaults to JSON}+# Services that name an authorization failure with their own code.+_DENIED_CODES: dict[str, str] = {"sns": "AuthorizationError"}+# Services whose Query API also answers JSON / smithy-rpc-v2-cbor, where the# error has to come back in the encoding the request arrived in._CBOR_CAPABLE = frozenset({"monitoring"})@@ -907,7 +910,9 @@ def extract_resource_arn(service: str, method: str, path: str,if "functions" in path_parts:fi = path_parts.index("functions")if fi + 1 < len(path_parts):- func_name = path_parts[fi + 1]+ func_name = unquote(path_parts[fi + 1])+ if func_name.startswith("arn:"):+ return func_namereturn f"arn:aws:lambda:{region}:{account_id}:function:{func_name}"if "layers" in path_parts:li = path_parts.index("layers")@@ -930,11 +935,13 @@ def extract_resource_arn(service: str, method: str, path: str,# POST /{account_id}/{queue_name}parts = [p for p in path.split("/") if p]if len(parts) >= 2 and parts[-2].isdigit():- queue_url = parts[-1]+ queue_url = "/".join(parts[-2:])if queue_url:- queue_name = queue_url.rstrip("/").split("/")[-1]- if queue_name:- return f"arn:aws:sqs:{region}:{account_id}:{queue_name}"+ # The queue belongs to the account its URL names, not always the caller's.+ parts = queue_url.rstrip("/").split("/")+ owner = parts[-2] if len(parts) >= 2 and re.fullmatch(r"\d{12}", parts[-2]) else account_id+ if parts[-1]:+ return f"arn:aws:sqs:{region}:{owner}:{parts[-1]}"# QueueName param (CreateQueue, GetQueueUrl)queue_name = _param(body, query_params, "QueueName")if queue_name:@@ -1974,10 +1981,27 @@ def _auth_failure(service: str, code: str, message: str, headers: dict) -> tuplereturn json_code, 400 if headers.get("x-amz-target") else 403, message+def _resource_policy_denial(service: str, action: str, principal_arn: str, resource_arn: str) -> str:+ """A denial's message when an explicit Deny in the resource's own policy decided, in the service's spelling."""+ prefix, _, name = action.partition(":")+ if service == "sqs":+ action = f"{prefix}:{name.lower()}"+ elif service == "sns":+ action = f"SNS:{name}"+ elif service == "s3":+ resource_arn = f'"{resource_arn}"'+ elif service == "apigateway":+ account = resource_arn.split(":")[4]+ resource_arn = resource_arn.replace(f":{account}:", f":********{account[-4:]}:", 1)+ return (f"User: {principal_arn} is not authorized to perform: {action} on resource: {resource_arn} "+ "with an explicit deny in a resource-based policy")++def access_denied_response(service: str, action: str, principal_arn: str,request_id: str, *, error_code: str = "",message: str = "", headers: dict | None = None,- resource_arn: str = "*", explicit_deny: bool = False) -> tuple:+ resource_arn: str = "*", explicit_deny: bool = False,+ resource_policy_arn: str = "") -> tuple:"""Format a denial matching the service's protocol.A denial the caller's SDK cannot parse is barely better than no denial: it@@ -2000,13 +2024,15 @@ def access_denied_response(service: str, action: str, principal_arn: str,400, {"Content-Type": "application/x-amz-json-1.1"},json.dumps({"__type": "AccessDeniedException", "Message": message}).encode(),)+ if not message and explicit_deny and resource_policy_arn:+ message = _resource_policy_denial(service, action, principal_arn, resource_policy_arn)if not message:reason = ("with an explicit deny in an identity-based policy" if explicit_denyelse f"because no identity-based policy allows the {action} action")message = f"User: {principal_arn} is not authorized to perform: {action} {reason}"- code = error_code or "AccessDenied"+ code = error_code or _DENIED_CODES.get(service, "AccessDenied")status = 403if code in _AUTH_FAILURES:code, status, message = _auth_failure(service, code, message, headers or {})@@ -2075,11 +2101,11 @@ def access_denied_response(service: str, action: str, principal_arn: str,"__type": json_type,"message": message,})- return (- status,- {- "Content-Type": "application/x-amz-json-1.0",- "x-amzn-errortype": json_type,- },- body.encode(),- )+ reply_headers = {+ "Content-Type": "application/x-amz-json-1.0",+ "x-amzn-errortype": json_type,+ }+ if service == "sqs":+ # awsQueryCompatible: SDKs report the legacy code from this header.+ reply_headers["x-amzn-query-error"] = f"{code};Sender"+ return status, reply_headers, body.encode()diff --git a/ministack/core/iam_evaluator.py b/ministack/core/iam_evaluator.pyindex f7b3566d..e1fcfb6d 100644--- a/ministack/core/iam_evaluator.py+++ b/ministack/core/iam_evaluator.py@@ -15,6 +15,7 @@ Evaluation order:import contextvarsimport datetime as _dtimport hmac+import importlibimport ipaddressimport jsonimport logging@@ -67,6 +68,7 @@ class EvalResult:principal_arn: str = ""matched_sid: str = ""reason: str = ""+ resource_policy_arn: str = "" # set when the resource's own policy denied@dataclass@@ -681,8 +683,22 @@ def _service_principal_matches(principal: Any, service: str) -> bool:if isinstance(s, str))+_ACCOUNT_PRINCIPAL = re.compile(r"\d{12}|arn:aws[a-z-]*:iam::\d{12}:root")+++def _names_caller(principal: Any, caller_arn: str) -> bool:+ """Whether a statement Principal names the caller itself (its ARN, its role, or ``*``), not only its account."""+ if isinstance(principal, dict):+ principal = principal.get("AWS", [])+ if isinstance(principal, str):+ principal = [principal]+ return any(isinstance(p, str) and not _ACCOUNT_PRINCIPAL.fullmatch(p)+ and _principal_matches({"AWS": p}, caller_arn) for p in principal)++def evaluate_resource_policy(doc: str | dict | None, ctx: EvalContext,- service: str | None = None) -> EvalResult:+ service: str | None = None,+ named_only: bool = False) -> EvalResult:"""Evaluate a resource-based policy for the principal in *ctx*.Such a document names the principals it applies to, so a statement counts@@ -707,7 +723,10 @@ def evaluate_resource_policy(doc: str | dict | None, ctx: EvalContext,if not isinstance(stmt, dict):continueprincipal = stmt.get("Principal", {})- if isinstance(principal, dict):+ if named_only:+ if _names_caller(principal, ctx.principal_arn):+ applicable.append(stmt)+ elif isinstance(principal, dict):if _principal_matches({"AWS": principal.get("AWS", [])},ctx.principal_arn):applicable.append(stmt)@@ -718,6 +737,56 @@ def evaluate_resource_policy(doc: str | dict | None, ctx: EvalContext,return evaluate(ctx, [parse_policy_document({"Statement": applicable})])+def combine_resource_policy(identity: EvalResult, ctx: EvalContext,+ policy: str | dict | None, owner_account: str | None,+ required: bool = False) -> EvalResult:+ """Combine an identity decision with the resource's own policy: a Deny in either wins."""+ # In the owner's account an Allow in either suffices, but a resource statement naming+ # only the account delegates to identity policies; across accounts both must allow.+ # With *required* (a KMS key policy) the resource policy must allow in the owner's account too.+ if identity.decision == "Deny":+ return identity+ resource = evaluate_resource_policy(policy, ctx)+ if resource.decision == "Deny":+ resource.resource_policy_arn = ctx.resource_arn+ return resource+ same_account = owner_account in (None, ctx.principal_account)+ if identity.decision == "Allow" and (+ resource.decision == "Allow" or (same_account and not required)):+ return identity+ if same_account and resource.decision == "Allow":+ named = evaluate_resource_policy(policy, ctx, named_only=True)+ if named.decision == "Allow":+ return named+ return resource if identity.decision == "Allow" else identity+++# Services whose resources carry their own policy: the module and the function+# returning ``(policy, owner account)`` for a resource ARN, or None.+_RESOURCE_POLICY_LOOKUPS = {+ "sqs": ("sqs", "queue_policy_for_arn"),+ "sns": ("sns", "topic_policy_for_arn"),+ "s3": ("s3", "bucket_policy_for_arn"),+ "lambda": ("lambda_svc", "function_policy_for_arn"),+ "secretsmanager": ("secretsmanager", "secret_policy_for_arn"),+ "ecr": ("ecr", "repository_policy_for_arn"),+ "kms": ("kms", "key_policy_for_arn"),+ "apigateway": ("apigateway_v1", "rest_api_policy_for_arn"),+}++# A key policy must allow even the owner's own users and roles.+_POLICY_REQUIRED = frozenset({"kms"})+++def _resource_policy(service: str, resource_arn: str) -> tuple | None:+ """The request resource's own policy and owner account, when its service keeps one."""+ lookup = _RESOURCE_POLICY_LOOKUPS.get(service)+ if lookup is None or not resource_arn.startswith("arn:"):+ return None+ module = importlib.import_module(f"ministack.services.{lookup[0]}")+ return getattr(module, lookup[1])(resource_arn)++# ---------------------------------------------------------------------------# Principal resolution# ---------------------------------------------------------------------------@@ -1336,7 +1405,10 @@ def enforce(access_key_id: str, iam_action: str, service: str,principal_keys=principal.keys,)- result = evaluate(ctx, principal.policies, *principal.limits)+ result = evaluate(ctx, principal.policies)+ found = _resource_policy(service, resource_arn)+ if found is not None:+ result = combine_resource_policy(result, ctx, *found, required=service in _POLICY_REQUIRED)if result.decision == "Allow":return Nonediff --git a/ministack/services/apigateway_v1.py b/ministack/services/apigateway_v1.pyindex 7eb08935..d69709ec 100644--- a/ministack/services/apigateway_v1.py+++ b/ministack/services/apigateway_v1.py@@ -907,6 +907,51 @@ def find_api_scope(api_id):return None+def rest_api_policy_for_arn(resource_arn):+ """The REST API's resource policy, ``execute-api:/`` expanded, and owner account, for the identity check."""+ parts = resource_arn.split(":", 5)+ if len(parts) < 6 or parts[2] != "execute-api":+ return None+ region, account_id, api_id = parts[3], parts[4], parts[5].split("/", 1)[0]+ home = region+ api = _rest_apis.get_scoped(account_id, region, api_id)+ if api is None:+ # Signed for another region than the API's: its policy still applies, read as the request's ARN.+ scope = find_api_scope(api_id)+ if scope is None:+ return None+ home = scope[1]+ api = _rest_apis.get_scoped(account_id, home, api_id) or {}+ policy = api.get("policy") or ""+ if not isinstance(policy, str):+ policy = json.dumps(policy)+ prefix = f"arn:aws:execute-api:{region}:{account_id}:{api_id}/"+ policy = policy.replace('"execute-api:/', f'"{prefix}')+ if home != region:+ policy = policy.replace(f"arn:aws:execute-api:{home}:{account_id}:{api_id}/", prefix)+ return policy, account_id+++def _anonymous_policy_error(api_id, stage_name, method, path, headers, account_id, region):+ """ACCESS_DENIED for a call without SigV4 that the REST API's resource policy does not allow."""+ from ministack.app import AUTH+ from ministack.core.iam_evaluator import EvalContext, evaluate_resource_policy++ if not AUTH or _header_ci(headers, "authorization").startswith("AWS4-"):+ return None+ arn = execute_api_arn(region, account_id, api_id, stage_name, method, path)+ policy = (rest_api_policy_for_arn(arn) or ("",))[0]+ ctx = EvalContext("*", "Anonymous", "", "execute-api:Invoke", arn, region)+ decision = evaluate_resource_policy(policy, ctx).decision if policy else "Allow"+ if decision == "Allow":+ return None+ reason = ("with an explicit deny in a resource-based policy" if decision == "Deny"+ else "because no resource-based policy allows the execute-api:Invoke action")+ shown = arn.replace(f":{account_id}:", f":********{account_id[-4:]}:", 1)+ return _gw_error("ACCESS_DENIED",+ f"User: anonymous is not authorized to perform: execute-api:Invoke on resource: {shown} {reason}")++def find_domain_scope(domain_name):"""Return (account_id, region, stored_name) owning a custom domain withinthe ambient account.@@ -1892,7 +1937,8 @@ async def _authorize_request_v1("""auth_type = (method_obj.get("authorizationType") or "NONE").upper()if auth_type in ("", "NONE"):- return None, None+ return _anonymous_policy_error(+ api_id, stage_name, method, request_path, headers, owner_account_id, owner_region), Noneif auth_type == "AWS_IAM":# Signatures are verified only under AUTH; here match AWS only to the extent# that a request with no Authorization header is rejected as unauthenticated.diff --git a/ministack/services/ecr.py b/ministack/services/ecr.pyindex 5b7653a1..53507e43 100644--- a/ministack/services/ecr.py+++ b/ministack/services/ecr.py@@ -425,6 +425,14 @@ def _get_authorization_token(data):})+def repository_policy_for_arn(resource_arn: str) -> tuple[str, str] | None:+ """The repository policy and owner account, for the identity check."""+ name = resource_arn.partition(":repository/")[2]+ if name not in _repositories:+ return None+ return _repo_policies.get(name) or "", get_account_id()++def _get_repository_policy(data):name = data.get("repositoryName", "")if name not in _repositories:diff --git a/ministack/services/kms.py b/ministack/services/kms.pyindex 10610f99..71bca6ba 100644--- a/ministack/services/kms.py+++ b/ministack/services/kms.py@@ -1500,7 +1500,7 @@ def _stamp_alias(alias_arn, created):# ---- Grants ----## Grants are stored and listed, but MiniStack does not evaluate them when-# authorizing other calls, the same way key policies are not evaluated.+# authorizing other calls._GRANT_OPERATIONS = {"Decrypt", "Encrypt", "GenerateDataKey", "GenerateDataKeyWithoutPlaintext",@@ -1746,6 +1746,14 @@ def _get_key_rotation_status(data):# ---- Key Policy ----+def key_policy_for_arn(resource_arn: str) -> tuple[str, str] | None:+ """The key policy and owner account, for the identity check."""+ rec = _resolve_key(resource_arn)+ if not rec:+ return None+ return rec.get("Policy") or "", get_account_id()++def _get_key_policy(data):rec = _resolve_key(data.get("KeyId", ""))if not rec:diff --git a/ministack/services/lambda_svc.py b/ministack/services/lambda_svc.pyindex bec7a143..5a3496a8 100644--- a/ministack/services/lambda_svc.py+++ b/ministack/services/lambda_svc.py@@ -6129,6 +6129,15 @@ def _remove_permission(return 204, {}, b""+def function_policy_for_arn(resource_arn: str) -> tuple[dict, str] | None:+ """The function's resource policy and owner account, for the identity check."""+ _, sep, ref = resource_arn.partition(":function:")+ func = _functions.get(_resolve_request_scoped_name(unquote(ref))) if sep else None+ if func is None:+ return None+ return func["policy"], get_account_id()++def _get_policy(func_name: str,query_params: dict | None = None,diff --git a/ministack/services/s3.py b/ministack/services/s3.pyindex 4640b0f5..064243ba 100644--- a/ministack/services/s3.py+++ b/ministack/services/s3.py@@ -834,6 +834,17 @@ def _bucket_owner_account(name: str) -> str | None:return None+def bucket_policy_for_arn(resource_arn: str) -> tuple[str, str] | None:+ """The bucket policy and owner for the identity check; ``_apply_bucket_scope`` gates foreign buckets."""+ if not resource_arn.startswith("arn:aws:s3:::"):+ return None+ bucket = resource_arn[len("arn:aws:s3:::"):].split("/", 1)[0]+ owner = get_account_id()+ if not _buckets.contains_scoped(owner, None, bucket):+ return None+ return _bucket_policies.get_scoped(owner, None, bucket) or "", owner++def _foreign_bucket_allows(owner_account: str, bucket_name: str, key: str,method: str, query_params: dict, caller: str) -> bool:"""Whether a caller who does not own the bucket may have this request.diff --git a/ministack/services/secretsmanager.py b/ministack/services/secretsmanager.pyindex 391f799e..57823488 100644--- a/ministack/services/secretsmanager.py+++ b/ministack/services/secretsmanager.py@@ -649,7 +649,9 @@ def _batch_get_secret_value(data, access_key=None):"Message": (f"User: {principal} is not authorized to perform: "f"secretsmanager:GetSecretValue on resource: {sid} "- + ("with an explicit deny in an identity-based policy"+ + ("with an explicit deny in a resource-based policy"+ if getattr(denied, "resource_policy_arn", "") else+ "with an explicit deny in an identity-based policy"if getattr(denied, "decision", "") == "Deny" else"because no identity-based policy allows the secretsmanager:GetSecretValue action")),@@ -1305,6 +1307,14 @@ def _replicate_secret_to_regions(data):# Resource policies# ---------------------------------------------------------------------------+def secret_policy_for_arn(resource_arn: str) -> tuple[str, str] | None:+ """The secret's resource policy and owner account, for the identity check."""+ secret = _secrets.get(resource_arn.partition(":secret:")[2][:-7])+ if not secret or secret["ARN"] != resource_arn:+ return None+ return _resource_policies.get(resource_arn) or "", get_account_id()++def _put_resource_policy(data):secret_id = data.get("SecretId")_, secret = _resolve(secret_id)diff --git a/ministack/services/sns.py b/ministack/services/sns.pyindex 1863fc81..e2aefb6e 100644--- a/ministack/services/sns.py+++ b/ministack/services/sns.py@@ -92,11 +92,6 @@ def _enforce_topic_policy(topic: dict, iam_action: str):every call passes, like the rest of the identity layer. Same-accountcallers then pass unless the Policy carries an explicit Deny for them;cross-account callers need an explicit Allow, like real SNS.-- Known boundary under AUTH=true: a caller with no identity Allow whose- access comes from this Policy alone is denied by the app-level identity- check before this resource check runs, where real SNS would allow the- union (same caveat as the queue check)."""from ministack.app import AUTHif not AUTH:@@ -124,6 +119,14 @@ def _enforce_topic_policy(topic: dict, iam_action: str):f"{iam_action} on resource: {topic_arn}", 403)+def topic_policy_for_arn(topic_arn: str) -> tuple[str, str] | None:+ """The topic's Policy and owner account, for the identity check."""+ topic = _topic_by_arn_any_scope(_normalize_arn(topic_arn))+ if topic is None:+ return None+ return topic.get("attributes", {}).get("Policy") or "", _topic_owner(topic)++def _get_topic(topic_arn: str, action: str | None = None):"""Resolve a topic by ARN, enforcing its Policy when *action* is given.diff --git a/ministack/services/sqs.py b/ministack/services/sqs.pyindex f1eae5c1..2e4d80d6 100644--- a/ministack/services/sqs.py+++ b/ministack/services/sqs.py@@ -118,12 +118,6 @@ def _enforce_queue_policy(q: dict, iam_action: str) -> None:Policy carries an explicit Deny for them. Cross-account callers need anexplicit Allow in the Policy, exactly like real SQS, which answersAccessDenied (403) otherwise.-- Known boundary under AUTH=true: a caller with no identity Allow whose- access comes from this Policy alone is denied by the app-level identity- check before this resource check runs, where real SQS would allow the- union. Lifting that needs the identity layer to defer to the resource- layer, which no AUTH=true server harness here can verify."""from ministack.app import AUTHif not AUTH:@@ -151,6 +145,14 @@ def _enforce_queue_policy(q: dict, iam_action: str) -> None:f"Access to the resource https://sqs.{get_region()}.amazonaws.com/ is denied.", 403)+def queue_policy_for_arn(queue_arn: str) -> tuple[str, str] | None:+ """The queue's Policy and owner account, for the identity check."""+ q = _queue_by_arn(queue_arn)+ if q is None:+ return None+ return q["attributes"].get("Policy") or "", _owner_from_queue_arn(queue_arn)[0]++def queue_policy_allows(queue_arn: str, service: str,source_arn: str, source_account: str) -> bool:"""Whether the queue's Policy lets an AWS service deliver to it.diff --git a/tests/conftest.py b/tests/conftest.pyindex a924f503..bf61db9c 100644--- a/tests/conftest.py+++ b/tests/conftest.py@@ -5,6 +5,7 @@ Pytest fixtures for MiniStack integration tests.import concurrent.futuresimport contextlibimport io+import jsonimport osimport socketimport statistics@@ -13,7 +14,7 @@ import timeimport urllib.requestimport uuidimport zipfile-from urllib.parse import urlparse+from urllib.parse import unquote, urlparseimport boto3import pytest@@ -112,6 +113,60 @@ def iot_test_ca(registration_code, common_name="ministack-test-ca"):return ca_pem, ca_key_pem, verification_pem+def iam_user(identity_policy=None):+ """An in-process IAM user with an access key in the default account: ``((key id, secret), arn)``."""+ from ministack.core.responses import get_account_id, request_scope+ from ministack.services import iam as iam_svc++ name = f"user-{uuid.uuid4().hex[:8]}"+ key = ("AKIA" + uuid.uuid4().hex[:16].upper(), uuid.uuid4().hex)+ arn = f"arn:aws:iam::{get_account_id()}:user/{name}"+ with request_scope(get_account_id(), REGION):+ iam_svc._users[name] = {"UserName": name, "Arn": arn, "UserId": "AIDA" + key[0][4:],+ "CreateDate": "2026-01-01", "Path": "/", "AttachedPolicies": [], "Tags": []}+ iam_svc._access_keys[key[0]] = {"UserName": name, "AccessKeyId": key[0], "SecretAccessKey": key[1],+ "Status": "Active", "CreateDate": "2026-01-01"}+ if identity_policy:+ iam_svc._user_inline_policies[name] = {"p": json.dumps(identity_policy)}+ return key, arn+++def auth(monkeypatch):+ """AUTH=true for the in-process app."""+ import ministack.app as app_mod++ monkeypatch.setattr(app_mod, "AUTH", True)+++def routed_request(key, service, method, path, body=b"", headers=None, host="localhost:4566"):+ """One in-process request through the whole app, SigV4-signed with *key* ``(key id, secret)`` unless it is None."""+ import asyncio++ from botocore.auth import S3SigV4Auth, SigV4Auth+ from botocore.awsrequest import AWSRequest+ from botocore.credentials import Credentials++ import ministack.app as app_mod++ request = AWSRequest(method, f"http://{host}{path}", data=body, headers={"host": host, **(headers or {})})+ if key:+ (S3SigV4Auth if service == "s3" else SigV4Auth)(Credentials(*key), service, REGION).add_auth(request)+ sent = []++ async def receive():+ return {"type": "http.request", "body": body, "more_body": False}++ async def send(message):+ sent.append(message)++ asyncio.run(app_mod.app({+ "type": "http", "method": method, "path": unquote(path), "raw_path": path.encode(), "query_string": b"",+ "headers": [(k.lower().encode(), v.encode()) for k, v in request.headers.items()]}, receive, send))+ return (sent[0]["status"], {k.decode().lower(): v.decode() for k, v in sent[0].get("headers", [])},+ b"".join(m.get("body", b"") for m in sent[1:]))++_SERIAL_TESTS = {"tests/test_athena.py::test_athena_queries_glue_backed_parquet","tests/test_rds.py::test_rds_pg_two_replicating_readers_provision_source_once",diff --git a/tests/test_apigatewayv1.py b/tests/test_apigatewayv1.pyindex a9a3a349..d639d6e2 100644--- a/tests/test_apigatewayv1.py+++ b/tests/test_apigatewayv1.py@@ -11,6 +11,7 @@ from urllib.parse import urlparseimport pytestimport yamlfrom botocore.exceptions import ClientError+from conftest import iam_user, routed_requestfrom ministack.core.responses import set_request_regionfrom ministack.services import apigateway_v1@@ -1213,6 +1214,92 @@ def test_apigwv1_execute_aws_iam_requires_auth_header(apigw_v1, lam):lam.delete_function(FunctionName=fname)+def _policy_api(policy, region="us-east-1"):+ """A deployed REST API with GET /iam (AWS_IAM) and GET /open (NONE), both MOCK, and *policy*."""+ set_request_region(region)+ data = {"name": f"rp-{_uuid_mod.uuid4().hex[:8]}"}+ if policy:+ data["policy"] = json.dumps(policy)+ api_id = json.loads(apigateway_v1._create_rest_api(data)[2])["id"]+ root_id = next(r["id"] for r in apigateway_v1._resources[api_id].values() if r["path"] == "/")+ for part, auth in (("iam", "AWS_IAM"), ("open", "NONE")):+ resource_id = json.loads(apigateway_v1._create_resource(api_id, root_id, {"pathPart": part})[2])["id"]+ apigateway_v1._put_method(api_id, resource_id, "GET", {"authorizationType": auth})+ apigateway_v1._put_integration(api_id, resource_id, "GET", {+ "type": "MOCK", "requestTemplates": {"application/json": '{"statusCode": 200}'}})+ apigateway_v1._put_method_response(api_id, resource_id, "GET", "200", {})+ apigateway_v1._put_integration_response(api_id, resource_id, "GET", "200", {})+ apigateway_v1._create_deployment(api_id, {"stageName": "s"})+ return api_id+++def _invoke(api_id, path, key=None, headers=None):+ """GET /s/<path> through the app, SigV4-signed with *key* or sent unsigned with *headers*."""+ return routed_request(key, "execute-api", "GET", f"/s/{path}", headers=headers,+ host=f"{api_id}.execute-api.localhost:4566")+++def _api_policy(*statements):+ return {"Version": "2012-10-17", "Statement": [+ {"Effect": effect, "Principal": principal, "Action": "execute-api:Invoke", "Resource": "execute-api:/*"}+ for effect, principal in statements]}+++_ACCOUNT = {"AWS": "arn:aws:iam::000000000000:root"}+_ALLOW_INVOKE = {"Statement": [{"Effect": "Allow", "Action": "execute-api:Invoke", "Resource": "*"}]}+++def test_api_policy_naming_the_user_allows_without_identity_policy(auth):+ key, user = iam_user()+ api_id = _policy_api(_api_policy(("Allow", {"AWS": user})))+ assert _invoke(api_id, "iam", key)[0] == 200+++def test_api_policy_naming_the_account_needs_an_identity_policy(auth):+ api_id = _policy_api(_api_policy(("Allow", _ACCOUNT)))+ key, _user = iam_user()+ assert _invoke(api_id, "iam", key)[0] == 403+ key, _user = iam_user(_ALLOW_INVOKE)+ assert _invoke(api_id, "iam", key)[0] == 200+++def test_api_policy_deny_beats_an_identity_allow(auth):+ key, user = iam_user(_ALLOW_INVOKE)+ api_id = _policy_api(_api_policy(("Allow", _ACCOUNT), ("Deny", {"AWS": user})))+ status, _headers, body = _invoke(api_id, "iam", key)+ assert status == 403+ assert json.loads(body)["message"] == (+ f"User: {user} is not authorized to perform: execute-api:Invoke on resource: "+ f"arn:aws:execute-api:us-east-1:********0000:{api_id}/s/GET/iam "+ "with an explicit deny in a resource-based policy")+++def test_api_policy_applies_to_a_call_signed_for_another_region(auth):+ key, user = iam_user(_ALLOW_INVOKE)+ try:+ api_id = _policy_api(_api_policy(("Allow", _ACCOUNT), ("Deny", {"AWS": user})), region="eu-west-1")+ finally:+ set_request_region("us-east-1")+ assert _invoke(api_id, "iam", key)[0] == 403+++def test_api_policy_applies_to_an_unsigned_call_on_a_method_without_authorization(auth):+ api_id = _policy_api(_api_policy(("Allow", _ACCOUNT)))+ status, headers, body = _invoke(api_id, "open")+ assert (status, headers["x-amzn-errortype"]) == (403, "AccessDeniedException")+ assert json.loads(body)["Message"] == (+ "User: anonymous is not authorized to perform: execute-api:Invoke on resource: "+ f"arn:aws:execute-api:us-east-1:********0000:{api_id}/s/GET/open "+ "because no resource-based policy allows the execute-api:Invoke action")+ assert _invoke(_policy_api(_api_policy(("Allow", "*"))), "open")[0] == 200+ assert _invoke(_policy_api(None), "open")[0] == 200+++def test_api_policy_treats_a_bearer_token_on_a_method_without_authorization_as_anonymous(auth):+ api_id = _policy_api(_api_policy(("Allow", _ACCOUNT)))+ assert _invoke(api_id, "open", headers={"authorization": "Bearer abc.def.ghi"})[0] == 403++def test_apigwv1_execute_lambda_proxy_multi_value_headers(apigw_v1, lam):"""Payload format 1.0 `multiValueHeaders` yields one header line per value.diff --git a/tests/test_ecr.py b/tests/test_ecr.pyindex fb998556..e5417e6b 100644--- a/tests/test_ecr.py+++ b/tests/test_ecr.py@@ -7,6 +7,7 @@ import boto3import pytestimport requestsfrom botocore.exceptions import ClientError+from conftest import iam_user, routed_requestfrom ministack.core.responses import (get_account_id,@@ -150,6 +151,50 @@ def test_ecr_repository_policy(ecr):except botocore.exceptions.ClientError as e:assert "RepositoryPolicyNotFoundException" in str(e)++def _policy_repository(effect, principal):+ """A repository whose policy has one statement, without a Resource, on ecr:ListImages."""+ name = f"rp-{_uuid_mod.uuid4().hex[:8]}"+ _create_repository(name)+ ecr_svc._set_repository_policy({"repositoryName": name, "policyText": json.dumps({+ "Version": "2012-10-17",+ "Statement": [{"Effect": effect, "Principal": {"AWS": principal}, "Action": "ecr:ListImages"}]})})+ return name+++def _list_images(key, name, field="__type"):+ status, _headers, body = routed_request(+ key, "ecr", "POST", "/", json.dumps({"repositoryName": name}).encode(),+ {"content-type": "application/x-amz-json-1.1",+ "x-amz-target": "AmazonEC2ContainerRegistry_V20150921.ListImages"})+ return status, json.loads(body).get(field)+++_ALLOW_ECR = {"Statement": [{"Effect": "Allow", "Action": "ecr:*", "Resource": "*"}]}+++def test_repository_policy_naming_the_user_allows_without_identity_policy(auth):+ key, user = iam_user()+ assert _list_images(key, _policy_repository("Allow", user)) == (200, None)+++def test_repository_policy_naming_the_account_needs_an_identity_policy(auth):+ name = _policy_repository("Allow", "arn:aws:iam::000000000000:root")+ key, _user = iam_user()+ assert _list_images(key, name) == (403, "AccessDeniedException")+ key, _user = iam_user(_ALLOW_ECR)+ assert _list_images(key, name) == (200, None)+++def test_repository_policy_deny_beats_an_identity_allow(auth):+ key, user = iam_user(_ALLOW_ECR)+ name = _policy_repository("Deny", user)+ assert _list_images(key, name) == (403, "AccessDeniedException")+ assert _list_images(key, name, "message") == (403, (+ f"User: {user} is not authorized to perform: ecr:ListImages on resource: "+ f"arn:aws:ecr:us-east-1:000000000000:repository/{name} with an explicit deny in a resource-based policy"))++def test_ecr_image_tag_mutability(ecr):ecr.put_image_tag_mutability(repositoryName="test-app", imageTagMutability="IMMUTABLE")resp = ecr.describe_repositories(repositoryNames=["test-app"])diff --git a/tests/test_iam_auth.py b/tests/test_iam_auth.pyindex 504eac18..e17a7ac3 100644--- a/tests/test_iam_auth.py+++ b/tests/test_iam_auth.py@@ -1354,6 +1354,40 @@ class TestCustomerManagedPolicyResolution:assert (get_account_id(), get_region()) == (self.OTHER, "eu-west-1")+class TestCombineResourcePolicy:+ """An identity decision combined with the policy of the resource the request addresses."""++ _USER = "arn:aws:iam::000000000000:user/u"++ def _decide(self, identity, principal, effect="Allow", owner="000000000000", caller=_USER):+ from ministack.core.iam_evaluator import combine_resource_policy++ ctx = EvalContext(principal_arn=caller, principal_type="User", principal_account="000000000000",+ action="sqs:SendMessage", resource_arn=f"arn:aws:sqs:us-east-1:{owner}:q",+ region="us-east-1")+ policy = {"Statement": [{"Effect": effect, "Principal": {"AWS": principal},+ "Action": "sqs:*", "Resource": "*"}]}+ return combine_resource_policy(EvalResult(identity, caller), ctx, policy, owner).decision++ @pytest.mark.parametrize("identity,principal,effect,owner,expected", [+ ("ImplicitDeny", _USER, "Allow", "000000000000", "Allow"),+ ("ImplicitDeny", "*", "Allow", "000000000000", "Allow"),+ ("ImplicitDeny", "arn:aws:iam::000000000000:root", "Allow", "000000000000", "ImplicitDeny"),+ ("ImplicitDeny", "000000000000", "Allow", "000000000000", "ImplicitDeny"),+ ("Allow", "arn:aws:iam::000000000000:root", "Allow", "000000000000", "Allow"),+ ("Allow", _USER, "Deny", "000000000000", "Deny"),+ ("Allow", "arn:aws:iam::000000000000:user/other", "Deny", "000000000000", "Allow"),+ ("ImplicitDeny", _USER, "Allow", "111111111111", "ImplicitDeny"),+ ("Allow", "000000000000", "Allow", "111111111111", "Allow"),+ ("Allow", "arn:aws:iam::111111111111:root", "Allow", "111111111111", "ImplicitDeny"),+ ])+ def test_decision(self, identity, principal, effect, owner, expected):+ assert self._decide(identity, principal, effect, owner) == expected++ def test_a_statement_naming_the_role_names_its_sessions(self):+ session = "arn:aws:sts::000000000000:assumed-role/r/s"+ assert self._decide("ImplicitDeny", "arn:aws:iam::000000000000:role/app/r", caller=session) == "Allow"+ assert self._decide("ImplicitDeny", "arn:aws:iam::000000000000:role/x", caller=session) == "ImplicitDeny"@contextlib.contextmanagerdef _iam_user(name, tags=()):"""A stored IAM user with one access key; yields the key and a setter for its inline policy."""@@ -1954,6 +1988,12 @@ class TestResourceArn:from ministack.core.iam_actions import extract_resource_arnassert extract_resource_arn("lambda", "POST", "/2015-03-31/functions/my-func/invocations", {}, b"", {}, "us-east-1", "123") == "arn:aws:lambda:us-east-1:123:function:my-func"+ def test_lambda_function_named_by_arn(self):+ from ministack.core.iam_actions import extract_resource_arn+ path = "/2015-03-31/functions/arn%3Aaws%3Alambda%3Aus-east-1%3A123%3Afunction%3Amy-func/invocations"+ assert extract_resource_arn(+ "lambda", "POST", path, {}, b"", {}, "us-east-1", "123"+ ) == "arn:aws:lambda:us-east-1:123:function:my-func"@pytest.mark.parametrize("arn", ["arn:aws:lambda:us-east-1:123:function:f", "arn%3Aaws%3Alambda%3Aus-east-1%3A123%3Afunction%3Af"])@pytest.mark.parametrize("method", ["GET", "POST", "DELETE"])@@ -1964,7 +2004,13 @@ class TestResourceArn:def test_sqs_queue_url(self):from ministack.core.iam_actions import extract_resource_arn- assert extract_resource_arn("sqs", "POST", "/", {}, b"", {"QueueUrl": ["http://localhost:4566/000000000000/my-queue"]}, "us-east-1", "123") == "arn:aws:sqs:us-east-1:123:my-queue"+ url = "http://localhost:4566/000000000000/my-queue"+ assert extract_resource_arn(+ "sqs", "POST", "/", {}, b"", {"QueueUrl": [url]}, "us-east-1", "123"+ ) == "arn:aws:sqs:us-east-1:000000000000:my-queue"+ assert extract_resource_arn(+ "sqs", "POST", "/", {}, b"", {"QueueUrl": ["my-queue"]}, "us-east-1", "123"+ ) == "arn:aws:sqs:us-east-1:123:my-queue"def test_sqs_create_queue(self):from ministack.core.iam_actions import extract_resource_arn@@ -3846,6 +3892,11 @@ class TestExtractResourceArn:assert self._arn("sqs", path="/000000000000/my-queue") == ("arn:aws:sqs:us-east-1:000000000000:my-queue")+ def test_sqs_queue_in_another_account_keeps_its_owner(self):+ body = json.dumps({"QueueUrl": "http://localhost:4566/111111111111/my-queue"}).encode()+ assert self._arn("sqs", body=body) == "arn:aws:sqs:us-east-1:111111111111:my-queue"+ assert self._arn("sqs", path="/111111111111/my-queue") == "arn:aws:sqs:us-east-1:111111111111:my-queue"+def test_sqs_without_a_queue_falls_back_to_star(self):assert self._arn("sqs", body=json.dumps({"MaxResults": 10}).encode()) == "*"diff --git a/tests/test_kms.py b/tests/test_kms.pyindex 86e74ff8..5f276b49 100644--- a/tests/test_kms.py+++ b/tests/test_kms.py@@ -10,6 +10,7 @@ import boto3import pytestfrom botocore.config import Configfrom botocore.exceptions import ClientError, ParamValidationError+from conftest import iam_user, routed_requestENDPOINT = os.environ.get("MINISTACK_ENDPOINT", "http://localhost:4566")@@ -1032,6 +1033,79 @@ def test_kms_get_put_key_policy(kms_client):assert got["Policy"] == customkms_client.schedule_key_deletion(KeyId=key_id, PendingWindowInDays=7)++def auth_key(monkeypatch):+ """Create keys in-process, optionally with a key policy, under AUTH=true."""+ import ministack.app as app_mod+ from ministack.services import kms as _kms++ created = []++ def make(*statements):+ data = {"KeySpec": "SYMMETRIC_DEFAULT", "KeyUsage": "ENCRYPT_DECRYPT"}+ if statements:+ data["Policy"] = json.dumps({"Version": "2012-10-17", "Statement": [+ {"Effect": effect, "Principal": {"AWS": principal}, "Action": action, "Resource": "*"}+ for effect, principal, action in statements]})+ status, _headers, body = _kms._create_key(data)+ assert status == 200+ created.append(json.loads(body)["KeyMetadata"]["KeyId"])+ return created[-1]++ monkeypatch.setattr(app_mod, "AUTH", True)+ yield make+ for key_id in created:+ _kms._keys.pop(key_id, None)+++def _kms_call(access_key, operation, key_id, field="__type"):+ params = {"KeyId": key_id}+ if operation == "Encrypt":+ params["Plaintext"] = base64.b64encode(b"hi").decode()+ else:+ params["KeySpec"] = "AES_256"+ status, _headers, body = routed_request(+ access_key, "kms", "POST", "/", json.dumps(params).encode(),+ {"content-type": "application/x-amz-json-1.1", "x-amz-target": f"TrentService.{operation}"})+ return status, json.loads(body).get(field)+++_ALLOW_KMS = {"Statement": [{"Effect": "Allow", "Action": "kms:*", "Resource": "*"}]}+_DENIED = (403, "AccessDeniedException")+++def test_key_policy_naming_the_user_allows_without_identity_policy(auth_key):+ access_key, user = iam_user()+ key_id = auth_key(("Allow", user, "kms:Encrypt"))+ assert _kms_call(access_key, "Encrypt", key_id) == (200, None)+ assert _kms_call(access_key, "GenerateDataKey", key_id) == _DENIED+++def test_key_policy_that_names_neither_user_nor_account_denies_an_identity_allow(auth_key):+ access_key, user = iam_user(_ALLOW_KMS)+ key_id = auth_key(("Allow", "arn:aws:iam::000000000000:user/someone-else", "kms:*"))+ assert _kms_call(access_key, "GenerateDataKey", key_id) == _DENIED+++def test_default_key_policy_hands_the_decision_to_identity_policies(auth_key):+ key_id = auth_key()+ access_key, _user = iam_user()+ assert _kms_call(access_key, "GenerateDataKey", key_id) == _DENIED+ access_key, _user = iam_user(_ALLOW_KMS)+ assert _kms_call(access_key, "GenerateDataKey", key_id) == (200, None)+++def test_key_policy_deny_beats_an_identity_allow(auth_key):+ access_key, user = iam_user(_ALLOW_KMS)+ key_id = auth_key(("Allow", "arn:aws:iam::000000000000:root", "kms:*"), ("Deny", user, "kms:GenerateDataKey"))+ assert _kms_call(access_key, "GenerateDataKey", key_id) == _DENIED+ assert _kms_call(access_key, "GenerateDataKey", key_id, "message") == (403, (+ f"User: {user} is not authorized to perform: kms:GenerateDataKey on resource: "+ f"arn:aws:kms:us-east-1:000000000000:key/{key_id} with an explicit deny in a resource-based policy"))+ assert _kms_call(access_key, "Encrypt", key_id) == (200, None)++def test_kms_tag_untag_list_v2(kms_client):"""TagResource / UntagResource / ListResourceTags."""key = kms_client.create_key()diff --git a/tests/test_lambda.py b/tests/test_lambda.pyindex 315e7235..2b45421a 100644--- a/tests/test_lambda.py+++ b/tests/test_lambda.py@@ -1,4 +1,5 @@import asyncio+import base64import contextlibimport ioimport json@@ -14,7 +15,7 @@ import uuid as _uuid_modimport zipfilefrom http.server import BaseHTTPRequestHandler, HTTPServerfrom unittest.mock import Mock, patch-from urllib.parse import urlparse+from urllib.parse import quote, urlparseimport boto3import pytest@@ -25,8 +26,10 @@ from conftest import (ENDPOINT,LoopProbe,concurrent_burst,+ iam_user,make_probe_lambda,patch_endpoint_dns,+ routed_request,)_endpoint = os.environ.get("MINISTACK_ENDPOINT", "http://localhost:4566").rstrip("/")@@ -4958,6 +4961,54 @@ def test_lambda_cross_account_layer_under_auth_names_the_calling_user(monkeypatcstore.pop_scoped(_CALLER_ACCOUNT, None, name, None)+def granted_function(monkeypatch):+ """A function whose policy grants lambda:GetFunction to the given principal, under AUTH=true."""+ import ministack.app as app_mod+ from ministack.services import lambda_svc++ names = []++ def make(principal):+ name = f"rp-fn-{_uuid_mod.uuid4().hex[:8]}"+ names.append(name)+ monkeypatch.setattr(app_mod, "AUTH", False)+ assert lambda_svc._create_function({+ "FunctionName": name, "Runtime": "python3.12", "Role": _LAMBDA_ROLE, "Handler": "index.handler",+ "Code": {"ZipFile": base64.b64encode(_make_zip("def handler(e, c): return 1")).decode()}})[0] == 201+ lambda_svc._add_permission(name, {"StatementId": "s", "Action": "lambda:GetFunction", "Principal": principal})+ monkeypatch.setattr(app_mod, "AUTH", True)+ return name++ yield make+ for name in names:+ lambda_svc._functions.pop(name, None)+++def test_function_policy_naming_the_user_allows_without_identity_policy(granted_function):+ key, user = iam_user()+ name = granted_function(user)+ assert routed_request(key, "lambda", "GET", f"/2015-03-31/functions/{name}")[0] == 200+ status, _headers, body = routed_request(key, "lambda", "GET", f"/2015-03-31/functions/{name}/configuration")+ assert (status, json.loads(body)["__type"]) == (403, "AccessDeniedException")+++def test_function_policy_applies_to_a_call_naming_the_function_by_arn(granted_function):+ key, user = iam_user()+ name = granted_function(user)+ arn = quote(f"arn:aws:lambda:us-east-1:000000000000:function:{name}", safe="")+ assert routed_request(key, "lambda", "GET", f"/2015-03-31/functions/{arn}")[0] == 200+++def test_function_policy_naming_the_account_needs_an_identity_policy(granted_function):+ name = granted_function("000000000000")+ key, _user = iam_user()+ status, _headers, body = routed_request(key, "lambda", "GET", f"/2015-03-31/functions/{name}")+ assert (status, json.loads(body)["__type"]) == (403, "AccessDeniedException")+ key, _user = iam_user({"Statement": [{"Effect": "Allow", "Action": "lambda:GetFunction", "Resource": "*"}]})+ assert routed_request(key, "lambda", "GET", f"/2015-03-31/functions/{name}")[0] == 200++@pytest.fixturedef shared_layer():"""Publish real layer bytes and provision the consumer's execution role."""diff --git a/tests/test_s3.py b/tests/test_s3.pyindex 7e4a00c1..e5f4fe9f 100644--- a/tests/test_s3.py+++ b/tests/test_s3.py@@ -12,7 +12,7 @@ from urllib.parse import urlparseimport pytestfrom botocore.exceptions import ClientError-from conftest import make_client, patch_endpoint_dns, sqs_policy_allow_s3+from conftest import iam_user, make_client, patch_endpoint_dns, routed_request, sqs_policy_allow_s3ENDPOINT = os.environ.get("MINISTACK_ENDPOINT", "http://localhost:4566").rstrip("/")@@ -1166,6 +1166,50 @@ def test_s3_bucket_policy(s3):assert stored["Version"] == "2012-10-17"assert len(stored["Statement"]) == 1++def _policy_bucket(effect, principal):+ """A bucket with one object and a bucket policy statement on s3:GetObject."""+ bucket = f"rp-{uuid.uuid4().hex[:10]}"+ assert _lock_call("PUT", f"/{bucket}")[0] == 200+ assert _lock_call("PUT", f"/{bucket}/k", body=b"x")[0] == 200+ policy = {"Version": "2012-10-17", "Statement": [{+ "Effect": effect, "Principal": {"AWS": principal}, "Action": "s3:GetObject",+ "Resource": f"arn:aws:s3:::{bucket}/*"}]}+ assert _lock_call("PUT", f"/{bucket}", body=json.dumps(policy).encode(), query={"policy": [""]})[0] == 204+ return bucket+++_ALLOW_S3 = {"Version": "2012-10-17", "Statement": [{"Effect": "Allow", "Action": "s3:*", "Resource": "*"}]}+++def test_bucket_policy_naming_the_user_allows_without_identity_policy(auth):+ key, user = iam_user()+ bucket = _policy_bucket("Allow", user)+ assert routed_request(key, "s3", "GET", f"/{bucket}/k")[0] == 200+++def test_bucket_policy_naming_the_account_needs_an_identity_policy(auth):+ bucket = _policy_bucket("Allow", "arn:aws:iam::000000000000:root")+ key, _user = iam_user()+ status, _headers, body = routed_request(key, "s3", "GET", f"/{bucket}/k")+ assert status == 403 and b"<Code>AccessDenied</Code>" in body+ key, _user = iam_user(_ALLOW_S3)+ assert routed_request(key, "s3", "GET", f"/{bucket}/k")[0] == 200+++def test_bucket_policy_deny_beats_an_identity_allow(auth):+ import xml.etree.ElementTree as ET++ key, user = iam_user(_ALLOW_S3)+ bucket = _policy_bucket("Deny", user)+ status, _headers, body = routed_request(key, "s3", "GET", f"/{bucket}/k")+ assert status == 403 and b"<Code>AccessDenied</Code>" in body+ assert ET.fromstring(body).findtext("Message") == (+ f'User: {user} is not authorized to perform: s3:GetObject on resource: "arn:aws:s3:::{bucket}/k" '+ "with an explicit deny in a resource-based policy")+ assert routed_request(key, "s3", "PUT", f"/{bucket}/k2", b"y")[0] == 200++def test_s3_object_tagging(s3):bkt = "intg-s3-objtags"s3.create_bucket(Bucket=bkt)diff --git a/tests/test_secretsmanager.py b/tests/test_secretsmanager.pyindex fdfee8b2..b26699c5 100644--- a/tests/test_secretsmanager.py+++ b/tests/test_secretsmanager.py@@ -7,6 +7,7 @@ import boto3import pytestfrom botocore.config import Configfrom botocore.exceptions import ClientError+from conftest import iam_user, routed_requestdef _regional_sm(region_name):@@ -990,6 +991,54 @@ def test_secretsmanager_force_delete_removes_resource_policy():sm.reset()+def _policy_secret(effect, principal):+ """A secret whose resource policy has one statement on GetSecretValue."""+ sm = _sm_importlib.import_module("ministack.services.secretsmanager")+ arn = sm.create_secret_in_process(f"rp-{_uuid_mod.uuid4().hex[:8]}", "v")+ _sm_invoke_action(sm, "PutResourcePolicy", {"SecretId": arn, "ResourcePolicy": json.dumps({+ "Version": "2012-10-17", "Statement": [{"Effect": effect, "Principal": {"AWS": principal},+ "Action": "secretsmanager:GetSecretValue", "Resource": "*"}]})})+ return arn+++def _get_secret_value(key, arn):+ status, _headers, body = routed_request(+ key, "secretsmanager", "POST", "/", json.dumps({"SecretId": arn}).encode(),+ {"content-type": "application/x-amz-json-1.1", "x-amz-target": "secretsmanager.GetSecretValue"})+ return status, json.loads(body).get("__type")+++_ALLOW_SECRETS = {"Statement": [{"Effect": "Allow", "Action": "secretsmanager:*", "Resource": "*"}]}+++def test_secret_policy_naming_the_user_allows_without_identity_policy(auth):+ key, user = iam_user()+ assert _get_secret_value(key, _policy_secret("Allow", user)) == (200, None)+++def test_secret_policy_naming_the_account_needs_an_identity_policy(auth):+ arn = _policy_secret("Allow", "arn:aws:iam::000000000000:root")+ key, _user = iam_user()+ assert _get_secret_value(key, arn) == (403, "AccessDeniedException")+ key, _user = iam_user(_ALLOW_SECRETS)+ assert _get_secret_value(key, arn) == (200, None)+++def test_secret_policy_deny_beats_an_identity_allow(auth):+ key, user = iam_user(_ALLOW_SECRETS)+ arn = _policy_secret("Deny", user)+ status, _headers, body = routed_request(+ key, "secretsmanager", "POST", "/", json.dumps({"SecretId": arn}).encode(),+ {"content-type": "application/x-amz-json-1.1", "x-amz-target": "secretsmanager.GetSecretValue"})+ assert (status, json.loads(body)) == (403, {"__type": "AccessDeniedException", "message": (+ f"User: {user} is not authorized to perform: secretsmanager:GetSecretValue on resource: {arn} "+ "with an explicit deny in a resource-based policy")})+ status, _headers, body = routed_request(+ key, "secretsmanager", "POST", "/", json.dumps({"SecretIdList": [arn]}).encode(),+ {"content-type": "application/x-amz-json-1.1", "x-amz-target": "secretsmanager.BatchGetSecretValue"})+ assert json.loads(body)["Errors"][0]["Message"].endswith("with an explicit deny in a resource-based policy")++def test_secretsmanager_arn_shaped_secret_name_does_not_bypass_scope_guard():sm = _sm_importlib.import_module("ministack.services.secretsmanager")sm.reset()diff --git a/tests/test_sqs.py b/tests/test_sqs.pyindex de59e41a..b602cc71 100644--- a/tests/test_sqs.py+++ b/tests/test_sqs.py@@ -12,10 +12,10 @@ import boto3import pytestfrom botocore.config import Configfrom botocore.exceptions import ClientError-from conftest import REGION, sqs_policy_allow_s3, sqs_policy_allow_sns+from conftest import REGION, iam_user, routed_request, sqs_policy_allow_s3, sqs_policy_allow_snsfrom ministack.core.iam_evaluator import EvalContext, evaluate_resource_policy-from ministack.core.responses import request_scope+from ministack.core.responses import get_account_id, request_scopefrom ministack.services import s3 as s3_svcfrom ministack.services import sns as sns_svcfrom ministack.services import sqs as sqs_svc@@ -1634,14 +1634,17 @@ def test_unicode_sqs_message(sqs):ACCT_A = "111111111111"ACCT_B = "222222222222"+HOME = get_account_id()def _reset_messaging_state():from ministack.core.iam_evaluator import _request_caller_arn+ from ministack.services import iam as iam_svcsqs_svc.reset()sns_svc.reset()s3_svc.reset()+ iam_svc.reset()_request_caller_arn.set("")@@ -2200,6 +2203,117 @@ class TestSnsFanoutPolicies:"Endpoint": "[email protected]"})) == (403, "AuthorizationError")+# ---------------------------------------------------------------------------+# Identity policy and resource policy together, through the router+# ---------------------------------------------------------------------------++def _routed_send(key, url, body="m"):+ return routed_request(key, "sqs", "POST", "/", json.dumps({"QueueUrl": url, "MessageBody": body}).encode(), {+ "content-type": "application/x-amz-json-1.0", "x-amz-target": "AmazonSQS.SendMessage"})+++def _routed_publish(key, arn):+ from urllib.parse import urlencode++ return routed_request(key, "sns", "POST", "/", urlencode({+ "Action": "Publish", "TopicArn": arn, "Message": "m"}).encode(),+ {"content-type": "application/x-www-form-urlencoded"})+++def _grant(effect, principal, action, resource):+ return {"Version": "2012-10-17", "Statement": [{+ "Effect": effect, "Principal": {"AWS": principal}, "Action": action, "Resource": resource}]}+++_ALLOW_MESSAGING = {"Version": "2012-10-17", "Statement": [{+ "Effect": "Allow", "Action": ["sqs:*", "sns:*"], "Resource": "*"}]}+++class TestIdentityAndResourcePolicy:+ """Same-account cases run in the default account, where IAM users live."""++ def test_queue_policy_naming_the_user_allows_without_identity_policy(self, auth):+ key, user = iam_user()+ name = _uniq("rp-q")+ url = _make_queue(HOME, name, _grant("Allow", user, "sqs:SendMessage", _qarn(HOME, name)))+ assert _routed_send(key, url, "granted")[0] == 200+ assert _queue_bodies(_qarn(HOME, name)) == ["granted"]++ def test_queue_policy_naming_the_account_needs_an_identity_policy(self, auth):+ key, _user = iam_user()+ name = _uniq("rp-q")+ url = _make_queue(HOME, name, _grant("Allow", f"arn:aws:iam::{HOME}:root",+ "sqs:SendMessage", _qarn(HOME, name)))+ status, headers, _body = _routed_send(key, url)+ assert status == 403+ assert headers["x-amzn-query-error"] == "AccessDenied;Sender"+ key, _user = iam_user(_ALLOW_MESSAGING)+ assert _routed_send(key, url)[0] == 200++ def test_queue_policy_deny_beats_an_identity_allow(self, auth):+ key, user = iam_user(_ALLOW_MESSAGING)+ name = _uniq("rp-q")+ url = _make_queue(HOME, name, _grant("Deny", user, "sqs:SendMessage", _qarn(HOME, name)))+ status, headers, body = _routed_send(key, url)+ assert status == 403+ assert headers["x-amzn-query-error"] == "AccessDenied;Sender"+ assert json.loads(body)["message"] == (+ f"User: {user} is not authorized to perform: sqs:sendmessage on resource: {_qarn(HOME, name)} "+ "with an explicit deny in a resource-based policy")+ assert _queue_bodies(_qarn(HOME, name)) == []++ def test_topic_policy_naming_the_user_allows_without_identity_policy(self, auth):+ key, user = iam_user()+ arn = _make_topic(HOME, _uniq("rp-t"))+ _set_topic_policy(HOME, arn, _grant("Allow", user, "sns:Publish", arn))+ assert _resp_code(_routed_publish(key, arn)) == (200, "")++ def test_topic_policy_naming_the_account_needs_an_identity_policy(self, auth):+ key, _user = iam_user()+ arn = _make_topic(HOME, _uniq("rp-t"))+ _set_topic_policy(HOME, arn, _grant("Allow", HOME, "sns:Publish", arn))+ assert _resp_code(_routed_publish(key, arn)) == (403, "AuthorizationError")+ key, _user = iam_user(_ALLOW_MESSAGING)+ assert _resp_code(_routed_publish(key, arn)) == (200, "")++ def test_topic_policy_deny_beats_an_identity_allow(self, auth):+ key, user = iam_user(_ALLOW_MESSAGING)+ arn = _make_topic(HOME, _uniq("rp-t"))+ _set_topic_policy(HOME, arn, _grant("Deny", user, "sns:Publish", arn))+ assert _resp_detail(_routed_publish(key, arn)) == (403, "AuthorizationError", (+ f"User: {user} is not authorized to perform: SNS:Publish on resource: {arn} "+ "with an explicit deny in a resource-based policy"))++ def test_default_topic_policy_grants_nothing_to_a_user(self, auth):+ key, _user = iam_user()+ arn = _make_topic(HOME, _uniq("rp-t"))+ assert _resp_code(_routed_publish(key, arn)) == (403, "AuthorizationError")++ def test_cross_account_needs_both_policies(self, auth):+ name = _uniq("rp-q")+ key, user = iam_user()+ url = _make_queue(ACCT_A, name, _grant("Allow", user, "sqs:SendMessage", _qarn(ACCT_A, name)))+ assert _routed_send(key, url)[0] == 403+ key, user = iam_user(_ALLOW_MESSAGING)+ _as(ACCT_A, sqs_svc._act_set_queue_attributes, {"QueueUrl": url, "Attributes": {+ "Policy": json.dumps(_grant("Allow", user, "sqs:SendMessage", _qarn(ACCT_A, name)))}}, url)+ assert _routed_send(key, url)[0] == 200++ def test_cross_account_ignores_a_same_named_queue_of_the_caller(self, auth):+ name = _uniq("rp-q")+ key, user = iam_user()+ home = _make_queue(HOME, name, _grant("Allow", user, "sqs:SendMessage", _qarn(HOME, name)))+ url = _make_queue(ACCT_A, name, _grant("Allow", user, "sqs:SendMessage", _qarn(ACCT_A, name)))+ assert _routed_send(key, url)[0] == 403+ key, user = iam_user(_ALLOW_MESSAGING)+ _as(HOME, sqs_svc._act_set_queue_attributes, {"QueueUrl": home, "Attributes": {+ "Policy": json.dumps(_grant("Deny", user, "sqs:SendMessage", _qarn(HOME, name)))}}, home)+ _as(ACCT_A, sqs_svc._act_set_queue_attributes, {"QueueUrl": url, "Attributes": {+ "Policy": json.dumps(_grant("Allow", user, "sqs:SendMessage", _qarn(ACCT_A, name)))}}, url)+ assert _routed_send(key, url, "foreign")[0] == 200+ assert _queue_bodies(_qarn(ACCT_A, name)) == ["foreign"]++# ---------------------------------------------------------------------------# AUTH=false stays permissive# ---------------------------------------------------------------------------