fix(iam): refuse a managed policy delete that leaves versions behind (#9224)

DeletePolicy read the attachment count alone, so a policy carrying a version
beside its default was deleted along with its history and answered nothing.
AWS refuses that delete with DeleteConflict 409 and three sentences of
wholly fixed text, "This policy has more than one version. Before you delete a
policy, you must delete the policy's versions. The default version is deleted
with the policy.", recorded against a real account on 2026-10-29, and the
operation's published description asks a caller for the same two steps:
detach the policy from every user, group and role, then delete all of the
policy's versions.

The refusal reports an attachment first and the versions second, the order
those steps are written in. Which of the two AWS names for a policy carrying
both is not recorded, so the page marks that order as this package's reading
rather than a recording, as it already does for attached ahead of inline.

Nothing clears those versions on the caller's behalf, on AWS or here, so
whoever wants the policy gone deletes them first. The CloudFormation
provisioner for AWS::IAM::ManagedPolicy owns the policies its stacks create
and publishes the new document as a new default version on every update, which
leaves the version before it stored: the delete that brings such a stack down
clears the other versions ahead of the policy, in the order the published
steps give, so a stack cannot end up able to create and update a policy it can
never take down again. The clearing asks the attachment question before a
single version goes and answers it with the sentence the delete would, so a
policy a principal the stack never recorded still holds keeps its history
instead of spending it on a delete that was going to be refused anyway.

The reads a delete decides on and the delete itself are under the lock every
other IAM write takes, which the writes to a policy's versions now take as
well, so a version published between the count and the delete is no longer
deleted along with the policy it was added to, and the write back that ends a
clearing cannot restore a policy another caller deleted in between. Inside it
the version map keeps its own monitor, and SetDefaultPolicyVersion moves the
default version id under that monitor beside the flags it already set there:
between those two writes a clearing would have read the id this call had just
replaced and dropped the version it had just made default.

Covered over the API by the refusal, its precedence over the attachment and
the control that deletes the other version and then the policy; at the service
level by the clearing that keeps the default with its document, the attachment
that refuses it with every version intact, and the version a SetDefault just
chose being the one kept; by a trial loop over a delete racing a version
publish; on the provisioner by the order its delete asks for; and end to end by
a stack that is created, updated and then deleted, with the policy gone after
it. One test fixture published a second version and tore the policy down with
one call, which the refusal now blocks, so it deletes that version first.
This commit is contained in:
Priamo Germosen authored and GitHub committed 2026-11-22 17:20:50 -04:00
1 parent d4af2a836e
commit 942cace935
9 files changed
+508 -85

No files matched your search

+29 -6
View File
@@ -706,10 +706,10 @@ 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
one dependency the caller has to clear. The five 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.
no entity name, no count, no version id, 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 |
| --- | --- |
@@ -717,10 +717,11 @@ a description, because a cleanup loop reads it to choose what to do next.
| 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.` |
| A managed policy has a version beside its default | `This policy has more than one version. Before you delete a policy, you must delete the policy's versions. The default version is deleted with the policy.` |
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.
The managed and inline rows 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,
@@ -729,6 +730,16 @@ pairing is there. Attached ahead of inline is the order `DeleteUser` already ans
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.
The last row is a policy's own delete rather than an entity's, and the one sentence of the five
that is three: a managed policy carrying a version beside its default is refused until the other
versions are deleted, and the text closes by saying the default is not one of them, which is the
same version `DeletePolicyVersion` refuses. `DeletePolicy` reports an attachment first and the
versions second, the order AWS's own steps for deleting a managed policy are written in, detach the
policy from every user, group and role and then delete all versions of the policy. Which of the two
AWS names for a policy carrying both is not recorded, so that order is this package's reading. The
attachment count was all a delete here read, so a policy with a version history went with the
history and answered nothing, leaving a caller that had skipped a published step no sign of 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
@@ -741,6 +752,18 @@ had rather than being emptied by a delete that could not finish, and the refusal
A stack that owns both resources deletes the profile before the role, since dependents go before
what they depend on.
Nothing clears a managed policy's versions on the caller's behalf, which is the behavior change for
a caller that deleted a versioned policy in one call: the versions go first, through
`ListPolicyVersions` and `DeletePolicyVersion`, which is the loop AWS publishes for it. Floci's own
CloudFormation provisioner for `AWS::IAM::ManagedPolicy` does that before it deletes a policy its
stack owns, since every update of such a policy publishes the new document as a new default version
and leaves the version before it stored: a delete that cleared nothing would leave a stack able to
create and update a policy it could never take down again. The clearing asks the attachment
question first and answers it with the sentence the delete would, so a policy that some principal
the stack never recorded still holds keeps its history instead of spending it on a delete that was
going to be refused anyway. That is the published order again: detach, then the versions, then the
policy.
### Access Keys
| Action | Description |
@@ -80,9 +80,11 @@ final class IamManagedPolicyDeletes {
}
/**
* Detaches the policy from every target, then deletes it. Deletion is idempotent: a principal,
* attachment or the policy itself already being gone (NoSuchEntity) is tolerated, while a
* permission or service failure propagates so the stack stays DELETE_FAILED.
* Detaches the policy from every target, clears the versions its updates left behind and then
* deletes it, which is the order AWS's own steps for deleting a managed policy give. Deletion
* is idempotent: a principal, attachment or the policy itself already being gone
* (NoSuchEntity) is tolerated, while a permission or service failure propagates so the stack
* stays DELETE_FAILED.
*/
static void detachAndDeletePolicy(IamService iamService, StackResource resource) {
String policyArn = resource.getPhysicalId();
@@ -134,9 +136,16 @@ final class IamManagedPolicyDeletes {
}
}
/** Deletes the policy, tolerating one already gone. */
/**
* Clears the versions AWS asks a caller to clear and then deletes the policy, tolerating one
* already gone. Every update of a stack-owned policy publishes the new document as a new
* default version and leaves the version before it stored, and IAM refuses to delete a policy
* that still has one, so a delete that cleared nothing would leave a stack able to create and
* update a policy it could never take down again.
*/
static void deletePolicyTolerating(IamService iamService, String policyArn) {
try {
iamService.clearNonDefaultPolicyVersions(policyArn);
iamService.deletePolicy(policyArn);
} catch (AwsException e) {
if (!"NoSuchEntity".equals(e.getErrorCode())) {
@@ -394,6 +394,22 @@ public class IamService implements SessionAccountLookup, ResourceProvider {
"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.";
/**
* What a managed policy's own delete is refused with while a version other than its default
* is still stored, three sentences of entirely fixed text: no ARN, no version id, no count.
* The last of them tells the caller what not to go looking for, the default version being
* the one version a delete takes with it and the one {@code DeletePolicyVersion} refuses.
*/
private static final String MUST_DELETE_POLICY_VERSIONS_FIRST =
"This policy has more than one version. Before you delete a policy, you must delete"
+ " the policy's versions. The default version is deleted with the policy.";
/**
* What a managed policy delete answers while an entity still has it attached, Floci's own
* wording rather than a recording. It is also what clearing the policy's other versions
* answers, since the clearing is only ever on the way to the delete.
*/
private static final String POLICY_STILL_ATTACHED =
"Cannot delete a policy attached to entities. Detach it first.";
public static final String FEATURE_ROOT_CREDENTIALS = "RootCredentialsManagement";
public static final String FEATURE_ROOT_SESSIONS = "RootSessions";
@@ -2171,15 +2187,93 @@ public class IamService implements SessionAccountLookup, ResourceProvider {
}
}
/**
* Deletes a customer-managed policy, which AWS does only once nothing is left on it: no
* entity attached to it, and no version beside the default one the delete takes with it. A
* policy an update published a new document for still holds the document before it, and that
* is enough to refuse the delete, so whoever wants the policy gone clears those versions
* first; {@link #clearNonDefaultPolicyVersions} is what Floci's own stacks do it with.
*
* <p>Which dependency a policy carrying both is told about follows the order AWS's own steps
* for deleting a managed policy are written in, the attachments and then the versions. That
* order is a reading rather than a recording, and {@code docs/services/iam.md} says so.
*
* <p>Both reads and the delete they decide are under {@code resourceNameLock}, which every
* write to a policy's versions and attachments takes as well: a version published between the
* count and the delete would otherwise be deleted along with the policy it was added to.
*/
public void deletePolicy(String policyArn) {
rejectIfAwsManaged(policyArn);
IamPolicy policy = getPolicy(policyArn);
if (policy.getAttachmentCount() > 0) {
throw new AwsException("DeleteConflict",
"Cannot delete a policy attached to entities. Detach it first.", 409);
synchronized (resourceNameLock) {
rejectIfAwsManaged(policyArn);
IamPolicy policy = getPolicy(policyArn);
if (policy.getAttachmentCount() > 0) {
throw new AwsException("DeleteConflict", POLICY_STILL_ATTACHED, 409);
}
if (hasAVersionBesideItsDefault(policy)) {
throw new AwsException("DeleteConflict", MUST_DELETE_POLICY_VERSIONS_FIRST, 409);
}
policies.delete(policyArn);
LOG.infov("Deleted IAM policy: {0}", policyArn);
}
}
/**
* Whether the policy holds anything besides the version a delete would take with it. Every
* policy carries a default version from the moment it is created and nothing can delete that
* one on its own, so a second version is exactly what an unfinished cleanup leaves behind.
*/
private static boolean hasAVersionBesideItsDefault(IamPolicy policy) {
Map<String, PolicyVersion> versions = policy.getVersions();
synchronized (versions) {
return versions.size() > 1;
}
}
/**
* Drops every version of a managed policy but its default, the work AWS leaves to whoever
* wants the policy deleted: {@link #deletePolicy} refuses while another version is stored and
* no IAM operation clears them in one go. Floci's CloudFormation provisioners own the
* policies their stacks created and publish a new default version on every update, so this is
* how such a stack takes its own policy down. It is refused while an entity still has the
* policy attached, with the sentence that delete would answer: the history is worth keeping
* for a delete that cannot go through anyway, and AWS's own steps detach before they clear.
*
* <p>The whole of it is under {@code resourceNameLock}, as the delete it leads to and every
* write to a policy's versions are, so the write back cannot resurrect a policy another
* caller deleted in between. The default is read and the rest dropped under the version map's
* own monitor as well, so a version published while this runs is either kept as the new
* default or dropped with the old ones, never deleted as a leftover of a default it has
* itself replaced.
*/
public void clearNonDefaultPolicyVersions(String policyArn) {
synchronized (resourceNameLock) {
rejectIfAwsManaged(policyArn);
IamPolicy policy = requirePolicy(policyArn, PolicyNotFound.ATTACHABLE);
// Asked before a single version goes. The delete this clears the way for is refused
// while anything still has the policy attached, a principal the caller never recorded
// included, and a clearing that ran first would have spent the history on a delete
// that was never going to happen. It is the published order too: detach, then the
// versions, then the policy.
if (policy.getAttachmentCount() > 0) {
throw new AwsException("DeleteConflict", POLICY_STILL_ATTACHED, 409);
}
Map<String, PolicyVersion> versions = policy.getVersions();
boolean cleared;
synchronized (versions) {
String defaultVersionId = policy.getDefaultVersionId();
// No default recorded at all: a policy from a store this version of Floci did not
// write. Dropping every version would leave the policy with no document to serve.
if (defaultVersionId == null) {
return;
}
cleared = versions.keySet()
.removeIf(versionId -> !versionId.equals(defaultVersionId));
}
if (cleared) {
policies.put(policyArn, policy);
LOG.infov("Cleared the non-default versions of IAM policy: {0}", policyArn);
}
}
policies.delete(policyArn);
LOG.infov("Deleted IAM policy: {0}", policyArn);
}
/** The roles, users and groups a managed policy is currently attached to. */
@@ -2334,46 +2428,50 @@ public class IamService implements SessionAccountLookup, ResourceProvider {
if (heldToBeingAPolicy) {
IamPolicyDocuments.checkManagedPolicy(document);
}
rejectIfAwsManaged(policyArn);
IamPolicy policy = requirePolicy(policyArn, PolicyNotFound.ATTACHABLE);
Map<String, PolicyVersion> versions = policy.getVersions();
PolicyVersion version;
synchronized (versions) {
if (versions.size() >= 5) {
throw new AwsException("LimitExceeded",
"A managed policy can have up to 5 versions.", 409);
synchronized (resourceNameLock) {
// Under the lock a policy delete reads the version count with, so a version
// cannot be added between that read and the delete it decides.
rejectIfAwsManaged(policyArn);
IamPolicy policy = requirePolicy(policyArn, PolicyNotFound.ATTACHABLE);
Map<String, PolicyVersion> versions = policy.getVersions();
PolicyVersion version;
synchronized (versions) {
if (versions.size() >= 5) {
throw new AwsException("LimitExceeded",
"A managed policy can have up to 5 versions.", 409);
}
// AWS version ids are monotonic and never reissued after a DeletePolicyVersion.
// The live keys' own max is only a floor, not the source of truth: deleting the
// highest-numbered surviving version would otherwise let a "derive from what's left"
// computation reissue its id. The stored high-water mark is the real counter.
int highestSurviving = versions.keySet().stream()
.mapToInt(id -> Integer.parseInt(id.substring(1)))
.max().orElse(0);
int nextVersionNum;
if (policy.getNextVersionNumber() == null) {
// A policy persisted before this field existed: the live-key floor alone can't
// reveal a version deleted before this field was ever recorded (e.g. v1-v4 live
// after a pre-migration DeletePolicyVersion("v5")). Since a policy can never hold
// more than 5 concurrent versions, no more than 5 stacked deletions could have
// happened at the top between two persists; jump the counter past that worst
// case rather than trust the live keys' max + 1 for an unknown history.
nextVersionNum = highestSurviving + 1 + 5;
} else {
nextVersionNum = Math.max(policy.getNextVersionNumber(), highestSurviving + 1);
}
String versionId = "v" + nextVersionNum;
version = new PolicyVersion(versionId, document, setAsDefault);
if (setAsDefault) {
versions.values().forEach(v -> v.setDefaultVersion(false));
policy.setDefaultVersionId(versionId);
}
versions.put(versionId, version);
policy.setNextVersionNumber(nextVersionNum + 1);
}
// AWS version ids are monotonic and never reissued after a DeletePolicyVersion.
// The live keys' own max is only a floor, not the source of truth: deleting the
// highest-numbered surviving version would otherwise let a "derive from what's left"
// computation reissue its id. The stored high-water mark is the real counter.
int highestSurviving = versions.keySet().stream()
.mapToInt(id -> Integer.parseInt(id.substring(1)))
.max().orElse(0);
int nextVersionNum;
if (policy.getNextVersionNumber() == null) {
// A policy persisted before this field existed: the live-key floor alone can't
// reveal a version deleted before this field was ever recorded (e.g. v1-v4 live
// after a pre-migration DeletePolicyVersion("v5")). Since a policy can never hold
// more than 5 concurrent versions, no more than 5 stacked deletions could have
// happened at the top between two persists; jump the counter past that worst
// case rather than trust the live keys' max + 1 for an unknown history.
nextVersionNum = highestSurviving + 1 + 5;
} else {
nextVersionNum = Math.max(policy.getNextVersionNumber(), highestSurviving + 1);
}
String versionId = "v" + nextVersionNum;
version = new PolicyVersion(versionId, document, setAsDefault);
if (setAsDefault) {
versions.values().forEach(v -> v.setDefaultVersion(false));
policy.setDefaultVersionId(versionId);
}
versions.put(versionId, version);
policy.setNextVersionNumber(nextVersionNum + 1);
policy.setUpdateDate(Instant.now());
policies.put(policyArn, policy);
return version;
}
policy.setUpdateDate(Instant.now());
policies.put(policyArn, policy);
return version;
}
public PolicyVersion getPolicyVersion(String policyArn, String versionId) {
@@ -2388,21 +2486,23 @@ public class IamService implements SessionAccountLookup, ResourceProvider {
}
public void deletePolicyVersion(String policyArn, String versionId) {
rejectIfAwsManaged(policyArn);
IamPolicy policy = requirePolicy(policyArn, PolicyNotFound.ATTACHABLE);
if (versionId.equals(policy.getDefaultVersionId())) {
throw new AwsException("DeleteConflict",
"Cannot delete the default version of a policy.", 409);
}
Map<String, PolicyVersion> versions = policy.getVersions();
synchronized (versions) {
if (!versions.containsKey(versionId)) {
throw new AwsException("NoSuchEntity",
"Policy version " + versionId + " does not exist.", 404);
synchronized (resourceNameLock) {
rejectIfAwsManaged(policyArn);
IamPolicy policy = requirePolicy(policyArn, PolicyNotFound.ATTACHABLE);
if (versionId.equals(policy.getDefaultVersionId())) {
throw new AwsException("DeleteConflict",
"Cannot delete the default version of a policy.", 409);
}
versions.remove(versionId);
Map<String, PolicyVersion> versions = policy.getVersions();
synchronized (versions) {
if (!versions.containsKey(versionId)) {
throw new AwsException("NoSuchEntity",
"Policy version " + versionId + " does not exist.", 404);
}
versions.remove(versionId);
}
policies.put(policyArn, policy);
}
policies.put(policyArn, policy);
}
public List<PolicyVersion> listPolicyVersions(String policyArn) {
@@ -2414,19 +2514,24 @@ public class IamService implements SessionAccountLookup, ResourceProvider {
}
public void setDefaultPolicyVersion(String policyArn, String versionId) {
rejectIfAwsManaged(policyArn);
IamPolicy policy = requirePolicy(policyArn, PolicyNotFound.ATTACHABLE);
Map<String, PolicyVersion> versions = policy.getVersions();
synchronized (versions) {
if (!versions.containsKey(versionId)) {
throw new AwsException("NoSuchEntity",
"Policy version " + versionId + " does not exist.", 404);
synchronized (resourceNameLock) {
rejectIfAwsManaged(policyArn);
IamPolicy policy = requirePolicy(policyArn, PolicyNotFound.ATTACHABLE);
Map<String, PolicyVersion> versions = policy.getVersions();
synchronized (versions) {
if (!versions.containsKey(versionId)) {
throw new AwsException("NoSuchEntity",
"Policy version " + versionId + " does not exist.", 404);
}
versions.values().forEach(v -> v.setDefaultVersion(false));
versions.get(versionId).setDefaultVersion(true);
// Inside the monitor with the flags: a clearing of the other versions reads this
// id to decide what to keep, and between the two writes it would read the one
// this call has just replaced and drop the version it just made default.
policy.setDefaultVersionId(versionId);
}
versions.values().forEach(v -> v.setDefaultVersion(false));
versions.get(versionId).setDefaultVersion(true);
policies.put(policyArn, policy);
}
policy.setDefaultVersionId(versionId);
policies.put(policyArn, policy);
}
public void tagPolicy(String policyArn, Map<String, String> newTags) {
@@ -234,6 +234,56 @@ class CloudFormationManagedPolicyUpdateIntegrationTest {
}
}
/**
* The stack still comes down after an update. The update publishes the new document as the
* default version and leaves the version before it on the policy, which IAM refuses to delete
* a policy over, so the delete clears the other versions first: without that a stack could
* create and update a managed policy it would never be able to take down again.
*/
@Test
void theStackComesDownAfterAnUpdateLeftAnEarlierVersion() {
String suffix = Long.toString(System.nanoTime(), 36);
String stackName = "cfn-mp-delete-" + suffix;
String policyName = "mp-delete-" + suffix;
String roleName = "mp-delete-role-" + suffix;
try {
createStack(stackName, managedPolicyTemplate(policyName, roleName, "s3:GetObject"));
assertStackStatus(stackName, "CREATE_COMPLETE");
updateStack(stackName, managedPolicyTemplate(policyName, roleName, "s3:PutObject"));
assertStackStatus(stackName, "UPDATE_COMPLETE");
CfnStackWaits.deleteStack(stackName, CFN_AUTH);
given()
.contentType("application/x-www-form-urlencoded")
.header("Authorization", IAM_AUTH)
.formParam("Action", "GetPolicy")
.formParam("PolicyArn", policyArn(policyName))
.when()
.post("/")
.then()
.statusCode(404);
} finally {
// An assertion failing ahead of the delete would otherwise leave the stack, its role
// and its policy in the store every class here shares. This asks for the delete and
// reports nothing, so it cannot mask the failure that brought it here; the delete
// under test is the one above.
sweepUp(stackName);
}
}
/** Asks for a stack to go and says nothing about the answer, for use in a teardown. */
private static void sweepUp(String stackName) {
given()
.contentType("application/x-www-form-urlencoded")
.header("Authorization", CFN_AUTH)
.formParam("Action", "DeleteStack")
.formParam("StackName", stackName)
.when()
.post("/");
}
@Test
void updateRetargetingRolesDetachesTheRemovedRole() {
String suffix = Long.toString(System.nanoTime(), 36);
@@ -172,6 +172,25 @@ class IamManagedPolicyCfnProvisionerTest {
order.verify(iam).deletePolicy(ARN);
}
/**
* The versions an update left on the policy go before the delete that would otherwise be
* refused over them, and after the detaches, which is the order AWS's steps for deleting a
* managed policy are written in.
*/
@Test
void deleteClearsTheVersionsAnUpdateLeftBeforeRemovingThePolicy() {
StackResource r = resource();
r.setPhysicalId(ARN);
r.getAttributes().put("ManagedPolicyRoleTargets", "web-role");
provisioner.delete(r, "us-east-1");
InOrder order = inOrder(iam);
order.verify(iam).detachRolePolicy("web-role", ARN);
order.verify(iam).clearNonDefaultPolicyVersions(ARN);
order.verify(iam).deletePolicy(ARN);
}
@Test
void deleteDetachesEveryStoredPrincipalBeforeRemovingThePolicy() {
StackResource r = resource();
@@ -201,6 +201,73 @@ class IamConcurrencyTest {
}
}
/**
* A policy delete and a version publish racing each other: one of them loses, and whichever
* does, the store is left consistent. A delete that reported success must leave nothing
* behind, where a version written back after it would have brought the policy with it.
*/
@Test
void aDeletedPolicyIsNeverBroughtBackByAVersionPublish() throws Exception {
int trials = 300;
ExecutorService pool = Executors.newFixedThreadPool(2);
try {
for (int trial = 0; trial < trials; trial++) {
IamService iam = newIamService();
IamPolicy p = iam.createPolicy("pol", "/", null, EMPTY_POLICY_DOCUMENT, null);
String arn = p.getArn();
CountDownLatch start = new CountDownLatch(1);
CountDownLatch done = new CountDownLatch(2);
AtomicBoolean deleted = new AtomicBoolean();
List<Throwable> errors = new CopyOnWriteArrayList<>();
pool.submit(tolerating(start, done, errors, "DeleteConflict", () -> {
iam.deletePolicy(arn);
deleted.set(true);
}));
pool.submit(tolerating(start, done, errors, "NoSuchEntity",
() -> iam.createPolicyVersion(arn, policyDocument("v"), false)));
start.countDown();
assertTrue(done.await(30, TimeUnit.SECONDS), "policy delete workers stalled");
if (!errors.isEmpty()) {
fail("policy delete trial " + trial + ": " + errors.get(0));
}
if (deleted.get() && !iam.listPolicies("Local", null).isEmpty()) {
fail("policy delete trial " + trial + ": a deleted policy is still listed");
}
if (!deleted.get() && iam.listPolicyVersions(arn).size() != 2) {
fail("policy delete trial " + trial + ": a refused delete lost a version");
}
}
} finally {
pool.shutdownNow();
}
}
/**
* A worker that waits for the start signal, runs {@code work} and keeps only the failures
* that are not the one error the race is allowed to produce.
*/
private static Runnable tolerating(CountDownLatch start, CountDownLatch done,
List<Throwable> errors, String tolerated, Runnable work) {
return () -> {
try {
start.await();
work.run();
} catch (AwsException e) {
if (!tolerated.equals(e.getErrorCode())) {
errors.add(e);
}
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
} catch (RuntimeException e) {
errors.add(e);
} finally {
done.countDown();
}
};
}
@Test
void policyVersionsStayRaceFree() throws Exception {
int trials = 400;
@@ -12,10 +12,12 @@ 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.
* Which dependency a blocked delete names, and in the sentence AWS was recorded answering. Four
* sentences cover the refusals: an instance profile still holding the role, a managed policy that
* has to be detached, an inline policy that has to be deleted, and a managed policy of the
* account's own that still has a version beside the default one its delete would take. 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.
@@ -35,6 +37,11 @@ class IamDeleteConflictDependencyIntegrationTest {
"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 MUST_DELETE_POLICY_VERSIONS =
"This policy has more than one version. Before you delete a policy, you must delete"
+ " the policy's versions. The default version is deleted with the policy.";
private static final String MUST_DETACH_FROM_ENTITIES =
"Cannot delete a policy attached to entities. Detach it first.";
private static final String TRUST_POLICY = "{\"Version\":\"2012-10-17\",\"Statement\":"
+ "[{\"Effect\":\"Allow\",\"Principal\":{\"Service\":\"ec2.amazonaws.com\"},"
@@ -43,6 +50,10 @@ class IamDeleteConflictDependencyIntegrationTest {
private static final String PERMISSION_POLICY = "{\"Version\":\"2012-10-17\",\"Statement\":"
+ "[{\"Effect\":\"Allow\",\"Action\":\"s3:GetObject\",\"Resource\":\"*\"}]}";
private static final String OTHER_PERMISSION_POLICY = "{\"Version\":\"2012-10-17\","
+ "\"Statement\":[{\"Effect\":\"Allow\",\"Action\":\"s3:PutObject\","
+ "\"Resource\":\"*\"}]}";
@RegisterExtension
final PartitionCleanup cleanup = new PartitionCleanup();
@@ -110,6 +121,22 @@ class IamDeleteConflictDependencyIntegrationTest {
return arn;
}
/**
* Publishes a second document on the policy, which stays beside the default rather than
* replacing it. Its teardown is registered after the policy's own, and teardowns run newest
* first, so the version is gone before anything tries to delete the policy.
*/
private String versionBeside(String policyArn) {
String versionId = iam("CreatePolicyVersion").formParam("PolicyArn", policyArn)
.formParam("PolicyDocument", OTHER_PERMISSION_POLICY)
.when().post("/").then().statusCode(200)
.extract().xmlPath().getString(
"CreatePolicyVersionResponse.CreatePolicyVersionResult.PolicyVersion.VersionId");
cleanup.register(() -> cleared(iam("DeletePolicyVersion")
.formParam("PolicyArn", policyArn).formParam("VersionId", versionId)));
return versionId;
}
private String attachToRole(String roleName) {
return attach("AttachRolePolicy", "DetachRolePolicy", "RoleName", roleName);
}
@@ -233,6 +260,46 @@ class IamDeleteConflictDependencyIntegrationTest {
.body(MESSAGE, equalTo(MUST_DELETE_POLICIES));
}
/**
* The policy's own delete: a version beside the default is a dependency of its own, and the
* sentence names the versions rather than the attachment the other refusal is about.
*/
@Test
void aPolicyWithAVersionBesideItsDefaultAsksForTheVersions() {
String policyArn = managedPolicy();
versionBeside(policyArn);
iam("DeletePolicy").formParam("PolicyArn", policyArn)
.when().post("/").then().statusCode(409)
.body(CODE, equalTo("DeleteConflict"))
.body(MESSAGE, equalTo(MUST_DELETE_POLICY_VERSIONS));
}
/**
* Attached and versioned at once: the attachment is named first, the order AWS's own steps
* for deleting a managed policy are written in. That order is a reading, not a recording.
*/
@Test
void theAttachmentIsNamedAheadOfTheVersions() {
String policyArn = attachToRole(createRole());
versionBeside(policyArn);
iam("DeletePolicy").formParam("PolicyArn", policyArn)
.when().post("/").then().statusCode(409)
.body(CODE, equalTo("DeleteConflict"))
.body(MESSAGE, equalTo(MUST_DETACH_FROM_ENTITIES));
}
/** The control for it: the other version is deleted and the policy goes with its default. */
@Test
void thePolicyGoesOnceTheVersionBesideItsDefaultIsDeleted() {
String policyArn = managedPolicy();
String versionId = versionBeside(policyArn);
iam("DeletePolicyVersion").formParam("PolicyArn", policyArn)
.formParam("VersionId", versionId).when().post("/").then().statusCode(200);
iam("DeletePolicy").formParam("PolicyArn", policyArn)
.when().post("/").then().statusCode(200);
}
/** The control: every dependency cleared in the order the refusals asked for, and it goes. */
@Test
void theRoleGoesOnceEachDependencyNamedIsCleared() {
@@ -225,10 +225,18 @@ class IamPolicyDocumentWriteIntegrationTest {
.formParam("PolicyDocument", "{\"Version\":\"2012-10-17\",\"Statement\":[{}]}"),
"Policy statement must contain actions.");
iam("CreatePolicyVersion")
String versionId = iam("CreatePolicyVersion")
.formParam("PolicyArn", arn)
.formParam("PolicyDocument", IDENTITY_POLICY)
.when().post("/").then().statusCode(200);
.when().post("/").then().statusCode(200)
.extract().xmlPath().getString(
"CreatePolicyVersionResponse.CreatePolicyVersionResult.PolicyVersion.VersionId");
// The policy now has a version beside its default, and a policy carrying one cannot be
// deleted, so this goes first: the teardowns registered here run newest first.
cleanup.register(() -> iam("DeletePolicyVersion")
.formParam("PolicyArn", arn).formParam("VersionId", versionId)
.when().post("/").then().statusCode(200));
}
/**
@@ -2214,6 +2214,81 @@ class IamServiceTest {
"setTags should defensively copy, not alias the caller's map");
}
@Test
void deletePolicyWithAVersionBesideItsDefaultNamesTheVersions() {
IamPolicy policy = iamService.createPolicy("P", "/", null, policyDocument("one"), null);
iamService.createPolicyVersion(policy.getArn(), policyDocument("two"), false);
AwsException ex = assertThrows(AwsException.class,
() -> iamService.deletePolicy(policy.getArn()));
assertEquals("DeleteConflict", ex.getErrorCode());
assertEquals("This policy has more than one version. Before you delete a policy, you must"
+ " delete the policy's versions. The default version is deleted with the policy.",
ex.getMessage());
}
/**
* What a stack's own cleanup does before it deletes a policy it owns: the default survives
* with its document, every other version is gone, and the delete goes through.
*/
@Test
void clearingTheOtherVersionsKeepsTheDefaultAndFreesTheDelete() {
String current = policyDocument("current");
IamPolicy policy = iamService.createPolicy("P", "/", null, policyDocument("first"), null);
String policyArn = policy.getArn();
iamService.createPolicyVersion(policyArn, policyDocument("second"), false);
iamService.createPolicyVersion(policyArn, current, true);
iamService.clearNonDefaultPolicyVersions(policyArn);
List<PolicyVersion> left = iamService.listPolicyVersions(policyArn);
assertEquals(1, left.size());
assertEquals("v3", left.getFirst().getVersionId());
assertEquals(current, left.getFirst().getDocument());
iamService.deletePolicy(policyArn);
AwsException gone = assertThrows(AwsException.class, () -> iamService.getPolicy(policyArn));
assertEquals("NoSuchEntity", gone.getErrorCode());
}
/**
* The clearing is on the way to a delete that an attachment refuses, so it asks about the
* attachment first: a stack whose policy some principal it never recorded still holds keeps
* every version it had, and hears the same sentence the delete would have given it.
*/
@Test
void clearingIsRefusedWhileThePolicyIsAttachedAndKeepsEveryVersion() {
iamService.createUser("outsider", "/");
IamPolicy policy = iamService.createPolicy("P", "/", null, policyDocument("one"), null);
String policyArn = policy.getArn();
iamService.createPolicyVersion(policyArn, policyDocument("two"), false);
iamService.attachUserPolicy("outsider", policyArn);
AwsException ex = assertThrows(AwsException.class,
() -> iamService.clearNonDefaultPolicyVersions(policyArn));
assertEquals("DeleteConflict", ex.getErrorCode());
assertEquals("Cannot delete a policy attached to entities. Detach it first.",
ex.getMessage());
assertEquals(2, iamService.listPolicyVersions(policyArn).size());
}
/** The version a SetDefaultPolicyVersion just chose is the one the clearing keeps. */
@Test
void clearingKeepsTheVersionJustMadeDefault() {
String second = policyDocument("second");
IamPolicy policy = iamService.createPolicy("P", "/", null, policyDocument("first"), null);
String policyArn = policy.getArn();
iamService.createPolicyVersion(policyArn, second, false);
iamService.setDefaultPolicyVersion(policyArn, "v2");
iamService.clearNonDefaultPolicyVersions(policyArn);
List<PolicyVersion> left = iamService.listPolicyVersions(policyArn);
assertEquals(1, left.size());
assertEquals("v2", left.getFirst().getVersionId());
assertEquals(second, left.getFirst().getDocument());
assertEquals("v2", iamService.getPolicy(policyArn).getDefaultVersionId());
}
@Test
void deletePolicyWithAttachmentsFails() {
iamService.createUser("alice", "/");