Skip to content

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

fix(iam): resolve customer-managed policies in the explicit account (#1901)

Adrian-Ryan Acala4698ae4540fe
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 88ef8497..969209f5 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -17,6 +17,7 @@ Versioning follows [Semantic Versioning](https://semver.org/).
### Fixed
+- **IAM — customer-managed permissions use the explicit account** — policy evaluation now resolves the complete policy ARN in the principal's account, so a different ambient request account cannot hide that policy or supply a foreign account's document. Permissions continue to follow the policy's current default version.
- **ECS — optional task-definition fields stay omitted** — registering an EC2 task definition without task-level `cpu`, `memory`, or `requiresCompatibilities` no longer invents `256`, `512`, or `["EC2"]` in register, describe, and deregister responses. Explicitly supplied values remain in the definition.
- **Cognito — `USER_SRP_AUTH` checks the password** — `PASSWORD_VERIFIER` answered random `SALT` and `SRP_B` values and accepted any response, so a wrong password, a missing `TIMESTAMP` or a disabled or unconfirmed user all got tokens. The challenge now carries SRP-6a parameters with a stable salt per user, and the response is refused with `NotAuthorizedException` unless its signature proves the stored password. `TIMESTAMP` must read `EEE MMM d HH:mm:ss z yyyy` with `UTC` or `GMT` as the zone, the signature is computed over its canonical form, `PASSWORD_CLAIM_SIGNATURE` must be base64, and a temporary password leads to `NEW_PASSWORD_REQUIRED`. A client without `ALLOW_USER_SRP_AUTH`, an unknown user under `LEGACY`, a disabled and an unconfirmed user are refused at `InitiateAuth`. The built-in `PASSWORD_VERIFIER` step of `CUSTOM_WITH_SRP` gets the same check. Contributed by @iot-rocket.
- **Cognito — refresh tokens are checked against the pool and client** — `REFRESH_TOKEN_AUTH` (`InitiateAuth`, `AdminInitiateAuth`) and `GetTokensFromRefreshToken` issued tokens for the first user in the pool when the refresh token was malformed, from another pool or of a deleted user, and accepted a token issued to another client; they now answer `NotAuthorizedException` with the message AWS gives for each case, and the refresh token from a SAML or OIDC federated sign-in now refreshes the federated user's session. Contributed by @iot-rocket.
diff --git a/ministack/core/iam_evaluator.py b/ministack/core/iam_evaluator.py
index 48190542..590f4afd 100644
--- a/ministack/core/iam_evaluator.py
+++ b/ministack/core/iam_evaluator.py
@@ -797,14 +797,13 @@ def _resolve_managed_policy_document(policy_arn: str,
return ver.get("Document")
return None
- # Customer-managed policy — look up by ARN
- # The _policies dict is keyed by policy name; .items() returns current account's
- for _name, policy in iam_svc._policies.items():
- if policy.get("Arn") == policy_arn:
- default_vid = policy.get("DefaultVersionId", "v1")
- versions = policy.get("Versions", {})
- ver = versions.get(default_vid, {})
- return ver.get("Document")
+ # Customer-managed policies are keyed by full ARN in the owner's account.
+ policy = iam_svc._policies.get_scoped(account_id, None, policy_arn)
+ if policy:
+ default_vid = policy.get("DefaultVersionId", "v1")
+ versions = policy.get("Versions", {})
+ ver = versions.get(default_vid, {})
+ return ver.get("Document")
return None
diff --git a/tests/test_iam_auth.py b/tests/test_iam_auth.py
index 7f5c22b1..441e9022 100644
--- a/tests/test_iam_auth.py
+++ b/tests/test_iam_auth.py
@@ -1082,6 +1082,72 @@ class TestEnforce:
iam_svc._access_keys.pop(fake_key, None)
iam_svc._users.pop("inline-user", None)
iam_svc._user_inline_policies.pop("inline-user", None)
+class TestCustomerManagedPolicyResolution:
+ """Customer policies belong to the explicit account and use full ARNs."""
+
+ OWNER = "111111111111"
+ OTHER = "222222222222"
+ ARN = f"arn:aws:iam::{OWNER}:policy/team/connect"
+ DOCUMENT = {"Statement": [{"Effect": "Allow", "Action": "rds-db:connect", "Resource": "*"}]}
+
+ @pytest.fixture
+ def policy(self, monkeypatch):
+ from ministack.core.responses import AccountScopedDict, request_scope
+ from ministack.services import iam as iam_svc
+
+ monkeypatch.setattr(iam_svc, "_policies", AccountScopedDict())
+ with request_scope(self.OWNER, "us-east-1"):
+ return iam_svc.store_policy(self.ARN, "connect", "/team/", self.DOCUMENT)
+
+ @pytest.mark.parametrize("requested,ambient,found", [
+ (OWNER, OTHER, True),
+ (OTHER, OWNER, False),
+ ])
+ def test_uses_explicit_account_and_preserves_context(self, policy, requested, ambient, found):
+ from ministack.core.iam_evaluator import _resolve_managed_policy_document
+ from ministack.core.responses import get_account_id, get_region, request_scope
+
+ with request_scope(ambient, "eu-west-1"):
+ document = _resolve_managed_policy_document(self.ARN, requested)
+ assert document == (policy["Versions"]["v1"]["Document"] if found else None)
+ assert (get_account_id(), get_region()) == (ambient, "eu-west-1")
+
+ @pytest.mark.parametrize("arn", [
+ ARN.replace("policy/team/", "policy/"),
+ ARN.replace("policy/team/", "policy/other/"),
+ ARN.replace(OWNER, OTHER),
+ ARN + "-missing",
+ ])
+ def test_requires_complete_matching_arn(self, policy, arn):
+ from ministack.core.iam_evaluator import _resolve_managed_policy_document
+ from ministack.core.responses import request_scope
+
+ with request_scope(self.OWNER, "us-east-1"):
+ assert _resolve_managed_policy_document(arn, self.OWNER) is None
+
+ def test_current_default_version_supplies_role_permissions(self, policy, monkeypatch):
+ from ministack.core.iam_evaluator import _gather_role_policies
+ from ministack.core.responses import AccountScopedDict, get_account_id, get_region, request_scope
+ from ministack.services import iam as iam_svc
+
+ monkeypatch.setattr(iam_svc, "_roles", AccountScopedDict())
+ iam_svc._roles.set_scoped(self.OWNER, None, "app", {"AttachedPolicies": [self.ARN]})
+ policy["Versions"]["v2"] = {"Document": json.dumps({"Statement": [
+ {"Effect": "Deny", "Action": "rds-db:connect", "Resource": "*"},
+ ]})}
+ ctx = EvalContext(
+ principal_arn=f"arn:aws:iam::{self.OWNER}:role/app", principal_type="AssumedRole",
+ principal_account=self.OWNER, action="rds-db:connect", resource_arn="*", region="us-east-1",
+ )
+ with request_scope(self.OTHER, "eu-west-1"):
+ assert evaluate(ctx, _gather_role_policies("app", self.OWNER)).decision == "Allow"
+ policy["DefaultVersionId"] = "v2"
+ assert evaluate(ctx, _gather_role_policies("app", self.OWNER)).decision == "Deny"
+ policy["DefaultVersionId"] = "v1"
+ assert evaluate(ctx, _gather_role_policies("app", self.OWNER)).decision == "Allow"
+ assert (get_account_id(), get_region()) == (self.OTHER, "eu-west-1")
+
+
class TestSeededAwsManagedPolicies:
"""The AWS-managed policies CDK, SAM and Serverless attach by their real ARNs
resolve to a document: the service-role/* path is the only one AWS has for the
diff --git a/tests/test_rds_iam.py b/tests/test_rds_iam.py
index 7f0cc70a..1cace031 100644
--- a/tests/test_rds_iam.py
+++ b/tests/test_rds_iam.py
@@ -386,7 +386,7 @@ class TestResourceBoundAuthorization:
else:
arn = f"arn:aws:iam::{ACCOUNT}:policy/connect"
iam._users.get_scoped(ACCOUNT, None, "alice")["AttachedPolicies"] = [arn]
- iam._policies.set_scoped(ACCOUNT, None, "connect", {
+ iam._policies.set_scoped(ACCOUNT, None, arn, {
"Arn": arn, "DefaultVersionId": "v1", "Versions": {"v1": {"Document": _authz_policy()}},
})
with request_scope(OTHER_ACCOUNT, "eu-west-1"):