diff --git a/docs/services/iam.md b/docs/services/iam.md index 48601fb9ba..b0b22e7f7c 100644 --- a/docs/services/iam.md +++ b/docs/services/iam.md @@ -38,6 +38,9 @@ | DeleteRole | Deletes an IAM role from the local IAM store. | | ListRoles | Lists IAM roles in the local account. | | UpdateRole | Updates mutable IAM role fields. | +| CreateServiceLinkedRole | Creates a role under /aws-service-role/ for a service principal. | +| DeleteServiceLinkedRole | Deletes a service-linked role and returns a deletion task id. | +| GetServiceLinkedRoleDeletionStatus | Returns the status of a service-linked role deletion. | | UpdateAssumeRolePolicy | Replaces a role's assume-role policy document. | | TagRole | Adds tags to an IAM role. | | UntagRole | Removes tags from an IAM role. | @@ -266,6 +269,33 @@ AWS_ACCESS_KEY_ID=$AKID AWS_SECRET_ACCESS_KEY=$SECRET \ aws s3 ls ``` +## Service-linked roles + +`CreateServiceLinkedRole` puts a role under `/aws-service-role//` and marks it as +service-linked. As on AWS, a role carrying that mark is protected: `AttachRolePolicy`, +`DetachRolePolicy`, `PutRolePolicy`, `DeleteRolePolicy`, `PutRolePermissionsBoundary`, +`DeleteRolePermissionsBoundary`, `UpdateRole`, `UpdateAssumeRolePolicy`, `AddRoleToInstanceProfile`, +`RemoveRoleFromInstanceProfile` and `DeleteRole` all answer `UnmodifiableEntity` and name the +linked service to go through instead. `TagRole` and `UntagRole` are allowed, as on AWS. Within the +IAM API `DeleteServiceLinkedRole` is the only way to remove such a role — the emulator's own +`/_floci/state/reset` still clears it along with everything else. + +Three deviations to be aware of: + +- **The role name is derived locally and will not match AWS for most services.** AWS lets each + linked service choose the name, and it is not computable from the service principal — + `lex.amazonaws.com` yields `AWSServiceRoleForLexBots` there, where Floci derives + `AWSServiceRoleForLex`. Read the name back from the create response rather than hardcoding + it, and do not rely on a name observed locally matching the one AWS mints. +- **Deletion is synchronous.** `DeleteServiceLinkedRole` completes before it returns, so the + task id it hands back is already finished and `GetServiceLinkedRoleDeletionStatus` always + reports `SUCCEEDED`. The `IN_PROGRESS`, `NOT_STARTED` and `FAILED` states never occur, and no + failure `Reason` is ever returned — a poll loop works, but its failure branch is never taken. +- **`CreateRole` accepts the `/aws-service-role/` path, which AWS reserves.** AWS rejects that + prefix on `CreateRole`; Floci allows it and treats the result as an ordinary role, since the + service-linked mark comes from the action that minted the role rather than from its path. Such + a role stays fully modifiable, and `DeleteServiceLinkedRole` answers `NoSuchEntity` for it. + ## Configuration | Variable | Default | Description | diff --git a/src/main/java/io/github/hectorvent/floci/core/common/AwsQueryController.java b/src/main/java/io/github/hectorvent/floci/core/common/AwsQueryController.java index a98ddc855b..39818cd879 100644 --- a/src/main/java/io/github/hectorvent/floci/core/common/AwsQueryController.java +++ b/src/main/java/io/github/hectorvent/floci/core/common/AwsQueryController.java @@ -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", diff --git a/src/main/java/io/github/hectorvent/floci/services/iam/IamQueryHandler.java b/src/main/java/io/github/hectorvent/floci/services/iam/IamQueryHandler.java index 5d5f49d619..91093faa47 100644 --- a/src/main/java/io/github/hectorvent/floci/services/iam/IamQueryHandler.java +++ b/src/main/java/io/github/hectorvent/floci/services/iam/IamQueryHandler.java @@ -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 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 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 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 params) { List roleList = iamService.listRoles(getParam(params, "PathPrefix")); var xml = new XmlBuilder().start("Roles"); diff --git a/src/main/java/io/github/hectorvent/floci/services/iam/IamService.java b/src/main/java/io/github/hectorvent/floci/services/iam/IamService.java index d809bb2732..ac3ecd8ab6 100644 --- a/src/main/java/io/github/hectorvent/floci/services/iam/IamService.java +++ b/src/main/java/io/github/hectorvent/floci/services/iam/IamService.java @@ -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 users; private final StorageBackend groups; @@ -60,6 +71,8 @@ public class IamService implements SessionAccountLookup { private final StorageBackend accessKeys; private final StorageBackend instanceProfiles; private final StorageBackend sessions; + /** Deletion is synchronous, so an issued task id is a completed one; the value is its role. */ + private final StorageBackend 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 sessions, RegionResolver regionResolver, boolean seedDeployerPrincipal) { + this(users, groups, roles, policies, accessKeys, instanceProfiles, sessions, + new InMemoryStorage<>(), regionResolver, seedDeployerPrincipal); + } + + IamService(StorageBackend users, + StorageBackend groups, + StorageBackend roles, + StorageBackend policies, + StorageBackend accessKeys, + StorageBackend instanceProfiles, + StorageBackend sessions, + StorageBackend 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//} 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. + * + *

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 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 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); diff --git a/src/main/java/io/github/hectorvent/floci/services/iam/model/IamRole.java b/src/main/java/io/github/hectorvent/floci/services/iam/model/IamRole.java index e964a83b9d..27f9002088 100644 --- a/src/main/java/io/github/hectorvent/floci/services/iam/model/IamRole.java +++ b/src/main/java/io/github/hectorvent/floci/services/iam/model/IamRole.java @@ -25,6 +25,8 @@ public class IamRole { private List attachedPolicyArns = new CopyOnWriteArrayList<>(); private Map 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; } } diff --git a/src/test/java/io/github/hectorvent/floci/services/iam/IamServiceLinkedRoleIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/iam/IamServiceLinkedRoleIntegrationTest.java new file mode 100644 index 0000000000..e7db97faa0 --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/iam/IamServiceLinkedRoleIntegrationTest.java @@ -0,0 +1,589 @@ +package io.github.hectorvent.floci.services.iam; + +import static org.hamcrest.Matchers.containsString; +import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.matchesRegex; +import static org.hamcrest.Matchers.startsWith; + +import org.junit.jupiter.api.MethodOrderer; +import org.junit.jupiter.api.Order; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestMethodOrder; + +import io.quarkus.test.junit.QuarkusTest; +import static io.restassured.RestAssured.given; + +/** + * Service-linked roles exist so Terraform's aws_iam_service_linked_role can apply and destroy + * against the emulator: the create must succeed, the role must be readable afterwards, and the + * delete must hand back a task id whose status can be polled. + */ +@QuarkusTest +@TestMethodOrder(MethodOrderer.OrderAnnotation.class) +class IamServiceLinkedRoleIntegrationTest { + + private static final String AUTH_HEADER = + "AWS4-HMAC-SHA256 Credential=test/20260227/us-east-1/iam/aws4_request"; + + private static final String SERVICE = "es.amazonaws.com"; + + private static final String OTHER_ACCOUNT_AUTH_HEADER = + "AWS4-HMAC-SHA256 Credential=222222222222/20260227/us-east-1/iam/aws4_request"; + + private static String deletionTaskId; + + @Test + @Order(1) + void createServiceLinkedRolePlacesItUnderTheServiceRolePath() { + given() + .formParam("Action", "CreateServiceLinkedRole") + .formParam("AWSServiceName", SERVICE) + .formParam("Description", "Managed by the linked service") + .header("Authorization", AUTH_HEADER) + .when() + .post("/") + .then() + .statusCode(200) + .body("CreateServiceLinkedRoleResponse.CreateServiceLinkedRoleResult.Role.RoleName", + equalTo("AWSServiceRoleForEs")) + .body("CreateServiceLinkedRoleResponse.CreateServiceLinkedRoleResult.Role.Path", + equalTo("/aws-service-role/" + SERVICE + "/")) + .body("CreateServiceLinkedRoleResponse.CreateServiceLinkedRoleResult.Role.Arn", + equalTo("arn:aws:iam::000000000000:role/aws-service-role/" + SERVICE + "/AWSServiceRoleForEs")) + .body("CreateServiceLinkedRoleResponse.CreateServiceLinkedRoleResult.Role.RoleId", + startsWith("AROA")); + } + + @Test + @Order(2) + void theRoleIsReadableAfterwards() { + given() + .formParam("Action", "GetRole") + .formParam("RoleName", "AWSServiceRoleForEs") + .header("Authorization", AUTH_HEADER) + .when() + .post("/") + .then() + .statusCode(200) + .body("GetRoleResponse.GetRoleResult.Role.Path", + equalTo("/aws-service-role/" + SERVICE + "/")); + } + + @Test + @Order(3) + void repeatingTheRequestWithoutASuffixIsRejectedAsADuplicate() { + given() + .formParam("Action", "CreateServiceLinkedRole") + .formParam("AWSServiceName", SERVICE) + .header("Authorization", AUTH_HEADER) + .when() + .post("/") + .then() + // Not EntityAlreadyExists: that is createRole's generic answer and is absent from this + // action's published error list, which does carry InvalidInput. + .statusCode(400) + .body("ErrorResponse.Error.Code", equalTo("InvalidInput")); + } + + @Test + @Order(4) + void aCustomSuffixMakesTheSecondRoleDistinct() { + given() + .formParam("Action", "CreateServiceLinkedRole") + .formParam("AWSServiceName", SERVICE) + .formParam("CustomSuffix", "debug") + .header("Authorization", AUTH_HEADER) + .when() + .post("/") + .then() + .statusCode(200) + .body("CreateServiceLinkedRoleResponse.CreateServiceLinkedRoleResult.Role.RoleName", + equalTo("AWSServiceRoleForEs_debug")); + } + + @Test + @Order(5) + void aMissingServiceNameIsRejected() { + given() + .formParam("Action", "CreateServiceLinkedRole") + .header("Authorization", AUTH_HEADER) + .when() + .post("/") + .then() + .statusCode(400) + .body("ErrorResponse.Error.Code", equalTo("InvalidInput")); + } + + @Test + @Order(6) + void deleteReturnsATaskIdInTheDocumentedFormat() { + deletionTaskId = given() + .formParam("Action", "DeleteServiceLinkedRole") + .formParam("RoleName", "AWSServiceRoleForEs_debug") + .header("Authorization", AUTH_HEADER) + .when() + .post("/") + .then() + .statusCode(200) + // AWS documents task/aws-service-role/// + .body("DeleteServiceLinkedRoleResponse.DeleteServiceLinkedRoleResult.DeletionTaskId", + matchesRegex("task/aws-service-role/\\Q" + SERVICE + "\\E/AWSServiceRoleForEs_debug/" + + "[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}")) + .extract().path("DeleteServiceLinkedRoleResponse.DeleteServiceLinkedRoleResult.DeletionTaskId"); + } + + @Test + @Order(7) + void theDeletedRoleIsGone() { + given() + .formParam("Action", "GetRole") + .formParam("RoleName", "AWSServiceRoleForEs_debug") + .header("Authorization", AUTH_HEADER) + .when() + .post("/") + .then() + .statusCode(404) + .body("ErrorResponse.Error.Code", equalTo("NoSuchEntity")); + } + + @Test + @Order(8) + void theDeletionStatusIsSucceeded() { + given() + .formParam("Action", "GetServiceLinkedRoleDeletionStatus") + .formParam("DeletionTaskId", deletionTaskId) + .header("Authorization", AUTH_HEADER) + .when() + .post("/") + .then() + .statusCode(200) + .body("GetServiceLinkedRoleDeletionStatusResponse" + + ".GetServiceLinkedRoleDeletionStatusResult.Status", + equalTo("SUCCEEDED")); + } + + @Test + @Order(9) + void anUnknownDeletionTaskIsRejected() { + given() + .formParam("Action", "GetServiceLinkedRoleDeletionStatus") + .formParam("DeletionTaskId", "task/aws-service-role/es.amazonaws.com/Nope/" + + "00000000-0000-0000-0000-000000000000") + .header("Authorization", AUTH_HEADER) + .when() + .post("/") + .then() + .statusCode(404) + .body("ErrorResponse.Error.Code", equalTo("NoSuchEntity")); + } + + /** + * CreateRole does not reserve the service-role prefix, so a caller can park an ordinary role at + * exactly {@code /aws-service-role/}. Recovering the principal from that path leaves an empty + * segment, which must be rejected rather than crashing out of a substring. + */ + @Test + @Order(11) + void deletingARoleParkedAtTheBareServiceRolePathIsRejected() { + given() + .formParam("Action", "CreateRole") + .formParam("RoleName", "ParkedAtThePrefix") + .formParam("Path", "/aws-service-role/") + .formParam("AssumeRolePolicyDocument", "{\"Version\":\"2012-10-17\",\"Statement\":[]}") + .header("Authorization", AUTH_HEADER) + .when() + .post("/") + .then() + .statusCode(200); + + given() + .formParam("Action", "DeleteServiceLinkedRole") + .formParam("RoleName", "ParkedAtThePrefix") + .header("Authorization", AUTH_HEADER) + .when() + .post("/") + .then() + .statusCode(404) + .body("ErrorResponse.Error.Code", equalTo("NoSuchEntity")); + } + + /** An all-dots service name matches AWS's own parameter pattern, so it must 400, never 500. */ + @Test + @Order(12) + void anAllDotsServiceNameIsRejected() { + given() + .formParam("Action", "CreateServiceLinkedRole") + .formParam("AWSServiceName", ".") + .header("Authorization", AUTH_HEADER) + .when() + .post("/") + .then() + .statusCode(400) + .body("ErrorResponse.Error.Code", equalTo("InvalidInput")); + } + + /** + * rds.amazonaws.com and rds.application-autoscaling.amazonaws.com are distinct roles on AWS. A + * config declaring both is exactly this issue's use case, so they must not collide on one name. + */ + @Test + @Order(13) + void principalsSharingALeadingLabelGetDistinctRoles() { + given() + .formParam("Action", "CreateServiceLinkedRole") + .formParam("AWSServiceName", "rds.amazonaws.com") + .header("Authorization", AUTH_HEADER) + .when() + .post("/") + .then() + .statusCode(200) + .body("CreateServiceLinkedRoleResponse.CreateServiceLinkedRoleResult.Role.RoleName", + equalTo("AWSServiceRoleForRds")); + + given() + .formParam("Action", "CreateServiceLinkedRole") + .formParam("AWSServiceName", "rds.application-autoscaling.amazonaws.com") + .header("Authorization", AUTH_HEADER) + .when() + .post("/") + .then() + .statusCode(200) + .body("CreateServiceLinkedRoleResponse.CreateServiceLinkedRoleResult.Role.RoleName", + equalTo("AWSServiceRoleForRdsApplicationAutoscaling")); + } + + /** + * Terraform recovers custom_suffix by splitting the role name on an underscore, and that + * attribute forces replacement — a name joined any other way never converges. + */ + @Test + @Order(14) + void theCustomSuffixIsJoinedWithAnUnderscore() { + given() + .formParam("Action", "CreateServiceLinkedRole") + .formParam("AWSServiceName", "autoscaling.amazonaws.com") + .formParam("CustomSuffix", "CustomResource") + .header("Authorization", AUTH_HEADER) + .when() + .post("/") + .then() + .statusCode(200) + .body("CreateServiceLinkedRoleResponse.CreateServiceLinkedRoleResult.Role.RoleName", + equalTo("AWSServiceRoleForAutoscaling_CustomResource")); + } + + /** AWS constrains AWSServiceName to [\w+=,.@-]{1,128}; anything else must not reach storage. */ + @Test + @Order(15) + void aServiceNameOutsideTheAwsPatternIsRejected() { + for (String bad : new String[]{"x\",\"AWS\":\"*", "a\"b.amazonaws.com", " ", "a/b.amazonaws.com", + "x".repeat(129)}) { + given() + .formParam("Action", "CreateServiceLinkedRole") + .formParam("AWSServiceName", bad) + .header("Authorization", AUTH_HEADER) + .when() + .post("/") + .then() + .statusCode(400) + .body("ErrorResponse.Error.Code", equalTo("InvalidInput")); + } + } + + /** The deletion task is account-scoped storage, so another account must not resolve it. */ + @Test + @Order(16) + void aDeletionTaskIsNotVisibleToAnotherAccount() { + given() + .formParam("Action", "CreateServiceLinkedRole") + .formParam("AWSServiceName", "kafka.amazonaws.com") + .header("Authorization", AUTH_HEADER) + .when() + .post("/") + .then() + .statusCode(200); + + String taskId = given() + .formParam("Action", "DeleteServiceLinkedRole") + .formParam("RoleName", "AWSServiceRoleForKafka") + .header("Authorization", AUTH_HEADER) + .when() + .post("/") + .then() + .statusCode(200) + .extract().path("DeleteServiceLinkedRoleResponse.DeleteServiceLinkedRoleResult.DeletionTaskId"); + + given() + .formParam("Action", "GetServiceLinkedRoleDeletionStatus") + .formParam("DeletionTaskId", taskId) + .header("Authorization", OTHER_ACCOUNT_AUTH_HEADER) + .when() + .post("/") + .then() + .statusCode(404) + .body("ErrorResponse.Error.Code", equalTo("NoSuchEntity")); + } + + /** + * CreateRole accepts the service-role prefix, so path is not evidence of how a role was made. + * An ordinary role sitting at a well-formed service-linked path must survive this action. + */ + @Test + @Order(17) + void anOrdinaryRoleAtAServiceLinkedPathIsNotDeletable() { + given() + .formParam("Action", "CreateRole") + .formParam("RoleName", "ImpostorAtTheServicePath") + .formParam("Path", "/aws-service-role/es.amazonaws.com/") + .formParam("AssumeRolePolicyDocument", "{\"Version\":\"2012-10-17\",\"Statement\":[]}") + .header("Authorization", AUTH_HEADER) + .when() + .post("/") + .then() + .statusCode(200); + + given() + .formParam("Action", "DeleteServiceLinkedRole") + .formParam("RoleName", "ImpostorAtTheServicePath") + .header("Authorization", AUTH_HEADER) + .when() + .post("/") + .then() + .statusCode(404) + .body("ErrorResponse.Error.Code", equalTo("NoSuchEntity")); + + // ...and it is still there. + given() + .formParam("Action", "GetRole") + .formParam("RoleName", "ImpostorAtTheServicePath") + .header("Authorization", AUTH_HEADER) + .when() + .post("/") + .then() + .statusCode(200); + } + + @Test + @Order(10) + void deletingAnOrdinaryRoleThroughThisActionIsRejected() { + given() + .formParam("Action", "CreateRole") + .formParam("RoleName", "NotServiceLinked") + .formParam("Path", "/") + .formParam("AssumeRolePolicyDocument", "{\"Version\":\"2012-10-17\",\"Statement\":[]}") + .header("Authorization", AUTH_HEADER) + .when() + .post("/") + .then() + .statusCode(200); + + given() + .formParam("Action", "DeleteServiceLinkedRole") + .formParam("RoleName", "NotServiceLinked") + .header("Authorization", AUTH_HEADER) + .when() + .post("/") + .then() + .statusCode(404) + .body("ErrorResponse.Error.Code", equalTo("NoSuchEntity")); + } + + private static void createServiceLinkedRole(String principal) { + given() + .formParam("Action", "CreateServiceLinkedRole") + .formParam("AWSServiceName", principal) + .header("Authorization", AUTH_HEADER) + .when() + .post("/") + .then() + .statusCode(200); + } + + @Test + @Order(18) + void attachingAManagedPolicyToAServiceLinkedRoleIsRejected() { + createServiceLinkedRole("attachprobe.amazonaws.com"); + + given() + .formParam("Action", "AttachRolePolicy") + .formParam("RoleName", "AWSServiceRoleForAttachprobe") + .formParam("PolicyArn", "arn:aws:iam::aws:policy/ReadOnlyAccess") + .header("Authorization", AUTH_HEADER) + .when() + .post("/") + .then() + .statusCode(400) + .body("ErrorResponse.Error.Code", equalTo("UnmodifiableEntity")); + } + + @Test + @Order(19) + void embeddingAnInlinePolicyInAServiceLinkedRoleIsRejected() { + createServiceLinkedRole("putprobe.amazonaws.com"); + + given() + .formParam("Action", "PutRolePolicy") + .formParam("RoleName", "AWSServiceRoleForPutprobe") + .formParam("PolicyName", "inline") + .formParam("PolicyDocument", "{\"Version\":\"2012-10-17\",\"Statement\":[]}") + .header("Authorization", AUTH_HEADER) + .when() + .post("/") + .then() + .statusCode(400) + .body("ErrorResponse.Error.Code", equalTo("UnmodifiableEntity")); + } + + @Test + @Order(20) + void deleteRoleOnAServiceLinkedRoleIsRejectedAndLeavesTheRoleInPlace() { + createServiceLinkedRole("delroleprobe.amazonaws.com"); + + given() + .formParam("Action", "DeleteRole") + .formParam("RoleName", "AWSServiceRoleForDelroleprobe") + .header("Authorization", AUTH_HEADER) + .when() + .post("/") + .then() + .statusCode(400) + .body("ErrorResponse.Error.Code", equalTo("UnmodifiableEntity")); + + given() + .formParam("Action", "GetRole") + .formParam("RoleName", "AWSServiceRoleForDelroleprobe") + .header("Authorization", AUTH_HEADER) + .when() + .post("/") + .then() + .statusCode(200); + } + + @Test + @Order(21) + void deleteServiceLinkedRoleStillRemovesARoleThatDeleteRoleRefuses() { + createServiceLinkedRole("slrdelete.amazonaws.com"); + + given() + .formParam("Action", "DeleteServiceLinkedRole") + .formParam("RoleName", "AWSServiceRoleForSlrdelete") + .header("Authorization", AUTH_HEADER) + .when() + .post("/") + .then() + .statusCode(200); + + given() + .formParam("Action", "GetRole") + .formParam("RoleName", "AWSServiceRoleForSlrdelete") + .header("Authorization", AUTH_HEADER) + .when() + .post("/") + .then() + .statusCode(404); + } + + private static void refusedAsUnmodifiable(String action, String... formParams) { + var request = given().header("Authorization", AUTH_HEADER).formParam("Action", action); + for (int i = 0; i < formParams.length; i += 2) { + request = request.formParam(formParams[i], formParams[i + 1]); + } + request + .when() + .post("/") + .then() + .statusCode(400) + .body("ErrorResponse.Error.Code", equalTo("UnmodifiableEntity")); + } + + /** The mark has to hold across every action AWS protects, not just the delete path. */ + @Test + @Order(24) + void theOtherRoleActionsAwsProtectsAreAlsoRefused() { + createServiceLinkedRole("protectprobe.amazonaws.com"); + String roleName = "AWSServiceRoleForProtectprobe"; + String readOnly = "arn:aws:iam::aws:policy/ReadOnlyAccess"; + + refusedAsUnmodifiable("UpdateRole", "RoleName", roleName, "Description", "hijacked"); + refusedAsUnmodifiable("UpdateAssumeRolePolicy", "RoleName", roleName, + "PolicyDocument", "{\"Version\":\"2012-10-17\",\"Statement\":[]}"); + refusedAsUnmodifiable("DetachRolePolicy", "RoleName", roleName, "PolicyArn", readOnly); + refusedAsUnmodifiable("DeleteRolePolicy", "RoleName", roleName, "PolicyName", "inline"); + refusedAsUnmodifiable("PutRolePermissionsBoundary", "RoleName", roleName, + "PermissionsBoundary", readOnly); + refusedAsUnmodifiable("DeleteRolePermissionsBoundary", "RoleName", roleName); + + given() + .formParam("Action", "CreateInstanceProfile") + .formParam("InstanceProfileName", "protectprobe-profile") + .header("Authorization", AUTH_HEADER) + .when() + .post("/") + .then() + .statusCode(200); + + refusedAsUnmodifiable("AddRoleToInstanceProfile", + "InstanceProfileName", "protectprobe-profile", "RoleName", roleName); + refusedAsUnmodifiable("RemoveRoleFromInstanceProfile", + "InstanceProfileName", "protectprobe-profile", "RoleName", roleName); + + // The trust policy is the one an attacker would rewrite, so pin that it survived intact. + given() + .formParam("Action", "GetRole") + .formParam("RoleName", roleName) + .header("Authorization", AUTH_HEADER) + .when() + .post("/") + .then() + .statusCode(200) + .body("GetRoleResponse.GetRoleResult.Role.AssumeRolePolicyDocument", + containsString("protectprobe.amazonaws.com")); + } + + /** AWS leaves tagging open on a service-linked role; the guard must not overreach. */ + @Test + @Order(25) + void taggingAServiceLinkedRoleIsStillAllowed() { + createServiceLinkedRole("tagprobe.amazonaws.com"); + + given() + .formParam("Action", "TagRole") + .formParam("RoleName", "AWSServiceRoleForTagprobe") + .formParam("Tags.member.1.Key", "team") + .formParam("Tags.member.1.Value", "platform") + .header("Authorization", AUTH_HEADER) + .when() + .post("/") + .then() + .statusCode(200); + } + + @Test + @Order(22) + void aCustomSuffixOutsideTheAllowedCharactersIsRejected() { + given() + .formParam("Action", "CreateServiceLinkedRole") + .formParam("AWSServiceName", "suffixprobe.amazonaws.com") + .formParam("CustomSuffix", "a/b") + .header("Authorization", AUTH_HEADER) + .when() + .post("/") + .then() + .statusCode(400) + .body("ErrorResponse.Error.Code", equalTo("InvalidInput")); + } + + @Test + @Order(23) + void aPrincipalDerivingARoleNamePastTheLengthLimitIsRejected() { + given() + .formParam("Action", "CreateServiceLinkedRole") + .formParam("AWSServiceName", "a".repeat(114) + ".amazonaws.com") + .header("Authorization", AUTH_HEADER) + .when() + .post("/") + .then() + .statusCode(400) + .body("ErrorResponse.Error.Code", equalTo("InvalidInput")); + } +}