Skip to content

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

fix(ssm): authorize parameter tag operations by ResourceId (#1894)

Adrian-Ryan Acala70dfbad7d39e
diff --git a/CHANGELOG.md b/CHANGELOG.md
index b405e752..77645546 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -29,6 +29,7 @@ Versioning follows [Semantic Versioning](https://semver.org/).
- **API Gateway v2 (HTTP API) — a request no stage or route matches answers AWS's exact 404 body** — an unmatched route answered `{"message": "No route found"}` and an unknown stage `{"message": "Stage '…' not found"}`; both now answer `{"message":"Not Found"}` (compact JSON), as AWS does. Contributed by @skialpine.
- **API Gateway v2 — `apiEndpoint` follows the gateway's TLS scheme** — with `USE_SSL=1` the gateway listener serves only HTTPS, but CreateApi and the `AWS::ApiGatewayV2::Api` CloudFormation resource always returned an `http://` `apiEndpoint`, which nothing answers. They now return `https://`, or `wss://` for a WebSocket API, as AWS does. Without `USE_SSL` the endpoint keeps `http://`. Contributed by @skialpine.
+- **SSM — parameter tag actions authorize the parameter named by `ResourceId`** — with `AUTH=true`, `AddTagsToResource`, `RemoveTagsFromResource`, and `ListTagsForResource` checked `Name` instead, so an exact ARN allow could fail and an exact ARN deny could be missed under a broad allow. Accepted parameter-name and ARN aliases now use the canonical parameter ARN for the IAM check. Tag authorization denials now match AWS's HTTP 400 JSON 1.1 response, including the canonical resource and explicit-deny reason.
## [1.5.19] — 2026-09-30
diff --git a/ministack/app.py b/ministack/app.py
index 42f45b38..b7beeb97 100644
--- a/ministack/app.py
+++ b/ministack/app.py
@@ -2491,7 +2491,10 @@ async def _dispatch_service_request(
message=denied.message,
headers=headers,
)
- return access_denied_response(service, iam_action, denied.principal_arn, request_id, headers=headers)
+ return access_denied_response(
+ service, iam_action, denied.principal_arn, request_id, headers=headers,
+ resource_arn=resource_arn, explicit_deny=denied.decision == "Deny",
+ )
handler = SERVICE_HANDLERS.get(service)
if not handler:
diff --git a/ministack/core/iam_actions.py b/ministack/core/iam_actions.py
index 45b75613..c7ad73ae 100644
--- a/ministack/core/iam_actions.py
+++ b/ministack/core/iam_actions.py
@@ -1261,6 +1261,29 @@ def extract_resource_arn(service: str, method: str, path: str,
return "*"
if service == "ssm":
+ action = _action_from_target(headers)
+ if action in {"AddTagsToResource", "RemoveTagsFromResource", "ListTagsForResource"}:
+ try:
+ data = json.loads(body) if body else {}
+ except (json.JSONDecodeError, TypeError):
+ return "*"
+ if not isinstance(data, dict) or data.get("ResourceType", "Parameter") != "Parameter":
+ return "*"
+ resource_id = data.get("ResourceId", "")
+ if not isinstance(resource_id, str) or not resource_id:
+ return "*"
+ if resource_id.startswith("arn:"):
+ # The handler also accepts parameter ARN aliases. Authorize
+ # accepted local aliases as the canonical parameter resource,
+ # while retaining foreign and malformed ARNs as supplied.
+ from ministack.services.ssm import _parameter_name_from_arn
+
+ parsed = _parameter_name_from_arn(resource_id)
+ if parsed and parsed[0] == account_id and parsed[1] == region:
+ resource_id = parsed[2]
+ else:
+ return resource_id
+ return f"arn:aws:ssm:{region}:{account_id}:parameter/{resource_id.lstrip('/')}"
name = _param(body, query_params, "Name")
if name:
return f"arn:aws:ssm:{region}:{account_id}:parameter{name if name.startswith('/') else '/' + name}"
@@ -1717,14 +1740,32 @@ def dynamodb_service_context(body: bytes) -> dict:
def access_denied_response(service: str, action: str, principal_arn: str,
request_id: str, *, error_code: str = "",
- message: str = "", headers: dict | None = None) -> tuple:
- """Format a 403 error response matching the service's protocol.
+ message: str = "", headers: dict | None = None,
+ resource_arn: str = "*", explicit_deny: bool = False) -> tuple:
+ """Format a denial matching the service's protocol.
A denial the caller's SDK cannot parse is barely better than no denial: it
surfaces as a bare 403 with the code buried in an unread body, so a client
catching AccessDenied misses it. `headers` lets the services that accept
more than one encoding answer in the one the request arrived in.
"""
+ if service == "ssm" and not error_code and action in {
+ "ssm:AddTagsToResource", "ssm:RemoveTagsFromResource", "ssm:ListTagsForResource",
+ }:
+ # Live AWS us-west-2: SSM tag authorization denials are HTTP 400,
+ # JSON 1.1, with a capitalized Message and the authorized resource.
+ reason = (
+ "with an explicit deny in an identity-based policy" if explicit_deny
+ else f"because no identity-based policy allows the {action} action"
+ )
+ message = (
+ f"User: {principal_arn} is not authorized to perform: {action} "
+ f"on resource: {resource_arn} {reason}"
+ )
+ return (
+ 400, {"Content-Type": "application/x-amz-json-1.1"},
+ json.dumps({"__type": "AccessDeniedException", "Message": message}).encode(),
+ )
if not message:
message = (
f"User: {principal_arn} is not authorized to perform: {action} "
diff --git a/tests/test_iam_auth.py b/tests/test_iam_auth.py
index dedc4b1e..b81924f9 100644
--- a/tests/test_iam_auth.py
+++ b/tests/test_iam_auth.py
@@ -2702,6 +2702,21 @@ class TestAccessDeniedResponse:
message="Token expired")
assert b"ExpiredTokenException" in b
+ @pytest.mark.parametrize("action", (
+ "AddTagsToResource", "RemoveTagsFromResource", "ListTagsForResource",
+ ))
+ def test_ssm_tag_credential_error_keeps_authentication_status(self, action):
+ from ministack.core.iam_actions import access_denied_response
+
+ status, _, body = access_denied_response(
+ "ssm", f"ssm:{action}", "", "r1",
+ error_code="UnrecognizedClientException", message="Invalid signing credentials",
+ )
+ assert status == 403
+ assert json.loads(body) == {
+ "__type": "UnrecognizedClientException", "message": "Invalid signing credentials",
+ }
+
# ---------------------------------------------------------------------------
# Integration: SimulateCustomPolicy (runs against server, AUTH=false OK)
@@ -2914,12 +2929,304 @@ class TestExtractResourceArn:
assert self._arn("ssm", body=body) == (
"arn:aws:ssm:us-east-1:000000000000:parameter/app/db")
+ @pytest.mark.parametrize("action", (
+ "AddTagsToResource", "RemoveTagsFromResource", "ListTagsForResource",
+ ))
+ @pytest.mark.parametrize("resource_id", ("app/db", "/app/db"))
+ def test_ssm_parameter_tags_use_resource_id(self, action, resource_id):
+ from ministack.core.iam_actions import extract_resource_arn
+
+ body = json.dumps({
+ "ResourceType": "Parameter", "ResourceId": resource_id,
+ "Name": "/wrong/parameter",
+ }).encode()
+ assert extract_resource_arn(
+ "ssm", "POST", "/", {"x-amz-target": f"AmazonSSM.{action}"},
+ body, {}, self.REGION, self.ACCOUNT,
+ ) == "arn:aws:ssm:us-east-1:000000000000:parameter/app/db"
+
+ def test_ssm_tag_arn_input_and_other_resource_types(self):
+ from ministack.core.iam_actions import extract_resource_arn
+
+ arn = "arn:aws:ssm:us-west-2:111111111111:parameter/app/db"
+ headers = {"x-amz-target": "AmazonSSM.ListTagsForResource"}
+ for local_alias in (
+ "arn:aws:ssm:us-east-1:000000000000:parameter//app/db",
+ "arn:aws:ssm:us-east-1:000000000000:parameterapp/db",
+ ):
+ assert extract_resource_arn(
+ "ssm", "POST", "/", headers,
+ json.dumps({"ResourceId": local_alias}).encode(),
+ {}, self.REGION, self.ACCOUNT,
+ ) == "arn:aws:ssm:us-east-1:000000000000:parameter/app/db"
+ assert extract_resource_arn(
+ "ssm", "POST", "/", headers,
+ json.dumps({"ResourceType": "Parameter", "ResourceId": arn}).encode(),
+ {}, self.REGION, self.ACCOUNT,
+ ) == arn
+ for foreign_arn in (
+ "arn:aws:ssm:us-west-2:000000000000:parameter/app/db",
+ "arn:aws:ssm:us-east-1:111111111111:parameter/app/db",
+ "arn:aws:ssm:us-east-1:000000000000:document/app/db",
+ ):
+ assert extract_resource_arn(
+ "ssm", "POST", "/", headers,
+ json.dumps({"ResourceType": "Parameter", "ResourceId": foreign_arn}).encode(),
+ {}, self.REGION, self.ACCOUNT,
+ ) == foreign_arn
+ assert extract_resource_arn(
+ "ssm", "POST", "/", headers,
+ json.dumps({
+ "ResourceType": "Document", "ResourceId": "/app/db", "Name": "/app/db",
+ }).encode(), {}, self.REGION, self.ACCOUNT,
+ ) == "*"
+ assert extract_resource_arn(
+ "ssm", "POST", "/", headers,
+ json.dumps({"ResourceType": "Parameter", "Name": "/app/db"}).encode(),
+ {}, self.REGION, self.ACCOUNT,
+ ) == "*"
+
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")
[email protected]("policy_mode", ("exact", "explicit-deny", "action-only"))
+def test_ssm_parameter_tag_actions_enforce_exact_resource_and_preserve_denied_tags(
+ monkeypatch, policy_mode,
+):
+ """Run the real ASGI route, IAM evaluator, and SSM tag handlers."""
+ from ministack import app as app_mod
+ from ministack.services import iam as iam_svc
+ from ministack.services import ssm as ssm_svc
+
+ monkeypatch.setattr(app_mod, "AUTH", True)
+ account, region = "123456789012", "us-east-1"
+ key, user = "AKIASSMTAGAUTHCASE", "ssm-tag-auth-case"
+ name_a, name_b = "/iam-ssm-tag/a", "/iam-ssm-tag/b"
+ legacy_name = "iam-ssm-tag/legacy"
+ arn_a = f"arn:aws:ssm:{region}:{account}:parameter/iam-ssm-tag/a"
+ arn_b = f"arn:aws:ssm:{region}:{account}:parameter/iam-ssm-tag/b"
+ legacy_arn = f"arn:aws:ssm:{region}:{account}:parameteriam-ssm-tag/legacy"
+ canonical_legacy_arn = f"arn:aws:ssm:{region}:{account}:parameter/iam-ssm-tag/legacy"
+ iam_svc._users.set_scoped(account, None, user, {"UserName": user, "AttachedPolicies": []})
+ iam_svc._access_keys.set_scoped(account, None, key, {
+ "AccessKeyId": key, "SecretAccessKey": "test-secret", "Status": "Active",
+ "UserName": user,
+ })
+ for name, arn in ((name_a, arn_a), (name_b, arn_b), (legacy_name, legacy_arn)):
+ ssm_svc._parameters.set_scoped(account, region, name, {"ARN": arn})
+ ssm_svc._tags.set_scoped(account, region, arn_b, {"existing": "before"})
+ ssm_svc._tags.set_scoped(account, region, legacy_arn, {"existing": "legacy"})
+
+ def call(action, resource_id, *, with_headers=False, **extra):
+ payload = {"ResourceType": "Parameter", "ResourceId": resource_id, **extra}
+ body = json.dumps(payload).encode()
+ sent = []
+
+ async def receive():
+ return {"type": "http.request", "body": body, "more_body": False}
+
+ async def send(message):
+ sent.append(message)
+
+ scope = {
+ "type": "http", "method": "POST", "path": "/", "query_string": b"",
+ "headers": [
+ (b"host", b"ssm.us-east-1.amazonaws.com"),
+ (b"x-amz-target", f"AmazonSSM.{action}".encode()),
+ (b"content-type", b"application/x-amz-json-1.1"),
+ (b"authorization", (
+ f"AWS4-HMAC-SHA256 Credential={key}/20260928/{region}/ssm/aws4_request"
+ ).encode()),
+ ],
+ }
+ asyncio.run(app_mod.app(scope, receive, send))
+ response = sent[0]["status"], json.loads(sent[1]["body"])
+ if with_headers:
+ return *response, {name.lower(): value for name, value in sent[0]["headers"]}
+ return response
+
+ def policy(*statements):
+ iam_svc._user_inline_policies.set_scoped(account, None, user, {
+ "tag-access": {"Version": "2012-10-17", "Statement": list(statements)},
+ })
+
+ actions = ["ssm:AddTagsToResource", "ssm:RemoveTagsFromResource", "ssm:ListTagsForResource"]
+ try:
+ if policy_mode == "exact":
+ policy({"Effect": "Allow", "Action": actions, "Resource": arn_a})
+ assert call("AddTagsToResource", name_a, Tags=[{"Key": "team", "Value": "a"}])[0] == 200
+ assert call("ListTagsForResource", "iam-ssm-tag/a") == (
+ 200, {"TagList": [{"Key": "team", "Value": "a"}]},
+ )
+ assert call("RemoveTagsFromResource", arn_a, TagKeys=["team"])[0] == 200
+ assert call("ListTagsForResource", name_a) == (200, {"TagList": []})
+ for action, extra in (
+ ("AddTagsToResource", {"Tags": [{"Key": "new", "Value": "bad"}]}),
+ ("RemoveTagsFromResource", {"TagKeys": ["existing"]}),
+ ("ListTagsForResource", {}),
+ ):
+ status, denied, response_headers = call(
+ action, name_b, Name=name_a, with_headers=True, **extra,
+ )
+ assert status == 400 and denied["__type"] == "AccessDeniedException"
+ assert f"on resource: {arn_b}" in denied["Message"]
+ assert f"because no identity-based policy allows the ssm:{action} action" in denied["Message"]
+ assert response_headers[b"content-type"] == b"application/x-amz-json-1.1"
+ assert b"x-amzn-errortype" not in response_headers
+ assert ssm_svc._tags.get_scoped(account, region, arn_b) == {"existing": "before"}
+ for foreign_arn in (
+ f"arn:aws:ssm:us-west-2:{account}:parameter/iam-ssm-tag/a",
+ f"arn:aws:ssm:{region}:111111111111:parameter/iam-ssm-tag/a",
+ ):
+ status, denied = call("ListTagsForResource", foreign_arn)
+ assert status == 400 and denied["__type"] == "AccessDeniedException"
+ status, denied = call(
+ "AddTagsToResource", name_a, ResourceType="Document",
+ Tags=[{"Key": "new", "Value": "bad"}],
+ )
+ assert status == 400 and denied["__type"] == "AccessDeniedException"
+ assert ssm_svc._tags.get_scoped(account, region, name_a) is None
+ elif policy_mode == "explicit-deny":
+ policy(
+ {"Effect": "Allow", "Action": actions, "Resource": "*"},
+ {"Effect": "Deny", "Action": actions, "Resource": arn_b},
+ )
+ for action, extra in (
+ ("AddTagsToResource", {"Tags": [{"Key": "new", "Value": "bad"}]}),
+ ("RemoveTagsFromResource", {"TagKeys": ["existing"]}),
+ ("ListTagsForResource", {}),
+ ):
+ for resource_id in (
+ name_b, "iam-ssm-tag/b", arn_b,
+ f"arn:aws:ssm:{region}:{account}:parameter//iam-ssm-tag/b",
+ ):
+ status, denied = call(action, resource_id, **extra)
+ assert status == 400 and denied["__type"] == "AccessDeniedException"
+ assert f"on resource: {arn_b}" in denied["Message"]
+ assert "with an explicit deny in an identity-based policy" in denied["Message"]
+ assert ssm_svc._tags.get_scoped(account, region, arn_b) == {"existing": "before"}
+ policy(
+ {"Effect": "Allow", "Action": actions, "Resource": "*"},
+ {"Effect": "Deny", "Action": actions, "Resource": canonical_legacy_arn},
+ )
+ status, denied = call(
+ "RemoveTagsFromResource", legacy_arn, TagKeys=["existing"],
+ )
+ assert status == 400 and denied["__type"] == "AccessDeniedException"
+ assert ssm_svc._tags.get_scoped(account, region, legacy_arn) == {"existing": "legacy"}
+ else:
+ policy({"Effect": "Allow", "Action": "ssm:ListTagsForResource", "Resource": arn_a})
+ assert call("ListTagsForResource", name_a) == (200, {"TagList": []})
+ for action, extra in (
+ ("AddTagsToResource", {"Tags": [{"Key": "new", "Value": "bad"}]}),
+ ("RemoveTagsFromResource", {"TagKeys": ["existing"]}),
+ ):
+ status, denied = call(action, name_a, **extra)
+ assert status == 400 and denied["__type"] == "AccessDeniedException"
+ assert f"ssm:{action}" in denied["Message"]
+ assert ssm_svc._tags.get_scoped(account, region, arn_a) is None
+ finally:
+ iam_svc._user_inline_policies.pop_scoped(account, None, user, None)
+ iam_svc._access_keys.pop_scoped(account, None, key, None)
+ iam_svc._users.pop_scoped(account, None, user, None)
+ for name in (name_a, name_b, legacy_name):
+ ssm_svc._parameters.pop_scoped(account, region, name, None)
+ for arn in (arn_a, arn_b, legacy_arn):
+ ssm_svc._tags.pop_scoped(account, region, arn, None)
+
+
+def test_ssm_parameter_tag_authorization_is_scoped_to_request_account_and_region(monkeypatch):
+ from ministack import app as app_mod
+ from ministack.services import iam as iam_svc
+ from ministack.services import ssm as ssm_svc
+
+ monkeypatch.setattr(app_mod, "AUTH", True)
+ name = "/iam-ssm-tag/scoped"
+ tenants = (
+ ("123456789012", "us-east-1", "AKIASSMTAGEAST", "ssm-tag-east"),
+ ("123456789012", "us-west-2", "AKIASSMTAGWEST", "ssm-tag-west"),
+ ("210987654321", "us-east-1", "AKIASSMTAGOTHER", "ssm-tag-other"),
+ )
+
+ def arn(account, region):
+ return f"arn:aws:ssm:{region}:{account}:parameter/iam-ssm-tag/scoped"
+
+ def call(account, region, key, resource_id):
+ body = json.dumps({
+ "ResourceType": "Parameter", "ResourceId": resource_id,
+ "Tags": [{"Key": "owner", "Value": key}],
+ }).encode()
+ sent = []
+
+ async def receive():
+ return {"type": "http.request", "body": body, "more_body": False}
+
+ async def send(message):
+ sent.append(message)
+
+ scope = {
+ "type": "http", "method": "POST", "path": "/", "query_string": b"",
+ "headers": [
+ (b"host", f"ssm.{region}.amazonaws.com".encode()),
+ (b"x-amz-target", b"AmazonSSM.AddTagsToResource"),
+ (b"content-type", b"application/x-amz-json-1.1"),
+ (b"authorization", (
+ f"AWS4-HMAC-SHA256 Credential={key}/20260928/{region}/ssm/aws4_request"
+ ).encode()),
+ ],
+ }
+ asyncio.run(app_mod.app(scope, receive, send))
+ return sent[0]["status"]
+
+ try:
+ for account, region, key, user in tenants:
+ parameter_arn = arn(account, region)
+ iam_svc._users.set_scoped(account, None, user, {
+ "UserName": user, "AttachedPolicies": [],
+ })
+ iam_svc._access_keys.set_scoped(account, None, key, {
+ "AccessKeyId": key, "SecretAccessKey": "test-secret", "Status": "Active",
+ "UserName": user,
+ })
+ iam_svc._user_inline_policies.set_scoped(account, None, user, {
+ "tag-access": {"Statement": [{
+ "Effect": "Allow", "Action": "ssm:AddTagsToResource", "Resource": parameter_arn,
+ }]},
+ })
+ ssm_svc._parameters.set_scoped(account, region, name, {"ARN": parameter_arn})
+ ssm_svc._tags.set_scoped(account, region, parameter_arn, {"owner": "before"})
+
+ for account, region, key, _ in tenants:
+ assert call(account, region, key, name) == 200
+ assert ssm_svc._tags.get_scoped(account, region, arn(account, region)) == {
+ "owner": key,
+ }
+
+ for account, region, key, _ in tenants:
+ for other_account, other_region, _, _ in tenants:
+ if (account, region) == (other_account, other_region):
+ continue
+ before = {
+ (a, r): ssm_svc._tags.get_scoped(a, r, arn(a, r)).copy()
+ for a, r, _, _ in tenants
+ }
+ assert call(account, region, key, arn(other_account, other_region)) == 400
+ assert all(
+ ssm_svc._tags.get_scoped(a, r, arn(a, r)) == before[a, r]
+ for a, r, _, _ in tenants
+ )
+ finally:
+ for account, region, key, user in tenants:
+ iam_svc._user_inline_policies.pop_scoped(account, None, user, None)
+ iam_svc._access_keys.pop_scoped(account, None, key, None)
+ iam_svc._users.pop_scoped(account, None, user, None)
+ ssm_svc._parameters.pop_scoped(account, region, name, None)
+ ssm_svc._tags.pop_scoped(account, region, arn(account, region), None)
+
+
# ---------------------------------------------------------------------------
# CreateFunction with an unresolvable role (#1506)
# ---------------------------------------------------------------------------