fix(iam): answer a blocked delete with the sentence for the dependency that blocks it (#9220)

IAM names exactly one blocking dependent and words each class with its own
wholly fixed sentence, no entity name and no count, because a cleanup loop
reads the sentence to choose its next step. Four of those recordings bear on
this package and three of them diverged.

- DeleteRole read a role's attached and inline policies together and answered
  the detach sentence for both, so an inline policy was told to detach
  something. The two are reported apart now: "Cannot delete entity, must
  detach all policies first." for a managed attachment and "Cannot delete
  entity, must delete policies first." for an embedded policy, which is the
  remedy that clears what is there. DeleteGroup conflated them the same way
  and selects the same two sentences now; DeleteUser already did and is the
  model both follow.
- DeleteRole never looked at instance profiles, so a role a profile held was
  deleted and left the profile naming nothing. A role an instance profile
  holds is "Cannot delete entity, must remove roles from instance profile
  first." and the profile has to let go of it first, as on AWS. The profile
  is reported ahead of an attached policy, which is recorded for a role that
  is both held and carrying attachments, and is what a cleanup loop needs,
  since detaching changes nothing while the pairing is there.
- DeleteInstanceProfile wording its own refusal now carries that same
  sentence, which is AWS's for both ends of the pairing.

The new membership check and the emptiness check it joins are both
check-then-act, so AddRoleToInstanceProfile takes the lock the deletes decide
under, outside the profile's own monitor as every path here already does: one
order throughout, and no pairing can land between a delete's read and what it
does with it.

Nothing takes a role out of a profile on the caller's behalf, on AWS or here.
The CloudFormation role provisioner keeps clearing the policies its stack owns
and lets the conflict reach the stack, with a provisioner case for it; a stack
owning both resources deletes the profile first, since dependents go before
what they depend on. The test fixture that tears a role down removes it from
any profile first, ahead of its policies, so teardown asks for the remedies in
the order the refusals name. The tolerance behind RemoveRoleFromInstanceProfile
stays for state reached another way, and the test that reached it by deleting
the role first now asserts the refusal and clears the pairing before the role.

Which profiles hold a role is kept as an index beside the profiles themselves,
written in the same two places a pairing is and read only under that lock, so
the check costs a lookup rather than a read of every profile in the account
while the lock is held. A scope is filled from storage the first time it is
asked about, so a pairing a restart inherited is in it before the first answer.

The two callers that delete a role of their own clear its policies first, so
each asks about the profile before it clears anything: otherwise a role that
turns out not to be deletable would be left in place with its permissions
stripped by a delete that could not finish.
This commit is contained in:
Priamo Germosen authored and GitHub committed 2026-11-22 15:14:52 -04:00
1 parent 9af8ca07a9
commit 82fdb36228
10 files changed
+602 -54

No files matched your search

+41 -2
View File
@@ -694,14 +694,53 @@ roles-per-instance-profile quota by any name, and this package used to answer pr
Removing a role the profile does not hold is `NoSuchEntity` 404 with `Role <roleName> in Instance
Profile <instanceProfileName> cannot be found.`, where this package removed nothing and answered
200. A role that was deleted while the profile still lists it is a different case and is still
removable, which is what the profile's own list decides.
200. A profile that lists a role which is no longer there is a different case and is still
removable, which is what the profile's own list decides; nothing served reaches that state any
more, since the role cannot be deleted while a profile holds it.
The two CloudFormation paths that detach a role read the profile's list and then remove what it
named, so a pairing some other caller detaches in between is tolerated there rather than failing a
stack delete or an update part way; a profile that has itself gone still ends the delete where it
always did.
### What a blocked delete names
A delete that a dependency blocks is `DeleteConflict` 409, and the sentence it carries names the
one dependency the caller has to clear. The four below are AWS's own, recorded against a real
account across capture runs between 2026-10-25 and 2026-11-16, and each is entirely fixed text:
no entity name, no count, nothing taken from the request. The wording is the contract rather than
a description, because a cleanup loop reads it to choose what to do next.
| What is still there | What the delete answers |
| --- | --- |
| The role is held by an instance profile | `Cannot delete entity, must remove roles from instance profile first.` |
| The instance profile still holds a role | `Cannot delete entity, must remove roles from instance profile first.` |
| A managed policy is attached | `Cannot delete entity, must detach all policies first.` |
| An inline policy is embedded | `Cannot delete entity, must delete policies first.` |
The last two are a selection rather than one sentence for both: a managed policy is detached and an
inline one is deleted, so the remedy named is the one that clears what is actually there. That
selection is recorded on the role, the group and the user alike.
`DeleteRole` reads the three in the order of the table, and the first step of it is recorded too: a
role both held by an instance profile and carrying attached policies is refused for the profile,
which is the answer a cleanup loop needs, since detaching the policy changes nothing while the
pairing is there. Attached ahead of inline is the order `DeleteUser` already answered; which of
those two AWS names first for an entity carrying both is not recorded, so the role and the group
follow the user rather than differ from it.
This package used to read a role's attached and inline policies together and answer the detach
sentence for either, conflate them the same way on a group, word the instance profile's own
refusal itself, and let a role be deleted while a profile still held it. That last one is a
behavior change for a caller that deleted a role out from under a profile: the profile has to let
go of it first, and the refusal says so. Nothing takes a role out of a profile on the caller's
behalf, on AWS or here. That holds for the two callers that delete a role of their own, the
CloudFormation role provisioner and the Identity Center permission-set cleanup: each asks about the
profile before it clears the policies it owns, so a role it turns out it cannot delete keeps what it
had rather than being emptied by a delete that could not finish, and the refusal reaches the caller.
A stack that owns both resources deletes the profile before the role, since dependents go before
what they depend on.
### Access Keys
| Action | Description |
@@ -418,6 +418,10 @@ public class IamRoleCfnProvisioner implements CfnResourceProvisioner {
LOG.debugv("IAM role already gone, treating as deleted: {0}", physicalId);
return;
}
// Asked before anything is cleared: the delete can be refused for an instance profile
// this stack does not own, and nothing takes a role out of one on the caller's behalf, so
// detaching first would leave a role that is still there and no longer has its policies.
iamService.requireNotHeldByAnInstanceProfile(physicalId);
for (String policyArn : new ArrayList<>(role.getAttachedPolicyArns())) {
iamService.detachRolePolicy(physicalId, policyArn);
}
@@ -77,6 +77,7 @@ import java.util.Arrays;
import java.util.Base64;
import java.util.Collection;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
@@ -380,6 +381,19 @@ public class IamService implements SessionAccountLookup, ResourceProvider {
private static final String CREDENTIAL_REPORT_KEY = "credential-report";
/** AWS generates a fresh report only if the most recent one is older than this. */
private static final Duration CREDENTIAL_REPORT_MAX_AGE = Duration.ofHours(4);
/**
* The sentences AWS answers a blocked delete with, each of them entirely fixed text: no
* entity name, no count, nothing taken from the request. A cleanup routine reads the sentence
* to choose its next step (detach a managed policy, delete an inline one, or remove a role
* from its instance profile), so the wording is what names the dependency; one that describes
* the blocker instead sends the caller after the wrong remedy.
*/
private static final String MUST_DETACH_POLICIES_FIRST =
"Cannot delete entity, must detach all policies first.";
private static final String MUST_DELETE_POLICIES_FIRST =
"Cannot delete entity, must delete policies first.";
private static final String MUST_REMOVE_PROFILE_ROLES_FIRST =
"Cannot delete entity, must remove roles from instance profile first.";
public static final String FEATURE_ROOT_CREDENTIALS = "RootCredentialsManagement";
public static final String FEATURE_ROOT_SESSIONS = "RootSessions";
@@ -494,6 +508,16 @@ public class IamService implements SessionAccountLookup, ResourceProvider {
// Undo handles retain their ownership keys; completed attempts leave no permanent history.
// Both keys and values are weak because each owner itself holds its canonical key.
private final Map<InlinePolicyKey, WeakReference<InlinePolicyOwner>> inlinePolicyOwners = new WeakHashMap<>();
/**
* Which instance profiles hold each role, by storage scope then role name: the reverse of the
* list each profile carries, so a role delete asks a map instead of reading every profile in
* the account. The profiles stay the record and this is only an index into them, kept true by
* being written in the same two places a pairing is, both under {@code resourceNameLock},
* which is also the only lock under which it may be read. A scope is filled from storage the
* first time it is asked about, so profiles that were already there, from a restart or a
* store this process did not write, are in it before the first answer.
*/
private final Map<String, Map<String, Set<String>>> profilesByRole = new HashMap<>();
/**
* Guards every check-then-write on a login profile. ChangePassword is the reason it has to
* exist: it reads the profile to compare the old password, then writes the new one, so two
@@ -1015,8 +1039,7 @@ public class IamService implements SessionAccountLookup, ResourceProvider {
synchronized (resourceNameLock) {
IamUser user = getUser(userName);
if (!user.getAttachedPolicyArns().isEmpty()) {
throw new AwsException("DeleteConflict",
"Cannot delete entity, must detach all policies first.", 409);
throw new AwsException("DeleteConflict", MUST_DETACH_POLICIES_FIRST, 409);
}
if (!user.getGroupNames().isEmpty()) {
throw new AwsException("DeleteConflict",
@@ -1027,8 +1050,7 @@ public class IamService implements SessionAccountLookup, ResourceProvider {
"Cannot delete entity, must delete login profile first.", 409);
}
if (!user.getInlinePolicies().isEmpty()) {
throw new AwsException("DeleteConflict",
"Cannot delete entity, must delete policies first.", 409);
throw new AwsException("DeleteConflict", MUST_DELETE_POLICIES_FIRST, 409);
}
// The credential locks are held across the delete rather than just the checks:
// CreateAccessKey, UploadSigningCertificate and EnableMFADevice each confirm the user
@@ -1284,9 +1306,11 @@ public class IamService implements SessionAccountLookup, ResourceProvider {
public void deleteGroup(String groupName) {
synchronized (resourceNameLock) {
IamGroup group = getGroup(groupName);
if (!group.getAttachedPolicyArns().isEmpty() || !group.getInlinePolicies().isEmpty()) {
throw new AwsException("DeleteConflict",
"Cannot delete entity, must detach all policies first.", 409);
if (!group.getAttachedPolicyArns().isEmpty()) {
throw new AwsException("DeleteConflict", MUST_DETACH_POLICIES_FIRST, 409);
}
if (!group.getInlinePolicies().isEmpty()) {
throw new AwsException("DeleteConflict", MUST_DELETE_POLICIES_FIRST, 409);
}
if (!group.getUserNames().isEmpty()) {
throw new AwsException("DeleteConflict",
@@ -1603,22 +1627,111 @@ public class IamService implements SessionAccountLookup, ResourceProvider {
deleteRole(roleName, null);
}
/** A service cleanup must not delete a different role that has since taken the name. */
/**
* A service cleanup must not delete a different role that has since taken the name.
*
* <p>One dependency is named at a time, and which one comes first is part of what AWS was
* recorded answering: a role both held by an instance profile and carrying attached policies
* is refused for the profile. Attached policies ahead of inline ones is the order
* {@link #deleteUser} already answers; which of those two AWS reports first is not recorded.
*/
public void deleteRole(String roleName, String expectedRoleId) {
synchronized (resourceNameLock) {
validateRoleName(roleName);
IamRole role = getRole(roleName);
requireSameRole(role, roleName, expectedRoleId);
requireNotServiceLinked(role, roleName);
if (!role.getAttachedPolicyArns().isEmpty() || !role.getInlinePolicies().isEmpty()) {
throw new AwsException("DeleteConflict",
"Cannot delete entity, must detach all policies first.", 409);
if (heldByAnInstanceProfile(roleName)) {
throw new AwsException("DeleteConflict", MUST_REMOVE_PROFILE_ROLES_FIRST, 409);
}
if (!role.getAttachedPolicyArns().isEmpty()) {
throw new AwsException("DeleteConflict", MUST_DETACH_POLICIES_FIRST, 409);
}
if (!role.getInlinePolicies().isEmpty()) {
throw new AwsException("DeleteConflict", MUST_DELETE_POLICIES_FIRST, 409);
}
roles.delete(roleName);
LOG.infov("Deleted IAM role: {0}", roleName);
}
}
/**
* Whether any instance profile still holds the role. The role itself is not re-read, since
* the caller resolved it already and a delete must not answer that a role it just found is
* missing; the membership read takes the profile's own monitor, the one the pairing writes
* hold. It is reached under {@code resourceNameLock}, which the attach path now takes outside
* that monitor, so no pairing can land between this answer and the delete that asked for it.
*/
/**
* Refuses up front what {@link #deleteRole} refuses for an instance profile. A caller that
* clears a role's own policies before deleting it asks first: otherwise a role held by a
* profile it does not own is stripped of its permissions and then cannot be deleted, which
* leaves it live and weaker than it was. The pairing can still be made after this answers,
* and such a caller is no worse off then than it was before the delete checked at all.
*/
public void requireNotHeldByAnInstanceProfile(String roleName) {
synchronized (resourceNameLock) {
if (heldByAnInstanceProfile(roleName)) {
throw new AwsException("DeleteConflict", MUST_REMOVE_PROFILE_ROLES_FIRST, 409);
}
}
}
private boolean heldByAnInstanceProfile(String roleName) {
return !profilesHolding(roleName).isEmpty();
}
/** The profile names holding the role, in this request's storage scope. */
private Set<String> profilesHolding(String roleName) {
return pairingIndex().getOrDefault(roleName, Set.of());
}
/**
* The pairing index for the scope this request reads profiles in, filled from those profiles
* the first time the scope comes up. Callers hold {@code resourceNameLock}: the maps are
* plain ones, and what they hold has to agree with a storage write taken under that lock.
*/
private Map<String, Set<String>> pairingIndex() {
return profilesByRole.computeIfAbsent(instanceProfileScope(), scope -> {
Map<String, Set<String>> index = new HashMap<>();
for (InstanceProfile profile : instanceProfiles.scan(k -> true)) {
List<String> roleNames = profile.getRoleNames();
synchronized (roleNames) {
for (String roleName : roleNames) {
index.computeIfAbsent(roleName, name -> new HashSet<>())
.add(profile.getInstanceProfileName());
}
}
}
return index;
});
}
/**
* The account profiles are read in, or the empty string outside account-aware storage. The
* index is scoped exactly as {@code instanceProfiles} is, so one account's pairings are never
* read as another's.
*/
private String instanceProfileScope() {
if (instanceProfiles instanceof AccountAwareStorageBackend<InstanceProfile> aware) {
String accountId = aware.accountId();
return accountId == null ? "" : accountId;
}
return "";
}
private void indexPairing(String instanceProfileName, String roleName) {
pairingIndex().computeIfAbsent(roleName, name -> new HashSet<>()).add(instanceProfileName);
}
private void unindexPairing(String instanceProfileName, String roleName) {
Map<String, Set<String>> index = pairingIndex();
Set<String> holding = index.get(roleName);
if (holding != null && holding.remove(instanceProfileName) && holding.isEmpty()) {
index.remove(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
@@ -2956,12 +3069,18 @@ public class IamService implements SessionAccountLookup, ResourceProvider {
}
public void deleteInstanceProfile(String instanceProfileName) {
InstanceProfile profile = getInstanceProfile(instanceProfileName);
if (!profile.getRoleNames().isEmpty()) {
throw new AwsException("DeleteConflict",
"Cannot delete instance profile with associated roles.", 409);
// Decided under the lock the attach path takes, so a role cannot be paired between the
// membership read and the delete; the profile's own monitor guards the read itself.
synchronized (resourceNameLock) {
InstanceProfile profile = getInstanceProfile(instanceProfileName);
List<String> roleNames = profile.getRoleNames();
synchronized (roleNames) {
if (!roleNames.isEmpty()) {
throw new AwsException("DeleteConflict", MUST_REMOVE_PROFILE_ROLES_FIRST, 409);
}
instanceProfiles.delete(instanceProfileName);
}
}
instanceProfiles.delete(instanceProfileName);
}
public List<InstanceProfile> listInstanceProfiles(String pathPrefix) {
@@ -2972,39 +3091,52 @@ public class IamService implements SessionAccountLookup, ResourceProvider {
}
public void addRoleToInstanceProfile(String instanceProfileName, String roleName) {
validateRoleName(roleName);
InstanceProfile profile = getInstanceProfile(instanceProfileName);
requireNotServiceLinked(getRole(roleName), roleName);
List<String> roleNames = profile.getRoleNames();
synchronized (roleNames) {
if (!roleNames.contains(roleName)) {
if (!roleNames.isEmpty()) {
// The quota name is what says which of the operation's limits fired, and it is
// this one rather than a roles-per-profile quota, which AWS publishes nowhere.
throw new AwsException("LimitExceeded",
"Cannot exceed quota for InstanceSessionsPerInstanceProfile: 1", 409);
// The lock DeleteRole and DeleteInstanceProfile decide under, taken outside the profile's
// own monitor as every path here does, so this cannot pair a role with a profile while
// either delete is between reading the pairing and acting on what it read.
synchronized (resourceNameLock) {
validateRoleName(roleName);
InstanceProfile profile = getInstanceProfile(instanceProfileName);
requireNotServiceLinked(getRole(roleName), roleName);
List<String> roleNames = profile.getRoleNames();
synchronized (roleNames) {
if (!roleNames.contains(roleName)) {
if (!roleNames.isEmpty()) {
// The quota name is what says which of the operation's limits fired, and
// it is this one rather than a roles-per-profile quota, which AWS
// publishes nowhere.
throw new AwsException("LimitExceeded",
"Cannot exceed quota for InstanceSessionsPerInstanceProfile: 1", 409);
}
roleNames.add(roleName);
instanceProfiles.put(instanceProfileName, profile);
indexPairing(instanceProfileName, roleName);
}
roleNames.add(roleName);
instanceProfiles.put(instanceProfileName, profile);
}
}
}
public void removeRoleFromInstanceProfile(String instanceProfileName, String roleName) {
validateRoleName(roleName);
InstanceProfile profile = getInstanceProfile(instanceProfileName);
// Tolerates an already-deleted role that the profile still lists, so guard only what is
// still there; what the profile never held is a different case and AWS refuses it.
roles.get(roleName).ifPresent(role -> requireNotServiceLinked(role, roleName));
List<String> roleNames = profile.getRoleNames();
// Whether the pairing is there and the removal of it are one decision, taken on the
// monitor the attach path holds, so a concurrent attach cannot land between them.
synchronized (roleNames) {
if (!roleNames.remove(roleName)) {
throw new AwsException("NoSuchEntity", "Role " + roleName + " in Instance Profile "
+ instanceProfileName + " cannot be found.", 404);
// The lock the attach and the two deletes decide under, outside the profile's own monitor
// as they all take it: the pairing index is written here and read by DeleteRole, and both
// have to see the same thing the profile's own list says.
synchronized (resourceNameLock) {
validateRoleName(roleName);
InstanceProfile profile = getInstanceProfile(instanceProfileName);
// Tolerates an already-deleted role that the profile still lists, so guard only what
// is still there; what the profile never held is a different case and AWS refuses it.
roles.get(roleName).ifPresent(role -> requireNotServiceLinked(role, roleName));
List<String> roleNames = profile.getRoleNames();
// Whether the pairing is there and the removal of it are one decision, taken on the
// monitor the attach path holds, so a concurrent attach cannot land between them.
synchronized (roleNames) {
if (!roleNames.remove(roleName)) {
throw new AwsException("NoSuchEntity", "Role " + roleName + " in Instance Profile "
+ instanceProfileName + " cannot be found.", 404);
}
instanceProfiles.put(instanceProfileName, profile);
unindexPairing(instanceProfileName, roleName);
}
instanceProfiles.put(instanceProfileName, profile);
}
}
@@ -135,6 +135,10 @@ public class SsoPermissionSetRoleProvisioner {
RequestScopes.runAs(provisioning.accountId(), region, () -> {
IamRole role = findRole(provisioning);
if (role != null && ownsRole(provisioning, role)) {
// Asked before the policies go: a role an instance profile holds cannot be
// deleted, and emptying it first would leave the assignment's role in place
// with nothing on it.
iam.requireNotHeldByAnInstanceProfile(role.getRoleName());
iam.replaceRolePolicies(role.getRoleName(), role.getRoleId(), List.of(), Map.of(), null, 0);
iam.deleteRole(role.getRoleName(), role.getRoleId());
}
@@ -648,6 +648,33 @@ class IamRoleCfnProvisionerTest {
order.verify(iam).deleteRole("app-role");
}
/**
* A role an instance profile still holds refuses the delete, and that refusal reaches the
* stack rather than being swallowed: AWS answers the same way, and taking a role out of a
* profile this stack may not own is not the provisioner's to do. It is asked before anything
* is cleared, so the role that stays keeps the policies it had rather than being emptied by a
* delete that could not finish.
*/
@Test
void deleteLetsAnInstanceProfileConflictReachTheStackWithNothingCleared() {
IamRole role = new IamRole("AROAheld-role", "held-role", "/",
"arn:aws:iam::" + ACCOUNT_ID + ":role/held-role", EMPTY_TRUST);
role.getAttachedPolicyArns().add("arn:aws:iam::aws:policy/ReadOnlyAccess");
role.getInlinePolicies().put("bucket-read", EMPTY_TRUST);
when(iam.getRole("held-role")).thenReturn(role);
doThrow(new AwsException("DeleteConflict",
"Cannot delete entity, must remove roles from instance profile first.", 409))
.when(iam).requireNotHeldByAnInstanceProfile("held-role");
AwsException refused = assertThrows(AwsException.class,
() -> provisioner.delete("AWS::IAM::Role", "held-role", "us-east-1"));
assertEquals("DeleteConflict", refused.getErrorCode());
verify(iam, never()).detachRolePolicy(anyString(), anyString());
verify(iam, never()).deleteRolePolicy(anyString(), anyString());
verify(iam, never()).deleteRole(anyString());
}
@Test
void deleteTreatsAnAlreadyMissingRoleAsDeleted() {
when(iam.getRole("gone-role")).thenThrow(new AwsException("NoSuchEntity", "gone", 404));
@@ -0,0 +1,254 @@
package io.floci.aws.services.iam;
import io.floci.aws.testing.PartitionCleanup;
import io.quarkus.test.junit.QuarkusTest;
import io.restassured.specification.RequestSpecification;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.anyOf;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.is;
/**
* Which dependency a blocked delete names, and in the sentence AWS was recorded answering. Three
* sentences cover the four refusals: an instance profile still holding the role, a managed policy
* that has to be detached, and an inline policy that has to be deleted. Each is entirely fixed
* text, so a caller reading it to pick its next step gets the dependency that is actually there.
*
* <p>{@code docs/services/iam.md} carries the recordings and says which part of the ordering is a
* reading rather than one of them.
*/
@QuarkusTest
class IamDeleteConflictDependencyIntegrationTest {
private static final String IAM_AUTH =
"AWS4-HMAC-SHA256 Credential=test/20261122/us-east-1/iam/aws4_request";
private static final String CODE = "ErrorResponse.Error.Code";
private static final String MESSAGE = "ErrorResponse.Error.Message";
private static final String MUST_DETACH_POLICIES =
"Cannot delete entity, must detach all policies first.";
private static final String MUST_DELETE_POLICIES =
"Cannot delete entity, must delete policies first.";
private static final String MUST_REMOVE_PROFILE_ROLES =
"Cannot delete entity, must remove roles from instance profile first.";
private static final String TRUST_POLICY = "{\"Version\":\"2012-10-17\",\"Statement\":"
+ "[{\"Effect\":\"Allow\",\"Principal\":{\"Service\":\"ec2.amazonaws.com\"},"
+ "\"Action\":\"sts:AssumeRole\"}]}";
private static final String PERMISSION_POLICY = "{\"Version\":\"2012-10-17\",\"Statement\":"
+ "[{\"Effect\":\"Allow\",\"Action\":\"s3:GetObject\",\"Resource\":\"*\"}]}";
@RegisterExtension
final PartitionCleanup cleanup = new PartitionCleanup();
/**
* What a teardown step accepts. A test here may clear a dependency itself, to show the delete
* going through once it is gone, so a resource that is already absent is the step's work
* already done rather than a leak. Anything else, a refusal above all, still reports.
*/
private static void cleared(RequestSpecification request) {
request.when().post("/").then().statusCode(anyOf(is(200), is(404)));
}
private static RequestSpecification iam(String action) {
return given().header("Authorization", IAM_AUTH).formParam("Action", action);
}
private static String unique(String prefix) {
return prefix + "-" + Long.toString(System.nanoTime(), 36);
}
private String createRole() {
String roleName = unique("conflict-role");
iam("CreateRole").formParam("RoleName", roleName)
.formParam("AssumeRolePolicyDocument", TRUST_POLICY)
.when().post("/").then().statusCode(200);
cleanup.register(() -> cleared(iam("DeleteRole").formParam("RoleName", roleName)));
return roleName;
}
private String createGroup() {
String groupName = unique("conflict-group");
iam("CreateGroup").formParam("GroupName", groupName)
.when().post("/").then().statusCode(200);
cleanup.register(() -> cleared(iam("DeleteGroup").formParam("GroupName", groupName)));
return groupName;
}
private String createUser() {
String userName = unique("conflict-user");
iam("CreateUser").formParam("UserName", userName)
.when().post("/").then().statusCode(200);
cleanup.register(() -> cleared(iam("DeleteUser").formParam("UserName", userName)));
return userName;
}
private String pairedProfile(String roleName) {
String profileName = unique("conflict-profile");
iam("CreateInstanceProfile").formParam("InstanceProfileName", profileName)
.when().post("/").then().statusCode(200);
cleanup.register(() -> cleared(iam("DeleteInstanceProfile")
.formParam("InstanceProfileName", profileName)));
iam("AddRoleToInstanceProfile").formParam("InstanceProfileName", profileName)
.formParam("RoleName", roleName).when().post("/").then().statusCode(200);
cleanup.register(() -> cleared(iam("RemoveRoleFromInstanceProfile")
.formParam("InstanceProfileName", profileName).formParam("RoleName", roleName)));
return profileName;
}
private String managedPolicy() {
String arn = iam("CreatePolicy").formParam("PolicyName", unique("conflict-policy"))
.formParam("PolicyDocument", PERMISSION_POLICY)
.when().post("/").then().statusCode(200)
.extract().xmlPath().getString("CreatePolicyResponse.CreatePolicyResult.Policy.Arn");
cleanup.register(() -> cleared(iam("DeletePolicy").formParam("PolicyArn", arn)));
return arn;
}
private String attachToRole(String roleName) {
return attach("AttachRolePolicy", "DetachRolePolicy", "RoleName", roleName);
}
private String attachToGroup(String groupName) {
return attach("AttachGroupPolicy", "DetachGroupPolicy", "GroupName", groupName);
}
/** Attaches a managed policy to the entity and hands back its ARN. */
private String attach(String action, String undo, String param, String entityName) {
String arn = managedPolicy();
iam(action).formParam(param, entityName).formParam("PolicyArn", arn)
.when().post("/").then().statusCode(200);
cleanup.register(() -> cleared(
iam(undo).formParam(param, entityName).formParam("PolicyArn", arn)));
return arn;
}
private String inlineOnRole(String roleName) {
return putInline("PutRolePolicy", "DeleteRolePolicy", "RoleName", roleName);
}
/** Embeds an inline policy in the entity and hands back its name. */
private String putInline(String action, String undo, String param, String entityName) {
String policyName = unique("conflict-inline");
iam(action).formParam(param, entityName).formParam("PolicyName", policyName)
.formParam("PolicyDocument", PERMISSION_POLICY)
.when().post("/").then().statusCode(200);
cleanup.register(() -> cleared(iam(undo).formParam(param, entityName)
.formParam("PolicyName", policyName)));
return policyName;
}
/** The role an instance profile holds: the caller is told to take it out of the profile. */
@Test
void aRoleAnInstanceProfileHoldsNamesTheProfile() {
String roleName = createRole();
pairedProfile(roleName);
iam("DeleteRole").formParam("RoleName", roleName)
.when().post("/").then().statusCode(409)
.body(CODE, equalTo("DeleteConflict"))
.body(MESSAGE, equalTo(MUST_REMOVE_PROFILE_ROLES));
}
/** The profile holding it is refused with the same sentence, which is AWS's for both ends. */
@Test
void theProfileHoldingARoleCarriesTheSameSentence() {
String profileName = pairedProfile(createRole());
iam("DeleteInstanceProfile").formParam("InstanceProfileName", profileName)
.when().post("/").then().statusCode(409)
.body(CODE, equalTo("DeleteConflict"))
.body(MESSAGE, equalTo(MUST_REMOVE_PROFILE_ROLES));
}
/**
* Both dependencies at once: the profile is reported, which is the precedence AWS was recorded
* answering and the one a cleanup loop needs, since detaching the policy changes nothing here.
*/
@Test
void theProfileIsNamedAheadOfTheAttachedPolicy() {
String roleName = createRole();
pairedProfile(roleName);
attachToRole(roleName);
iam("DeleteRole").formParam("RoleName", roleName)
.when().post("/").then().statusCode(409)
.body(MESSAGE, equalTo(MUST_REMOVE_PROFILE_ROLES));
}
/** A managed policy is detached, and the sentence says so. */
@Test
void aRoleCarryingAManagedPolicyAsksForADetach() {
String roleName = createRole();
attachToRole(roleName);
iam("DeleteRole").formParam("RoleName", roleName)
.when().post("/").then().statusCode(409)
.body(CODE, equalTo("DeleteConflict"))
.body(MESSAGE, equalTo(MUST_DETACH_POLICIES));
}
/** An inline policy is deleted rather than detached, and the sentence says that instead. */
@Test
void aRoleCarryingAnInlinePolicyAsksForADelete() {
String roleName = createRole();
inlineOnRole(roleName);
iam("DeleteRole").formParam("RoleName", roleName)
.when().post("/").then().statusCode(409)
.body(CODE, equalTo("DeleteConflict"))
.body(MESSAGE, equalTo(MUST_DELETE_POLICIES));
}
/** The group keeps the detach sentence for a managed policy, as the user already does. */
@Test
void aGroupCarryingAManagedPolicyAsksForADetach() {
String groupName = createGroup();
attachToGroup(groupName);
iam("DeleteGroup").formParam("GroupName", groupName)
.when().post("/").then().statusCode(409)
.body(CODE, equalTo("DeleteConflict"))
.body(MESSAGE, equalTo(MUST_DETACH_POLICIES));
}
/** The group's inline policy is a delete, the remedy that actually clears it. */
@Test
void aGroupCarryingAnInlinePolicyAsksForADelete() {
String groupName = createGroup();
putInline("PutGroupPolicy", "DeleteGroupPolicy", "GroupName", groupName);
iam("DeleteGroup").formParam("GroupName", groupName)
.when().post("/").then().statusCode(409)
.body(CODE, equalTo("DeleteConflict"))
.body(MESSAGE, equalTo(MUST_DELETE_POLICIES));
}
/** The user path is the model the other two follow, and it answers what it already did. */
@Test
void aUserCarryingAnInlinePolicyStillAsksForADelete() {
String userName = createUser();
putInline("PutUserPolicy", "DeleteUserPolicy", "UserName", userName);
iam("DeleteUser").formParam("UserName", userName)
.when().post("/").then().statusCode(409)
.body(CODE, equalTo("DeleteConflict"))
.body(MESSAGE, equalTo(MUST_DELETE_POLICIES));
}
/** The control: every dependency cleared in the order the refusals asked for, and it goes. */
@Test
void theRoleGoesOnceEachDependencyNamedIsCleared() {
String roleName = createRole();
String profileName = pairedProfile(roleName);
String policyArn = attachToRole(roleName);
String inlineName = inlineOnRole(roleName);
iam("RemoveRoleFromInstanceProfile").formParam("InstanceProfileName", profileName)
.formParam("RoleName", roleName).when().post("/").then().statusCode(200);
iam("DeleteInstanceProfile").formParam("InstanceProfileName", profileName)
.when().post("/").then().statusCode(200);
iam("DetachRolePolicy").formParam("RoleName", roleName).formParam("PolicyArn", policyArn)
.when().post("/").then().statusCode(200);
iam("DeleteRolePolicy").formParam("RoleName", roleName).formParam("PolicyName", inlineName)
.when().post("/").then().statusCode(200);
iam("DeleteRole").formParam("RoleName", roleName).when().post("/").then().statusCode(200);
}
}
@@ -13,8 +13,8 @@ import static org.hamcrest.Matchers.is;
/**
* What the instance profile pair refuses, in the sentences AWS was recorded answering: a second
* role names the quota that fired, and removing a role the profile never held is a 404 rather than
* a quiet success.
* role names the quota that fired, removing a role the profile never held is a 404 rather than a
* quiet success, and the role a profile holds goes only after the pairing does.
*
* <p>{@code docs/services/iam.md} carries the recordings.
*/
@@ -97,14 +97,16 @@ class IamInstanceProfileRefusalIntegrationTest {
}
/**
* A role deleted while the profile still lists it stays removable, which is the case the
* tolerance was there for and is not the one AWS refuses. The role goes first and the pairing
* after it, so the removal is the one that reaches a profile listing a role that is not there.
* The pairing goes before the role does, which is what puts the state the removal tolerates
* (a profile listing a role that is no longer there) out of reach of anything served: the
* delete is refused while the profile holds the role, and succeeds once it does not. The
* tolerance stays for state reached another way, and the sentence the refusal carries is
* covered with the other three in {@link IamDeleteConflictDependencyIntegrationTest}.
*/
@Test
void aRoleDeletedWhileStillListedStaysRemovable() {
void theRoleAProfileHoldsGoesOnlyAfterThePairing() {
String profileName = createProfile();
String roleName = unique("profile-ghost-role");
String roleName = unique("profile-paired-role");
iam("CreateRole").formParam("RoleName", roleName)
.formParam("AssumeRolePolicyDocument", TRUST_POLICY)
.when().post("/").then().statusCode(200);
@@ -116,9 +118,11 @@ class IamInstanceProfileRefusalIntegrationTest {
.formParam("InstanceProfileName", profileName)
.formParam("RoleName", roleName)
.when().post("/").then().statusCode(anyOf(is(200), is(404))));
iam("DeleteRole").formParam("RoleName", roleName).when().post("/").then().statusCode(200);
iam("DeleteRole").formParam("RoleName", roleName).when().post("/").then().statusCode(409)
.body(CODE, equalTo("DeleteConflict"));
iam("RemoveRoleFromInstanceProfile").formParam("InstanceProfileName", profileName)
.formParam("RoleName", roleName).when().post("/").then().statusCode(200);
iam("DeleteRole").formParam("RoleName", roleName).when().post("/").then().statusCode(200);
}
/** The control: the first role still attaches, and removing it still succeeds. */
@@ -2939,6 +2939,59 @@ class IamServiceTest {
assertEquals("P1", profiles.getFirst().getInstanceProfileName());
}
/**
* A role delete asks which profiles hold the role rather than reading every profile in the
* account, so clearing out many roles while many profiles are about costs one lookup each and
* still refuses exactly the role that is paired.
*/
@Test
void deletingManyRolesWithManyProfilesRefusesOnlyThePairedOne() {
for (int i = 0; i < 40; i++) {
iamService.createInstanceProfile("BulkProfile" + i, "/");
iamService.createRole("BulkRole" + i, "/", EMPTY_POLICY_DOCUMENT, null, 0, null);
}
iamService.addRoleToInstanceProfile("BulkProfile7", "BulkRole7");
for (int i = 0; i < 40; i++) {
if (i != 7) {
iamService.deleteRole("BulkRole" + i);
}
}
assertEquals("DeleteConflict", assertThrows(AwsException.class,
() -> iamService.deleteRole("BulkRole7")).getErrorCode());
iamService.removeRoleFromInstanceProfile("BulkProfile7", "BulkRole7");
iamService.deleteRole("BulkRole7");
}
/**
* A pairing the store already carried is seen by a service that did not write it: the lookup
* is filled from the profiles it finds, so a restart does not make a held role deletable.
*/
@Test
void aPairingAlreadyInStorageStillBlocksTheDelete() {
StorageBackend<String, IamRole> roles = new InMemoryStorage<>();
StorageBackend<String, InstanceProfile> profiles = new InMemoryStorage<>();
IamService before = iamServiceOn(roles, profiles);
before.createRole("CarriedRole", "/", EMPTY_POLICY_DOCUMENT, null, 0, null);
before.createInstanceProfile("CarriedProfile", "/");
before.addRoleToInstanceProfile("CarriedProfile", "CarriedRole");
IamService after = iamServiceOn(roles, profiles);
assertEquals("DeleteConflict", assertThrows(AwsException.class,
() -> after.deleteRole("CarriedRole")).getErrorCode());
after.removeRoleFromInstanceProfile("CarriedProfile", "CarriedRole");
after.deleteRole("CarriedRole");
}
private static IamService iamServiceOn(StorageBackend<String, IamRole> roles,
StorageBackend<String, InstanceProfile> instanceProfiles) {
return new IamService(new InMemoryStorage<>(), new InMemoryStorage<>(), roles, new InMemoryStorage<>(),
new InMemoryStorage<>(), instanceProfiles, new InMemoryStorage<>(),
new RegionResolver("us-east-1", "000000000000"), false);
}
// =========================================================================
// AWS Managed Policy Seeding
// =========================================================================
@@ -28,6 +28,7 @@ import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.ArgumentMatchers.isNull;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoInteractions;
@@ -109,6 +110,27 @@ class SsoPermissionSetRoleProvisionerTest {
assertEquals(List.of(cleanupFailure), List.of(thrown.getSuppressed()));
}
/**
* Removing an assignment empties the role before deleting it, so a role an instance profile
* holds has to be refused before that: otherwise the delete it cannot finish would leave the
* assignment's role in place with nothing on it.
*/
@Test
void anAssignmentWhoseRoleAProfileHoldsKeepsItsPolicies() {
PermissionSetProvisioning provisioning = new PermissionSetProvisioning("permission-set", ACCOUNT, STATUS,
ARN, "role-id");
when(iam.findRole(ACCOUNT, NAME)).thenReturn(Optional.of(new IamRole("role-id", NAME, PATH, ARN, "{}")));
doThrow(new AwsException("DeleteConflict",
"Cannot delete entity, must remove roles from instance profile first.", 409))
.when(iam).requireNotHeldByAnInstanceProfile(NAME);
assertEquals("DeleteConflict", assertThrows(AwsException.class,
() -> provisioner.remove(provisioning, "us-east-1")).getErrorCode());
verify(iam, never()).replaceRolePolicies(anyString(), anyString(), any(), any(), any(), anyInt());
verify(iam, never()).deleteRole(anyString(), anyString());
}
@Test
void provisioningJsonPreservesRoleIdentityAndAcceptsLegacyRecords() throws Exception {
ObjectMapper mapper = new ObjectMapper();
@@ -278,14 +278,23 @@ public final class EnforcementFixtures {
}
/**
* Deletes a role, and first the policies it carries: Floci answers {@code DeleteConflict},
* "must detach all policies first", for a role holding either an inline or a managed one.
* Deletes a role, and first what IAM wants gone before it will: any instance profile holding
* it, then its managed attachments and its inline policies. Each of those is refused with its
* own {@code DeleteConflict} sentence, and the profile is reported ahead of the policies, so a
* teardown that left one in place would be told to remedy something else.
*/
public static void removeRole(int port, String authorization, String roleName) {
if (iam(port, authorization, "GetRole", "RoleName", roleName)
.extract().statusCode() == 404) {
return;
}
for (String profileName : iam(port, authorization, "ListInstanceProfilesForRole",
"RoleName", roleName).statusCode(200).extract().xmlPath()
.getList("ListInstanceProfilesForRoleResponse.ListInstanceProfilesForRoleResult"
+ ".InstanceProfiles.member.InstanceProfileName", String.class)) {
iam(port, authorization, "RemoveRoleFromInstanceProfile",
"InstanceProfileName", profileName, "RoleName", roleName).statusCode(200);
}
for (String policyName : iam(port, authorization, "ListRolePolicies", "RoleName", roleName)
.statusCode(200).extract().xmlPath()
.getList("ListRolePoliciesResponse.ListRolePoliciesResult.PolicyNames.member",