Skip to content

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

fix(logs): include ownership and tagging context in IAM checks (#2065)

Adrian-Ryan Acalaaf6776ea0a25
diff --git a/CHANGELOG.md b/CHANGELOG.md
index aa726ff5..6f8899c6 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -23,6 +23,8 @@ Versioning follows [Semantic Versioning](https://semver.org/).
- **IoT — `DescribeCertificate` reports `certificateMode`** — the field was missing from the description. It is now `SNI_ONLY` for a certificate registered with `RegisterCertificateWithoutCA` and `DEFAULT` for the others, as AWS reports it. Contributed by @iot-rocket.
### Fixed
+- **CloudWatch Logs — IAM tag conditions** — under `AUTH=true`, authorization now includes existing resource tags, incoming request tags, and the tag keys being added or removed. Ownership-based allows work and explicit denies can prevent removal of protected tags before state changes. ARN-based tagging APIs authorize the supplied resource ARN instead of `*` and share a validated, account- and region-scoped target lookup with the handlers. Foreign or malformed tagging ARNs, including log group ARNs ending in `:*`, fail with HTTP 400 `ValidationException` before policy evaluation, as observed on AWS. Authorization denials match live AWS's HTTP 400 JSON 1.1 envelope with a capitalized `Message` naming the resource. Contributed by @AdrianAcala.
+
- **Step Functions — `$$.State.RetryCount`** — the Context Object's `State` carried only `Name` and `EnteredTime`, so `"x.$": "$$.State.RetryCount"` resolved to `null`, and a Task's `Parameters` were evaluated once, so a retry resent the first attempt's values. `State.RetryCount` (a number in the Context Object documentation) is now `0` when a state is entered and counts its retries (Task, Parallel and Map), and a Task's `Parameters` are evaluated for each attempt, as JSONata `Arguments` already were.
- **Step Functions — `StopExecution` keeps its `error` and `cause`** — they were recorded only in the `ExecutionAborted` history event, so `DescribeExecution` of the aborted execution returned neither. They are now kept on the execution and returned by `DescribeExecution`; AWS returns the `cause` of an execution stopped with one.
- **Step Functions — the first matching retrier decides** — a retrier that had used its `MaxAttempts` (or had `MaxAttempts: 0`) was skipped, so a later matching retrier such as `States.ALL` retried the error anyway. The first retrier whose `ErrorEquals` matches now decides: once it has used its attempts the state fails (or goes to its `Catch`), as the Developer Guide's error-handling examples describe.
diff --git a/ministack/app.py b/ministack/app.py
index f1b76ec6..8ec88c67 100644
--- a/ministack/app.py
+++ b/ministack/app.py
@@ -2497,6 +2497,7 @@ async def _dispatch_service_request(
eventbridge_resource_arns,
extract_iam_action,
extract_resource_arn,
+ logs_service_context,
)
from ministack.core.iam_evaluator import AuthError, enforce, pin_request_caller
from ministack.core.responses import get_account_id
@@ -2511,6 +2512,28 @@ async def _dispatch_service_request(
service_context = (
dynamodb_service_context(body) if service == "dynamodb" else None
)
+ if service == "logs":
+ from ministack.services import cloudwatch_logs
+
+ logs_validation_error = None
+ if iam_action in {"logs:TagResource", "logs:UntagResource", "logs:ListTagsForResource"}:
+ try:
+ logs_payload = json.loads(body or b"{}")
+ except (json.JSONDecodeError, UnicodeDecodeError):
+ logs_payload = None
+ if isinstance(logs_payload, dict):
+ logs_validation_error = cloudwatch_logs.validate_tag_resource_arn(
+ logs_payload.get("resourceArn", ""), account_id=get_account_id(), region=region,
+ )
+ service_context = logs_service_context(
+ iam_action.split(":", 1)[1], body, resource_arn, region, get_account_id()
+ )
+ denied = enforce(
+ access_key, iam_action, service, region,
+ resource_arn=resource_arn, service_context=service_context,
+ )
+ if service == "logs" and logs_validation_error is not None and not isinstance(denied, AuthError):
+ return logs_validation_error
# A DynamoDB transaction is not itself an IAM action: each item is
# authorized as the single-item action it performs, on its table.
transaction_checks = (
diff --git a/ministack/core/iam_actions.py b/ministack/core/iam_actions.py
index 2f14c11b..4fe197ac 100644
--- a/ministack/core/iam_actions.py
+++ b/ministack/core/iam_actions.py
@@ -1043,6 +1043,9 @@ def extract_resource_arn(service: str, method: str, path: str,
return "*"
if service == "logs":
+ action = headers.get("x-amz-target", "").rsplit(".", 1)[-1]
+ if action in {"TagResource", "UntagResource", "ListTagsForResource"}:
+ return _safe_json_field(body, "resourceArn") or "*"
name = _safe_json_field(body, "logGroupName")
if name:
return f"arn:aws:logs:{region}:{account_id}:log-group:{name}"
@@ -1696,6 +1699,51 @@ def dynamodb_resource_arns(body: bytes, region: str, account_id: str) -> list[st
]
+def logs_service_context(action: str, body: bytes, resource_arn: str,
+ region: str, account_id: str) -> dict:
+ """Tag conditions from the Logs payload and the existing scoped resource.
+
+ Read stored tags before dispatch: incoming tags must not replace ownership
+ context, and an untag request must still see the tags it proposes removing.
+ """
+ from ministack.services import cloudwatch_logs as logs
+
+ try:
+ data = json.loads(body or b"{}")
+ except (json.JSONDecodeError, TypeError, UnicodeDecodeError):
+ return {}
+ if not isinstance(data, dict):
+ return {}
+
+ context = {}
+
+ def add_tags(prefix, tags):
+ if not isinstance(tags, dict):
+ return
+ for name, value in tags.items():
+ key = f"{prefix}/{name}".lower()
+ if key not in context:
+ context[key] = value
+ else:
+ previous = context[key]
+ context[key] = (previous if isinstance(previous, list) else [previous]) + [value]
+
+ if action in {"CreateLogGroup", "TagLogGroup", "TagResource"}:
+ tags = data.get("tags", {})
+ if isinstance(tags, dict):
+ add_tags("aws:RequestTag", tags)
+ context["aws:TagKeys"] = list(tags)
+ elif action in {"UntagLogGroup", "UntagResource"}:
+ keys = data.get("tags" if action == "UntagLogGroup" else "tagKeys", [])
+ if isinstance(keys, list):
+ context["aws:TagKeys"] = keys
+
+ if action == "CreateLogGroup":
+ return context
+ record = logs.resolve_tag_resource(resource_arn, account_id=account_id, region=region)
+ if record is not None:
+ add_tags("aws:ResourceTag", record.get("tags", {}))
+ return context
_DYNAMODB_TRANSACT_ITEM_ACTIONS = {
"ConditionCheck": "dynamodb:ConditionCheckItem",
"Put": "dynamodb:PutItem",
@@ -1793,9 +1841,9 @@ def access_denied_response(service: str, action: str, principal_arn: str,
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:
- # SSM authorization denials are HTTP 400, JSON 1.1, with a capitalized
- # Message naming the resource.
+ if service in {"ssm", "logs"} and not error_code:
+ # SSM and Logs authorization denials are HTTP 400, JSON 1.1, with a
+ # capitalized Message naming the resource, as observed on live AWS.
reason = (
"with an explicit deny in an identity-based policy" if explicit_deny
else f"because no identity-based policy allows the {action} action"
diff --git a/ministack/core/iam_evaluator.py b/ministack/core/iam_evaluator.py
index fef193d5..bbf43d56 100644
--- a/ministack/core/iam_evaluator.py
+++ b/ministack/core/iam_evaluator.py
@@ -206,8 +206,10 @@ def _resolve_condition_key(key: str, ctx: EvalContext) -> Any:
if k == "aws:sourceip":
return ctx.source_ip
if k == "aws:tagkeys":
- return ctx.tag_keys
+ return ctx.service_context.get(k, ctx.tag_keys)
if k.startswith("aws:requesttag/"):
+ if k in ctx.service_context:
+ return ctx.service_context[k]
tag_key = key[len("aws:RequestTag/"):]
values = [value for name, value in ctx.request_tags.items() if name.lower() == tag_key.lower()]
if len(values) == 1:
diff --git a/ministack/services/cloudwatch_logs.py b/ministack/services/cloudwatch_logs.py
index 28289b6e..fc4b404a 100644
--- a/ministack/services/cloudwatch_logs.py
+++ b/ministack/services/cloudwatch_logs.py
@@ -348,6 +348,10 @@ async def handle_request(method, path, headers, body, query_params):
handler = handlers.get(action)
if not handler:
return error_response_json("InvalidOperationException", f"Unknown action: {action}", 400)
+ if action in {"TagResource", "UntagResource", "ListTagsForResource"}:
+ invalid = validate_tag_resource_arn(data.get("resourceArn", ""))
+ if invalid is not None:
+ return invalid
return handler(data)
@@ -1468,26 +1472,57 @@ def _list_tags_log_group(data):
# Tags – modern ARN-based APIs
# ---------------------------------------------------------------------------
-def _resolve_tag_record_by_arn(arn: str):
- """Resolve a logs ARN to the mutable dict holding its ``tags``. The
- ARN-based tag operations accept log groups AND the vended-delivery trio
- (delivery sources, delivery destinations, deliveries) — the AWS provider
- reads tags back on every one of them after create."""
- group = _resolve_group_by_arn(arn)
- if group:
- return _log_groups[group].setdefault("tags", {})
- for marker, store in (
- (":delivery-source:", _delivery_sources),
- (":delivery-destination:", _delivery_destinations),
- (":delivery:", _deliveries),
- ):
- if marker in arn:
- record = store.get(arn.rsplit(":", 1)[-1])
- if record is not None:
- return record.setdefault("tags", {})
+def _tag_resource_identity(arn: str, account_id: str, region: str):
+ parsed = parse_arn(arn)
+ resource_type, _, name = parsed.resource.partition(":")
+ stores = {
+ "log-group": _log_groups,
+ "delivery-source": _delivery_sources,
+ "delivery-destination": _delivery_destinations,
+ "delivery": _deliveries,
+ }
+ pattern = r"[\w./#-]+" if resource_type == "log-group" else r"[\w.-]+"
+ if (parsed.partition != "aws" or parsed.service != "logs"
+ or parsed.account_id != account_id or parsed.region != region
+ or resource_type not in stores or not re.fullmatch(pattern, name, flags=re.ASCII)):
+ raise ArnParseError("Invalid resourceArn")
+ return stores[resource_type], resource_type, name
+
+
+def validate_tag_resource_arn(arn: str, *, account_id: str | None = None,
+ region: str | None = None):
+ """Modern tag APIs validate scope and ARN shape before IAM policy checks."""
+ try:
+ _tag_resource_identity(arn, account_id or get_account_id(), region or get_region())
+ except ArnParseError:
+ # Observed on live Logs: lowercase message, JSON 1.1, no error header.
+ return json_response({"__type": "ValidationException", "message": "Invalid resourceArn"},
+ 400, content_type="application/x-amz-json-1.1")
return None
+def resolve_tag_resource(arn: str, *, account_id: str | None = None,
+ region: str | None = None):
+ """Use the same validated, scoped resource for IAM context and tag dispatch."""
+ account_id, region = account_id or get_account_id(), region or get_region()
+ try:
+ store, resource_type, name = _tag_resource_identity(arn, account_id, region)
+ except ArnParseError:
+ return None
+ record = store.get_scoped(account_id, region, name)
+ if record is None:
+ return None
+ stored_arn = record.get("arn", "")
+ if resource_type == "log-group":
+ stored_arn = stored_arn.removesuffix(":*")
+ return record if stored_arn == arn else None
+
+
+def _resolve_tag_record_by_arn(arn: str):
+ record = resolve_tag_resource(arn)
+ return record.setdefault("tags", {}) if record is not None else None
+
+
def _tag_resource(data):
arn = data.get("resourceArn", "")
tags = _resolve_tag_record_by_arn(arn)
diff --git a/tests/test_cloudwatch_logs.py b/tests/test_cloudwatch_logs.py
index 6e5228be..0fb95711 100644
--- a/tests/test_cloudwatch_logs.py
+++ b/tests/test_cloudwatch_logs.py
@@ -1102,7 +1102,7 @@ def test_logs_tag_resource(logs):
logs.create_log_group(logGroupName=group)
groups = logs.describe_log_groups(logGroupNamePrefix=group)["logGroups"]
- arn = groups[0]["arn"]
+ arn = groups[0]["arn"].removesuffix(":*")
logs.tag_resource(resourceArn=arn, tags={"team": "platform", "env": "staging"})
@@ -1121,7 +1121,7 @@ def test_logs_untag_resource(logs):
logs.create_log_group(logGroupName=group, tags={"keep": "yes", "remove": "me"})
groups = logs.describe_log_groups(logGroupNamePrefix=group)["logGroups"]
- arn = groups[0]["arn"]
+ arn = groups[0]["arn"].removesuffix(":*")
logs.untag_resource(resourceArn=arn, tagKeys=["remove"])
diff --git a/tests/test_logs_iam_context.py b/tests/test_logs_iam_context.py
new file mode 100644
index 00000000..176e7fd6
--- /dev/null
+++ b/tests/test_logs_iam_context.py
@@ -0,0 +1,311 @@
+"""Exercise Logs tag conditions through the ASGI authorization boundary."""
+
+import asyncio
+import json
+
+import pytest
+
+from ministack import app as app_mod
+from ministack.services import cloudwatch_logs as logs
+from ministack.services import iam
+
+
+def logs_auth(monkeypatch):
+ monkeypatch.setattr(app_mod, "AUTH", True)
+ account, region = "123456789012", "us-east-1"
+ user, key = "logs-tag-context", "AKIALOGSTAGCONTEXT"
+ iam._users.set_scoped(account, None, user, {"UserName": user, "AttachedPolicies": []})
+ iam._access_keys.set_scoped(account, None, key, {
+ "AccessKeyId": key, "SecretAccessKey": "test", "Status": "Active", "UserName": user,
+ })
+ created = []
+
+ def call(action, *, root=False, request_region=region, with_headers=False, raw_body=None, **payload):
+ body = json.dumps(payload).encode() if raw_body is None else raw_body
+ 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"logs.{request_region}.amazonaws.com".encode()),
+ (b"x-amz-target", f"Logs_20140328.{action}".encode()),
+ (b"content-type", b"application/x-amz-json-1.1"),
+ (b"authorization", (
+ f"AWS4-HMAC-SHA256 Credential={account if root else key}"
+ f"/20261006/{request_region}/logs/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 create(name, tags=None, request_region=region):
+ assert call("CreateLogGroup", root=True, request_region=request_region,
+ logGroupName=name, tags=tags or {})[0] == 200
+ created.append((request_region, name))
+ return f"arn:aws:logs:{request_region}:{account}:log-group:{name}"
+
+ def policy(*statements):
+ iam._user_inline_policies.set_scoped(account, None, user, {
+ "context": {"Version": "2012-10-17", "Statement": list(statements)},
+ })
+
+ try:
+ yield call, create, policy, account, region
+ finally:
+ iam._user_inline_policies.pop_scoped(account, None, user, None)
+ iam._access_keys.pop_scoped(account, None, key, None)
+ iam._users.pop_scoped(account, None, user, None)
+ for request_region, name in created:
+ logs._log_groups.pop_scoped(account, request_region, name, None)
+ logs._log_groups.pop_scoped(account, region, "logs-context-create", None)
+
+
+def assert_denied(response, *, explicit=False):
+ status, body = response
+ assert status == 400 and body["__type"] == "AccessDeniedException"
+ if explicit:
+ assert "explicit deny" in body["Message"]
+
+
[email protected]("explicit", [False, True])
+def test_authorization_denial_matches_live_logs_error_envelope(logs_auth, explicit):
+ call, create, policy, _, _ = logs_auth
+ arn = create("logs-context-denial-envelope", {"protect": "true"})
+ if explicit:
+ policy(
+ {"Effect": "Allow", "Action": "logs:UntagResource", "Resource": arn},
+ {"Effect": "Deny", "Action": "logs:UntagResource", "Resource": arn},
+ )
+ else:
+ policy()
+ status, body, headers = call("UntagResource", resourceArn=arn, tagKeys=["protect"], with_headers=True)
+ assert_denied((status, body), explicit=explicit)
+ assert f"on resource: {arn}" in body["Message"]
+ if not explicit:
+ assert "because no identity-based policy allows the logs:UntagResource action" in body["Message"]
+ assert headers[b"content-type"] == b"application/x-amz-json-1.1"
+ assert b"x-amzn-errortype" not in headers
+ assert "message" not in body
+
+
[email protected]("action", ["PutRetentionPolicy", "ListTagsLogGroup", "ListTagsForResource"])
+def test_owner_tag_allows_only_matching_existing_group(logs_auth, action):
+ call, create, policy, _, _ = logs_auth
+ for owner in ("team-a", "team-b", None):
+ name = f"logs-context-owner-{owner}"
+ arn = create(name, {"owner": owner} if owner else {})
+ policy({"Effect": "Allow", "Action": f"logs:{action}", "Resource": arn + "*",
+ "Condition": {"StringEquals": {"aws:ResourceTag/owner": "team-a"}}})
+ params = {"resourceArn": arn} if action == "ListTagsForResource" else {"logGroupName": name}
+ if action == "PutRetentionPolicy":
+ params["retentionInDays"] = 7
+ response = call(action, **params)
+ if owner == "team-a":
+ assert response[0] == 200
+ else:
+ assert_denied(response)
+
+
[email protected]("legacy", [False, True])
+def test_protect_tag_deny_prevents_removal_without_blocking_other_tags(logs_auth, legacy):
+ call, create, policy, _, _ = logs_auth
+ name = "logs-context-protected"
+ arn = create(name, {"protect": "true", "harmless": "yes"})
+ action = "UntagLogGroup" if legacy else "UntagResource"
+ policy(
+ {"Effect": "Allow", "Action": f"logs:{action}", "Resource": "*"},
+ {"Effect": "Deny", "Action": f"logs:{action}", "Resource": "*",
+ "Condition": {"StringEquals": {"aws:ResourceTag/protect": "true"},
+ "ForAnyValue:StringEquals": {"aws:TagKeys": ["protect"]}}},
+ )
+ target = {"logGroupName": name} if legacy else {"resourceArn": arn}
+ field = "tags" if legacy else "tagKeys"
+ assert_denied(call(action, **target, **{field: ["harmless", "protect"]}), explicit=True)
+ assert call("ListTagsForResource", root=True, resourceArn=arn) == (
+ 200, {"tags": {"protect": "true", "harmless": "yes"}},
+ )
+ assert call(action, **target, **{field: ["harmless"]})[0] == 200
+ assert call("ListTagsForResource", root=True, resourceArn=arn) == (200, {"tags": {"protect": "true"}})
+
+
[email protected]("action", ["CreateLogGroup", "TagLogGroup", "TagResource"])
+def test_request_tags_and_keys_use_the_operation_payload(logs_auth, action):
+ call, create, policy, _, _ = logs_auth
+ name = "logs-context-create"
+ arn = f"arn:aws:logs:us-east-1:123456789012:log-group:{name}"
+ if action != "CreateLogGroup":
+ create(name, {"owner": "team-a"})
+ policy({"Effect": "Allow", "Action": f"logs:{action}", "Resource": arn + "*",
+ "Condition": {"StringEquals": {"aws:RequestTag/owner": "team-a"},
+ "ForAllValues:StringEquals": {"aws:TagKeys": ["owner"]}}})
+ target = {"resourceArn": arn} if action == "TagResource" else {"logGroupName": name}
+ for tags in ({"owner": "team-b"}, {}, {"owner": "team-a", "extra": "bad"}):
+ assert_denied(call(action, **target, tags=tags))
+ assert call(action, **target, tags={"owner": "team-a"})[0] == 200
+
+
+def test_modern_tag_actions_enforce_exact_target_arn(logs_auth):
+ call, create, policy, _, _ = logs_auth
+ allowed = create("logs-context-exact-allow")
+ denied = create("logs-context-exact-deny", {"protect": "true"})
+ policy({"Effect": "Allow", "Action": ["logs:TagResource", "logs:UntagResource", "logs:ListTagsForResource"],
+ "Resource": allowed})
+ assert call("TagResource", resourceArn=allowed, tags={"owner": "team-a"})[0] == 200
+ assert call("ListTagsForResource", resourceArn=allowed) == (200, {"tags": {"owner": "team-a"}})
+ assert call("UntagResource", resourceArn=allowed, tagKeys=["owner"])[0] == 200
+ for action, extra in (("TagResource", {"tags": {"owner": "wrong"}}),
+ ("UntagResource", {"tagKeys": ["protect"]}), ("ListTagsForResource", {})):
+ assert_denied(call(action, resourceArn=denied, logGroupName="logs-context-exact-allow", **extra))
+ assert call("ListTagsForResource", root=True, resourceArn=denied) == (200, {"tags": {"protect": "true"}})
+
+
[email protected]("legacy", [False, True])
+def test_incoming_owner_tag_cannot_replace_existing_ownership_context(logs_auth, legacy):
+ call, create, policy, _, _ = logs_auth
+ name = "logs-context-change-owner"
+ arn = create(name, {"owner": "team-b"})
+ action = "TagLogGroup" if legacy else "TagResource"
+ policy({"Effect": "Allow", "Action": f"logs:{action}", "Resource": "*",
+ "Condition": {"StringEquals": {"aws:ResourceTag/owner": "team-a",
+ "aws:RequestTag/owner": "team-a"}}})
+ target = {"logGroupName": name} if legacy else {"resourceArn": arn}
+ assert_denied(call(action, **target, tags={"owner": "team-a"}))
+ assert call("ListTagsForResource", root=True, resourceArn=arn) == (200, {"tags": {"owner": "team-b"}})
+
+
+def test_disabled_auth_keeps_logs_tag_calls_permissive(logs_auth, monkeypatch):
+ call, create, policy, _, _ = logs_auth
+ arn = create("logs-context-auth-disabled", {"protect": "true"})
+ policy({"Effect": "Deny", "Action": "logs:*", "Resource": "*"})
+ monkeypatch.setattr(app_mod, "AUTH", False)
+ assert call("UntagResource", root=True, resourceArn=arn, tagKeys=["protect"])[0] == 200
+ assert call("ListTagsForResource", root=True, resourceArn=arn) == (200, {"tags": {}})
+
+
[email protected]("resource_type,store", [
+ ("delivery-source", logs._delivery_sources),
+ ("delivery-destination", logs._delivery_destinations),
+ ("delivery", logs._deliveries),
+])
+def test_modern_tag_context_uses_the_supported_delivery_resource(logs_auth, resource_type, store):
+ call, _, policy, account, region = logs_auth
+ name = "logs-context-delivery"
+ arn = f"arn:aws:logs:{region}:{account}:{resource_type}:{name}"
+ store.set_scoped(account, region, name, {"arn": arn, "tags": {"owner": "team-a", "protect": "true"}})
+ policy(
+ {"Effect": "Allow", "Action": ["logs:ListTagsForResource", "logs:UntagResource"], "Resource": arn,
+ "Condition": {"StringEquals": {"aws:ResourceTag/owner": "team-a"}}},
+ {"Effect": "Deny", "Action": "logs:UntagResource", "Resource": arn,
+ "Condition": {"ForAnyValue:StringEquals": {"aws:TagKeys": ["protect"]}}},
+ )
+ try:
+ assert call("ListTagsForResource", resourceArn=arn) == (
+ 200, {"tags": {"owner": "team-a", "protect": "true"}},
+ )
+ assert_denied(call("UntagResource", resourceArn=arn, tagKeys=["protect"]), explicit=True)
+ assert store.get_scoped(account, region, name)["tags"]["protect"] == "true"
+ finally:
+ store.pop_scoped(account, region, name, None)
+
+
+def test_owner_context_is_scoped_to_resource_account_and_region(logs_auth):
+ call, create, policy, account, region = logs_auth
+ name = "logs-context-scope"
+ local = create(name, {"owner": "team-a"})
+ remote_region = create(name, {"owner": "team-b"}, request_region="us-west-2")
+ logs._log_groups.set_scoped("111111111111", region, name, {
+ "arn": f"arn:aws:logs:{region}:111111111111:log-group:{name}:*", "tags": {"owner": "team-a"},
+ })
+ policy({"Effect": "Allow", "Action": "logs:ListTagsForResource", "Resource": "*",
+ "Condition": {"StringEquals": {"aws:ResourceTag/owner": "team-a"}}})
+ try:
+ assert call("ListTagsForResource", resourceArn=local)[0] == 200
+ assert_denied(call("ListTagsForResource", resourceArn=remote_region, request_region="us-west-2"))
+ for invalid in (remote_region, local.replace(account, "111111111111")):
+ assert call("ListTagsForResource", resourceArn=invalid) == (
+ 400, {"__type": "ValidationException", "message": "Invalid resourceArn"},
+ )
+ finally:
+ logs._log_groups.pop_scoped("111111111111", region, name, None)
+
+
[email protected]("auth", [False, True])
[email protected]("resource_type,store", [
+ ("log-group", logs._log_groups),
+ ("delivery-source", logs._delivery_sources),
+ ("delivery-destination", logs._delivery_destinations),
+ ("delivery", logs._deliveries),
+])
+def test_modern_tag_actions_reject_aliases_to_unrelated_arns(
+ logs_auth, monkeypatch, auth, resource_type, store):
+ call, create, policy, account, region = logs_auth
+ name = "logs-context-resolver"
+ tags = {"owner": "team-a", "protect": "true"}
+ arn = f"arn:aws:logs:{region}:{account}:{resource_type}:{name}"
+ if resource_type == "log-group":
+ create(name, tags)
+ else:
+ store.set_scoped(account, region, name, {"arn": arn, "tags": dict(tags)})
+ monkeypatch.setattr(app_mod, "AUTH", auth)
+ invalid_arns = [
+ arn.replace(account, "111111111111"),
+ arn.replace(region, "us-west-2"),
+ arn.replace(":logs:", ":s3:"),
+ arn.replace("arn:aws:", "arn:aws-cn:"),
+ arn + ":**" if resource_type == "log-group" else arn.replace(
+ f":{resource_type}:", f":{resource_type}:other:"),
+ ]
+ if resource_type == "log-group":
+ invalid_arns.append(arn + ":*")
+ try:
+ for invalid in invalid_arns:
+ # Permission on the supplied ARN must never authorize a mutation
+ # or a read of the same-named local resource.
+ policy({"Effect": "Allow", "Action": "logs:*", "Resource": invalid})
+ for action, extra in (
+ ("TagResource", {"tags": {"protect": "false"}}),
+ ("UntagResource", {"tagKeys": ["protect"]}),
+ ("ListTagsForResource", {}),
+ ):
+ assert call(action, root=not auth, resourceArn=invalid, **extra) == (
+ 400, {"__type": "ValidationException", "message": "Invalid resourceArn"},
+ )
+ assert store.get_scoped(account, region, name)["tags"] == tags
+ finally:
+ if resource_type != "log-group":
+ store.pop_scoped(account, region, name, None)
+
+
+def test_invalid_tag_arn_precedes_policy_denial_but_preserves_credential_errors(logs_auth):
+ call, create, policy, account, _ = logs_auth
+ arn = create("logs-context-validation", {"protect": "true"})
+ policy({"Effect": "Deny", "Action": "logs:*", "Resource": "*"})
+ status, body, headers = call("UntagResource", resourceArn=arn + ":*",
+ tagKeys=["protect"], with_headers=True)
+ assert (status, body) == (400, {"__type": "ValidationException", "message": "Invalid resourceArn"})
+ assert headers[b"content-type"] == b"application/x-amz-json-1.1"
+ assert b"x-amzn-errortype" not in headers
+ iam._access_keys.get_scoped(account, None, "AKIALOGSTAGCONTEXT")["Status"] = "Inactive"
+ status, body = call("UntagResource", resourceArn=arn + ":*", tagKeys=["protect"])
+ assert status == 403 and body["__type"] == "InvalidClientTokenId"
+
+
[email protected]("auth", [False, True])
+def test_tag_arn_validation_preserves_malformed_json_error(logs_auth, monkeypatch, auth):
+ call, _, _, _, _ = logs_auth
+ monkeypatch.setattr(app_mod, "AUTH", auth)
+ for action in ("TagResource", "UntagResource", "ListTagsForResource"):
+ assert call(action, root=True, raw_body=b"{") == (
+ 400, {"__type": "SerializationException", "message": "Invalid JSON"},
+ )