fix(iam): enforce case-insensitive resource names (#3986)

* fix(iam): enforce case-insensitive resource names

Reject duplicate IAM user, group, role, and managed policy names that differ only by case.

Signed-off-by: XuJian <265865031+xujiantop-crypto@users.noreply.github.com>

* test(iam): cover case-insensitive resource names

Signed-off-by: XuJian <265865031+xujiantop-crypto@users.noreply.github.com>

* test(iam): verify case-insensitive names end to end

Signed-off-by: xujiantop-crypto <265865031+xujiantop-crypto@users.noreply.github.com>

* fix(iam): enforce instance profile name uniqueness

* fix(iam): preserve name uniqueness on group rename and legacy data

* fix(iam): exclude managed catalog mirrors from name conflicts

---------

Signed-off-by: XuJian <265865031+xujiantop-crypto@users.noreply.github.com>
Signed-off-by: xujiantop-crypto <265865031+xujiantop-crypto@users.noreply.github.com>
This commit is contained in:
XuJian authored and GitHub committed 2026-09-23 09:06:17 -04:00
1 parent 133ef62d27
commit d8a4f5e58e
4 files changed
+598 -127

No files matched your search

@@ -44,7 +44,9 @@ import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.function.Function;
import java.util.regex.Pattern;
import java.util.stream.Stream;
/**
* Core IAM business logic — users, groups, roles, policies, access keys, instance profiles.
@@ -150,6 +152,8 @@ public class IamService implements SessionAccountLookup, ResourceProvider {
private final RegionResolver regionResolver;
private final boolean seedDeployerPrincipal;
private final String seededAccountAlias;
/** Guards case-insensitive IAM name uniqueness checks and their corresponding writes. */
private final Object resourceNameLock = new Object();
/**
* AWS-managed policies (arn:aws:iam::aws:policy/...), keyed by ARN. These are global —
@@ -370,17 +374,19 @@ public class IamService implements SessionAccountLookup, ResourceProvider {
// =========================================================================
public IamUser createUser(String userName, String path) {
if (users.get(userName).isPresent()) {
throw new AwsException("EntityAlreadyExists",
"User with name " + userName + " already exists.", 409);
synchronized (resourceNameLock) {
if (containsNameIgnoreCase(users, IamUser::getUserName, userName)) {
throw new AwsException("EntityAlreadyExists",
"User with name " + userName + " already exists.", 409);
}
String userId = "AIDA" + randomId(16);
String normalizedPath = normalizePath(path);
String arn = iamArn("user", normalizedPath, userName);
IamUser user = new IamUser(userId, userName, normalizedPath, arn);
users.put(userName, user);
LOG.infov("Created IAM user: {0}", userName);
return user;
}
String userId = "AIDA" + randomId(16);
String normalizedPath = normalizePath(path);
String arn = iamArn("user", normalizedPath, userName);
IamUser user = new IamUser(userId, userName, normalizedPath, arn);
users.put(userName, user);
LOG.infov("Created IAM user: {0}", userName);
return user;
}
public IamUser getUser(String userName) {
@@ -444,45 +450,50 @@ public class IamService implements SessionAccountLookup, ResourceProvider {
* name-based lookup.
*/
public void updateUser(String userName, String newUserName, String newPath, String expectedUserId) {
IamUser user = getUser(userName);
if (expectedUserId != null && !expectedUserId.equals(user.getUserId())) {
throw new AwsException("EntityAlreadyExists",
"User " + userName + " was replaced by a different user of the same name; "
+ "refusing to apply an update meant for the original user.", 409);
}
if (newUserName != null && !newUserName.equals(userName)) {
if (users.get(newUserName).isPresent()) {
synchronized (resourceNameLock) {
IamUser user = getUser(userName);
if (expectedUserId != null && !expectedUserId.equals(user.getUserId())) {
throw new AwsException("EntityAlreadyExists",
"User with name " + newUserName + " already exists.", 409);
"User " + userName + " was replaced by a different user of the same name; "
+ "refusing to apply an update meant for the original user.", 409);
}
List<AccessKey> keysToMove = userAccessKeys(userName);
users.delete(userName);
user.setUserName(newUserName);
if (newPath != null) user.setPath(normalizePath(newPath));
user.setArn(iamArn("user", user.getPath(), newUserName));
users.put(newUserName, user);
loginProfiles.get(userName).ifPresent(profile -> {
loginProfiles.delete(userName);
profile.setUserName(newUserName);
loginProfiles.put(newUserName, profile);
});
for (AccessKey key : keysToMove) {
key.setUserName(newUserName);
accessKeys.put(key.getAccessKeyId(), key);
}
for (String groupName : user.getGroupNames()) {
groups.get(groupName).ifPresent(group -> {
group.getUserNames().remove(userName);
group.getUserNames().add(newUserName);
groups.put(groupName, group);
if (newUserName != null && !newUserName.equals(userName)) {
boolean nameTaken = resourcesInCurrentAccount(users)
.filter(existing -> !existing.getUserId().equals(user.getUserId()))
.anyMatch(existing -> existing.getUserName().equalsIgnoreCase(newUserName));
if (nameTaken) {
throw new AwsException("EntityAlreadyExists",
"User with name " + newUserName + " already exists.", 409);
}
List<AccessKey> keysToMove = userAccessKeys(userName);
users.delete(userName);
user.setUserName(newUserName);
if (newPath != null) user.setPath(normalizePath(newPath));
user.setArn(iamArn("user", user.getPath(), newUserName));
users.put(newUserName, user);
loginProfiles.get(userName).ifPresent(profile -> {
loginProfiles.delete(userName);
profile.setUserName(newUserName);
loginProfiles.put(newUserName, profile);
});
for (AccessKey key : keysToMove) {
key.setUserName(newUserName);
accessKeys.put(key.getAccessKeyId(), key);
}
for (String groupName : user.getGroupNames()) {
groups.get(groupName).ifPresent(group -> {
group.getUserNames().remove(userName);
group.getUserNames().add(newUserName);
groups.put(groupName, group);
});
}
} else {
if (newPath != null) {
user.setPath(normalizePath(newPath));
user.setArn(iamArn("user", user.getPath(), userName));
}
users.put(userName, user);
}
} else {
if (newPath != null) {
user.setPath(normalizePath(newPath));
user.setArn(iamArn("user", user.getPath(), userName));
}
users.put(userName, user);
}
}
@@ -507,17 +518,19 @@ public class IamService implements SessionAccountLookup, ResourceProvider {
// =========================================================================
public IamGroup createGroup(String groupName, String path) {
if (groups.get(groupName).isPresent()) {
throw new AwsException("EntityAlreadyExists",
"Group with name " + groupName + " already exists.", 409);
synchronized (resourceNameLock) {
if (containsNameIgnoreCase(groups, IamGroup::getGroupName, groupName)) {
throw new AwsException("EntityAlreadyExists",
"Group with name " + groupName + " already exists.", 409);
}
String groupId = "AGPA" + randomId(16);
String normalizedPath = normalizePath(path);
String arn = iamArn("group", normalizedPath, groupName);
IamGroup group = new IamGroup(groupId, groupName, normalizedPath, arn);
groups.put(groupName, group);
LOG.infov("Created IAM group: {0}", groupName);
return group;
}
String groupId = "AGPA" + randomId(16);
String normalizedPath = normalizePath(path);
String arn = iamArn("group", normalizedPath, groupName);
IamGroup group = new IamGroup(groupId, groupName, normalizedPath, arn);
groups.put(groupName, group);
LOG.infov("Created IAM group: {0}", groupName);
return group;
}
public IamGroup getGroup(String groupName) {
@@ -528,34 +541,42 @@ public class IamService implements SessionAccountLookup, ResourceProvider {
public void updateGroup(String groupName, String newGroupName, String newPath) {
validateIamResourceName(groupName, "GroupName");
if (newGroupName != null) validateIamResourceName(newGroupName, "NewGroupName");
if (newGroupName != null) {
validateIamResourceName(newGroupName, "NewGroupName");
}
validateIamPath(newPath, "NewPath");
IamGroup group = getGroup(groupName);
if (newGroupName != null && !newGroupName.equals(groupName)) {
if (groups.get(newGroupName).isPresent()) {
throw new AwsException("EntityAlreadyExists",
"Group with name " + newGroupName + " already exists.", 409);
synchronized (resourceNameLock) {
IamGroup group = getGroup(groupName);
if (newGroupName != null && !newGroupName.equals(groupName)) {
boolean nameTaken = resourcesInCurrentAccount(groups)
.filter(existing -> !existing.getGroupId().equals(group.getGroupId()))
.anyMatch(existing -> existing.getGroupName().equalsIgnoreCase(newGroupName));
if (nameTaken) {
throw new AwsException("EntityAlreadyExists",
"Group with name " + newGroupName + " already exists.", 409);
}
groups.delete(groupName);
group.setGroupName(newGroupName);
if (newPath != null) {
group.setPath(normalizePath(newPath));
}
group.setArn(iamArn("group", group.getPath(), newGroupName));
groups.put(newGroupName, group);
// Keep member references in sync so group policies still resolve after a rename.
for (String memberName : group.getUserNames()) {
users.get(memberName).ifPresent(member -> {
member.getGroupNames().remove(groupName);
member.getGroupNames().add(newGroupName);
users.put(memberName, member);
});
}
} else {
if (newPath != null) {
group.setPath(normalizePath(newPath));
group.setArn(iamArn("group", group.getPath(), groupName));
}
groups.put(groupName, group);
}
groups.delete(groupName);
group.setGroupName(newGroupName);
if (newPath != null) group.setPath(normalizePath(newPath));
group.setArn(iamArn("group", group.getPath(), newGroupName));
groups.put(newGroupName, group);
// Members still carry the old name in their own groupNames list — without this,
// ListGroupsForUser drops the renamed group and its policies stop resolving for them.
for (String memberName : group.getUserNames()) {
users.get(memberName).ifPresent(member -> {
member.getGroupNames().remove(groupName);
member.getGroupNames().add(newGroupName);
users.put(memberName, member);
});
}
} else {
if (newPath != null) {
group.setPath(normalizePath(newPath));
group.setArn(iamArn("group", group.getPath(), groupName));
}
groups.put(groupName, group);
}
}
@@ -615,20 +636,22 @@ public class IamService implements SessionAccountLookup, ResourceProvider {
public IamRole createRole(String roleName, String path, String assumeRolePolicyDocument,
String description, int maxSessionDuration, Map<String, String> tags) {
if (roles.get(roleName).isPresent()) {
throw new AwsException("EntityAlreadyExists",
"Role with name " + roleName + " already exists.", 409);
synchronized (resourceNameLock) {
if (containsNameIgnoreCase(roles, IamRole::getRoleName, roleName)) {
throw new AwsException("EntityAlreadyExists",
"Role with name " + roleName + " already exists.", 409);
}
String roleId = "AROA" + randomId(16);
String normalizedPath = normalizePath(path);
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);
roles.put(roleName, role);
LOG.infov("Created IAM role: {0}", roleName);
return role;
}
String roleId = "AROA" + randomId(16);
String normalizedPath = normalizePath(path);
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);
roles.put(roleName, role);
LOG.infov("Created IAM role: {0}", roleName);
return role;
}
public IamRole getRole(String roleName) {
@@ -714,19 +737,21 @@ public class IamService implements SessionAccountLookup, ResourceProvider {
"The derived role name " + roleName + " exceeds the "
+ ROLE_NAME_MAX_LENGTH + "-character role name limit.", 400);
}
// createRole would answer EntityAlreadyExists, which this action does not document; the
// duplicate-suffix case is an InvalidInput as far as its published error list is concerned.
if (roles.get(roleName).isPresent()) {
throw new AwsException("InvalidInput",
"A role named " + roleName + " already exists; supply a different CustomSuffix.", 400);
synchronized (resourceNameLock) {
// createRole would answer EntityAlreadyExists, which this action does not document; the
// duplicate-suffix case is an InvalidInput as far as its published error list is concerned.
if (containsNameIgnoreCase(roles, IamRole::getRoleName, roleName)) {
throw new AwsException("InvalidInput",
"A role named " + roleName + " already exists; supply a different CustomSuffix.", 400);
}
String trustPolicy = "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Allow\","
+ "\"Principal\":{\"Service\":\"" + awsServiceName + "\"},\"Action\":\"sts:AssumeRole\"}]}";
IamRole role = createRole(roleName, SERVICE_LINKED_ROLE_PATH + awsServiceName + "/",
trustPolicy, description, 0, Map.of());
role.setServiceLinkedRole(true);
roles.put(roleName, role);
return role;
}
String trustPolicy = "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Allow\","
+ "\"Principal\":{\"Service\":\"" + awsServiceName + "\"},\"Action\":\"sts:AssumeRole\"}]}";
IamRole role = createRole(roleName, SERVICE_LINKED_ROLE_PATH + awsServiceName + "/",
trustPolicy, description, 0, Map.of());
role.setServiceLinkedRole(true);
roles.put(roleName, role);
return role;
}
/**
@@ -854,18 +879,25 @@ public class IamService implements SessionAccountLookup, ResourceProvider {
public IamPolicy createPolicy(String policyName, String path, String description,
String document, Map<String, String> tags) {
String normalizedPath = normalizePath(path);
String arn = iamArn("policy", normalizedPath, policyName);
if (policies.get(arn).isPresent()) {
throw new AwsException("EntityAlreadyExists",
"Policy " + arn + " already exists.", 409);
synchronized (resourceNameLock) {
String normalizedPath = normalizePath(path);
String arn = iamArn("policy", normalizedPath, policyName);
boolean nameTaken = resourcesInCurrentAccount(policies)
.filter(existing -> existing.getArn() == null
|| !existing.getArn().startsWith(AwsManagedPolicies.ARN_PREFIX))
.map(IamPolicy::getPolicyName)
.anyMatch(existingName -> existingName != null && existingName.equalsIgnoreCase(policyName));
if (nameTaken) {
throw new AwsException("EntityAlreadyExists",
"Policy " + arn + " already exists.", 409);
}
String policyId = "ANPA" + randomId(16);
IamPolicy policy = new IamPolicy(policyId, policyName, normalizedPath, arn, description, document);
if (tags != null) policy.getTags().putAll(tags);
policies.put(arn, policy);
LOG.infov("Created IAM policy: {0}", arn);
return policy;
}
String policyId = "ANPA" + randomId(16);
IamPolicy policy = new IamPolicy(policyId, policyName, normalizedPath, arn, description, document);
if (tags != null) policy.getTags().putAll(tags);
policies.put(arn, policy);
LOG.infov("Created IAM policy: {0}", arn);
return policy;
}
public IamPolicy getPolicy(String policyArn) {
@@ -1462,17 +1494,20 @@ public class IamService implements SessionAccountLookup, ResourceProvider {
// =========================================================================
public InstanceProfile createInstanceProfile(String instanceProfileName, String path) {
if (instanceProfiles.get(instanceProfileName).isPresent()) {
throw new AwsException("EntityAlreadyExists",
"Instance profile " + instanceProfileName + " already exists.", 409);
synchronized (resourceNameLock) {
if (containsNameIgnoreCase(
instanceProfiles, InstanceProfile::getInstanceProfileName, instanceProfileName)) {
throw new AwsException("EntityAlreadyExists",
"Instance profile " + instanceProfileName + " already exists.", 409);
}
String profileId = "AIPA" + randomId(16);
String normalizedPath = normalizePath(path);
String arn = iamArn("instance-profile", normalizedPath, instanceProfileName);
InstanceProfile profile = new InstanceProfile(profileId, instanceProfileName, normalizedPath, arn);
instanceProfiles.put(instanceProfileName, profile);
LOG.infov("Created instance profile: {0}", instanceProfileName);
return profile;
}
String profileId = "AIPA" + randomId(16);
String normalizedPath = normalizePath(path);
String arn = iamArn("instance-profile", normalizedPath, instanceProfileName);
InstanceProfile profile = new InstanceProfile(profileId, instanceProfileName, normalizedPath, arn);
instanceProfiles.put(instanceProfileName, profile);
LOG.infov("Created instance profile: {0}", instanceProfileName);
return profile;
}
public Optional<InstanceProfile> findInstanceProfile(String accountId, String profileName) {
@@ -2605,6 +2640,25 @@ public class IamService implements SessionAccountLookup, ResourceProvider {
return AwsArnUtils.Arn.of("iam", "", regionResolver.getAccountId(), resourceType + path + name).toString();
}
private static <T> boolean containsNameIgnoreCase(StorageBackend<String, T> storage,
Function<T, String> nameExtractor,
String requestedName) {
return resourcesInCurrentAccount(storage)
.map(nameExtractor)
.anyMatch(existingName -> existingName != null && existingName.equalsIgnoreCase(requestedName));
}
private static <T> Stream<T> resourcesInCurrentAccount(StorageBackend<String, T> storage) {
if (storage instanceof AccountAwareStorageBackend<T> accountAware) {
String accountId = accountAware.accountId();
// Include unmigrated legacy names, which belong to the configured default account.
return accountAware.scanAllAccountEntries(key -> true).stream()
.filter(entry -> accountId.equals(entry.accountId()))
.map(entry -> entry.value());
}
return storage.scan(key -> true).stream();
}
private static String normalizePath(String path) {
if (path == null || path.isEmpty()) return "/";
String p = path;
@@ -0,0 +1,182 @@
package io.github.hectorvent.floci.services.iam;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.common.RegionResolver;
import io.github.hectorvent.floci.core.common.RequestContext;
import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend;
import io.github.hectorvent.floci.core.storage.InMemoryStorage;
import io.github.hectorvent.floci.core.storage.StorageBackend;
import io.github.hectorvent.floci.services.iam.model.IamGroup;
import io.github.hectorvent.floci.services.iam.model.IamPolicy;
import io.github.hectorvent.floci.services.iam.model.IamRole;
import io.github.hectorvent.floci.services.iam.model.IamUser;
import io.github.hectorvent.floci.services.iam.model.InstanceProfile;
import jakarta.enterprise.inject.Instance;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.function.Executable;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.EnumSource;
import org.junit.jupiter.params.provider.ValueSource;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
class IamCaseInsensitiveLegacyNamesTest {
private static final String DEFAULT_ACCOUNT = "000000000000";
private static final String OTHER_ACCOUNT = "111111111111";
private static final String LEGACY_NAME = "LegacyName";
private static final String LEGACY_POLICY_ARN =
"arn:aws:iam::000000000000:policy/legacy/LegacyName";
private final StorageBackend<String, IamUser> users = new InMemoryStorage<>();
private final StorageBackend<String, IamGroup> groups = new InMemoryStorage<>();
private final StorageBackend<String, IamRole> roles = new InMemoryStorage<>();
private final StorageBackend<String, IamPolicy> policies = new InMemoryStorage<>();
private final StorageBackend<String, InstanceProfile> profiles = new InMemoryStorage<>();
enum ResourceType { USER, GROUP, ROLE, POLICY, INSTANCE_PROFILE }
@BeforeEach
void seedUnprefixedLegacyResources() {
IamService legacyService = new IamService(users, groups, roles, policies,
new InMemoryStorage<>(), profiles, new InMemoryStorage<>(),
new RegionResolver("us-east-1", DEFAULT_ACCOUNT));
for (ResourceType type : ResourceType.values()) {
create(legacyService, type, LEGACY_NAME);
}
}
@ParameterizedTest
@EnumSource(ResourceType.class)
void createRejectsExactAndCaseVariantOfUnmigratedLegacyName(ResourceType type) {
IamService service = serviceFor(DEFAULT_ACCOUNT);
String originalId = legacyId(type);
assertAlreadyExists(() -> create(service, type, LEGACY_NAME));
assertAlreadyExists(() -> create(service, type, "legacyname"));
assertEquals(originalId, legacyId(type));
assertEquals(originalId, readId(service, type, DEFAULT_ACCOUNT));
}
@ParameterizedTest
@EnumSource(ResourceType.class)
void anotherAccountCanReuseLegacyNameWithoutClaimingLegacyResource(ResourceType type) {
String originalId = legacyId(type);
IamService otherService = serviceFor(OTHER_ACCOUNT);
String otherId = create(otherService, type, LEGACY_NAME);
assertNotEquals(originalId, otherId);
assertEquals(originalId, legacyId(type));
assertEquals(otherId, readId(otherService, type, OTHER_ACCOUNT));
IamService defaultService = serviceFor(DEFAULT_ACCOUNT);
assertAlreadyExists(() -> create(defaultService, type, "legacyname"));
assertEquals(originalId, readId(defaultService, type, DEFAULT_ACCOUNT));
}
@Test
void updateUserRejectsUnmigratedLegacyNameAndPreservesSource() {
IamService service = serviceFor(DEFAULT_ACCOUNT);
IamUser source = service.createUser("RenameSource", "/source/");
String originalId = legacyId(ResourceType.USER);
assertAlreadyExists(() -> service.updateUser("RenameSource", LEGACY_NAME, null));
assertAlreadyExists(() -> service.updateUser("RenameSource", "legacyname", null));
assertEquals(source.getUserId(), service.getUser("RenameSource").getUserId());
assertEquals("RenameSource", source.getUserName());
assertEquals("/source/", source.getPath());
assertEquals(originalId, legacyId(ResourceType.USER));
}
@ParameterizedTest
@ValueSource(booleans = {false, true})
void awsManagedPolicyMirrorsDoNotReserveCustomerPolicyNames(boolean accountPrefixed) {
String managedArn = AwsManagedPolicies.ARN_PREFIX + "/AdministratorAccess";
String mirrorKey = accountPrefixed ? DEFAULT_ACCOUNT + "/" + managedArn : managedArn;
IamPolicy mirror = new IamPolicy("ANPALEGACYAWS", "AdministratorAccess", "/", managedArn,
null, "{}");
policies.put(mirrorKey, mirror);
IamService service = serviceFor(DEFAULT_ACCOUNT);
IamPolicy customerPolicy = service.createPolicy("AdministratorAccess", "/customer/", null, "{}", null);
assertEquals("arn:aws:iam::000000000000:policy/customer/AdministratorAccess", customerPolicy.getArn());
assertEquals("ANPALEGACYAWS", policies.get(mirrorKey).orElseThrow().getPolicyId());
assertAlreadyExists(() -> service.createPolicy("administratoraccess", "/other/", null, "{}", null));
}
@Test
void updateGroupRejectsUnmigratedLegacyNameAndPreservesSource() {
IamService service = serviceFor(DEFAULT_ACCOUNT);
IamGroup source = service.createGroup("RenameSource", "/source/");
String originalId = legacyId(ResourceType.GROUP);
assertAlreadyExists(() -> service.updateGroup("RenameSource", LEGACY_NAME, null));
assertAlreadyExists(() -> service.updateGroup("RenameSource", "legacyname", null));
assertEquals(source.getGroupId(), service.getGroup("RenameSource").getGroupId());
assertEquals("RenameSource", source.getGroupName());
assertEquals("/source/", source.getPath());
assertEquals(originalId, legacyId(ResourceType.GROUP));
}
@SuppressWarnings("unchecked")
private IamService serviceFor(String accountId) {
RequestContext context = new RequestContext();
context.setAccountId(accountId);
Instance<RequestContext> contexts = mock(Instance.class);
when(contexts.get()).thenReturn(context);
return new IamService(scoped(users, contexts), scoped(groups, contexts), scoped(roles, contexts),
scoped(policies, contexts), new InMemoryStorage<>(), scoped(profiles, contexts),
new InMemoryStorage<>(), new RegionResolver("us-east-1", accountId));
}
private static <T> AccountAwareStorageBackend<T> scoped(StorageBackend<String, T> raw,
Instance<RequestContext> contexts) {
return new AccountAwareStorageBackend<>(raw, contexts, DEFAULT_ACCOUNT);
}
private static String create(IamService service, ResourceType type, String name) {
return switch (type) {
case USER -> service.createUser(name, "/legacy/").getUserId();
case GROUP -> service.createGroup(name, "/legacy/").getGroupId();
case ROLE -> service.createRole(name, "/legacy/", "{}", null, 3600, null).getRoleId();
case POLICY -> service.createPolicy(name, "/legacy/", null, "{}", null).getPolicyId();
case INSTANCE_PROFILE -> service.createInstanceProfile(name, "/legacy/").getInstanceProfileId();
};
}
private String legacyId(ResourceType type) {
return switch (type) {
case USER -> users.get(LEGACY_NAME).orElseThrow().getUserId();
case GROUP -> groups.get(LEGACY_NAME).orElseThrow().getGroupId();
case ROLE -> roles.get(LEGACY_NAME).orElseThrow().getRoleId();
case POLICY -> policies.get(LEGACY_POLICY_ARN).orElseThrow().getPolicyId();
case INSTANCE_PROFILE -> profiles.get(LEGACY_NAME).orElseThrow().getInstanceProfileId();
};
}
private static String readId(IamService service, ResourceType type, String accountId) {
return switch (type) {
case USER -> service.getUser(LEGACY_NAME).getUserId();
case GROUP -> service.getGroup(LEGACY_NAME).getGroupId();
case ROLE -> service.getRole(LEGACY_NAME).getRoleId();
case POLICY -> service.getPolicy("arn:aws:iam::" + accountId + ":policy/legacy/" + LEGACY_NAME)
.getPolicyId();
case INSTANCE_PROFILE -> service.getInstanceProfile(LEGACY_NAME).getInstanceProfileId();
};
}
private static void assertAlreadyExists(Executable operation) {
AwsException exception = assertThrows(AwsException.class, operation);
assertEquals("EntityAlreadyExists", exception.getErrorCode());
assertEquals(409, exception.getHttpStatus());
}
}
@@ -0,0 +1,116 @@
package io.github.hectorvent.floci.services.iam;
import io.quarkus.test.junit.QuarkusTest;
import io.restassured.response.ValidatableResponse;
import org.junit.jupiter.api.Test;
import java.util.Map;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.equalTo;
@QuarkusTest
class IamCaseInsensitiveNamesIntegrationTest {
private static final String AUTHORIZATION =
"AWS4-HMAC-SHA256 Credential=test/20260920/us-east-1/iam/aws4_request";
private static final String ACCOUNT_A_AUTHORIZATION =
"AWS4-HMAC-SHA256 Credential=111111111111/20260920/us-east-1/iam/aws4_request";
private static final String ACCOUNT_B_AUTHORIZATION =
"AWS4-HMAC-SHA256 Credential=222222222222/20260920/us-east-1/iam/aws4_request";
private static final String TRUST_POLICY =
"{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Allow\","
+ "\"Principal\":{\"Service\":\"lambda.amazonaws.com\"},"
+ "\"Action\":\"sts:AssumeRole\"}]}";
private static final String POLICY_DOCUMENT =
"{\"Version\":\"2012-10-17\",\"Statement\":[]}";
@Test
void createActionsRejectNamesThatDifferOnlyByCase() {
iam("CreateUser", Map.of("UserName", "CaseCollisionUser")).statusCode(200);
assertAlreadyExists("CreateUser", Map.of("UserName", "casecollisionuser"));
iam("CreateGroup", Map.of("GroupName", "CaseCollisionGroup")).statusCode(200);
assertAlreadyExists("CreateGroup", Map.of("GroupName", "casecollisiongroup"));
iam("CreateRole", Map.of(
"RoleName", "CaseCollisionRole",
"AssumeRolePolicyDocument", TRUST_POLICY)).statusCode(200);
assertAlreadyExists("CreateRole", Map.of(
"RoleName", "casecollisionrole",
"AssumeRolePolicyDocument", TRUST_POLICY));
iam("CreatePolicy", Map.of(
"PolicyName", "CaseCollisionPolicy",
"Path", "/first/",
"PolicyDocument", POLICY_DOCUMENT)).statusCode(200);
assertAlreadyExists("CreatePolicy", Map.of(
"PolicyName", "casecollisionpolicy",
"Path", "/second/",
"PolicyDocument", POLICY_DOCUMENT));
iam("CreateInstanceProfile", Map.of("InstanceProfileName", "CaseCollisionProfile"))
.statusCode(200);
assertAlreadyExists(
"CreateInstanceProfile", Map.of("InstanceProfileName", "casecollisionprofile"));
}
@Test
void caseInsensitiveUniquenessRemainsScopedToTheAccount() {
Map<String, String> parameters = Map.of("UserName", "AccountScopedCaseName");
iam(ACCOUNT_A_AUTHORIZATION, "CreateUser", parameters).statusCode(200);
iam(ACCOUNT_B_AUTHORIZATION, "CreateUser", parameters).statusCode(200);
}
@Test
void updateUserRejectsAnotherUserNameThatDiffersOnlyByCase() {
iam("CreateUser", Map.of("UserName", "CaseRenameTarget")).statusCode(200);
iam("CreateUser", Map.of("UserName", "CaseRenameSource")).statusCode(200);
assertAlreadyExists("UpdateUser", Map.of(
"UserName", "CaseRenameSource",
"NewUserName", "CASERENAMETARGET"));
iam("GetUser", Map.of("UserName", "CaseRenameSource"))
.statusCode(200)
.body("GetUserResponse.GetUserResult.User.UserName", equalTo("CaseRenameSource"));
}
private static void assertAlreadyExists(String action, Map<String, String> parameters) {
iam(action, parameters)
.statusCode(409)
.body("ErrorResponse.Error.Code", equalTo("EntityAlreadyExists"));
}
@Test
void updateGroupRejectsCaseCollisionWithoutChangingTheSourceGroup() {
iam("CreateGroup", Map.of("GroupName", "CaseGroupRenameTarget")).statusCode(200);
iam("CreateGroup", Map.of("GroupName", "CaseGroupRenameSource", "Path", "/original/"))
.statusCode(200);
assertAlreadyExists("UpdateGroup", Map.of(
"GroupName", "CaseGroupRenameSource",
"NewGroupName", "casegrouprenametarget",
"NewPath", "/changed/"));
iam("GetGroup", Map.of("GroupName", "CaseGroupRenameSource"))
.statusCode(200)
.body("GetGroupResponse.GetGroupResult.Group.GroupName", equalTo("CaseGroupRenameSource"))
.body("GetGroupResponse.GetGroupResult.Group.Path", equalTo("/original/"));
}
private static ValidatableResponse iam(String action, Map<String, String> parameters) {
return iam(AUTHORIZATION, action, parameters);
}
private static ValidatableResponse iam(String authorization, String action, Map<String, String> parameters) {
return given()
.formParam("Action", action)
.formParams(parameters)
.header("Authorization", authorization)
.when()
.post("/")
.then();
}
}
@@ -186,6 +186,17 @@ class IamServiceTest {
assertThrows(AwsException.class, () -> iamService.createUser("alice", "/"));
}
@Test
void createUserRejectsNameThatDiffersOnlyByCase() {
iamService.createUser("CaseUser", "/");
AwsException error = assertThrows(AwsException.class,
() -> iamService.createUser("caseuser", "/"));
assertEquals("EntityAlreadyExists", error.getErrorCode());
assertEquals(409, error.getHttpStatus());
}
@Test
void getUserNotFoundThrows() {
assertThrows(AwsException.class, () -> iamService.getUser("nonexistent"));
@@ -231,6 +242,29 @@ class IamServiceTest {
assertEquals("/new/", renamed.getPath());
}
@Test
void updateUserRejectsAnotherUserNameThatDiffersOnlyByCase() {
iamService.createUser("CaseUser", "/");
iamService.createUser("Other", "/");
AwsException error = assertThrows(AwsException.class,
() -> iamService.updateUser("Other", "CASEUSER", null));
assertEquals("EntityAlreadyExists", error.getErrorCode());
assertEquals(409, error.getHttpStatus());
assertEquals("Other", iamService.getUser("Other").getUserName());
}
@Test
void updateUserAllowsChangingOnlyItsOwnNameCase() {
iamService.createUser("CaseUser", "/");
iamService.updateUser("CaseUser", "caseuser", null);
assertEquals("caseuser", iamService.getUser("caseuser").getUserName());
assertThrows(AwsException.class, () -> iamService.getUser("CaseUser"));
}
@Test
void tagAndUntagUser() {
iamService.createUser("alice", "/");
@@ -463,6 +497,17 @@ class IamServiceTest {
assertEquals("arn:aws:iam::000000000000:group/developers", group.getArn());
}
@Test
void createGroupRejectsNameThatDiffersOnlyByCase() {
iamService.createGroup("CaseGroup", "/");
AwsException error = assertThrows(AwsException.class,
() -> iamService.createGroup("casegroup", "/"));
assertEquals("EntityAlreadyExists", error.getErrorCode());
assertEquals(409, error.getHttpStatus());
}
@Test
void addAndRemoveUserFromGroup() {
iamService.createUser("alice", "/");
@@ -541,6 +586,17 @@ class IamServiceTest {
assertEquals("Lambda role", role.getDescription());
}
@Test
void createRoleRejectsNameThatDiffersOnlyByCase() {
iamService.createRole("CaseRole", "/", "{}", null, 3600, null);
AwsException error = assertThrows(AwsException.class,
() -> iamService.createRole("caserole", "/", "{}", null, 3600, null));
assertEquals("EntityAlreadyExists", error.getErrorCode());
assertEquals(409, error.getHttpStatus());
}
@Test
void updateAssumeRolePolicyWithMatchingExpectedIdApplies() {
IamRole role = iamService.createRole("LambdaExec", "/", "{}", null, 3600, null);
@@ -600,6 +656,17 @@ class IamServiceTest {
assertEquals("AWSServiceRoleForAccessAnalyzer_myapp", role.getRoleName());
}
@Test
void createServiceLinkedRoleRejectsCaseInsensitiveRoleNameCollisionAsInvalidInput() {
iamService.createRole("awsserviceroleforaccessanalyzer", "/", "{}", null, 0, null);
AwsException error = assertThrows(AwsException.class,
() -> iamService.createServiceLinkedRole("access-analyzer.amazonaws.com", null, null));
assertEquals("InvalidInput", error.getErrorCode());
assertEquals(400, error.getHttpStatus());
}
@Test
void deleteRoleWithAttachedPolicyFails() {
iamService.createRole("LambdaExec", "/", "{}", null, 0, null);
@@ -637,6 +704,17 @@ class IamServiceTest {
assertEquals(doc, policy.getDefaultDocument());
}
@Test
void createPolicyRejectsCaseInsensitiveNameAcrossPaths() {
iamService.createPolicy("CasePolicy", "/first/", null, "{}", null);
AwsException error = assertThrows(AwsException.class,
() -> iamService.createPolicy("casepolicy", "/second/", null, "{}", null));
assertEquals("EntityAlreadyExists", error.getErrorCode());
assertEquals(409, error.getHttpStatus());
}
@Test
void awsManagedReadOnlyPolicyAllowsReadsButDeniesWrites() {
String arn = AwsManagedPolicies.ARN_PREFIX + "/AmazonS3ReadOnlyAccess";
@@ -801,6 +879,36 @@ class IamServiceTest {
"a legacy-rehydrated policy must not reissue the id of a version deleted before upgrade");
}
@Test
void updateGroupRejectsAnotherGroupNameThatDiffersOnlyByCase() {
IamGroup target = iamService.createGroup("CaseGroup", "/");
IamGroup source = iamService.createGroup("OtherGroup", "/original/");
AwsException exception = assertThrows(AwsException.class,
() -> iamService.updateGroup("OtherGroup", "casegroup", "/changed/"));
assertEquals("EntityAlreadyExists", exception.getErrorCode());
assertEquals(source.getGroupId(), iamService.getGroup("OtherGroup").getGroupId());
assertEquals("/original/", iamService.getGroup("OtherGroup").getPath());
assertEquals(target.getGroupId(), iamService.getGroup("CaseGroup").getGroupId());
}
@Test
void updateGroupAllowsChangingOnlyItsOwnNameCaseAndPreservesMembers() {
IamGroup original = iamService.createGroup("CaseGroup", "/original/");
iamService.createUser("case-group-member", "/");
iamService.addUserToGroup("CaseGroup", "case-group-member");
iamService.updateGroup("CaseGroup", "casegroup", "/changed/");
IamGroup renamed = iamService.getGroup("casegroup");
assertEquals(original.getGroupId(), renamed.getGroupId());
assertEquals("/changed/", renamed.getPath());
assertEquals(List.of("case-group-member"), renamed.getUserNames());
assertEquals(List.of("casegroup"), iamService.getUser("case-group-member").getGroupNames());
assertThrows(AwsException.class, () -> iamService.getGroup("CaseGroup"));
}
@Test
void updateGroupMalformedNewGroupNameIsRejected() {
iamService.createGroup("orig-group", "/");
@@ -1202,6 +1310,17 @@ class IamServiceTest {
assertEquals("arn:aws:iam::000000000000:instance-profile/MyProfile", profile.getArn());
}
@Test
void createInstanceProfileRejectsNameThatDiffersOnlyByCase() {
iamService.createInstanceProfile("CaseProfile", "/");
AwsException error = assertThrows(AwsException.class,
() -> iamService.createInstanceProfile("caseprofile", "/"));
assertEquals("EntityAlreadyExists", error.getErrorCode());
assertEquals(409, error.getHttpStatus());
}
@Test
void addAndRemoveRoleFromInstanceProfile() {
iamService.createRole("LambdaExec", "/", "{}", null, 0, null);