Ministack: Free, open-source local AWS emulator - 60+ services, Terraform compatible, real databases. Free forever. MIT licensed.
Python awsaws-emulatoraws-localaws-sdkdevtoolsdockerdynamodbec2emulatorlambdalocalstacklocalstack-alternativeministackmock-awsopen-sourcepythons3sqsterraform
fix(sts): enforce role trust denies and request conditions (#1958)
Adrian-Ryan Acala191ce2120022
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 5437fc54..1361cf75 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -7,6 +7,9 @@ Versioning follows [Semantic Versioning](https://semver.org/).## [Unreleased]+### Fixed++- **STS — role trust denies and conditions are enforced** — with `AUTH=true`, `AssumeRole` now rejects matching explicit denies, including `NotAction` exclusions, and evaluates `sts:ExternalId` and `sts:RoleSessionName` conditions before issuing credentials. A denied call registers no session. Local JSON requests use the supplied role ARN for authorization and receive JSON trust-denial errors; Query requests retain XML responses. With `AUTH=false`, trust denies and conditions remain permissive.### Added- **Athena — databases, DDL, and Trino-style table references** — `ListDatabases` and `GetDatabase` read the Glue Data Catalog; `CREATE EXTERNAL TABLE` and `DROP TABLE` apply to it, creating the Glue table Athena would (formats, SerDe, TBLPROPERTIES); `CREATE TABLE` without `EXTERNAL` is rejected as Athena rejects it, and Iceberg tables are not supported; a query may name a table as `"awsdatacatalog"."db"."t"` or `db.t`. Contributed by @sjincho.diff --git a/ministack/core/iam_actions.py b/ministack/core/iam_actions.pyindex b1c179b7..8dad6b56 100644--- a/ministack/core/iam_actions.py+++ b/ministack/core/iam_actions.py@@ -990,7 +990,7 @@ def extract_resource_arn(service: str, method: str, path: str,return "*"if service == "sts":- role_arn = _query_param(query_params, "RoleArn")+ role_arn = _query_param(query_params, "RoleArn") or _safe_json_field(body, "RoleArn")if role_arn:return role_arnreturn "*"diff --git a/ministack/core/iam_evaluator.py b/ministack/core/iam_evaluator.pyindex 590f4afd..73d00557 100644--- a/ministack/core/iam_evaluator.py+++ b/ministack/core/iam_evaluator.py@@ -1228,9 +1228,12 @@ def validate_role_arn(role_arn: str) -> str | None:# ---------------------------------------------------------------------------def evaluate_trust_policy(trust_doc: str | dict,- caller_arn: str) -> bool:+ caller_arn: str, ctx: EvalContext | None = None) -> bool:"""Check if a role's trust policy allows the given caller to assume it.+ Matching denies override allows, regardless of statement order. Conditions+ use the shared evaluator; omitted request context leaves STS keys absent.+Supports Principal forms:- ``"*"`` — anyone- ``{"AWS": "arn:aws:iam::ACCT:root"}`` — account root@@ -1251,23 +1254,40 @@ def evaluate_trust_policy(trust_doc: str | dict,if isinstance(statements, dict):statements = [statements]+ if ctx is None:+ ctx = EvalContext(+ principal_arn=caller_arn,+ principal_type=("User" if ":user/" in caller_arn else+ "AssumedRole" if ":assumed-role/" in caller_arn else "Root"),+ principal_account=_account_from_arn(caller_arn) or "",+ action="sts:AssumeRole", resource_arn="*", region="",+ )+ allowed = Falsefor stmt in statements:if not isinstance(stmt, dict):continue- if stmt.get("Effect") != "Allow":+ if stmt.get("Effect") not in ("Allow", "Deny"):continue- # Check Action includes sts:AssumeRole (or *)+ # Match the requested action, including exclusions in NotAction.actions = stmt.get("Action", [])+ not_actions = stmt.get("NotAction", [])if isinstance(actions, str):actions = [actions]- if not any(fnmatch_iam("sts:AssumeRole", a) for a in actions):+ if isinstance(not_actions, str):+ not_actions = [not_actions]+ if not (actions or not_actions) or not _action_matches("sts:AssumeRole", actions, not_actions):continue# Check Principalprincipal = stmt.get("Principal", {})- if _principal_matches(principal, caller_arn):- return True+ if not _principal_matches(principal, caller_arn):+ continue+ if not _conditions_met(stmt.get("Condition", {}), ctx):+ continue+ if stmt["Effect"] == "Deny":+ return False+ allowed = True- return False+ return alloweddef _principal_matches(principal: Any, caller_arn: str) -> bool:diff --git a/ministack/services/sts.py b/ministack/services/sts.pyindex 7d091320..0241cafa 100644--- a/ministack/services/sts.py+++ b/ministack/services/sts.py@@ -17,7 +17,7 @@ from urllib.parse import parse_qsfrom ministack.core.arn import ArnParseError, parse_arnfrom ministack.core.iam_evaluator import CredentialResolutionError, resolve_credential-from ministack.core.responses import get_account_id, json_response, new_uuid+from ministack.core.responses import error_response_json, get_account_id, get_region, json_response, new_uuidfrom ministack.core.router import extract_access_key_id# Shared helpers — IAM and STS are a natural pair; STS is stateless@@ -186,7 +186,7 @@ async def handle_request(method, path, headers, body, query_params):# When AUTH=true, validate role exists and trust policy permits the callerfrom ministack.app import AUTHif AUTH:- from ministack.core.iam_evaluator import evaluate_trust_policy+ from ministack.core.iam_evaluator import EvalContext, evaluate_trust_policyfrom ministack.services import iam as iam_svc# Extract role name from ARNrole_name = role_arn.split("/")[-1] if "/" in role_arn else ""@@ -216,10 +216,22 @@ async def handle_request(method, path, headers, body, query_params):# Evaluate trust policytrust_doc = role.get("AssumeRolePolicyDocument", "{}")caller_arn = caller["userArn"]- if not evaluate_trust_policy(trust_doc, caller_arn):- return _error(403, "AccessDenied",- f"User: {caller_arn} is not authorized to perform: "- f"sts:AssumeRole on resource: {role_arn}", ns="sts")+ trust_context = EvalContext(+ principal_arn=caller_arn,+ principal_type=caller["principalType"],+ principal_account=caller["accountId"],+ action="sts:AssumeRole", resource_arn=role_arn, region=get_region(),+ service_context={+ "sts:externalid": _p(params, "ExternalId", None),+ "sts:rolesessionname": _p(params, "RoleSessionName", None),+ },+ )+ if not evaluate_trust_policy(trust_doc, caller_arn, trust_context):+ message = (f"User: {caller_arn} is not authorized to perform: "+ f"sts:AssumeRole on resource: {role_arn}")+ if use_json:+ return error_response_json("AccessDenied", message, 403)+ return _error(403, "AccessDenied", message, ns="sts")duration = int(_p(params, "DurationSeconds") or 3600)expiration = _future(duration)diff --git a/tests/test_sts_trust.py b/tests/test_sts_trust.pynew file mode 100644index 00000000..23bdd25d--- /dev/null+++ b/tests/test_sts_trust.py@@ -0,0 +1,209 @@+"""Local role trust regressions using exact IAM user principals and role grants."""++import asyncio+import json+import xml.etree.ElementTree as ET+from urllib.parse import urlencode++import pytest++from ministack.core.iam_evaluator import evaluate_trust_policy++ACCOUNT = "123456789012"+CALLER = f"arn:aws:iam::{ACCOUNT}:user/trust-deployer"+ROLE_NAME = "trust-deployment"+ROLE_ARN = f"arn:aws:iam::{ACCOUNT}:role/{ROLE_NAME}"+ALLOW = {"Effect": "Allow", "Principal": {"AWS": CALLER}, "Action": "sts:AssumeRole"}+REQUIRED = {+ "StringEquals": {"sts:ExternalId": "deployment-id"},+ "StringLike": {"sts:RoleSessionName": ["deploy-?*", "release-?*"]},+}+++def _document(*statements):+ return json.dumps({"Version": "2012-10-17", "Statement": list(statements)})++[email protected]("deny_first", [False, True])+def test_trust_explicit_deny_overrides_allow_without_context(deny_first):+ deny = dict(ALLOW, Effect="Deny")+ statements = [deny, ALLOW] if deny_first else [ALLOW, deny]+ assert not evaluate_trust_policy(_document(*statements), CALLER)+++def test_trust_required_external_id_without_context_is_denied():+ assert not evaluate_trust_policy(+ _document(dict(ALLOW, Condition={"StringEquals": {"sts:ExternalId": "deployment-id"}})),+ CALLER,+ )++[email protected](params=["query", "json"])+def trust_api(request, monkeypatch):+ from ministack import app as app_mod+ from ministack.core.responses import AccountScopedDict, set_request_account_id+ from ministack.services import iam, sts++ monkeypatch.setattr(app_mod, "AUTH", True)+ monkeypatch.setattr(sts, "_sessions", {})+ monkeypatch.setattr(iam, "_users", AccountScopedDict())+ monkeypatch.setattr(iam, "_roles", AccountScopedDict())+ monkeypatch.setattr(iam, "_access_keys", AccountScopedDict())+ set_request_account_id(ACCOUNT)+ protocol = request.param+ source_key = ""++ def call(service, action, **params):+ headers = {}+ if source_key and service == "sts":+ headers["authorization"] = (+ f"AWS4-HMAC-SHA256 Credential={source_key}/20260929/us-east-1/sts/aws4_request, "+ "SignedHeaders=host, Signature=unused"+ )+ if protocol == "json":+ target = "IAMService" if service == "iam" else "AWSSecurityTokenServiceV20110615"+ headers.update({"content-type": "application/x-amz-json-1.1", "x-amz-target": f"{target}.{action}"})+ body = json.dumps(params).encode()+ else:+ headers["content-type"] = "application/x-www-form-urlencoded"+ body = urlencode({"Action": action, **params}).encode()+ if service == "sts":+ return asyncio.run(app_mod._dispatch_service_request(+ "POST", "/", headers, body, {}, "trust-test-request",+ ))+ return asyncio.run(iam.handle_request("POST", "/", headers, body, {}))++ try:+ assert call("iam", "CreateUser", UserName="trust-deployer")[0] == 200+ status, _, body = call("iam", "CreateAccessKey", UserName="trust-deployer")+ assert status == 200+ source_key = ET.fromstring(body).findtext(".//{*}AccessKeyId")+ assert source_key+ assert call("iam", "PutUserPolicy", UserName="trust-deployer", PolicyName="assume",+ PolicyDocument=_document({+ "Effect": "Allow", "Action": "sts:AssumeRole", "Resource": ROLE_ARN,+ }))[0] == 200+ yield call, sts._sessions, protocol+ finally:+ call("iam", "DeleteRole", RoleName=ROLE_NAME)+ if source_key:+ call("iam", "DeleteAccessKey", UserName="trust-deployer", AccessKeyId=source_key)+ call("iam", "DeleteUserPolicy", UserName="trust-deployer", PolicyName="assume")+ call("iam", "DeleteUser", UserName="trust-deployer")+++def _assume(api, expected_status, **params):+ call, sessions, protocol = api+ before = dict(sessions)+ status, headers, body = call("sts", "AssumeRole", RoleArn=ROLE_ARN, **params)+ assert status == expected_status, body+ if status == 403:+ if protocol == "json":+ assert headers["Content-Type"].startswith("application/x-amz-json")+ assert headers["x-amzn-errortype"] == "AccessDenied"+ error = json.loads(body)+ assert error["__type"] == "AccessDenied"+ assert "sts:AssumeRole" in error["message"]+ else:+ assert "xml" in headers["Content-Type"]+ assert ET.fromstring(body).findtext(".//{*}Code") == "AccessDenied"+ assert b"Credentials" not in body+ assert sessions == before+ else:+ if protocol == "json":+ assert headers["Content-Type"].startswith("application/x-amz-json")+ access_key = json.loads(body)["Credentials"]["AccessKeyId"]+ else:+ access_key = ET.fromstring(body).findtext(".//{*}Credentials/{*}AccessKeyId")+ assert set(sessions) - set(before) == {access_key}+ assert sessions[access_key]["SourcePrincipalArn"] == CALLER+ assert sessions[access_key]["Arn"].endswith("/" + params["RoleSessionName"])+++def _install_policy(api, operation, policy):+ call, _, _ = api+ initial = policy if operation == "CreateRole" else _document(ALLOW)+ assert call("iam", "CreateRole", RoleName=ROLE_NAME, AssumeRolePolicyDocument=initial)[0] == 200+ if operation == "UpdateAssumeRolePolicy":+ _assume(api, 200, RoleSessionName="before-update")+ assert call("iam", operation, RoleName=ROLE_NAME, PolicyDocument=policy)[0] == 200++[email protected]("operation", ["CreateRole", "UpdateAssumeRolePolicy"])[email protected]("params, expected", [+ ({"ExternalId": "deployment-id", "RoleSessionName": "deploy-123"}, 200),+ ({"ExternalId": "deployment-id", "RoleSessionName": "release-123"}, 200),+ ({"ExternalId": "wrong", "RoleSessionName": "deploy-123"}, 403),+ ({"RoleSessionName": "deploy-123"}, 403),+ ({"ExternalId": "deployment-id", "RoleSessionName": "other-123"}, 403),+])+def test_trust_requires_external_id_and_session_name(trust_api, operation, params, expected):+ _install_policy(trust_api, operation, _document(dict(ALLOW, Condition=REQUIRED)))+ _assume(trust_api, expected, **params)++[email protected]("operation", ["CreateRole", "UpdateAssumeRolePolicy"])[email protected]("deny_first", [False, True])[email protected]("deny_changes, expected", [+ ({}, 403),+ ({"Principal": {"AWS": f"arn:aws:iam::{ACCOUNT}:user/other"}}, 200),+ ({"Action": "sts:AssumeRoleWithSAML"}, 200),+ ({"Condition": {"StringEquals": {"sts:ExternalId": "deployment-id"}}}, 403),+ ({"Condition": {"StringEquals": {"sts:ExternalId": "other-id"}}}, 200),+ ({"Condition": {"StringLike": {"sts:RoleSessionName": "deploy-*"}}}, 403),+])+def test_trust_only_matching_denies_override_allow(trust_api, operation, deny_first, deny_changes, expected):+ deny = dict(ALLOW, Effect="Deny", **deny_changes)+ statements = [deny, ALLOW] if deny_first else [ALLOW, deny]+ _install_policy(trust_api, operation, _document(*statements))+ _assume(trust_api, expected, ExternalId="deployment-id", RoleSessionName="deploy-123")+++def test_trust_update_replaces_conditions_and_deny(trust_api):+ call, _, _ = trust_api+ _install_policy(trust_api, "CreateRole", _document(dict(ALLOW, Condition=REQUIRED)))+ _assume(trust_api, 200, ExternalId="deployment-id", RoleSessionName="deploy-123")+ assert call("iam", "UpdateAssumeRolePolicy", RoleName=ROLE_NAME,+ PolicyDocument=_document(ALLOW, dict(ALLOW, Effect="Deny")))[0] == 200+ _assume(trust_api, 403, ExternalId="deployment-id", RoleSessionName="deploy-123")+ assert call("iam", "UpdateAssumeRolePolicy", RoleName=ROLE_NAME,+ PolicyDocument=_document(ALLOW))[0] == 200+ _assume(trust_api, 200, RoleSessionName="unrestricted")+++def test_trust_condition_key_presence(trust_api):+ # Missing request values must remain absent, rather than becoming "".+ _install_policy(trust_api, "CreateRole", _document(dict(+ ALLOW, Condition={"Null": {"sts:ExternalId": "true"}},+ )))+ _assume(trust_api, 200, RoleSessionName="without-id")+ _assume(trust_api, 403, ExternalId="deployment-id", RoleSessionName="with-id")++[email protected]("operation", ["CreateRole", "UpdateAssumeRolePolicy"])[email protected]("deny_first", [False, True])[email protected]("excluded, condition, expected", [+ ("sts:AssumeRoleWithSAML", {}, 403),+ (["sts:AssumeRoleWithSAML", "sts:AssumeRoleWithWebIdentity"], {}, 403),+ (["sts:AssumeRoleWithSAML", "STS:Assume*"], {}, 200),+ ("sts:AssumeRoleWithSAML", {"StringEquals": {"sts:ExternalId": "other-id"}}, 200),+])+def test_trust_not_action_denies(trust_api, operation, deny_first, excluded, condition, expected):+ deny = {"Effect": "Deny", "Principal": {"AWS": CALLER},+ "NotAction": excluded, "Condition": condition}+ statements = [deny, ALLOW] if deny_first else [ALLOW, deny]+ _install_policy(trust_api, operation, _document(*statements))+ _assume(trust_api, expected, ExternalId="deployment-id", RoleSessionName="deploy-123")++[email protected]("operation", ["CreateRole", "UpdateAssumeRolePolicy"])[email protected]("policy", [+ _document(ALLOW, dict(ALLOW, Effect="Deny")),+ _document(dict(ALLOW, Condition=REQUIRED)),+])+def test_trust_denies_and_conditions_remain_permissive_without_auth(trust_api, monkeypatch, operation, policy):+ from ministack import app as app_mod++ monkeypatch.setattr(app_mod, "AUTH", False)+ _install_policy(trust_api, operation, policy)+ _assume(trust_api, 200, RoleSessionName="unrestricted")