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(iam): auth policy scoped by key (#1508)
Nahuel Nucera494421779b4f
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex ce2f8387..a98ab0e9 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -11,6 +11,9 @@ Versioning follows [Semantic Versioning](https://semver.org/).- **SNS — `GetPlatformApplicationAttributes` / `SetPlatformApplicationAttributes`** — a platform application could be created and deleted but never read back or updated: both actions answered `400 InvalidAction`, so `terraform plan` on an `aws_sns_platform_application` failed at refresh (`reading SNS Platform Application (...): Unknown action: GetPlatformApplicationAttributes`) and the resource could never reach a clean state. Both now answer with the documented shapes — `Get` returns the attribute map as `entry` key/value pairs, `Set` merges the supplied entries (`PlatformCredential`, `PlatformPrincipal`, the `Event*` topic ARNs, `*FeedbackRoleArn`, `Enabled`, ...) and returns only `ResponseMetadata` — with `InvalidParameter` (400) for a missing `PlatformApplicationArn` or `Attributes` and `NotFound` (404) for an unknown application. `CreatePlatformApplication` also seeds `Enabled=true`, as AWS reports for a newly created application.### Fixed+- **IAM — a resource-scoped policy works for JSON-protocol services (`AUTH=true`)** — `extract_resource_arn` read SQS, ACM, SSM and CloudWatch parameters from the query form only. SQS moved to the JSON protocol in 2023 and the others accept it, so for current SDKs nothing reached the query params, the resource fell back to `*`, and no queue-, certificate-, parameter- or alarm-scoped statement could match: every least-privilege policy for those services denied every call, while `Resource: "*"` allowed them. Those branches now read the request body and fall back to the query form, and SQS also resolves a queue addressed by request path. Reported by @rsimples.+- **IAM — `kms:Decrypt` resolves the key from the ciphertext (`AUTH=true`)** — `Decrypt` and `ReEncrypt` carry no `KeyId` for a symmetric key, since AWS recovers it from metadata in the ciphertext blob and evaluates IAM against that key's ARN. MiniStack fell back to `*`, so a policy naming the key allowed `Encrypt` and denied `Decrypt` for the same key. The key id is now recovered from the blob the same way the KMS handler recovers it. Reported by @rsimples.+- **Lambda — `CreateFunction` with an unresolvable role answers 400, not 500 (`AUTH=true`)** — the role check sat inside `_build_config`, which is declared to return a config dict, so its error tuple was assigned to `config` and the next attribute read raised `AttributeError: 'tuple' object has no attribute 'get'`; the client got `500 InternalError` with nothing about the role, and a half-created record was left behind for a background thread to trip over. The role is now validated before anything is built or stored, and the caller answers `400 InvalidParameterValueException`. Reported by @rsimples.- **Cognito — group membership records the resolved Username** — `AdminAddUserToGroup` stored the caller-supplied name in the group's member list, but the list is read back as `_users` keys. In a pool with `UsernameAttributes = ["email"]` that name is an email alias, not the key, so `ListUsersInGroup` returned an empty list for a group that had just accepted the user, `AdminRemoveUserFromGroup` did not match the entry it had added, and `DeleteGroup` left the group on the user's own group list. Both operations now key on the resolved Username.- **Cognito — `AdminDeleteUser` deletes the user an email alias resolves to** — in a pool with `UsernameAttributes = ["email"]`, `AdminCreateUser` stores the user under a generated UUID Username and keeps the email as an alias attribute, as real Cognito does. `AdminDeleteUser` resolved the alias correctly but then deleted by the caller-supplied name, which is not the key, so the call raised `KeyError` and answered `500 InternalError` while the user survived. A seed or test fixture that deletes and creates the same user therefore failed with `UsernameExistsException` on every run after the first. The delete now uses the resolved Username.- **S3 — a presigned upload no longer drops the `x-amz-*` headers it was signed with** — a presigned URL is sent by a caller who has only the URL and a body, so SigV4 lets the `x-amz-*` headers an operation asked for be hoisted into the query string, where the signature covers them exactly as a signed header would. SDKs presign that way and real S3 applies those params as the headers they stand for. MiniStack only ever read headers, so a presigned `PutObject` carrying user metadata in its query string answered `200` and stored the object with no metadata at all. Hoisted `x-amz-*` params are now folded back into the request headers before routing (user metadata, storage class, tagging, ACL, SSE and copy source) while an explicitly sent header still wins over its hoisted twin, and the SigV4 signing params are never mistaken for one. Contributed by @dennmart.diff --git a/ministack/core/iam_actions.py b/ministack/core/iam_actions.pyindex 55e9c869..e1a5509a 100644--- a/ministack/core/iam_actions.py+++ b/ministack/core/iam_actions.py@@ -5,6 +5,7 @@ IAM action string (``service:ActionName``) from each request's protocol,and formats per-protocol AccessDenied error responses."""+import base64import jsonimport loggingimport os@@ -551,6 +552,50 @@ def _query_param(query_params: dict, key: str) -> str:return val or ""+def _param(body: bytes, query_params: dict, *fields: str) -> str:+ """Read a request parameter from the JSON body, falling back to the query form.++ Several services moved to the JSON protocol (SQS in 2023, plus ACM, SSM and+ CloudWatch), where the parameters travel in the body and nothing reaches+ ``query_params``, while older clients still send the query form. Reading+ both keeps one branch correct for either wire shape.+ """+ for field in fields:+ val = _safe_json_field(body, field)+ if val:+ return val+ for field in fields:+ val = _query_param(query_params, field)+ if val:+ return val+ return ""+++_KMS_KEY_ID_RE = re.compile(+ r"^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$"+)+++def _kms_key_id_from_ciphertext(ciphertext_b64: str) -> str:+ """Recover the key id our symmetric ciphertext carries in its first 36 bytes.++ Decrypt and ReEncrypt do not require a KeyId: "AWS KMS can get this+ information from metadata that it adds to the symmetric ciphertext blob."+ IAM still evaluates against that key's ARN, so the resource has to be+ resolved the same way the KMS handler resolves it.+ """+ if not ciphertext_b64:+ return ""+ try:+ raw = base64.b64decode(ciphertext_b64)+ except Exception:+ return ""+ if len(raw) <= 68:+ return ""+ candidate = raw[:36].decode("utf-8", errors="ignore")+ return candidate if _KMS_KEY_ID_RE.match(candidate) else ""++def extract_resource_arn(service: str, method: str, path: str,headers: dict, body: bytes,query_params: dict, region: str,@@ -594,16 +639,21 @@ def extract_resource_arn(service: str, method: str, path: str,return "*"if service == "sqs":- # Queue URL is in the path or QueueUrl param- queue_url = _query_param(query_params, "QueueUrl")+ # SQS speaks the JSON protocol, so QueueUrl arrives in the body for+ # current SDKs and in the query form for older ones.+ queue_url = _param(body, query_params, "QueueUrl")+ if not queue_url:+ # Query-protocol callers address the queue by path instead:+ # 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]if queue_url:- # Extract queue name from URL- q_parts = queue_url.rstrip("/").split("/")- queue_name = q_parts[-1] if q_parts else ""+ queue_name = queue_url.rstrip("/").split("/")[-1]if queue_name:return f"arn:aws:sqs:{region}:{account_id}:{queue_name}"- # QueueName param (CreateQueue)- queue_name = _query_param(query_params, "QueueName")+ # QueueName param (CreateQueue, GetQueueUrl)+ queue_name = _param(body, query_params, "QueueName")if queue_name:return f"arn:aws:sqs:{region}:{account_id}:{queue_name}"return "*"@@ -623,6 +673,11 @@ def extract_resource_arn(service: str, method: str, path: str,if service == "kms":key_id = _safe_json_field(body, "KeyId")+ if not key_id:+ # Decrypt, and ReEncrypt's source key, carry no KeyId for symmetric+ # keys — the key is recovered from the ciphertext.+ key_id = _kms_key_id_from_ciphertext(+ _safe_json_field(body, "CiphertextBlob"))if key_id:# KeyId can be an ARN, alias, or key IDif key_id.startswith("arn:"):@@ -840,7 +895,7 @@ def extract_resource_arn(service: str, method: str, path: str,# --- Query-based services ---if service == "acm":- arn = _query_param(query_params, "CertificateArn")+ arn = _param(body, query_params, "CertificateArn")if arn:return arnreturn "*"@@ -855,7 +910,7 @@ def extract_resource_arn(service: str, method: str, path: str,if service == "monitoring":# CloudWatch alarms- name = _query_param(query_params, "AlarmName")+ name = _param(body, query_params, "AlarmName")if name:return f"arn:aws:cloudwatch:{region}:{account_id}:alarm:{name}"ns = _query_param(query_params, "Namespace")@@ -906,7 +961,7 @@ def extract_resource_arn(service: str, method: str, path: str,return "*"if service == "ssm":- name = _query_param(query_params, "Name")+ name = _param(body, query_params, "Name")if name:return f"arn:aws:ssm:{region}:{account_id}:parameter{name if name.startswith('/') else '/' + name}"return "*"diff --git a/ministack/services/lambda_svc.py b/ministack/services/lambda_svc.pyindex 193ddd3f..8c52bad9 100644--- a/ministack/services/lambda_svc.py+++ b/ministack/services/lambda_svc.py@@ -1298,10 +1298,6 @@ def _build_config(name: str, data: dict, code_zip: bytes | None = None) -> dict:env["Variables"] = {}role_arn = data.get("Role", f"arn:aws:iam::{get_account_id()}:role/lambda-role")- from ministack.core.iam_evaluator import validate_role_arn- role_err = validate_role_arn(role_arn)- if role_err:- return error_response_json("InvalidParameterValueException", role_err, 400)config = {"FunctionName": name,@@ -1964,6 +1960,15 @@ def _create_function(data: dict):data = dict(data)data["Layers"] = layers_cfg+ # Validate the execution role before building anything: _build_config+ # returns a config dict, so the error has to be raised by the caller, and+ # nothing may be persisted for a function that is going to be refused.+ from ministack.core.iam_evaluator import validate_role_arn+ role_err = validate_role_arn(+ data.get("Role", f"arn:aws:iam::{get_account_id()}:role/lambda-role"))+ if role_err:+ return error_response_json("InvalidParameterValueException", role_err, 400)+config = _build_config(name, data, code_zip)if image_uri:config["ImageUri"] = image_uridiff --git a/tests/test_iam_auth.py b/tests/test_iam_auth.pyindex c7903a56..a563c451 100644--- a/tests/test_iam_auth.py+++ b/tests/test_iam_auth.py@@ -1123,3 +1123,151 @@ def test_put_role_policy_rejects_malformed_document(iam):assert exc.value.response["Error"]["Code"] == "MalformedPolicyDocument"finally:iam.delete_role(RoleName="validation-test-role-2")+++# ---------------------------------------------------------------------------+# Resource ARN extraction (#1504, #1505)+#+# Several services moved to the JSON protocol, so their parameters arrive in+# the body and never reach query_params. A branch that reads only query params+# falls back to "*", which no resource-scoped statement matches, and every+# least-privilege policy for that service denies.+# ---------------------------------------------------------------------------++class TestExtractResourceArn:+ ACCOUNT = "000000000000"+ REGION = "us-east-1"++ def _arn(self, service, body=b"", query=None, path="/", method="POST"):+ from ministack.core.iam_actions import extract_resource_arn+ return extract_resource_arn(+ service, method, path, {}, body, query or {},+ self.REGION, self.ACCOUNT,+ )++ def test_sqs_queue_url_from_json_body(self):+ # SQS is a JSON-protocol service: current SDKs send QueueUrl in the body.+ body = json.dumps({+ "QueueUrl": "http://localhost:4566/000000000000/my-queue",+ "MessageBody": "x",+ }).encode()+ assert self._arn("sqs", body=body) == (+ "arn:aws:sqs:us-east-1:000000000000:my-queue")++ def test_sqs_queue_name_from_json_body(self):+ body = json.dumps({"QueueName": "my-queue"}).encode()+ assert self._arn("sqs", body=body) == (+ "arn:aws:sqs:us-east-1:000000000000:my-queue")++ def test_sqs_queue_url_from_query_form_still_works(self):+ query = {"QueueUrl": ["http://localhost:4566/000000000000/my-queue"]}+ assert self._arn("sqs", query=query) == (+ "arn:aws:sqs:us-east-1:000000000000:my-queue")++ def test_sqs_queue_from_request_path(self):+ # Query-protocol callers address the queue by path.+ assert self._arn("sqs", path="/000000000000/my-queue") == (+ "arn:aws:sqs:us-east-1:000000000000:my-queue")++ def test_sqs_without_a_queue_falls_back_to_star(self):+ assert self._arn("sqs", body=json.dumps({"MaxResults": 10}).encode()) == "*"++ def test_kms_key_id_from_body(self):+ body = json.dumps({"KeyId": "1234abcd-12ab-34cd-56ef-1234567890ab"}).encode()+ assert self._arn("kms", body=body) == (+ "arn:aws:kms:us-east-1:000000000000:key/"+ "1234abcd-12ab-34cd-56ef-1234567890ab")++ def test_kms_decrypt_resolves_the_key_from_the_ciphertext(self):+ # Decrypt carries no KeyId for a symmetric key: "AWS KMS can get this+ # information from metadata that it adds to the symmetric ciphertext+ # blob." IAM still evaluates against that key's ARN.+ import base64+ key_id = "1234abcd-12ab-34cd-56ef-1234567890ab"+ blob = key_id.encode() + b"\x00" * 32 + b"\x00" * 16 + b"payload"+ body = json.dumps({+ "CiphertextBlob": base64.b64encode(blob).decode(),+ }).encode()+ assert self._arn("kms", body=body) == (+ f"arn:aws:kms:us-east-1:000000000000:key/{key_id}")++ def test_kms_unparseable_ciphertext_falls_back_to_star(self):+ import base64+ body = json.dumps({+ "CiphertextBlob": base64.b64encode(b"too-short").decode(),+ }).encode()+ assert self._arn("kms", body=body) == "*"++ def test_kms_explicit_key_id_wins_over_the_ciphertext(self):+ import base64+ blob = ("1234abcd-12ab-34cd-56ef-1234567890ab".encode()+ + b"\x00" * 48 + b"payload")+ body = json.dumps({+ "KeyId": "alias/my-key",+ "CiphertextBlob": base64.b64encode(blob).decode(),+ }).encode()+ assert self._arn("kms", body=body) == (+ "arn:aws:kms:us-east-1:000000000000:alias/my-key")++ def test_acm_certificate_arn_from_json_body(self):+ arn = "arn:aws:acm:us-east-1:000000000000:certificate/abc"+ body = json.dumps({"CertificateArn": arn}).encode()+ assert self._arn("acm", body=body) == arn++ def test_ssm_parameter_name_from_json_body(self):+ body = json.dumps({"Name": "/app/db"}).encode()+ assert self._arn("ssm", body=body) == (+ "arn:aws:ssm:us-east-1:000000000000:parameter/app/db")++ def test_cloudwatch_alarm_name_from_json_body(self):+ body = json.dumps({"AlarmName": "cpu-high"}).encode()+ assert self._arn("monitoring", body=body) == (+ "arn:aws:cloudwatch:us-east-1:000000000000:alarm:cpu-high")+++# ---------------------------------------------------------------------------+# CreateFunction with an unresolvable role (#1506)+# ---------------------------------------------------------------------------++def test_lambda_create_function_with_a_missing_role_answers_400(monkeypatch):+ """The role check must reach the client, not blow up inside _build_config."""+ import io+ import zipfile++ import ministack.app as app_mod+ from ministack.services import lambda_svc++ buf = io.BytesIO()+ with zipfile.ZipFile(buf, "w") as z:+ z.writestr("index.js", "exports.handler=async()=>({})")++ monkeypatch.setattr(app_mod, "AUTH", True, raising=False)+ name = "iam-auth-missing-role-fn"+ status, _headers, body = lambda_svc._create_function({+ "FunctionName": name,+ "Runtime": "nodejs22.x",+ "Handler": "index.handler",+ "Role": "arn:aws:iam::000000000000:role/does-not-exist",+ "Code": {"ZipFile": __import__("base64").b64encode(buf.getvalue()).decode()},+ })+ assert status == 400+ payload = json.loads(body)+ assert payload["__type"] == "InvalidParameterValueException"+ assert "does-not-exist" in payload["message"]+ # Nothing may be persisted for a function that was refused.+ assert name not in lambda_svc._functions+++def test_lambda_build_config_returns_a_config_not_an_error(monkeypatch):+ """_build_config is annotated -> dict; it must never return an error tuple."""+ import ministack.app as app_mod+ from ministack.services import lambda_svc++ monkeypatch.setattr(app_mod, "AUTH", True, raising=False)+ config = lambda_svc._build_config("f", {+ "Runtime": "nodejs22.x",+ "Handler": "index.handler",+ "Role": "arn:aws:iam::000000000000:role/does-not-exist",+ })+ assert isinstance(config, dict)+ assert config["FunctionName"] == "f"