Skip to content

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

fix(iam): make user and role tag keys case insensitive (#2130)

gakuto-cw2100cb61a37a15
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 89953c7f..7561f4b2 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -8,6 +8,7 @@ Versioning follows [Semantic Versioning](https://semver.org/).
## [Unreleased]
### Fixed
+- **IAM / CloudFormation — user and role tag keys** — IAM user and role tag keys now compare without case while preserving their spelling. Create and tag operations reject duplicate keys, untag operations match keys regardless of case, and CloudFormation validates duplicate keys and merges stack tags accordingly. User tag updates also compare keys without case. Other resource types retain case-sensitive tag handling.
- **Signer — signing material checks in `PutSigningProfile` under `AUTH=true`** — `PutSigningProfile` accepted any certificate ARN, or no `signingMaterial` at all, on every platform; with `AUTH=true` the IoT and FreeRTOS platforms now refuse a profile without `signingMaterial` and a certificate ARN that is malformed, in another region or account, unknown to ACM or not issued, and the Lambda and Notation platforms refuse any `signingMaterial`, with AWS's errors. Contributed by @iot-rocket.
### Added
diff --git a/ministack/services/cloudformation/provisioners.py b/ministack/services/cloudformation/provisioners.py
index fea7050e..408a63fe 100644
--- a/ministack/services/cloudformation/provisioners.py
+++ b/ministack/services/cloudformation/provisioners.py
@@ -1189,10 +1189,18 @@ def _with_stack_tags(resource_type: str, props: dict, stack_tags: list,
own = [{"Key": key, "Value": value} for key, value in own.items()]
own_list = [t for t in (own or []) if isinstance(t, dict) and "Key" in t]
present = {t["Key"] for t in own_list}
+ if resource_type in ("AWS::IAM::User", "AWS::IAM::Role"):
+ _validate_iam_identity_tag_keys(resource_type, own_list)
+ present = {_iam._identity_tag_key(k) for k in present}
+ extra = {k: v for k, v in extra.items() if _iam._identity_tag_key(k) not in present}
+ else:
+ extra = {k: v for k, v in extra.items() if k not in present}
merged = own_list + [
{"Key": key, "Value": value}
- for key, value in extra.items() if key not in present
+ for key, value in extra.items()
]
+ if resource_type in ("AWS::IAM::User", "AWS::IAM::Role"):
+ _validate_iam_identity_tag_keys(resource_type, merged)
out = dict(props)
out[prop] = merged
return out
@@ -2385,7 +2393,14 @@ def _lambda_url_delete(physical_id, props):
# --- IAM Role ---
+def _validate_iam_identity_tag_keys(resource_type, tags):
+ """Validate only user/role key uniqueness, before merging or changing state."""
+ if _iam._identity_tags_have_duplicate_keys([{"Key": t.get("Key", "")} for t in tags]):
+ raise ValueError(f"{resource_type} Tags contain duplicate keys (case insensitive)")
+
+
def _iam_role_create(logical_id, props, stack_name):
+ _validate_iam_identity_tag_keys("AWS::IAM::Role", props.get("Tags") or [])
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()
@@ -2439,6 +2454,7 @@ def _iam_role_update(physical_id, old_props, new_props, stack_name, logical_id=N
RoleName and Path are replaced in ``_update_resource``; the rest updates
in place, so policies attached from outside the template survive.
"""
+ _validate_iam_identity_tag_keys("AWS::IAM::Role", new_props.get("Tags") or [])
name = new_props.get("RoleName") or _physical_name(
stack_name, logical_id or physical_id, max_len=64
)
@@ -2569,6 +2585,7 @@ def _iam_user_create(logical_id, props, stack_name):
def _iam_user_update(physical_id, old_props, new_props, stack_name, logical_id=None):
+ _validate_iam_identity_tag_keys("AWS::IAM::User", new_props.get("Tags") or [])
user = _iam._users.get(physical_id)
if user is None:
return _iam_user_create(logical_id or physical_id, new_props, stack_name)
@@ -2577,11 +2594,15 @@ def _iam_user_update(physical_id, old_props, new_props, stack_name, logical_id=N
user["Path"] = path
user["Arn"] = f"arn:aws:iam::{get_account_id()}:user{path}{physical_id}"
_iam_user_reconcile(physical_id, old_props, new_props, "update")
- old_tags, new_tags = _tag_map(old_props.get("Tags")), _tag_map(new_props.get("Tags"))
- removed = sorted(old_tags.keys() - new_tags.keys())
+ old_tags, new_tags = [
+ {_iam._identity_tag_key(k): (k, v) for k, v in _tag_map(props.get("Tags")).items()}
+ for props in (old_props, new_props)
+ ]
+ removed = [old_tags[k][0] for k in sorted(old_tags.keys() - new_tags.keys())]
if removed:
_iam_user_call(_iam._untag_user, {"UserName": physical_id, **_ec_query({"TagKeys": removed})}, "update")
- changed = [{"Key": k, "Value": v} for k, v in new_tags.items() if old_tags.get(k) != v]
+ changed = [{"Key": key, "Value": value} for k, (key, value) in new_tags.items()
+ if old_tags.get(k) != (key, value)]
if changed:
_iam_user_call(_iam._tag_user, {"UserName": physical_id, **_ec_query({"Tags": changed})}, "update")
return physical_id, {"Arn": user["Arn"]}
diff --git a/ministack/services/iam.py b/ministack/services/iam.py
index 03a87293..82cc047d 100644
--- a/ministack/services/iam.py
+++ b/ministack/services/iam.py
@@ -420,6 +420,9 @@ def _create_user(p):
if name in _users:
return _error(409, "EntityAlreadyExists",
f"User with name {name} already exists.", ns="iam")
+ tags = _extract_tags(p)
+ if _identity_tags_have_duplicate_keys(tags):
+ return _error(400, "InvalidInput", "Duplicate tag keys found. Tag keys are case insensitive.", ns="iam")
path = _p(p, "Path") or "/"
_users[name] = {
"UserName": name,
@@ -429,7 +432,7 @@ def _create_user(p):
"Path": path,
"PermissionsBoundary": _p(p, "PermissionsBoundary"),
"AttachedPolicies": [],
- "Tags": _extract_tags(p),
+ "Tags": tags,
}
return _xml(200, "CreateUserResponse",
f"<CreateUserResult><User>{_user_xml(name)}</User></CreateUserResult>",
@@ -546,6 +549,9 @@ def _create_role(p):
if name in _roles:
return _error(409, "EntityAlreadyExists",
f"Role with name {name} already exists.", ns="iam")
+ tags = _extract_tags(p)
+ if _identity_tags_have_duplicate_keys(tags):
+ return _error(400, "InvalidInput", "Duplicate tag keys found. Tag keys are case insensitive.", ns="iam")
path = _p(p, "Path") or "/"
_roles[name] = {
"RoleName": name,
@@ -559,7 +565,7 @@ def _create_role(p):
"PermissionsBoundary": _p(p, "PermissionsBoundary"),
"AttachedPolicies": [],
"InlinePolicies": {},
- "Tags": _extract_tags(p),
+ "Tags": tags,
}
return _xml(200, "CreateRoleResponse",
f"<CreateRoleResult><Role>{_role_xml(name)}</Role></CreateRoleResult>",
@@ -1439,9 +1445,11 @@ def _tag_role(p):
return _error(404, "NoSuchEntity",
f"Role {role_name} not found.", ns="iam")
new_tags = _extract_tags(p)
- existing = {t["Key"]: t for t in role["Tags"]}
+ if _identity_tags_have_duplicate_keys(new_tags):
+ return _error(400, "InvalidInput", "Duplicate tag keys found. Tag keys are case insensitive.", ns="iam")
+ existing = {_identity_tag_key(t["Key"]): t for t in role["Tags"]}
for t in new_tags:
- existing[t["Key"]] = t
+ existing[_identity_tag_key(t["Key"])] = t
role["Tags"] = list(existing.values())
return _xml(200, "TagRoleResponse", "", ns="iam")
@@ -1452,8 +1460,8 @@ def _untag_role(p):
if not role:
return _error(404, "NoSuchEntity",
f"Role {role_name} not found.", ns="iam")
- keys_to_remove = _extract_tag_keys(p)
- role["Tags"] = [t for t in role["Tags"] if t["Key"] not in keys_to_remove]
+ keys_to_remove = {_identity_tag_key(key) for key in _extract_tag_keys(p)}
+ role["Tags"] = [t for t in role["Tags"] if _identity_tag_key(t["Key"]) not in keys_to_remove]
return _xml(200, "UntagRoleResponse", "", ns="iam")
@@ -1475,6 +1483,20 @@ def _list_role_tags(p):
# -------------------- Tags: users --------------------
+def _identity_tag_key(key):
+ """Compare IAM user/role keys without case, retaining the stored spelling.
+
+ Evidence: the IAM tagging guide, not a real AWS run. Other IAM resources
+ keep their case-sensitive tag handling.
+ """
+ return key.lower()
+
+
+def _identity_tags_have_duplicate_keys(tags):
+ keys = [_identity_tag_key(t["Key"]) for t in tags]
+ return len(keys) != len(set(keys))
+
+
def _tag_user(p):
user_name = _p(p, "UserName")
user = _users.get(user_name)
@@ -1482,9 +1504,11 @@ def _tag_user(p):
return _error(404, "NoSuchEntity",
f"The user with name {user_name} cannot be found.", ns="iam")
new_tags = _extract_tags(p)
- existing = {t["Key"]: t for t in user["Tags"]}
+ if _identity_tags_have_duplicate_keys(new_tags):
+ return _error(400, "InvalidInput", "Duplicate tag keys found. Tag keys are case insensitive.", ns="iam")
+ existing = {_identity_tag_key(t["Key"]): t for t in user["Tags"]}
for t in new_tags:
- existing[t["Key"]] = t
+ existing[_identity_tag_key(t["Key"])] = t
user["Tags"] = list(existing.values())
return _xml(200, "TagUserResponse", "", ns="iam")
@@ -1495,8 +1519,8 @@ def _untag_user(p):
if not user:
return _error(404, "NoSuchEntity",
f"The user with name {user_name} cannot be found.", ns="iam")
- keys_to_remove = _extract_tag_keys(p)
- user["Tags"] = [t for t in user["Tags"] if t["Key"] not in keys_to_remove]
+ keys_to_remove = {_identity_tag_key(key) for key in _extract_tag_keys(p)}
+ user["Tags"] = [t for t in user["Tags"] if _identity_tag_key(t["Key"]) not in keys_to_remove]
return _xml(200, "UntagUserResponse", "", ns="iam")
diff --git a/tests/test_iam_tag_case.py b/tests/test_iam_tag_case.py
new file mode 100644
index 00000000..95a51353
--- /dev/null
+++ b/tests/test_iam_tag_case.py
@@ -0,0 +1,220 @@
+"""IAM tagging guide / API references and MiniStack tests, not real AWS runs."""
+
+import copy
+import json
+import uuid
+
+import pytest
+from botocore.exceptions import ClientError
+from test_cfn import _delete_cfn_test_stack, _wait_stack
+
+from ministack.services.cloudformation.provisioners import _reconcile_tag_list, _with_stack_tags
+
+_TRUST = {"Statement": [{"Effect": "Allow", "Principal": {"Service": "lambda.amazonaws.com"},
+ "Action": "sts:AssumeRole"}]}
+
+
+def _tags(tags):
+ result = {t["Key"]: t["Value"] for t in tags}
+ assert len(result) == len(tags), f"Duplicate tag keys in response: {tags}"
+ return result
+
+
+def _custom_tags(tags):
+ return _tags([t for t in tags if not t["Key"].lower().startswith("aws:")])
+
+
[email protected]("resource", ["user", "role"])
+def test_iam_identity_tag_keys_ignore_case_and_preserve_spelling(iam, resource):
+ name = f"tag-case-{resource}-{uuid.uuid4().hex[:8]}"
+ params = {f"{resource.title()}Name": name}
+ create_params = {"AssumeRolePolicyDocument": json.dumps(_TRUST)} if resource == "role" else {}
+ original = [{"Key": "Department", "Value": "Finance"}, {"Key": "ExternalKey", "Value": "Keep"}]
+ getattr(iam, f"create_{resource}")(**params, **create_params, Tags=original)
+ try:
+ assert _tags(getattr(iam, f"get_{resource}")(**params)[resource.title()]["Tags"]) == _tags(original)
+ # Untag must match both the original spelling and a subsequently changed spelling.
+ getattr(iam, f"untag_{resource}")(**params, TagKeys=["DEPARTMENT"])
+ assert getattr(iam, f"list_{resource}_tags")(**params)["Tags"] == [original[1]]
+ getattr(iam, f"tag_{resource}")(**params, Tags=[original[0]])
+ # A spelling-only update and a case-sensitive value change must both take effect.
+ for key, value in [("department", "Finance"), ("DEPARTMENT", "finance")]:
+ getattr(iam, f"tag_{resource}")(**params, Tags=[{"Key": key, "Value": value}])
+ expected = {key: value, "ExternalKey": "Keep"}
+ assert _tags(getattr(iam, f"get_{resource}")(**params)[resource.title()]["Tags"]) == expected
+ assert _tags(getattr(iam, f"list_{resource}_tags")(**params)["Tags"]) == expected
+ getattr(iam, f"untag_{resource}")(**params, TagKeys=["DePaRtMeNt", "missing"])
+ assert getattr(iam, f"list_{resource}_tags")(**params)["Tags"] == [original[1]]
+ finally:
+ getattr(iam, f"delete_{resource}")(**params)
+
+
[email protected]("resource", ["user", "role"])
[email protected]("operation", ["create", "tag"])
[email protected]("second_key", ["Department", "department"])
+def test_iam_identity_duplicate_tag_keys_reject_entire_request(iam, resource, operation, second_key):
+ params = {f"{resource.title()}Name": f"tag-duplicate-{resource}-{uuid.uuid4().hex[:8]}"}
+ create_params = {"AssumeRolePolicyDocument": json.dumps(_TRUST)} if resource == "role" else {}
+ original = [{"Key": "Department", "Value": "Finance"}]
+ if operation == "tag":
+ getattr(iam, f"create_{resource}")(**params, **create_params, Tags=original)
+ try:
+ with pytest.raises(ClientError) as exc:
+ getattr(iam, f"{operation}_{resource}")(**params,
+ **(create_params if operation == "create" else {}), Tags=[
+ {"Key": "Unrelated", "Value": "MustNotBeAdded"},
+ {"Key": "Department", "Value": "HR"}, {"Key": second_key, "Value": "HR"},
+ ])
+ assert exc.value.response["Error"]["Code"] == "InvalidInput"
+ assert exc.value.response["ResponseMetadata"]["HTTPStatusCode"] == 400
+ if operation == "tag":
+ assert getattr(iam, f"list_{resource}_tags")(**params)["Tags"] == original
+ else:
+ with pytest.raises(iam.exceptions.NoSuchEntityException):
+ getattr(iam, f"get_{resource}")(**params)
+ finally:
+ try:
+ getattr(iam, f"delete_{resource}")(**params)
+ except iam.exceptions.NoSuchEntityException:
+ pass
+
+
[email protected]("resource", ["policy", "instance_profile"])
+def test_iam_other_resource_tag_keys_remain_case_sensitive(iam, resource):
+ name = f"tag-case-{resource}-{uuid.uuid4().hex[:8]}"
+ tags = [{"Key": "Costcenter", "Value": "1234"}, {"Key": "costcenter", "Value": "5678"}]
+ if resource == "policy":
+ arn = iam.create_policy(PolicyName=name, PolicyDocument=json.dumps({
+ "Statement": [{"Effect": "Allow", "Action": "s3:ListBucket", "Resource": "*"}],
+ }), Tags=[tags[0]])["Policy"]["Arn"]
+ params = {"PolicyArn": arn}
+ else:
+ iam.create_instance_profile(InstanceProfileName=name, Tags=[tags[0]])
+ params = {"InstanceProfileName": name}
+ try:
+ getattr(iam, f"tag_{resource}")(**params, Tags=[tags[1]])
+ assert _tags(getattr(iam, f"list_{resource}_tags")(**params)["Tags"]) == _tags(tags)
+ getattr(iam, f"untag_{resource}")(**params, TagKeys=["Costcenter"])
+ assert getattr(iam, f"list_{resource}_tags")(**params)["Tags"] == [tags[1]]
+ finally:
+ getattr(iam, f"delete_{resource}")(**params)
+
+
+def _identity_template(resource, name, tags, after=False):
+ props = {f"{resource.title()}Name": name, "Tags": tags}
+ if resource == "role":
+ props.update(AssumeRolePolicyDocument=_TRUST, Description="After" if after else "Before")
+ else:
+ props["Path"] = "/after/" if after else "/before/"
+ return json.dumps({"Resources": {"Identity": {"Type": f"AWS::IAM::{resource.title()}", "Properties": props}}})
+
+
[email protected]("resource", ["user", "role"])
[email protected]("source", ["template", "stack"])
+def test_cfn_iam_identity_tag_case_update_and_removal(cfn, iam, resource, source):
+ name = f"cfn-{resource}-tag-case-{uuid.uuid4().hex[:8]}"
+ params = {f"{resource.title()}Name": name}
+ original_tag = {"Key": "Department", "Value": "Finance"}
+ body = _identity_template(resource, name, [original_tag] if source == "template" else [])
+ cfn.create_stack(StackName=name, TemplateBody=body, Capabilities=["CAPABILITY_NAMED_IAM"],
+ Tags=[original_tag] if source == "stack" else [])
+ try:
+ assert _wait_stack(cfn, name)["StackStatus"] == "CREATE_COMPLETE"
+ before = getattr(iam, f"get_{resource}")(**params)[resource.title()]
+ assert _custom_tags(before["Tags"]) == {"Department": "Finance"}
+ # First change only the key's spelling, then change its value too.
+ for value in ["Finance", "HR"]:
+ desired_tags = [{"Key": "department", "Value": value}, {"Key": "Added", "Value": "New"}]
+ body = _identity_template(resource, name, desired_tags if source == "template" else [])
+ cfn.update_stack(StackName=name, TemplateBody=body,
+ Tags=desired_tags if source == "stack" else [], Capabilities=["CAPABILITY_NAMED_IAM"])
+ assert _wait_stack(cfn, name)["StackStatus"] == "UPDATE_COMPLETE"
+ identity = getattr(iam, f"get_{resource}")(**params)[resource.title()]
+ assert identity[f"{resource.title()}Id"] == before[f"{resource.title()}Id"]
+ assert _custom_tags(identity["Tags"]) == {"department": value, "Added": "New"}
+ # Change a managed key's spelling externally; do not add unrelated external tags.
+ getattr(iam, f"tag_{resource}")(**params, Tags=[{"Key": "DEPARTMENT", "Value": "ExternalEdit"}])
+ assert _custom_tags(getattr(iam, f"list_{resource}_tags")(**params)["Tags"]) == {
+ "DEPARTMENT": "ExternalEdit", "Added": "New"}
+ cfn.update_stack(StackName=name, TemplateBody=_identity_template(resource, name, []), Tags=[],
+ Capabilities=["CAPABILITY_NAMED_IAM"])
+ assert _wait_stack(cfn, name)["StackStatus"] == "UPDATE_COMPLETE"
+ identity = getattr(iam, f"get_{resource}")(**params)[resource.title()]
+ assert identity[f"{resource.title()}Id"] == before[f"{resource.title()}Id"]
+ assert _custom_tags(getattr(iam, f"list_{resource}_tags")(**params)["Tags"]) == {}
+ finally:
+ _delete_cfn_test_stack(cfn, name)
+
+
[email protected]("resource", ["user", "role"])
+def test_cfn_iam_identity_stack_tag_merge_preserves_resource_spelling(cfn, iam, resource):
+ """At 50 custom tags, a case-insensitive merge must not create a 51st key.
+
+ IAM allows 50 user/role tags; aws: tags do not count toward that limit:
+ https://docs.aws.amazon.com/IAM/latest/APIReference/API_CreateUser.html
+ https://docs.aws.amazon.com/IAM/latest/APIReference/API_CreateRole.html
+ https://docs.aws.amazon.com/AWSCloudFormation/latest/TemplateReference/aws-properties-resource-tags.html
+ """
+ name = f"cfn-{resource}-tag-merge-{uuid.uuid4().hex[:8]}"
+ own = [{"Key": "department", "Value": "Resource"}, *[
+ {"Key": f"Key-{i}", "Value": "Value"} for i in range(48)]]
+ cfn.create_stack(StackName=name, TemplateBody=_identity_template(resource, name, own), Capabilities=["CAPABILITY_NAMED_IAM"],
+ Tags=[{"Key": "Department", "Value": "Stack"}, {"Key": "StackOnly", "Value": "Keep"}])
+ try:
+ assert _wait_stack(cfn, name)["StackStatus"] == "CREATE_COMPLETE"
+ actual = getattr(iam, f"list_{resource}_tags")(**{f"{resource.title()}Name": name})["Tags"]
+ assert [t for t in actual if t["Key"].lower() == "department"] == [own[0]]
+ assert _custom_tags(actual) == {**_tags(own), "StackOnly": "Keep"}
+ finally:
+ _delete_cfn_test_stack(cfn, name)
+
+
[email protected]("operation", ["create", "update"])
[email protected]("resource", ["user", "role"])
+def test_cfn_iam_identity_duplicate_tag_keys_leave_state_unchanged(cfn, iam, operation, resource):
+ name = f"cfn-{resource}-tag-duplicate-{uuid.uuid4().hex[:8]}"
+ params = {f"{resource.title()}Name": name}
+ before = None
+ if operation == "update":
+ cfn.create_stack(StackName=name, TemplateBody=_identity_template(resource, name, [{"Key": "Department", "Value": "Finance"}]),
+ Capabilities=["CAPABILITY_NAMED_IAM"])
+ assert _wait_stack(cfn, name)["StackStatus"] == "CREATE_COMPLETE"
+ before = getattr(iam, f"get_{resource}")(**params)[resource.title()]
+ try:
+ # Both duplicate forms use the predicate covered by the IAM API tests.
+ tags = [{"Key": "Department", "Value": "HR"}, {"Key": "department", "Value": "HR"}]
+ getattr(cfn, f"{operation}_stack")(StackName=name, TemplateBody=_identity_template(resource, name, tags, after=True),
+ Capabilities=["CAPABILITY_NAMED_IAM"])
+ assert _wait_stack(cfn, name)["StackStatus"] == (
+ "UPDATE_ROLLBACK_COMPLETE" if operation == "update" else "ROLLBACK_COMPLETE")
+ if before is not None:
+ assert getattr(iam, f"get_{resource}")(**params)[resource.title()] == before
+ else:
+ with pytest.raises(iam.exceptions.NoSuchEntityException):
+ getattr(iam, f"get_{resource}")(**params)
+ finally:
+ _delete_cfn_test_stack(cfn, name)
+
+
[email protected]("resource_type", ["AWS::SQS::Queue", "AWS::SSM::Parameter"])
+def test_cfn_other_resource_stack_tag_merge_remains_case_sensitive(resource_type):
+ # Protect the list/map branches of the shared merge without provisioning other services.
+ props = {"Tags": [{"Key": "department", "Value": "Resource"}]} if resource_type == "AWS::SQS::Queue" else {
+ "Tags": {"department": "Resource"}}
+ original = copy.deepcopy(props)
+ result = _with_stack_tags(resource_type, props, [{"Key": "Department", "Value": "Stack"}],
+ "stack-name", "stack-id", "Resource")
+ tags = result["Tags"]
+ actual = tags if isinstance(tags, dict) else _tags(tags)
+ assert {k: v for k, v in actual.items() if not k.lower().startswith("aws:")} == {
+ "Department": "Stack", "department": "Resource"}
+ assert props == original
+
+
+def test_cfn_other_resource_tag_reconciliation_remains_case_sensitive():
+ store = [{"Key": "Department", "Value": "External"}, {"Key": "department", "Value": "Before"}]
+ _reconcile_tag_list(store, {"Tags": [{"Key": "department", "Value": "Before"}]},
+ {"Tags": [{"Key": "DEPARTMENT", "Value": "After"}]})
+ assert _tags(store) == {"Department": "External", "DEPARTMENT": "After"}
+ _reconcile_tag_list(store, {"Tags": [{"Key": "DEPARTMENT", "Value": "After"}]}, {})
+ assert _tags(store) == {"Department": "External"}