Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 7 additions & 7 deletions moto/iam/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -2031,7 +2031,7 @@ def create_policy(
iam_policy_document_validator = IAMPolicyDocumentValidator(policy_document)
iam_policy_document_validator.validate()

clean_tags = self._tag_verification(tags)
clean_tags = self._tag_verification(tags, case_sensitive=True)
policy = ManagedPolicy(
policy_name,
account_id=self.account_id,
Expand Down Expand Up @@ -2250,15 +2250,16 @@ def list_role_policies(self, role_name: str) -> list[str]:
return list(role.policies.keys())

def _tag_verification(
self, tags: list[dict[str, str]]
self, tags: list[dict[str, str]], case_sensitive: bool = False
) -> dict[str, dict[str, str]]:
if len(tags) > 50:
raise TooManyTags(tags)

tag_keys: dict[str, dict[str, str]] = {}
for tag in tags:
# Need to index by the lowercase tag key since the keys are case insensitive, but their case is retained.
ref_key = tag["Key"].lower()
# Users and roles have case-insensitive keys; other IAM resources
# can opt into keeping case-distinct keys separate.
ref_key = tag["Key"] if case_sensitive else tag["Key"].lower()
self._check_tag_duplicate(tag_keys, ref_key)
self._validate_tag_key(tag["Key"])
if len(tag["Value"]) > 256:
Expand Down Expand Up @@ -2360,7 +2361,7 @@ def list_policy_tags(
return tags, marker

def tag_policy(self, policy_arn: str, tags: list[dict[str, str]]) -> None:
clean_tags = self._tag_verification(tags)
clean_tags = self._tag_verification(tags, case_sensitive=True)
policy = self.get_policy(policy_arn)
policy.tags.update(clean_tags)

Expand All @@ -2371,10 +2372,9 @@ def untag_policy(self, policy_arn: str, tag_keys: list[str]) -> None:
policy = self.get_policy(policy_arn)

for key in tag_keys:
ref_key = key.lower()
self._validate_tag_key(key, exception_param="tagKeys")

policy.tags.pop(ref_key, None)
policy.tags.pop(key, None)

def create_policy_version(
self, policy_arn: str, policy_document: str, set_as_default: bool
Expand Down
51 changes: 20 additions & 31 deletions tests/test_iam/test_iam.py
Original file line number Diff line number Diff line change
Expand Up @@ -1014,20 +1014,18 @@ def test_create_policy_with_duplicate_tag():


@mock_aws()
def test_create_policy_with_duplicate_tag_different_casing():
def test_create_policy_with_case_distinct_tags():
conn = boto3.client("iam", region_name="us-east-1")

# Duplicate tag with different casing:
with pytest.raises(ClientError) as ce:
conn.create_policy(
PolicyName="TestCreatePolicyWithTags3",
PolicyDocument=MOCK_POLICY,
Tags=[{"Key": "a", "Value": ""}, {"Key": "A", "Value": ""}],
)
assert (
"Duplicate tag keys found. Please note that Tag keys are case insensitive."
in ce.value.response["Error"]["Message"]
)
tags = [{"Key": "a", "Value": "lower"}, {"Key": "A", "Value": "upper"}]
policy = conn.create_policy(
PolicyName="TestCreatePolicyWithTags3",
PolicyDocument=MOCK_POLICY,
Tags=tags,
)["Policy"]
assert {tag["Key"]: tag["Value"] for tag in policy["Tags"]} == {
"a": "lower",
"A": "upper",
}


@mock_aws()
Expand Down Expand Up @@ -1276,27 +1274,18 @@ def test_updating_existing_tagged_policy_with_duplicate_tag():


@mock_aws()
def test_updating_existing_tagged_policy_with_duplicate_tag_different_casing():
def test_updating_existing_tagged_policy_with_case_distinct_tags():
conn = boto3.client("iam", region_name="us-east-1")
conn.create_policy(PolicyName="TestTagPolicy", PolicyDocument=MOCK_POLICY)
arn = conn.create_policy(PolicyName="TestTagPolicy", PolicyDocument=MOCK_POLICY)[
"Policy"
]["Arn"]
conn.tag_policy(
PolicyArn=f"arn:aws:iam::{ACCOUNT_ID}:policy/TestTagPolicy",
Tags=[
{"Key": "somekey", "Value": "somevalue"},
{"Key": "someotherkey", "Value": "someothervalue"},
],
)

# Duplicate tag with different casing:
with pytest.raises(ClientError) as ce:
conn.tag_policy(
PolicyArn=f"arn:aws:iam::{ACCOUNT_ID}:policy/TestTagPolicy",
Tags=[{"Key": "a", "Value": ""}, {"Key": "A", "Value": ""}],
)
assert (
"Duplicate tag keys found. Please note that Tag keys are case insensitive."
in ce.value.response["Error"]["Message"]
PolicyArn=arn,
Tags=[{"Key": "a", "Value": "lower"}, {"Key": "A", "Value": "upper"}],
)
assert {
tag["Key"]: tag["Value"] for tag in conn.list_policy_tags(PolicyArn=arn)["Tags"]
} == {"a": "lower", "A": "upper"}


@mock_aws()
Expand Down
57 changes: 57 additions & 0 deletions tests/test_iam/test_policy_tag_case.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
import json

import boto3

from moto import mock_aws

POLICY = json.dumps(
{
"Version": "2012-10-17",
"Statement": [{"Effect": "Allow", "Action": "s3:ListBucket", "Resource": "*"}],
}
)


@mock_aws
def test_create_policy_allows_case_distinct_tag_keys():
client = boto3.client("iam", region_name="us-east-1")
tags = [
{"Key": "Costcenter", "Value": "1234"},
{"Key": "costcenter", "Value": "5678"},
]
policy = client.create_policy(
PolicyName="case-sensitive", PolicyDocument=POLICY, Tags=tags
)["Policy"]
assert {tag["Key"]: tag["Value"] for tag in policy["Tags"]} == {
"Costcenter": "1234",
"costcenter": "5678",
}


@mock_aws
def test_tag_policy_updates_only_the_exact_key():
client = boto3.client("iam", region_name="us-east-1")
arn = client.create_policy(
PolicyName="case-sensitive",
PolicyDocument=POLICY,
Tags=[{"Key": "Costcenter", "Value": "1234"}],
)["Policy"]["Arn"]
client.tag_policy(PolicyArn=arn, Tags=[{"Key": "costcenter", "Value": "5678"}])
client.tag_policy(PolicyArn=arn, Tags=[{"Key": "Costcenter", "Value": "updated"}])
assert {
tag["Key"]: tag["Value"]
for tag in client.list_policy_tags(PolicyArn=arn)["Tags"]
} == {"Costcenter": "updated", "costcenter": "5678"}


@mock_aws
def test_untag_policy_does_not_match_a_different_case():
client = boto3.client("iam", region_name="us-east-1")
tags = [{"Key": "Costcenter", "Value": "1234"}]
arn = client.create_policy(
PolicyName="case-sensitive", PolicyDocument=POLICY, Tags=tags
)["Policy"]["Arn"]
client.untag_policy(PolicyArn=arn, TagKeys=["costcenter"])
assert client.list_policy_tags(PolicyArn=arn)["Tags"] == tags
client.untag_policy(PolicyArn=arn, TagKeys=["Costcenter"])
assert client.list_policy_tags(PolicyArn=arn)["Tags"] == []