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(iam): refuse trust policies that carry NotPrincipal (#2283)
iot-rocketcc92c7a54803
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex c75824ba..7b3e8abd 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -8,6 +8,7 @@ Versioning follows [Semantic Versioning](https://semver.org/).## [Unreleased]### Fixed+- **IAM — trust policies with `NotPrincipal`** — `CreateRole`, `UpdateAssumeRolePolicy` and `AWS::IAM::Role` stored a trust policy with a `NotPrincipal` statement; they now answer `MalformedPolicyDocument` with IAM's message, `Allow with NotPrincipal is not allowed.` when an `Allow` statement carries it and `AssumeRole policy must not contain NotPrincipal field.` for a `Deny`, with `AUTH` on or off. Contributed by @iot-rocket.- **S3 — `x-amz-grant-*` headers** — `PutBucketAcl` and `PutObjectAcl` answered the grant headers with 400 `MissingSecurityHeader`, and `CreateBucket`, `PutObject` and `CopyObject` dropped them. On buckets with ACLs enabled all five now set an ACL of exactly the named grants, in the order S3 lists them, and refuse what S3 refuses: a malformed grant, an unknown group, an email grantee, and grant headers next to `x-amz-acl` or an ACL body. On a bucket with ACLs disabled (`BucketOwnerEnforced`) `PutBucketAcl` and `PutObjectAcl` refuse grant headers with 400 `AccessControlListNotSupported`. Contributed by @iot-rocket.- **S3 — Block Public Access settings and public bucket ACL grants** — any one of the four Block Public Access settings shut off every public grant on a bucket, none refused setting a public ACL, and a public bucket ACL opened every read and write in the bucket. `BlockPublicAcls` now refuses a call that sets a public ACL on a bucket with ACLs enabled (403 `AccessDenied`) and leaves the grants in place, `IgnorePublicAcls` drops public ACL grants and `RestrictPublicBuckets` the bucket policy. A bucket ACL grants what its permission covers: `READ` the listings, `WRITE` adding and removing objects, `READ_ACP` and `WRITE_ACP` the bucket ACL. Contributed by @iot-rocket.- **IoT — `NaN` and `Infinity` in job documents and shadow updates** — `CreateJob` and `CreateJobTemplate` (inline and `documentSource`) and `UpdateThingShadow` (HTTP and the MQTT `update`, `get` and `delete` topics) accepted `NaN`, `Infinity` and `-Infinity`, and a shadow wrote them back as bare tokens, which is not JSON; they are now refused as invalid JSON with the messages AWS gives (`Payload contains invalid json` for shadows, also for any other invalid shadow payload), and a shadow number beyond a double's range, such as `1E400`, is stored as the string `"Infinity"` or `"-Infinity"` as on AWS. Contributed by @iot-rocket.diff --git a/ministack/services/cloudformation/provisioners.py b/ministack/services/cloudformation/provisioners.pyindex 2ce536a2..52355d57 100644--- a/ministack/services/cloudformation/provisioners.py+++ b/ministack/services/cloudformation/provisioners.py@@ -2539,8 +2539,16 @@ def _validate_iam_identity_tag_keys(resource_type, tags):raise ValueError(_iam.DUPLICATE_IDENTITY_TAG_KEYS)+def _validate_iam_role_trust_policy(props):+ """IAM's refusal of a NotPrincipal trust policy, before any state changes."""+ trust_err = _iam._trust_policy_not_principal_error(props.get("AssumeRolePolicyDocument"))+ if trust_err:+ raise ValueError(trust_err)++def _iam_role_create(logical_id, props, stack_name):_validate_iam_identity_tag_keys("AWS::IAM::Role", props.get("Tags") or [])+ _validate_iam_role_trust_policy(props)name = props.get("RoleName") or _physical_name(stack_name, logical_id, max_len=64)arn = f"arn:aws:iam::{get_account_id()}:role{props.get('Path', '/')}{name}"role_id = "AROA" + new_uuid().replace("-", "")[:17].upper()@@ -2595,6 +2603,7 @@ def _iam_role_update(physical_id, old_props, new_props, stack_name, logical_id=Nin place, so policies attached from outside the template survive."""_validate_iam_identity_tag_keys("AWS::IAM::Role", new_props.get("Tags") or [])+ _validate_iam_role_trust_policy(new_props)name = new_props.get("RoleName") or _physical_name(stack_name, logical_id or physical_id, max_len=64)diff --git a/ministack/services/iam.py b/ministack/services/iam.pyindex 17ca78e8..60555e24 100644--- a/ministack/services/iam.py+++ b/ministack/services/iam.py@@ -557,6 +557,26 @@ def _validate_role_description(description):return None+def _trust_policy_not_principal_error(doc):+ """IAM's message refusing a role trust policy that carries NotPrincipal, or None."""+ if isinstance(doc, str):+ try:+ doc = json.loads(doc)+ except ValueError:+ return None+ statements = doc.get("Statement") if isinstance(doc, dict) else None+ if isinstance(statements, dict):+ statements = [statements]+ if not isinstance(statements, list):+ return None+ flagged = [s for s in statements if isinstance(s, dict) and "NotPrincipal" in s]+ if any(s.get("Effect") == "Allow" for s in flagged):+ return "Allow with NotPrincipal is not allowed."+ if flagged:+ return "AssumeRole policy must not contain NotPrincipal field."+ return None++def _create_role(p):name = _p(p, "RoleName")description = _p(p, "Description")@@ -566,6 +586,9 @@ def _create_role(p):if name in _roles:return _error(409, "EntityAlreadyExists",f"Role with name {name} already exists.", ns="iam")+ trust_err = _trust_policy_not_principal_error(_p(p, "AssumeRolePolicyDocument"))+ if trust_err:+ return _error(400, "MalformedPolicyDocument", trust_err, ns="iam")boundary_err = _p(p, "PermissionsBoundary") and _boundary_policy_error(_p(p, "PermissionsBoundary"))if boundary_err:return boundary_err@@ -656,6 +679,9 @@ def _update_assume_role_policy(p):if name not in _roles:return _error(404, "NoSuchEntity",f"Role {name} not found.", ns="iam")+ trust_err = _trust_policy_not_principal_error(_p(p, "PolicyDocument"))+ if trust_err:+ return _error(400, "MalformedPolicyDocument", trust_err, ns="iam")_roles[name]["AssumeRolePolicyDocument"] = _p(p, "PolicyDocument")return _xml(200, "UpdateAssumeRolePolicyResponse", "", ns="iam")diff --git a/tests/test_cfn.py b/tests/test_cfn.pyindex 350adb3d..94b66247 100644--- a/tests/test_cfn.py+++ b/tests/test_cfn.py@@ -22093,6 +22093,42 @@ def test_cfn_update_iam_role_in_place(cfn, iam):_delete_cfn_test_stack(cfn, stack_name)[email protected]("operation, effect, message", [+ ("create", "Allow", "Allow with NotPrincipal is not allowed."),+ ("update", "Deny", "AssumeRole policy must not contain NotPrincipal field."),+], ids=["create", "update"])+def test_cfn_iam_role_not_principal_trust_policy_fails_the_resource(cfn, iam, operation, effect, message):+ """IAM refuses a trust policy with NotPrincipal, so the role is not created or keeps its old one."""+ name = f"cfn-np-role-{_uuid_mod.uuid4().hex[:8]}"+ plain = {"Effect": "Allow", "Principal": {"Service": "lambda.amazonaws.com"}, "Action": "sts:AssumeRole"}+ refused = {"Effect": effect, "NotPrincipal": {"AWS": "arn:aws:iam::111122223333:root"}, "Action": "sts:AssumeRole"}++ def tpl(statements):+ return json.dumps({"Resources": {"Role": {"Type": "AWS::IAM::Role", "Properties": {+ "RoleName": name, "AssumeRolePolicyDocument": {"Version": "2012-10-17", "Statement": statements}}}}})++ try:+ if operation == "update":+ cfn.create_stack(StackName=name, TemplateBody=tpl([plain]), Capabilities=["CAPABILITY_NAMED_IAM"])+ assert _wait_stack(cfn, name)["StackStatus"] == "CREATE_COMPLETE"+ statements = [plain, refused] if effect == "Deny" else [refused]+ getattr(cfn, f"{operation}_stack")(StackName=name, TemplateBody=tpl(statements),+ Capabilities=["CAPABILITY_NAMED_IAM"])+ assert _wait_stack(cfn, name)["StackStatus"] == (+ "UPDATE_ROLLBACK_COMPLETE" if operation == "update" else "ROLLBACK_COMPLETE")+ reasons = [e.get("ResourceStatusReason", "") for e in cfn.describe_stack_events(StackName=name)["StackEvents"]+ if e["LogicalResourceId"] == "Role" and e["ResourceStatus"] == f"{operation.upper()}_FAILED"]+ assert any(message in r for r in reasons), reasons+ if operation == "update":+ trust = iam.get_role(RoleName=name)["Role"]["AssumeRolePolicyDocument"]+ assert trust["Statement"] == [plain]+ else:+ with pytest.raises(iam.exceptions.NoSuchEntityException):+ iam.get_role(RoleName=name)+ finally:+ _delete_cfn_test_stack(cfn, name)++def test_cfn_update_iam_managed_policy_in_place(cfn, iam):"""A managed policy's document update creates a new default version onthe same ARN, exactly as CloudFormation's handler does."""diff --git a/tests/test_iam.py b/tests/test_iam.pyindex df8aae9d..80e3cf83 100644--- a/tests/test_iam.py+++ b/tests/test_iam.py@@ -72,6 +72,52 @@ def test_iam_get_role(iam):assert resp["Role"]["RoleName"] == "iam-test-role"+_TRUST_ALLOW_ROOT = {"Effect": "Allow", "Principal": {"AWS": "arn:aws:iam::000000000000:root"},+ "Action": "sts:AssumeRole"}+_TRUST_ALLOW_NOT_PRINCIPAL = {"Effect": "Allow", "NotPrincipal": {"AWS": "arn:aws:iam::111122223333:root"},+ "Action": "sts:AssumeRole"}+_TRUST_DENY_NOT_PRINCIPAL = {"Effect": "Deny", "NotPrincipal": {"AWS": "arn:aws:iam::000000000000:root"},+ "Action": "sts:AssumeRole"}++[email protected]("statement, message", [+ ([_TRUST_ALLOW_NOT_PRINCIPAL], "Allow with NotPrincipal is not allowed."),+ (_TRUST_ALLOW_NOT_PRINCIPAL, "Allow with NotPrincipal is not allowed."),+ ([_TRUST_ALLOW_ROOT, _TRUST_DENY_NOT_PRINCIPAL], "AssumeRole policy must not contain NotPrincipal field."),+ ([_TRUST_DENY_NOT_PRINCIPAL, _TRUST_ALLOW_NOT_PRINCIPAL], "Allow with NotPrincipal is not allowed."),+], ids=["allow", "allow-object", "deny", "deny-then-allow"])+def test_iam_role_trust_policy_not_principal_refused(iam, statement, message):+ name = f"not-principal-role-{_uuid_mod.uuid4().hex[:8]}"+ refused = json.dumps({"Version": "2012-10-17", "Statement": statement})+ plain = {"Version": "2012-10-17", "Statement": [_TRUST_ALLOW_ROOT]}+ with pytest.raises(ClientError) as exc:+ iam.create_role(RoleName=name, AssumeRolePolicyDocument=refused)+ assert exc.value.response["ResponseMetadata"]["HTTPStatusCode"] == 400+ assert exc.value.response["Error"]["Code"] == "MalformedPolicyDocument"+ assert exc.value.response["Error"]["Message"] == message+ with pytest.raises(ClientError) as exc:+ iam.get_role(RoleName=name)+ assert exc.value.response["Error"]["Code"] == "NoSuchEntity"++ iam.create_role(RoleName=name, AssumeRolePolicyDocument=json.dumps(plain))+ try:+ with pytest.raises(ClientError) as exc:+ iam.update_assume_role_policy(RoleName=name, PolicyDocument=refused)+ assert exc.value.response["ResponseMetadata"]["HTTPStatusCode"] == 400+ assert exc.value.response["Error"]["Code"] == "MalformedPolicyDocument"+ assert exc.value.response["Error"]["Message"] == message+ assert iam.get_role(RoleName=name)["Role"]["AssumeRolePolicyDocument"] == plain+ # The name and the role's existence are checked before the document.+ with pytest.raises(ClientError) as exc:+ iam.create_role(RoleName=name, AssumeRolePolicyDocument=refused)+ assert exc.value.response["Error"]["Code"] == "EntityAlreadyExists"+ with pytest.raises(ClientError) as exc:+ iam.update_assume_role_policy(RoleName=f"{name}-missing", PolicyDocument=refused)+ assert exc.value.response["Error"]["Code"] == "NoSuchEntity"+ finally:+ iam.delete_role(RoleName=name)++def test_iam_update_role_description(iam):name = f"description-role-{_uuid_mod.uuid4().hex[:8]}"iam.create_role(