IAM: Keep AWS managed policies cache clean (#6716)

This commit is contained in:
Bert Blommers 2023-08-24 07:54:32 +00:00 committed by GitHub
parent 6a1a5ca5a2
commit 8ff53ff417
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 50 additions and 5 deletions

View File

@ -1,4 +1,5 @@
import base64
import copy
import os
import string
from datetime import datetime
@ -438,6 +439,12 @@ class ManagedPolicy(Policy, CloudFormationModel):
)
return policy
def __eq__(self, other: Any) -> bool:
return self.arn == other.arn
def __hash__(self) -> int:
return self.arn.__hash__()
@property
def physical_resource_id(self) -> str:
return self.arn
@ -1791,8 +1798,8 @@ class IAMBackend(BaseBackend):
self.initialize_service_roles()
def _init_aws_policies(self) -> List[ManagedPolicy]:
# AWS defines some of its own managed policies and we periodically
# import them via `make aws_managed_policies`
# AWS defines some of its own managed policies
# we periodically import them via `make aws_managed_policies`
aws_managed_policies_data_parsed = json.loads(aws_managed_policies_data)
return [
AWSManagedPolicy.from_data(name, self.account_id, d)
@ -1800,7 +1807,7 @@ class IAMBackend(BaseBackend):
]
def _init_managed_policies(self) -> Dict[str, ManagedPolicy]:
return dict((p.arn, p) for p in self.aws_managed_policies)
return dict((p.arn, copy.deepcopy(p)) for p in self.aws_managed_policies)
def reset(self) -> None:
region_name = self.region_name

View File

@ -3368,7 +3368,7 @@ def test_get_account_summary():
"ServerCertificatesQuota": 20,
"MFADevices": 0,
"UserPolicySizeQuota": 2048,
"PolicyVersionsInUse": 1,
"PolicyVersionsInUse": 0,
"ServerCertificates": 0,
"Roles": 0,
"RolesQuota": 1000,
@ -3438,7 +3438,7 @@ def test_get_account_summary():
"ServerCertificatesQuota": 20,
"MFADevices": 1,
"UserPolicySizeQuota": 2048,
"PolicyVersionsInUse": 4,
"PolicyVersionsInUse": 3,
"ServerCertificates": 1,
"Roles": 1,
"RolesQuota": 1000,

View File

@ -0,0 +1,38 @@
import boto3
import json
from moto import mock_iam
# Test IAM User Inline Policy
def test_policies_are_not_kept_after_mock_ends():
iam_client = boto3.client("iam", "us-east-1")
with mock_iam():
role_name = "test"
assume_role_policy_document = {
"Version": "2012-10-17",
"Statement": {
"Effect": "Allow",
"Principal": {"AWS": "*"},
"Action": "sts:AssumeRole",
},
}
iam_client.create_role(
RoleName=role_name,
AssumeRolePolicyDocument=json.dumps(assume_role_policy_document),
)
iam_client.attach_role_policy(
RoleName=role_name,
PolicyArn="arn:aws:iam::aws:policy/ReadOnlyAccess",
)
iam_policies = iam_client.list_policies(Scope="AWS", OnlyAttached=True)[
"Policies"
]
assert len(iam_policies) == 1
assert iam_policies[0]["Arn"] == "arn:aws:iam::aws:policy/ReadOnlyAccess"
assert iam_client.list_roles()["Roles"][0]["RoleName"] == "test"
with mock_iam():
resp = iam_client.list_policies(Scope="AWS", OnlyAttached=True)
assert len(resp["Policies"]) == 0