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

@@ -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", "/");