Skip to content

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

fix(iam): a negated operator applies to an absent key, and BatchGetSecretValue checks each secret (#1861)

iot-rocket776edf835450
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 07bb27a4..009393c8 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -9,6 +9,9 @@ Versioning follows [Semantic Versioning](https://semver.org/).
### Fixed
+- **IAM — a negated condition operator is true when its key is absent** — the evaluator treated an absent key as a failed condition for every operator, so a `Deny` guarded by `StringNotEquals`, `StringNotLike`, `ArnNotLike`, `NotIpAddress` or another negated operator never applied to a request without that key. AWS evaluates such a condition as true and denies. The single-valued negated operators now do the same, while `ForAnyValue` and the affirmative operators still fail on an absent key. Contributed by @iot-rocket.
+- **KMS — `GenerateDataKey` returns `KeyMaterialId`** — requests without `Recipient` now include the identifier of the wrapping key material. The identifier remains stable across requests and persistence reloads, and changes when the wrapping material changes. Fixes #1853.
+- **Secrets Manager — `BatchGetSecretValue` returns only the secrets the caller may read** — under `AUTH=true` a grant on `secretsmanager:BatchGetSecretValue` alone returned every secret in the request, and `Filters` were ignored, so a filtered call returned the whole store. Each secret now needs `secretsmanager:GetSecretValue` and lands in `Errors` as `AccessDeniedException` without it, a call by `Filters` also needs `secretsmanager:ListSecrets`, and the filters select the secrets as in `ListSecrets`. Contributed by @iot-rocket.
- **CloudFormation — change set members follow the action** — `Add` and `Remove` changes carried `Replacement: False`, a `Remove` had no physical id, `PolicyAction` was never sent and a `Metadata` or policy detail had no `RequiresRecreation`. `Remove` and `Modify` now name the physical resource, a `Remove` answers `PolicyAction: Delete` and a replacing `Modify` `ReplaceAndDelete` unless the resource retains or snapshots, and attribute details answer `Never`. Contributed by @iot-rocket.
- **CloudFormation — `AWS::SQS::Queue` applies every queue property** — `RedrivePolicy`, `RedriveAllowPolicy`, `KmsMasterKeyId`, `KmsDataKeyReusePeriodSeconds`, `SqsManagedSseEnabled`, `DeduplicationScope` and `FifoThroughputLimit` were dropped on create and update, so a dead-letter queue declared in a template never received messages, and a value SQS refuses now fails the resource instead of being stored. Contributed by @iot-rocket.
- **Lambda — Docker executor honors timeouts above 300 seconds** — pass the configured `Timeout` to AWS RIE through `AWS_LAMBDA_FUNCTION_TIMEOUT`, preventing its default 300-second limit from ending longer invocations early. Timeout updates recycle warm containers so the RIE deadline follows the new configuration (#1844).
diff --git a/ministack/core/iam_evaluator.py b/ministack/core/iam_evaluator.py
index 98cb4b4c..a5a16e93 100644
--- a/ministack/core/iam_evaluator.py
+++ b/ministack/core/iam_evaluator.py
@@ -364,6 +364,13 @@ _CONDITION_OPS: dict[str, Any] = {
"binaryequals": _op_string_equals,
}
+# Operators that require the key NOT to match
+_NEGATED_OPS = frozenset({
+ "stringnotequals", "stringnotequalsignorecase", "stringnotlike",
+ "numericnotequals", "datenotequals", "arnnotequals", "arnnotlike",
+ "notipaddress",
+})
+
def _evaluate_single_condition(operator: str, actual: Any,
expected_values: list[str]) -> bool:
@@ -397,7 +404,9 @@ def _evaluate_single_condition(operator: str, actual: Any,
return False
if actual is None:
- return if_exists or for_all # ForAllValues on missing key = true (empty set)
+ # An absent key satisfies ...IfExists, ForAllValues (empty set) and a
+ # negated single-valued operator; ForAnyValue and affirmative ones fail.
+ return if_exists or for_all or (not for_any and op_lower in _NEGATED_OPS)
# Multi-valued context key
if isinstance(actual, list):
diff --git a/ministack/services/secretsmanager.py b/ministack/services/secretsmanager.py
index 0ca25fd3..6ff02885 100644
--- a/ministack/services/secretsmanager.py
+++ b/ministack/services/secretsmanager.py
@@ -485,6 +485,12 @@ async def handle_request(method, path, headers, body, query_params):
handler = handlers.get(action)
if not handler:
return error_response_json("InvalidRequestException", f"Unknown action: {action}", 400)
+ if action == "BatchGetSecretValue":
+ from ministack.app import AUTH
+ from ministack.core.router import extract_access_key_id
+
+ access_key = (extract_access_key_id(headers, query_params) or "") if AUTH else None
+ return handler(data, access_key)
return handler(data)
@@ -601,15 +607,51 @@ def _get_secret_value(data):
return json_response(result)
-def _batch_get_secret_value(data):
+def _batch_get_secret_value(data, access_key=None):
+ """``access_key`` is None without AUTH. With it, a request by ``Filters``
+ also needs ``secretsmanager:ListSecrets``, and a secret the caller holds no
+ ``secretsmanager:GetSecretValue`` on is reported in ``Errors``. The primary
+ check has already authenticated the key, so only policy denials occur."""
+ from ministack.core.iam_actions import access_denied_response
+ from ministack.core.iam_evaluator import enforce
+
secret_ids = data.get("SecretIdList", [])
results = []
errors = []
- targets = secret_ids if secret_ids else sorted(
- n for n, s in _secrets.items() if not s.get("DeletedDate"))
+ def authorize(action, resource_arn):
+ if access_key is None:
+ return None
+ return enforce(access_key, action, "secretsmanager", get_region(), resource_arn=resource_arn)
+
+ if secret_ids:
+ targets = secret_ids
+ else:
+ denied = authorize("secretsmanager:ListSecrets", "*")
+ if denied:
+ return access_denied_response("secretsmanager", "secretsmanager:ListSecrets",
+ getattr(denied, "principal_arn", ""), new_uuid())
+ names = sorted(n for n, s in _secrets.items() if not s.get("DeletedDate"))
+ targets = [_secrets[n]["ARN"] for n in _filter_secret_names(names, data.get("Filters", []))]
for sid in targets:
+ _, secret = _resolve(sid)
+ resource_arn = secret["ARN"] if secret else (
+ sid if sid.startswith("arn:")
+ else f"arn:aws:secretsmanager:{get_region()}:{get_account_id()}:secret:{sid}")
+ denied = authorize("secretsmanager:GetSecretValue", resource_arn)
+ if denied:
+ principal = getattr(denied, "principal_arn", "")
+ errors.append({
+ "SecretId": sid,
+ "ErrorCode": "AccessDeniedException",
+ "Message": (
+ f"User: {principal} is not authorized to perform: "
+ f"secretsmanager:GetSecretValue on resource: {sid} because no "
+ "identity-based policy allows the secretsmanager:GetSecretValue action"
+ ),
+ })
+ continue
resp = _get_secret_value({"SecretId": sid})
status, _, body = resp
parsed = json.loads(body) if isinstance(body, bytes) else json.loads(body)
@@ -631,25 +673,10 @@ def _list_secrets(data):
filters = data.get("Filters", [])
include_planned_deletion = bool(data.get("IncludePlannedDeletion", False))
- names = sorted(
+ names = _filter_secret_names(sorted(
n for n, s in _secrets.items()
if include_planned_deletion or not s.get("DeletedDate")
- )
-
- for f in filters:
- key = f.get("Key", "")
- values = [v.lower() for v in f.get("Values", [])]
- if key == "name":
- names = [n for n in names if any(v in n.lower() for v in values)]
- elif key == "tag-key":
- names = [n for n in names
- if any(t.get("Key", "").lower() in values for t in _secrets[n].get("Tags", []))]
- elif key == "tag-value":
- names = [n for n in names
- if any(t.get("Value", "").lower() in values for t in _secrets[n].get("Tags", []))]
- elif key == "description":
- names = [n for n in names
- if any(v in _secrets[n].get("Description", "").lower() for v in values)]
+ ), filters)
start = 0
if next_token:
@@ -686,6 +713,25 @@ def _list_secrets(data):
return json_response(resp)
+def _filter_secret_names(names, filters):
+ """The ``names`` that pass every ListSecrets-style filter."""
+ for f in filters:
+ key = f.get("Key", "")
+ values = [v.lower() for v in f.get("Values", [])]
+ if key == "name":
+ names = [n for n in names if any(v in n.lower() for v in values)]
+ elif key == "tag-key":
+ names = [n for n in names
+ if any(t.get("Key", "").lower() in values for t in _secrets[n].get("Tags", []))]
+ elif key == "tag-value":
+ names = [n for n in names
+ if any(t.get("Value", "").lower() in values for t in _secrets[n].get("Tags", []))]
+ elif key == "description":
+ names = [n for n in names
+ if any(v in _secrets[n].get("Description", "").lower() for v in values)]
+ return names
+
+
def _delete_secret(data):
secret_id = data.get("SecretId")
key, secret = _resolve(secret_id)
diff --git a/tests/test_iam_auth.py b/tests/test_iam_auth.py
index 78c3003b..8a2137b8 100644
--- a/tests/test_iam_auth.py
+++ b/tests/test_iam_auth.py
@@ -471,6 +471,54 @@ class TestConditions:
assert evaluate(ctx, [stmts]).decision == "ImplicitDeny"
+# Measured with iam simulate-custom-policy: Allow *, plus a Deny under the one
+# condition. D = explicit deny, A = allowed, for the key absent / matching / other.
+_ARN = "arn:aws:sns:eu-central-1:111122223333:topic"
+_KEY_PRESENCE_CASES = [
+ ("StringNotEquals", "blue", "blue", "red", "DAD"),
+ ("StringNotEqualsIgnoreCase", "BLUE", "blue", "red", "DAD"),
+ ("StringNotLike", "bl*", "blue", "red", "DAD"),
+ ("NumericNotEquals", "10", "10", "5", "DAD"),
+ ("DateNotEquals", "2030-01-01T00:00:00Z", "2030-01-01T00:00:00Z", "2031-01-01T00:00:00Z", "DAD"),
+ ("ArnNotEquals", _ARN, _ARN, _ARN + "-other", "DAD"),
+ ("ArnNotLike", "arn:aws:sns:*:111122223333:top*", _ARN, _ARN[:-5] + "other", "DAD"),
+ ("NotIpAddress", "10.0.0.0/8", "10.1.2.3", "192.168.1.1", "DAD"),
+ ("ForAnyValue:StringNotEquals", ["team"], ["team"], ["other"], "AAD"),
+ ("ForAllValues:StringNotEquals", ["team"], ["team"], ["other"], "DAD"),
+ ("ForAnyValue:StringNotLike", ["te*"], ["team"], ["other"], "AAD"),
+ ("ForAllValues:StringNotLike", ["te*"], ["team"], ["other"], "DAD"),
+ ("StringNotEqualsIfExists", "blue", "blue", "red", "DAD"),
+ ("StringEquals", "blue", "blue", "red", "ADA"),
+ ("StringLike", "bl*", "blue", "red", "ADA"),
+ ("NumericLessThan", "10", "5", "20", "ADA"),
+ ("DateGreaterThan", "2030-01-01T00:00:00Z", "2031-01-01T00:00:00Z", "2029-01-01T00:00:00Z", "ADA"),
+ ("ArnLike", "arn:aws:sns:*:111122223333:top*", _ARN, _ARN[:-5] + "other", "ADA"),
+ ("IpAddress", "10.0.0.0/8", "10.1.2.3", "192.168.1.1", "ADA"),
+ ("Bool", "true", "true", "false", "ADA"),
+ ("ForAnyValue:StringEquals", ["team"], ["team"], ["other"], "ADA"),
+ ("ForAllValues:StringEquals", ["team"], ["team"], ["other"], "DDA"),
+ ("StringEqualsIfExists", "blue", "blue", "red", "DDA"),
+ ("Null", "true", "blue", "blue", "DAA"),
+]
+
+
[email protected]("state", range(3), ids=["absent", "matching", "other"])
[email protected]("operator, policy_value, matching, other, measured", [
+ pytest.param(*case, id=case[0]) for case in _KEY_PRESENCE_CASES
+])
+def test_condition_operator_by_key_presence(operator, policy_value, matching, other, measured, state):
+ ctx = _ctx()
+ value = (None, matching, other)[state]
+ if value is not None:
+ ctx.service_context = {"test:key": value}
+ stmts = parse_policy_document({"Statement": [
+ {"Effect": "Allow", "Action": "*", "Resource": "*"},
+ {"Effect": "Deny", "Action": "*", "Resource": "*",
+ "Condition": {operator: {"test:key": policy_value}}},
+ ]})
+ expected = "Deny" if measured[state] == "D" else "Allow"
+ assert evaluate(ctx, [stmts]).decision == expected
+
class TestResourceAccountCondition:
"""``aws:ResourceAccount`` (and the ``s3:ResourceAccount`` alias) resolve to the
diff --git a/tests/test_secretsmanager.py b/tests/test_secretsmanager.py
index 209adb39..54578ddc 100644
--- a/tests/test_secretsmanager.py
+++ b/tests/test_secretsmanager.py
@@ -736,6 +736,99 @@ def test_secretsmanager_batch_get_secret_value_with_missing(sm):
assert len(resp["Errors"]) == 1
assert resp["Errors"][0]["SecretId"] == "nonexistent-secret"
+
+# ---------------------------------------------------------------------------
+# BatchGetSecretValue checks GetSecretValue per secret, ListSecrets for Filters
+# ---------------------------------------------------------------------------
+
+_BGSV_USER = "bgsv-user"
+_BGSV_KEY = "AKIABGSVTESTUSER0001"
+_BGSV_BATCH = {"Effect": "Allow", "Action": "secretsmanager:BatchGetSecretValue", "Resource": "*"}
+_BGSV_GET_A = {"Effect": "Allow", "Action": "secretsmanager:GetSecretValue", "Resource": "{A}"}
+_BGSV_LIST = {"Effect": "Allow", "Action": "secretsmanager:ListSecrets", "Resource": "*"}
+_BGSV_FILTER = {"Filters": [{"Key": "name", "Values": ["bgsv-probe-"]}]}
+
+
+def _bgsv_denied(action, resource=None):
+ on = f" on resource: {resource}" if resource else ""
+ return (f"User: arn:aws:iam::000000000000:user/{_BGSV_USER} is not authorized to perform: "
+ f"{action}{on} because no identity-based policy allows the {action} action")
+
+
[email protected]("auth_enabled, statements, request_body, values, errors, denied", [
+ pytest.param(True, [_BGSV_BATCH, _BGSV_GET_A], {"SecretIdList": ["{a}", "{b}"]}, ["{a}"],
+ [("{b}", "AccessDeniedException")], None, id="names"),
+ pytest.param(True, [_BGSV_BATCH, _BGSV_GET_A], {"SecretIdList": ["{A}", "{B}"]}, ["{a}"],
+ [("{B}", "AccessDeniedException")], None, id="arns"),
+ pytest.param(True, [_BGSV_BATCH, _BGSV_GET_A], _BGSV_FILTER, None, None,
+ "secretsmanager:ListSecrets", id="filters-without-list"),
+ pytest.param(True, [_BGSV_BATCH, _BGSV_GET_A, _BGSV_LIST], _BGSV_FILTER, ["{a}"],
+ [("{B}", "AccessDeniedException")], None, id="filters-with-list"),
+ pytest.param(True, [dict(_BGSV_GET_A, Resource=["{A}", "{B}"])], {"SecretIdList": ["{a}"]}, None, None,
+ "secretsmanager:BatchGetSecretValue", id="no-batch-grant"),
+ pytest.param(True, [_BGSV_BATCH, dict(_BGSV_GET_A, Resource="*")], {"SecretIdList": ["{a}", "bgsv-missing"]},
+ ["{a}"], [("bgsv-missing", "ResourceNotFoundException")], None, id="missing"),
+ pytest.param(False, [], _BGSV_FILTER, ["{a}", "{b}"], [], None, id="no-auth-filters"),
+])
+def test_secretsmanager_batch_get_secret_value_authorizes_each_secret(
+ monkeypatch, auth_enabled, statements, request_body, values, errors, denied):
+ import asyncio
+
+ from ministack import app as app_mod
+ from ministack.core.responses import request_scope
+ from ministack.services import iam as iam_svc
+ from ministack.services import secretsmanager as sm_svc
+
+ account = "000000000000"
+ monkeypatch.setattr(app_mod, "AUTH", auth_enabled)
+ names = {"a": "bgsv-probe-a", "b": "bgsv-probe-b", "c": "bgsv-other"}
+ with request_scope(account, "us-east-1"):
+ arns = {k.upper(): json.loads(sm_svc._create_secret({"Name": n, "SecretString": n})[2])["ARN"]
+ for k, n in names.items()}
+ fill = {**names, **arns}
+
+ def render(value):
+ text = json.dumps(value)
+ for placeholder, real in fill.items():
+ text = text.replace(f"{{{placeholder}}}", real)
+ return json.loads(text)
+
+ iam_svc._users.set_scoped(account, None, _BGSV_USER, {
+ "UserName": _BGSV_USER, "UserId": "AIDABGSVTESTUSER", "AttachedPolicies": [],
+ "Arn": f"arn:aws:iam::{account}:user/{_BGSV_USER}",
+ })
+ iam_svc._user_inline_policies[_BGSV_USER] = {"p": {"Statement": render(statements)}}
+ iam_svc._access_keys.set_scoped(account, None, _BGSV_KEY, {
+ "AccessKeyId": _BGSV_KEY, "SecretAccessKey": "secret", "Status": "Active", "UserName": _BGSV_USER,
+ })
+ try:
+ status, _, payload = asyncio.run(app_mod._dispatch_service_request(
+ "POST", "/", {
+ "host": "secretsmanager.us-east-1.localhost",
+ "authorization": f"AWS4-HMAC-SHA256 Credential={_BGSV_KEY}/20260915/us-east-1/secretsmanager/aws4_request",
+ "content-type": "application/x-amz-json-1.1",
+ "x-amz-target": "secretsmanager.BatchGetSecretValue",
+ }, json.dumps(render(request_body)).encode(), {}, "req-1",
+ ))
+ finally:
+ iam_svc._access_keys.pop_scoped(account, None, _BGSV_KEY, None)
+ iam_svc._user_inline_policies.pop(_BGSV_USER, None)
+ iam_svc._users.pop_scoped(account, None, _BGSV_USER, None)
+ for name in names.values():
+ sm_svc._secrets.pop(name, None)
+ body = json.loads(payload)
+ if denied:
+ assert body["__type"] == "AccessDeniedException"
+ assert body["message"] == _bgsv_denied(denied)
+ return
+ assert status == 200
+ assert [v["Name"] for v in body["SecretValues"]] == render(values)
+ expected_errors = [(render(sid), code) for sid, code in errors]
+ assert [(e["SecretId"], e["ErrorCode"]) for e in body["Errors"]] == expected_errors
+ for (sid, code), error in zip(expected_errors, body["Errors"]):
+ if code == "AccessDeniedException":
+ assert error["Message"] == _bgsv_denied("secretsmanager:GetSecretValue", sid)
+
def test_secretsmanager_kms_key_id_on_create_and_describe(sm):
sm.create_secret(Name="kms-test-secret", SecretString="val", KmsKeyId="alias/my-key")
resp = sm.describe_secret(SecretId="kms-test-secret")