fix(iam): reject duplicate tag keys and make user and role tags case-insensitive (#4484) (#4520)

Reject duplicate tag keys in a single request with 400 InvalidInput, matching AWS IAM behavior:
- Users and roles treat tag keys case-insensitively for duplicate checks.
- Policies, instance profiles, OIDC and SAML providers treat tag keys case-sensitively for duplicate checks.
- User and role tag updates preserve existing tag key casing.
- UntagUser and UntagRole remove tags case-insensitively.
- Re-tagging an existing tag with alternate casing stays within the 50-tag quota.

Signed-off-by: Abdul Wali Dal <148618788+abdulwalidal@users.noreply.github.com>
This commit is contained in:
Abdul Wali Dal authored and GitHub committed 2026-09-27 20:08:38 -04:00
1 parent 238e21770e
commit a43dcfa689
4 files changed
+287 -26

No files matched your search

@@ -26,9 +26,11 @@ import java.time.Instant;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import java.util.TreeSet;
import java.util.regex.Pattern;
@@ -256,7 +258,7 @@ public class IamQueryHandler {
private Response handleCreateUser(MultivaluedMap<String, String> params) {
String userName = getParam(params, "UserName");
String path = getParam(params, "Path");
Map<String, String> tags = extractTags(params);
Map<String, String> tags = extractTags(params, true);
IamUser user = iamService.createUser(userName, path);
if (!tags.isEmpty()) iamService.tagUser(userName, tags);
user = iamService.getUser(userName);
@@ -317,7 +319,7 @@ public class IamQueryHandler {
private Response handleTagUser(MultivaluedMap<String, String> params) {
String userName = getParam(params, "UserName");
iamService.tagUser(userName, extractTags(params));
iamService.tagUser(userName, extractTags(params, true));
return Response.ok(AwsQueryResponse.envelopeNoResult("TagUser", AwsNamespaces.IAM)).build();
}
@@ -402,7 +404,7 @@ public class IamQueryHandler {
private Response handleCreateSAMLProvider(MultivaluedMap<String, String> params, String authorization) {
SAMLProvider provider = samlProviderService.create(regionResolver.getPartition(),
accountResolver.resolve(authorization), getParam(params, "Name"),
getParam(params, "SAMLMetadataDocument"), extractTags(params));
getParam(params, "SAMLMetadataDocument"), extractTags(params, false));
return Response.ok(AwsQueryResponse.envelope("CreateSAMLProvider", AwsNamespaces.IAM,
new XmlBuilder().elem("SAMLProviderArn", provider.getArn())
.raw(tagsElement(new TreeMap<>(provider.getTags()))).build())).build();
@@ -436,7 +438,7 @@ public class IamQueryHandler {
private Response handleTagSAMLProvider(MultivaluedMap<String, String> params, String authorization) {
String accountId = accountResolver.resolve(authorization);
samlProviderService.tag(accountId, getParam(params, "SAMLProviderArn"), extractTags(params));
samlProviderService.tag(accountId, getParam(params, "SAMLProviderArn"), extractTags(params, false));
return Response.ok(AwsQueryResponse.envelopeNoResult("TagSAMLProvider", AwsNamespaces.IAM)).build();
}
@@ -471,7 +473,7 @@ public class IamQueryHandler {
getParam(params, "Url"),
getMemberList(params, "ClientIDList"),
getMemberList(params, "ThumbprintList"),
extractTags(params));
extractTags(params, false));
var xml = new XmlBuilder().elem("OpenIDConnectProviderArn", provider.getArn());
if (!provider.getTags().isEmpty()) {
xml.start("Tags").raw(tagsXml(provider.getTags())).end("Tags");
@@ -528,7 +530,7 @@ public class IamQueryHandler {
}
private Response handleTagOpenIDConnectProvider(MultivaluedMap<String, String> params) {
iamService.tagOpenIDConnectProvider(getParam(params, "OpenIDConnectProviderArn"), extractTags(params));
iamService.tagOpenIDConnectProvider(getParam(params, "OpenIDConnectProviderArn"), extractTags(params, false));
return Response.ok(AwsQueryResponse.envelopeNoResult("TagOpenIDConnectProvider", AwsNamespaces.IAM)).build();
}
@@ -779,7 +781,7 @@ public class IamQueryHandler {
String trustPolicy = getParam(params, "AssumeRolePolicyDocument");
String description = getParam(params, "Description");
int maxSession = getIntParam(params, "MaxSessionDuration", 3600);
Map<String, String> tags = extractTags(params);
Map<String, String> tags = extractTags(params, true);
IamRole role = iamService.createRole(roleName, path, trustPolicy, description, maxSession, tags);
String result = new XmlBuilder().start("Role").raw(roleXml(role, true)).end("Role").build();
return Response.ok(AwsQueryResponse.envelope("CreateRole", AwsNamespaces.IAM, result)).build();
@@ -841,7 +843,7 @@ public class IamQueryHandler {
}
private Response handleTagRole(MultivaluedMap<String, String> params) {
iamService.tagRole(getParam(params, "RoleName"), extractTags(params));
iamService.tagRole(getParam(params, "RoleName"), extractTags(params, true));
return Response.ok(AwsQueryResponse.envelopeNoResult("TagRole", AwsNamespaces.IAM)).build();
}
@@ -866,7 +868,7 @@ public class IamQueryHandler {
String path = getParam(params, "Path");
String description = getParam(params, "Description");
String document = getParam(params, "PolicyDocument");
Map<String, String> tags = extractTags(params);
Map<String, String> tags = extractTags(params, false);
IamPolicy policy = iamService.createPolicy(policyName, path, description, document, tags);
String result = new XmlBuilder().start("Policy").raw(policyXml(policy, true)).end("Policy").build();
return Response.ok(AwsQueryResponse.envelope("CreatePolicy", AwsNamespaces.IAM, result)).build();
@@ -1113,7 +1115,7 @@ public class IamQueryHandler {
}
private Response handleTagPolicy(MultivaluedMap<String, String> params) {
iamService.tagPolicy(getParam(params, "PolicyArn"), extractTags(params));
iamService.tagPolicy(getParam(params, "PolicyArn"), extractTags(params, false));
return Response.ok(AwsQueryResponse.envelopeNoResult("TagPolicy", AwsNamespaces.IAM)).build();
}
@@ -1381,7 +1383,7 @@ public class IamQueryHandler {
// =========================================================================
private Response handleCreateInstanceProfile(MultivaluedMap<String, String> params) {
Map<String, String> tags = extractTags(params);
Map<String, String> tags = extractTags(params, false);
InstanceProfile profile = iamService.createInstanceProfile(
getParam(params, "InstanceProfileName"), getParam(params, "Path"));
if (!tags.isEmpty()) {
@@ -2160,17 +2162,22 @@ public class IamQueryHandler {
/**
* Every IAM request that carries tags types them as {@code tagListType}, whose {@code max: 50}
* binds the members as sent, so the count is taken here, before the map collapses repeated keys.
* Duplicate keys in the request are rejected with InvalidInput (case-insensitively for users and
* roles, and case-sensitively for other IAM resource types).
*/
private Map<String, String> extractTags(MultivaluedMap<String, String> params) {
private Map<String, String> extractTags(MultivaluedMap<String, String> params, boolean caseInsensitiveKeys) {
List<Map.Entry<String, String>> members = new ArrayList<>();
for (int i = 1; ; i++) {
String key = params.getFirst("Tags.member." + i + ".Key");
String value = params.getFirst("Tags.member." + i + ".Value");
if (key == null) break;
if (key == null) {
break;
}
members.add(Map.entry(key, value != null ? value : ""));
}
checkListLength(members.size(), "tags");
Map<String, String> tags = new HashMap<>();
Set<String> seenKeys = new HashSet<>();
Map<String, String> tags = new LinkedHashMap<>();
for (int i = 0; i < members.size(); i++) {
String key = members.get(i).getKey();
String value = members.get(i).getValue();
@@ -2194,6 +2201,19 @@ public class IamQueryHandler {
throw tagValidationError(value, at + ".value",
"Member must satisfy regular expression pattern: " + TAG_VALUE_PATTERN.pattern());
}
if (caseInsensitiveKeys) {
for (String seenKey : seenKeys) {
if (seenKey.equalsIgnoreCase(key)) {
throw new AwsException("InvalidInput",
"Duplicate tag keys found. Please note that Tag keys are case insensitive.", 400);
}
}
seenKeys.add(key);
} else {
if (!seenKeys.add(key)) {
throw new AwsException("InvalidInput", "Duplicate tag keys found.", 400);
}
}
tags.put(key, value);
}
return tags;
@@ -2303,7 +2323,7 @@ public class IamQueryHandler {
}
private Response handleTagInstanceProfile(MultivaluedMap<String, String> params) {
iamService.tagInstanceProfile(getParam(params, "InstanceProfileName"), extractTags(params));
iamService.tagInstanceProfile(getParam(params, "InstanceProfileName"), extractTags(params, false));
return Response.ok(AwsQueryResponse.envelopeNoResult("TagInstanceProfile", AwsNamespaces.IAM)).build();
}
@@ -521,7 +521,7 @@ public class IamService implements SessionAccountLookup, ResourceProvider {
public void tagUser(String userName, Map<String, String> newTags) {
synchronized (tagLock) {
IamUser user = getUser(userName);
user.setTags(mergeTagsWithinQuota(user.getTags(), newTags, "TagsPerUser"));
user.setTags(mergeTagsWithinQuota(user.getTags(), newTags, "TagsPerUser", true));
users.put(userName, user);
}
}
@@ -529,7 +529,7 @@ public class IamService implements SessionAccountLookup, ResourceProvider {
public void untagUser(String userName, List<String> tagKeys) {
synchronized (tagLock) {
IamUser user = getUser(userName);
tagKeys.forEach(user.getTags()::remove);
removeTagsCaseInsensitive(user.getTags(), tagKeys);
users.put(userName, user);
}
}
@@ -671,8 +671,12 @@ public class IamService implements SessionAccountLookup, ResourceProvider {
String arn = iamArn("role", normalizedPath, roleName);
IamRole role = new IamRole(roleId, roleName, normalizedPath, arn, assumeRolePolicyDocument);
role.setDescription(description);
if (maxSessionDuration > 0) role.setMaxSessionDuration(maxSessionDuration);
if (tags != null) role.getTags().putAll(tags);
if (maxSessionDuration > 0) {
role.setMaxSessionDuration(maxSessionDuration);
}
if (tags != null) {
role.setTags(mergeTagsWithinQuota(role.getTags(), tags, "TagsPerRole", true));
}
roles.put(roleName, role);
LOG.infov("Created IAM role: {0}", roleName);
return role;
@@ -885,7 +889,7 @@ public class IamService implements SessionAccountLookup, ResourceProvider {
public void tagRole(String roleName, Map<String, String> newTags) {
synchronized (tagLock) {
IamRole role = getRole(roleName);
role.setTags(mergeTagsWithinQuota(role.getTags(), newTags, "TagsPerRole"));
role.setTags(mergeTagsWithinQuota(role.getTags(), newTags, "TagsPerRole", true));
roles.put(roleName, role);
}
}
@@ -893,7 +897,7 @@ public class IamService implements SessionAccountLookup, ResourceProvider {
public void untagRole(String roleName, List<String> tagKeys) {
synchronized (tagLock) {
IamRole role = getRole(roleName);
tagKeys.forEach(role.getTags()::remove);
removeTagsCaseInsensitive(role.getTags(), tagKeys);
roles.put(roleName, role);
}
}
@@ -1256,7 +1260,7 @@ public class IamService implements SessionAccountLookup, ResourceProvider {
rejectIfAwsManaged(policyArn);
synchronized (tagLock) {
IamPolicy policy = getPolicy(policyArn);
policy.setTags(mergeTagsWithinQuota(policy.getTags(), newTags, "TagsPerPolicy"));
policy.setTags(mergeTagsWithinQuota(policy.getTags(), newTags, "TagsPerPolicy", false));
policies.put(policyArn, policy);
}
}
@@ -2079,7 +2083,7 @@ public class IamService implements SessionAccountLookup, ResourceProvider {
}
synchronized (oidcProviderLock) {
OpenIDConnectProvider provider = getOpenIDConnectProvider(arn);
provider.setTags(mergeTagsWithinQuota(provider.getTags(), newTags, "TagsPerOpenIdConnectProvider"));
provider.setTags(mergeTagsWithinQuota(provider.getTags(), newTags, "TagsPerOpenIdConnectProvider", false));
oidcProviders.put(arn, provider);
}
}
@@ -2825,15 +2829,31 @@ public class IamService implements SessionAccountLookup, ResourceProvider {
validateIamResourceName(instanceProfileName, "InstanceProfileName");
synchronized (tagLock) {
InstanceProfile profile = getInstanceProfile(instanceProfileName);
profile.setTags(mergeTagsWithinQuota(profile.getTags(), newTags, "TagsPerInstanceProfile"));
profile.setTags(mergeTagsWithinQuota(profile.getTags(), newTags, "TagsPerInstanceProfile", false));
instanceProfiles.put(instanceProfileName, profile);
}
}
private static Map<String, String> mergeTagsWithinQuota(Map<String, String> current,
Map<String, String> newTags, String quota) {
Map<String, String> newTags, String quota, boolean caseInsensitive) {
Map<String, String> merged = new LinkedHashMap<>(current);
merged.putAll(newTags == null ? Map.of() : newTags);
if (newTags != null) {
if (caseInsensitive) {
for (Map.Entry<String, String> entry : newTags.entrySet()) {
String newKey = entry.getKey();
String newValue = entry.getValue();
String existingKey = findKeyIgnoreCase(merged, newKey);
if (existingKey != null) {
merged.keySet().removeIf(k -> k.equalsIgnoreCase(newKey) && !k.equals(existingKey));
merged.put(existingKey, newValue);
} else {
merged.put(newKey, newValue);
}
}
} else {
merged.putAll(newTags);
}
}
if (merged.size() > MAX_TAGS_PER_RESOURCE) {
throw new AwsException("LimitExceeded",
"Cannot exceed quota for " + quota + ": " + MAX_TAGS_PER_RESOURCE, 409);
@@ -2841,6 +2861,26 @@ public class IamService implements SessionAccountLookup, ResourceProvider {
return merged;
}
private static String findKeyIgnoreCase(Map<String, String> map, String targetKey) {
for (String key : map.keySet()) {
if (key.equalsIgnoreCase(targetKey)) {
return key;
}
}
return null;
}
private static void removeTagsCaseInsensitive(Map<String, String> tags, List<String> tagKeys) {
if (tags == null || tagKeys == null || tags.isEmpty() || tagKeys.isEmpty()) {
return;
}
for (String tagKey : tagKeys) {
if (tagKey != null) {
tags.keySet().removeIf(existingKey -> existingKey.equalsIgnoreCase(tagKey));
}
}
}
public void untagInstanceProfile(String instanceProfileName, List<String> tagKeys) {
validateIamResourceName(instanceProfileName, "InstanceProfileName");
synchronized (tagLock) {