feat(iam): add service-linked role create, delete and deletion status (#2179)

* feat(iam): add service-linked role create, delete and deletion status

aws_iam_service_linked_role calls CreateServiceLinkedRole directly, and one
unsupported operation fails a whole account-bootstrap module. Delete and
GetServiceLinkedRoleDeletionStatus come with it, because create alone leaves
terraform destroy broken.

The role lands under /aws-service-role/<principal>/ with a trust policy for
that principal, and is readable by GetRole afterwards, which is what the
issue asks for.

The role NAME is a deterministic stand-in, not AWS's. The prefix is chosen
by the linked service and is not computable from the principal — AWS turns
lex.amazonaws.com into AWSServiceRoleForLexBots — so this derives a name
from the principal's labels instead: es.amazonaws.com becomes
AWSServiceRoleForEs.
Every label contributes, because rds.amazonaws.com and
rds.application-autoscaling.amazonaws.com are separate roles on AWS and a
config declaring both must not collide on one name.

A CustomSuffix is joined with an underscore, which is the separator callers
parse back out; Terraform recovers custom_suffix by splitting the role name
on it, and that attribute forces replacement, so any other join never
converges.

Deletion is synchronous, so the returned task id is already complete and its
status is SUCCEEDED. Task ids use the documented
task/aws-service-role/<principal>/<role>/<uuid> shape and are held in a
StorageFactory-backed store, so they are account-scoped and survive a
restart like every other IAM record.

Closes #2122

* fix(iam): classify service-linked roles by origin, not by path

CreateRole accepts the /aws-service-role/ prefix, so a role sitting at a
well-formed service-linked path is not necessarily one. Path-based
classification let DeleteServiceLinkedRole delete an ordinary role that
merely lived there.

Roles minted by CreateServiceLinkedRole now carry a marker, and the delete
path keys on that instead. The field is additive, so a role persisted
before this change reads as not service-linked, which is correct.

* fix(iam): protect service-linked roles from ordinary role mutations

DeleteServiceLinkedRole could answer 409 DeleteConflict, a code absent from
that action's published error list (LimitExceeded, NoSuchEntity,
ServiceFailure). It got there by routing through deleteRole, which refuses a
role that still has policies attached — and nothing stopped a caller from
attaching one to a service-linked role first.

AWS never reaches that state. It publishes UnmodifiableEntity (400) on twelve
role actions, and the message names the linked service to go through instead.
So refuse the mutation rather than handle the conflict it would otherwise
cause. This guards the eleven the emulator implements — AttachRolePolicy,
DetachRolePolicy, PutRolePolicy, DeleteRolePolicy,
Put/DeleteRolePermissionsBoundary, UpdateRole, UpdateAssumeRolePolicy,
Add/RemoveRoleFromInstanceProfile and DeleteRole; UpdateRoleDescription is the
twelfth and has no handler here. Several were silent: DeleteRole removed a
service-linked role at 200, UpdateAssumeRolePolicy rewrote its trust policy,
and AddRoleToInstanceProfile attached it to an instance profile. TagRole and
UntagRole stay open, matching AWS. DeleteServiceLinkedRole now removes the
role directly, since deleteRole refuses it.

Also validate CreateServiceLinkedRole's own inputs. CustomSuffix must match
[\w+=,.@-]{1,64}, as AWS constrains it — a suffix containing '/' previously
produced a role name outside RoleName's own pattern, leaving an ARN whose name
segment cannot be recovered. And a derived name over 64 characters is
rejected, because AWS caps RoleName at 64 on every action that takes one and
on the Role this action returns.

Document the three deviations that remain: the role name is derived locally
and will not match AWS for most services, deletion is synchronous so the
deletion status is always SUCCEEDED, and CreateRole accepts the
/aws-service-role/ path that AWS reserves.
This commit is contained in:
soreavis authored and GitHub committed 2026-08-09 15:11:51 -04:00
1 parent d78520d5cb
commit c8403ac6fc
6 files changed
+818 -2

No files matched your search

@@ -82,6 +82,7 @@ public class AwsQueryController {
"CreateGroup", "GetGroup", "DeleteGroup", "ListGroups",
"AddUserToGroup", "RemoveUserFromGroup", "ListGroupsForUser",
"CreateRole", "GetRole", "DeleteRole", "ListRoles", "UpdateRole",
"CreateServiceLinkedRole", "DeleteServiceLinkedRole", "GetServiceLinkedRoleDeletionStatus",
"CreatePolicy", "GetPolicy", "DeletePolicy", "ListPolicies", "ListEntitiesForPolicy",
"CreatePolicyVersion", "GetPolicyVersion", "DeletePolicyVersion",
"ListPolicyVersions", "SetDefaultPolicyVersion",
@@ -82,6 +82,9 @@ public class IamQueryHandler {
case "DeleteRole" -> handleDeleteRole(params);
case "ListRoles" -> handleListRoles(params);
case "UpdateRole" -> handleUpdateRole(params);
case "CreateServiceLinkedRole" -> handleCreateServiceLinkedRole(params);
case "DeleteServiceLinkedRole" -> handleDeleteServiceLinkedRole(params);
case "GetServiceLinkedRoleDeletionStatus" -> handleGetServiceLinkedRoleDeletionStatus(params);
case "UpdateAssumeRolePolicy" -> handleUpdateAssumeRolePolicy(params);
case "TagRole" -> handleTagRole(params);
case "UntagRole" -> handleUntagRole(params);
@@ -399,6 +402,27 @@ public class IamQueryHandler {
return Response.ok(AwsQueryResponse.envelopeNoResult("DeleteRole", AwsNamespaces.IAM)).build();
}
private Response handleCreateServiceLinkedRole(MultivaluedMap<String, String> params) {
IamRole role = iamService.createServiceLinkedRole(
getParam(params, "AWSServiceName"),
getParam(params, "CustomSuffix"),
getParam(params, "Description"));
String result = new XmlBuilder().start("Role").raw(roleXml(role)).end("Role").build();
return Response.ok(AwsQueryResponse.envelope("CreateServiceLinkedRole", AwsNamespaces.IAM, result)).build();
}
private Response handleDeleteServiceLinkedRole(MultivaluedMap<String, String> params) {
String deletionTaskId = iamService.deleteServiceLinkedRole(getParam(params, "RoleName"));
String result = new XmlBuilder().elem("DeletionTaskId", deletionTaskId).build();
return Response.ok(AwsQueryResponse.envelope("DeleteServiceLinkedRole", AwsNamespaces.IAM, result)).build();
}
private Response handleGetServiceLinkedRoleDeletionStatus(MultivaluedMap<String, String> params) {
String status = iamService.getServiceLinkedRoleDeletionStatus(getParam(params, "DeletionTaskId"));
String result = new XmlBuilder().elem("Status", status).build();
return Response.ok(AwsQueryResponse.envelope("GetServiceLinkedRoleDeletionStatus", AwsNamespaces.IAM, result)).build();
}
private Response handleListRoles(MultivaluedMap<String, String> params) {
List<IamRole> roleList = iamService.listRoles(getParam(params, "PathPrefix"));
var xml = new XmlBuilder().start("Roles");
@@ -6,6 +6,7 @@ import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.common.RegionResolver;
import io.github.hectorvent.floci.core.common.SessionAccountLookup;
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.core.storage.StorageFactory;
import io.github.hectorvent.floci.services.iam.model.AccessKey;
@@ -31,6 +32,8 @@ import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.regex.Pattern;
/**
* Core IAM business logic — users, groups, roles, policies, access keys, instance profiles.
@@ -52,6 +55,14 @@ public class IamService implements SessionAccountLookup {
private static final String DEFAULT_DEPLOYER_USER = "floci-deployer";
private static final String DEFAULT_DEPLOYER_ACCESS_KEY_ID = "floci";
private static final String DEFAULT_DEPLOYER_SECRET_ACCESS_KEY = "floci";
private static final String SERVICE_LINKED_ROLE_PATH = "/aws-service-role/";
private static final String SERVICE_LINKED_ROLE_NAME_PREFIX = "AWSServiceRoleFor";
private static final String AMAZONAWS_DOMAIN = ".amazonaws.com";
/** AWSServiceName as AWS constrains it: 1-128 characters of {@code [\w+=,.@-]}. */
private static final Pattern SERVICE_PRINCIPAL_PATTERN = Pattern.compile("[\\w+=,.@-]{1,128}");
/** CustomSuffix as AWS constrains it: 1-64 characters of {@code [\w+=,.@-]}. */
private static final Pattern CUSTOM_SUFFIX_PATTERN = Pattern.compile("[\\w+=,.@-]{1,64}");
private static final int ROLE_NAME_MAX_LENGTH = 64;
private final StorageBackend<String, IamUser> users;
private final StorageBackend<String, IamGroup> groups;
@@ -60,6 +71,8 @@ public class IamService implements SessionAccountLookup {
private final StorageBackend<String, AccessKey> accessKeys;
private final StorageBackend<String, InstanceProfile> instanceProfiles;
private final StorageBackend<String, SessionCredential> sessions;
/** Deletion is synchronous, so an issued task id is a completed one; the value is its role. */
private final StorageBackend<String, String> serviceLinkedRoleDeletions;
private final RegionResolver regionResolver;
private final boolean seedDeployerPrincipal;
@@ -80,6 +93,7 @@ public class IamService implements SessionAccountLookup {
storageFactory.create("iam", "iam-access-keys.json", new TypeReference<>() {}),
storageFactory.create("iam", "iam-instance-profiles.json", new TypeReference<>() {}),
storageFactory.create("iam", "iam-sessions.json", new TypeReference<>() {}),
storageFactory.create("iam", "iam-slr-deletions.json", new TypeReference<>() {}),
regionResolver,
config.services().iam().seedDeployerPrincipal()
);
@@ -105,6 +119,20 @@ public class IamService implements SessionAccountLookup {
StorageBackend<String, SessionCredential> sessions,
RegionResolver regionResolver,
boolean seedDeployerPrincipal) {
this(users, groups, roles, policies, accessKeys, instanceProfiles, sessions,
new InMemoryStorage<>(), regionResolver, seedDeployerPrincipal);
}
IamService(StorageBackend<String, IamUser> users,
StorageBackend<String, IamGroup> groups,
StorageBackend<String, IamRole> roles,
StorageBackend<String, IamPolicy> policies,
StorageBackend<String, AccessKey> accessKeys,
StorageBackend<String, InstanceProfile> instanceProfiles,
StorageBackend<String, SessionCredential> sessions,
StorageBackend<String, String> serviceLinkedRoleDeletions,
RegionResolver regionResolver,
boolean seedDeployerPrincipal) {
this.users = users;
this.groups = groups;
this.roles = roles;
@@ -112,6 +140,7 @@ public class IamService implements SessionAccountLookup {
this.accessKeys = accessKeys;
this.instanceProfiles = instanceProfiles;
this.sessions = sessions;
this.serviceLinkedRoleDeletions = serviceLinkedRoleDeletions;
this.regionResolver = regionResolver;
this.seedDeployerPrincipal = seedDeployerPrincipal;
}
@@ -383,8 +412,31 @@ public class IamService implements SessionAccountLookup {
return roles.get(roleName);
}
/**
* AWS publishes UnmodifiableEntity on twelve role actions, and its message names the linked
* service the caller has to go through instead. This guards the eleven of them the emulator
* implements; UpdateRoleDescription is the twelfth and has no handler here. TagRole and
* UntagRole are deliberately not guarded — AWS does not publish the error on either, and
* TagRole's reference says the role "can be a regular role or a service-linked role".
* Within the IAM API, {@link #deleteServiceLinkedRole} is the only way to remove such a role.
*/
private static void requireNotServiceLinked(IamRole role, String roleName) {
if (role.isServiceLinkedRole()) {
throw new AwsException("UnmodifiableEntity",
"Role " + roleName + " is a service-linked role for " + linkedServicePrincipal(role)
+ "; request the change through that service.", 400);
}
}
/** The linked service, recovered from the {@code /aws-service-role/<principal>/} path. */
private static String linkedServicePrincipal(IamRole role) {
String path = role.getPath();
return path.substring(SERVICE_LINKED_ROLE_PATH.length(), path.length() - 1);
}
public void deleteRole(String roleName) {
IamRole role = getRole(roleName);
requireNotServiceLinked(role, roleName);
if (!role.getAttachedPolicyArns().isEmpty() || !role.getInlinePolicies().isEmpty()) {
throw new AwsException("DeleteConflict",
"Cannot delete entity, must detach all policies first.", 409);
@@ -393,6 +445,111 @@ public class IamService implements SessionAccountLookup {
LOG.infov("Deleted IAM role: {0}", roleName);
}
/**
* The linked service — not the caller and not the principal string — chooses the role-name
* prefix, so {@code lex.amazonaws.com} yields {@code AWSServiceRoleForLexBots} and the real name
* cannot be computed from the principal. The emulator mints a deterministic stand-in from the
* principal's labels instead; callers need the create to succeed and the role to be readable
* afterwards, which this satisfies, but the name will not match AWS for most services.
*
* <p>A {@code CustomSuffix} is joined with an underscore because that is the separator callers
* parse back out: Terraform recovers {@code custom_suffix} by splitting the role name on
* {@code _}, and that attribute forces replacement, so a name without one never converges.
*/
public IamRole createServiceLinkedRole(String awsServiceName, String customSuffix, String description) {
if (awsServiceName == null || !SERVICE_PRINCIPAL_PATTERN.matcher(awsServiceName).matches()) {
throw new AwsException("InvalidInput",
"AWSServiceName must be 1-128 characters matching [\\w+=,.@-], for example es.amazonaws.com.", 400);
}
if (customSuffix != null && !customSuffix.isEmpty()
&& !CUSTOM_SUFFIX_PATTERN.matcher(customSuffix).matches()) {
throw new AwsException("InvalidInput",
"CustomSuffix must be 1-64 characters matching [\\w+=,.@-].", 400);
}
String roleName = SERVICE_LINKED_ROLE_NAME_PREFIX + derivedServiceName(awsServiceName)
+ (customSuffix == null || customSuffix.isEmpty() ? "" : "_" + customSuffix);
// AWSServiceName allows 128 characters, but AWS caps RoleName at 64 — on every action that
// takes one, and on the Role this action returns — so a longer principal would derive a
// name AWS could not represent.
if (roleName.length() > ROLE_NAME_MAX_LENGTH) {
throw new AwsException("InvalidInput",
"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);
}
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;
}
/**
* Deletion is synchronous here, so the task the caller is handed back is already complete —
* {@link #getServiceLinkedRoleDeletionStatus} answers SUCCEEDED for it immediately.
*/
public String deleteServiceLinkedRole(String roleName) {
if (roleName == null) {
throw new AwsException("NoSuchEntity", "The request must include RoleName.", 404);
}
IamRole role = getRole(roleName);
// The path cannot classify a role — CreateRole will put an ordinary one under the
// service-role prefix — so only roles minted here are deletable through this action. The
// error is NoSuchEntity because that is what this action's published list carries.
if (!role.isServiceLinkedRole()) {
throw new AwsException("NoSuchEntity",
"There is no service-linked role with name " + roleName + ".", 404);
}
String servicePrincipal = linkedServicePrincipal(role);
// Not deleteRole: that action refuses a service-linked role outright, and its
// detach-first conflict is not in this action's published error list either.
roles.delete(roleName);
LOG.infov("Deleted service-linked IAM role: {0}", roleName);
String deletionTaskId = "task" + SERVICE_LINKED_ROLE_PATH + servicePrincipal + "/"
+ roleName + "/" + UUID.randomUUID();
serviceLinkedRoleDeletions.put(deletionTaskId, roleName);
return deletionTaskId;
}
/**
* Every dot- and hyphen-separated label contributes, because the leading one alone is not unique:
* {@code rds.amazonaws.com} and {@code rds.application-autoscaling.amazonaws.com} are separate
* roles on AWS, and a config declaring both must not collide on one name here.
*/
private static String derivedServiceName(String awsServiceName) {
String core = awsServiceName == null ? "" : awsServiceName;
if (core.endsWith(AMAZONAWS_DOMAIN)) {
core = core.substring(0, core.length() - AMAZONAWS_DOMAIN.length());
}
StringBuilder derived = new StringBuilder();
for (String segment : core.split("[.-]")) {
if (!segment.isEmpty()) {
derived.append(Character.toUpperCase(segment.charAt(0))).append(segment.substring(1));
}
}
if (derived.isEmpty()) {
throw new AwsException("InvalidInput",
"The request must include a valid AWSServiceName, for example es.amazonaws.com.", 400);
}
return derived.toString();
}
public String getServiceLinkedRoleDeletionStatus(String deletionTaskId) {
if (deletionTaskId == null || serviceLinkedRoleDeletions.get(deletionTaskId).isEmpty()) {
throw new AwsException("NoSuchEntity",
"The deletion task with id " + deletionTaskId + " cannot be found.", 404);
}
return "SUCCEEDED";
}
public List<IamRole> listRoles(String pathPrefix) {
String prefix = pathPrefix != null ? pathPrefix : "/";
return roles.scan(k -> true).stream()
@@ -402,6 +559,7 @@ public class IamService implements SessionAccountLookup {
public void updateRole(String roleName, String description, int maxSessionDuration) {
IamRole role = getRole(roleName);
requireNotServiceLinked(role, roleName);
if (description != null) role.setDescription(description);
if (maxSessionDuration > 0) role.setMaxSessionDuration(maxSessionDuration);
roles.put(roleName, role);
@@ -409,6 +567,7 @@ public class IamService implements SessionAccountLookup {
public void updateAssumeRolePolicy(String roleName, String policyDocument) {
IamRole role = getRole(roleName);
requireNotServiceLinked(role, roleName);
role.setAssumeRolePolicyDocument(policyDocument);
roles.put(roleName, role);
}
@@ -723,6 +882,7 @@ public class IamService implements SessionAccountLookup {
public void attachRolePolicy(String roleName, String policyArn) {
IamRole role = getRole(roleName);
requireNotServiceLinked(role, roleName);
IamPolicy policy = getPolicy(policyArn);
if (!role.getAttachedPolicyArns().contains(policyArn)) {
role.getAttachedPolicyArns().add(policyArn);
@@ -734,6 +894,7 @@ public class IamService implements SessionAccountLookup {
public void detachRolePolicy(String roleName, String policyArn) {
IamRole role = getRole(roleName);
requireNotServiceLinked(role, roleName);
if (!role.getAttachedPolicyArns().remove(policyArn)) {
throw new AwsException("NoSuchEntity",
"Policy " + policyArn + " is not attached to role " + roleName + ".", 404);
@@ -824,6 +985,7 @@ public class IamService implements SessionAccountLookup {
public void putRolePolicy(String roleName, String policyName, String policyDocument) {
IamRole role = getRole(roleName);
requireNotServiceLinked(role, roleName);
role.getInlinePolicies().put(policyName, policyDocument);
roles.put(roleName, role);
}
@@ -840,6 +1002,7 @@ public class IamService implements SessionAccountLookup {
public void deleteRolePolicy(String roleName, String policyName) {
IamRole role = getRole(roleName);
requireNotServiceLinked(role, roleName);
if (role.getInlinePolicies().remove(policyName) == null) {
throw new AwsException("NoSuchEntity",
"Policy " + policyName + " not found for role " + roleName + ".", 404);
@@ -948,7 +1111,7 @@ public class IamService implements SessionAccountLookup {
public void addRoleToInstanceProfile(String instanceProfileName, String roleName) {
InstanceProfile profile = getInstanceProfile(instanceProfileName);
getRole(roleName); // validates existence
requireNotServiceLinked(getRole(roleName), roleName);
List<String> roleNames = profile.getRoleNames();
synchronized (roleNames) {
if (!roleNames.contains(roleName)) {
@@ -964,6 +1127,8 @@ public class IamService implements SessionAccountLookup {
public void removeRoleFromInstanceProfile(String instanceProfileName, String roleName) {
InstanceProfile profile = getInstanceProfile(instanceProfileName);
// Tolerates an already-deleted role, so guard only what is still there.
roles.get(roleName).ifPresent(role -> requireNotServiceLinked(role, roleName));
profile.getRoleNames().remove(roleName);
instanceProfiles.put(instanceProfileName, profile);
}
@@ -1253,8 +1418,9 @@ public class IamService implements SessionAccountLookup {
}
public void putRolePermissionsBoundary(String roleName, String permissionsBoundaryArn) {
getPolicy(permissionsBoundaryArn); // validate policy exists
IamRole role = getRole(roleName);
requireNotServiceLinked(role, roleName);
getPolicy(permissionsBoundaryArn); // validate policy exists
role.setPermissionsBoundaryArn(permissionsBoundaryArn);
roles.put(roleName, role);
LOG.infov("Set permissions boundary for role {0}: {1}", roleName, permissionsBoundaryArn);
@@ -1262,6 +1428,7 @@ public class IamService implements SessionAccountLookup {
public void deleteRolePermissionsBoundary(String roleName) {
IamRole role = getRole(roleName);
requireNotServiceLinked(role, roleName);
if (role.getPermissionsBoundaryArn() == null) {
throw new AwsException("NoSuchEntity",
"Role " + roleName + " does not have a permissions boundary.", 404);
@@ -25,6 +25,8 @@ public class IamRole {
private List<String> attachedPolicyArns = new CopyOnWriteArrayList<>();
private Map<String, String> inlinePolicies = new ConcurrentHashMap<>();
private String permissionsBoundaryArn;
/** Set only by CreateServiceLinkedRole; the path alone cannot classify a role. */
private boolean serviceLinkedRole;
public IamRole() {}
@@ -79,4 +81,7 @@ public class IamRole {
public String getPermissionsBoundaryArn() { return permissionsBoundaryArn; }
public void setPermissionsBoundaryArn(String permissionsBoundaryArn) { this.permissionsBoundaryArn = permissionsBoundaryArn; }
public boolean isServiceLinkedRole() { return serviceLinkedRole; }
public void setServiceLinkedRole(boolean serviceLinkedRole) { this.serviceLinkedRole = serviceLinkedRole; }
}