Skip to content

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

fix(iam): correct condition-list negation and request-tag key matching (#1895)

Adrian-Ryan Acala512c45277e81
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 77645546..cfa6ea17 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -28,6 +28,7 @@ Versioning follows [Semantic Versioning](https://semver.org/).
- **SQS — `QueueUrl` matches the gateway's TLS scheme (`USE_SSL=1`)** — `CreateQueue`/`GetQueueUrl`/`ListQueues` always returned `http://` URLs, and the AWS SDK v3 uses the QueueUrl itself as the request endpoint (`useQueueUrlAsEndpoint` defaults true), so a client handed that URL left the TLS-only gateway. The `AWS::SQS::Queue` CloudFormation provisioner built the same hardcoded scheme and now reuses the shared helper. Contributed by @skialpine.
- **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.
+- **IAM — condition value lists and request-tag key matching** — negated conditions now match only when none of their policy values match, so a `StringNotEquals` deny listing permitted values no longer denies one of those values. Request-tag condition keys match every tag name without regard to case, including names that differ only by case; affirmative conditions match any of those values and negated conditions match none. Comparisons of tag values keep the selected operator's case rules.
- **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.
diff --git a/ministack/core/iam_evaluator.py b/ministack/core/iam_evaluator.py
index c4836105..48190542 100644
--- a/ministack/core/iam_evaluator.py
+++ b/ministack/core/iam_evaluator.py
@@ -209,7 +209,10 @@ def _resolve_condition_key(key: str, ctx: EvalContext) -> Any:
return ctx.tag_keys
if k.startswith("aws:requesttag/"):
tag_key = key[len("aws:RequestTag/"):]
- return ctx.request_tags.get(tag_key)
+ values = [value for name, value in ctx.request_tags.items() if name.lower() == tag_key.lower()]
+ if len(values) == 1:
+ return values[0]
+ return values if values else None
if k in ("aws:resourceaccount", "s3:resourceaccount"):
# The account that owns the resource. The emulator hosts one account
# per request and models no cross-account access, so it is the
@@ -374,7 +377,7 @@ _NEGATED_OPS = frozenset({
def _evaluate_single_condition(operator: str, actual: Any,
expected_values: list[str]) -> bool:
- """One condition key vs its expected values. Values are OR'd."""
+ """Compare policy values using OR for affirmative operators and NOR for negated ones."""
op_lower = operator.lower()
# Null check: tests key presence/absence
@@ -415,29 +418,22 @@ def _evaluate_single_condition(operator: str, actual: Any,
actual_list = [str(actual)]
expected_str = [str(v) for v in expected_values]
+ combine = all if op_lower in _NEGATED_OPS else any
+
+ def matches_expected(value: str) -> bool:
+ return combine(op_func(value, expected) for expected in expected_str)
if for_all:
- # Every actual value must match at least one expected value
- return all(
- any(op_func(av, ev) for ev in expected_str)
- for av in actual_list
- )
+ return all(matches_expected(value) for value in actual_list)
if for_any:
- # At least one actual value must match at least one expected value
- return any(
- any(op_func(av, ev) for ev in expected_str)
- for av in actual_list
- )
+ return any(matches_expected(value) for value in actual_list)
- # Standard: any expected value matching any actual value satisfies the condition
- return any(
- op_func(str(actual), ev) for ev in expected_str
- )
+ return matches_expected(str(actual))
def _conditions_met(conditions: dict, ctx: EvalContext) -> bool:
"""All condition blocks must be satisfied (AND between operators).
- Multiple values within a key are OR'd."""
+ Policy values use OR for affirmative operators and NOR for negated ones."""
if not conditions:
return True
for operator, key_values in conditions.items():
@@ -449,6 +445,23 @@ def _conditions_met(conditions: dict, ctx: EvalContext) -> bool:
expected = [expected]
elif not isinstance(expected, list):
expected = [str(expected)]
+ if key.lower().startswith("aws:requesttag/") and isinstance(actual, list):
+ # Case variants are distinct request tags, each with one
+ # value. Evaluate even set operators against each individual
+ # tag, then match any variant for affirmative operators and
+ # none for negated operators, as AWS does.
+ op = operator.lower()
+ if op.endswith("ifexists"):
+ op = op[:-8]
+ if op.startswith("foranyvalue:"):
+ op = op[12:]
+ elif op.startswith("forallvalues:"):
+ op = op[13:]
+ combine = all if op in _NEGATED_OPS else any
+ if not combine(_evaluate_single_condition(operator, value, expected)
+ for value in actual):
+ return False
+ continue
if not _evaluate_single_condition(operator, actual, expected):
return False
return True
diff --git a/tests/test_iam_auth.py b/tests/test_iam_auth.py
index b81924f9..7f5c22b1 100644
--- a/tests/test_iam_auth.py
+++ b/tests/test_iam_auth.py
@@ -520,6 +520,114 @@ def test_condition_operator_by_key_presence(operator, policy_value, matching, ot
assert evaluate(ctx, [stmts]).decision == expected
+_NEGATED_VALUE_LIST_CASES = [
+ ("StringNotEquals", ["qualification", "recovery"], "qualification", "recovery", "neighbor"),
+ ("StringNotEqualsIgnoreCase", ["QUALIFICATION", "RECOVERY"], "qualification", "recovery", "neighbor"),
+ ("StringNotLike", ["qual*", "rec*"], "qualification", "recovery", "neighbor"),
+ ("NumericNotEquals", ["10", "20"], "10", "20", "30"),
+ ("DateNotEquals", ["2030-01-01T00:00:00Z", "2031-01-01T00:00:00Z"],
+ "2030-01-01T00:00:00Z", "2031-01-01T00:00:00Z", "2032-01-01T00:00:00Z"),
+ ("ArnNotEquals", [_ARN, _ARN + "-recovery"], _ARN, _ARN + "-recovery", _ARN + "-neighbor"),
+ ("ArnNotLike", [_ARN + "*", "arn:aws:sqs:*:111122223333:recovery*"],
+ _ARN, "arn:aws:sqs:eu-central-1:111122223333:recovery", "arn:aws:sqs:eu-central-1:111122223333:neighbor"),
+ ("NotIpAddress", ["10.0.0.0/8", "192.168.0.0/16"], "10.1.2.3", "192.168.1.1", "172.16.1.1"),
+]
+
+
+class TestConditionValueLists:
+ @pytest.mark.parametrize("operator, policy_values, first, second, other", [
+ pytest.param(*case, id=case[0]) for case in _NEGATED_VALUE_LIST_CASES
+ ])
+ @pytest.mark.parametrize("state", range(3), ids=["first-listed", "second-listed", "unlisted"])
+ @pytest.mark.parametrize("suffix", ["", "IfExists"])
+ def test_negated_deny_matches_none_of_the_policy_values(
+ self, operator, policy_values, first, second, other, state, suffix
+ ):
+ # AWS docs: policy values for a negated matching operator use NOR.
+ ctx = _ctx()
+ ctx.service_context = {"test:key": (first, second, other)[state]}
+ stmts = parse_policy_document({"Statement": [
+ {"Effect": "Allow", "Action": "*", "Resource": "*"},
+ {"Effect": "Deny", "Action": "*", "Resource": "*",
+ "Condition": {operator + suffix: {"test:key": policy_values}}},
+ ]})
+ assert evaluate(ctx, [stmts]).decision == ("Deny" if state == 2 else "Allow")
+
+ @pytest.mark.parametrize("operator", ["StringNotEquals", "StringNotLike"])
+ @pytest.mark.parametrize("quantifier", ["ForAnyValue", "ForAllValues"])
+ @pytest.mark.parametrize("request_values, any_denies, all_denies", [
+ (["qualification", "recovery"], False, False),
+ (["qualification", "neighbor"], True, False),
+ (["neighbor", "other"], True, True),
+ ([], False, True),
+ (None, False, True),
+ ])
+ def test_negated_set_quantifiers(self, operator, quantifier, request_values, any_denies, all_denies):
+ ctx = _ctx()
+ if request_values is not None:
+ ctx.service_context = {"test:key": request_values}
+ values = ["qual*", "rec*"] if operator == "StringNotLike" else ["qualification", "recovery"]
+ stmts = parse_policy_document({"Statement": [
+ {"Effect": "Allow", "Action": "*", "Resource": "*"},
+ {"Effect": "Deny", "Action": "*", "Resource": "*",
+ "Condition": {f"{quantifier}:{operator}": {"test:key": values}}},
+ ]})
+ denies = any_denies if quantifier == "ForAnyValue" else all_denies
+ assert evaluate(ctx, [stmts]).decision == ("Deny" if denies else "Allow")
+
+ @pytest.mark.parametrize("policy_key", [
+ "aws:RequestTag/Environment", "aws:RequestTag/environment", "AWS:REQUESTTAG/ENVIRONMENT",
+ ])
+ @pytest.mark.parametrize("tag_value, expected", [("production", "Allow"), ("Production", "ImplicitDeny")])
+ def test_request_tag_keys_ignore_case_but_string_equals_values_do_not(self, policy_key, tag_value, expected):
+ ctx = _ctx()
+ ctx.request_tags = {"Environment": tag_value}
+ ctx.tag_keys = ["Environment"]
+ stmts = parse_policy_document({"Statement": [{
+ "Effect": "Allow", "Action": "*", "Resource": "*",
+ "Condition": {"StringEquals": {policy_key: "production"}},
+ }]})
+ assert evaluate(ctx, [stmts]).decision == expected
+
+ @pytest.mark.parametrize("policy_key, expected", [("Environment", "Allow"), ("environment", "ImplicitDeny")])
+ def test_tag_keys_string_equals_preserves_case(self, policy_key, expected):
+ ctx = _ctx()
+ ctx.request_tags = {"Environment": "production"}
+ ctx.tag_keys = ["Environment"]
+ stmts = parse_policy_document({"Statement": [{
+ "Effect": "Allow", "Action": "*", "Resource": "*",
+ "Condition": {"ForAllValues:StringEquals": {"aws:TagKeys": [policy_key]}},
+ }]})
+ assert evaluate(ctx, [stmts]).decision == expected
+
+ @pytest.mark.parametrize("policy_key", ["Environment", "environment", "ENVIRONMENT"])
+ @pytest.mark.parametrize("quantifier", ["", "ForAnyValue:", "ForAllValues:"])
+ @pytest.mark.parametrize("operator", ["StringEquals", "StringLike", "StringNotEquals", "StringNotLike"])
+ @pytest.mark.parametrize("suffix", ["", "IfExists"])
+ @pytest.mark.parametrize("tag_values", [
+ ("production", "test"), ("production", "production"), ("test", "dev"),
+ ], ids=["mixed", "both-match", "none-match"])
+ @pytest.mark.parametrize("reverse_tags", [False, True])
+ def test_case_colliding_request_tags_match_all_case_variants(
+ self, policy_key, quantifier, operator, suffix, tag_values, reverse_tags
+ ):
+ # Live AWS, us-west-2: signed SQS CreateQueue with a disposable IAM
+ # user's policy. An affirmative operator matches any case variant;
+ # a negated operator matches only if none of the variants match.
+ tags = list(zip(["Environment", "environment"], tag_values))
+ ctx = _ctx()
+ ctx.request_tags = dict(reversed(tags) if reverse_tags else tags)
+ stmts = parse_policy_document({"Statement": [{
+ "Effect": "Allow", "Action": "*", "Resource": "*",
+ "Condition": {quantifier + operator + suffix: {f"aws:RequestTag/{policy_key}": "production"}},
+ }]})
+ matches = "production" in tag_values
+ if operator in ("StringNotEquals", "StringNotLike"):
+ matches = not matches
+ assert evaluate(ctx, [stmts]).decision == ("Allow" if matches else "ImplicitDeny")
+
+
+
class TestResourceAccountCondition:
"""``aws:ResourceAccount`` (and the ``s3:ResourceAccount`` alias) resolve to the
account that owns the resource. The emulator hosts one account per request and