From 942cace935a1685bfb8a9f740ca55bbda9dd4aa3 Mon Sep 17 00:00:00 2001 From: Priamo Germosen <6233424+pgermosen@users.noreply.github.com> Date: Sun, 22 Nov 2026 17:20:50 -0400 Subject: [PATCH] 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. --- docs/services/iam.md | 35 ++- .../provisioners/IamManagedPolicyDeletes.java | 17 +- .../io/floci/aws/services/iam/IamService.java | 243 +++++++++++++----- ...ionManagedPolicyUpdateIntegrationTest.java | 50 ++++ .../IamManagedPolicyCfnProvisionerTest.java | 19 ++ .../aws/services/iam/IamConcurrencyTest.java | 67 +++++ ...leteConflictDependencyIntegrationTest.java | 75 +++++- ...IamPolicyDocumentWriteIntegrationTest.java | 12 +- .../aws/services/iam/IamServiceTest.java | 75 ++++++ 9 files changed, 508 insertions(+), 85 deletions(-) diff --git a/docs/services/iam.md b/docs/services/iam.md index c16cf9e2f4..c16f67cf0e 100644 --- a/docs/services/iam.md +++ b/docs/services/iam.md @@ -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 | diff --git a/src/main/java/io/floci/aws/services/cloudformation/provisioners/IamManagedPolicyDeletes.java b/src/main/java/io/floci/aws/services/cloudformation/provisioners/IamManagedPolicyDeletes.java index cc8977d748..20488eabba 100644 --- a/src/main/java/io/floci/aws/services/cloudformation/provisioners/IamManagedPolicyDeletes.java +++ b/src/main/java/io/floci/aws/services/cloudformation/provisioners/IamManagedPolicyDeletes.java @@ -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())) { diff --git a/src/main/java/io/floci/aws/services/iam/IamService.java b/src/main/java/io/floci/aws/services/iam/IamService.java index 4e7947f72c..7627964967 100644 --- a/src/main/java/io/floci/aws/services/iam/IamService.java +++ b/src/main/java/io/floci/aws/services/iam/IamService.java @@ -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. + * + *
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. + * + *
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 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 {@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() {
diff --git a/src/test/java/io/floci/aws/services/iam/IamPolicyDocumentWriteIntegrationTest.java b/src/test/java/io/floci/aws/services/iam/IamPolicyDocumentWriteIntegrationTest.java
index c512ac8cff..667f2ee2e4 100644
--- a/src/test/java/io/floci/aws/services/iam/IamPolicyDocumentWriteIntegrationTest.java
+++ b/src/test/java/io/floci/aws/services/iam/IamPolicyDocumentWriteIntegrationTest.java
@@ -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));
}
/**
diff --git a/src/test/java/io/floci/aws/services/iam/IamServiceTest.java b/src/test/java/io/floci/aws/services/iam/IamServiceTest.java
index ba5b20119a..830ccee990 100644
--- a/src/test/java/io/floci/aws/services/iam/IamServiceTest.java
+++ b/src/test/java/io/floci/aws/services/iam/IamServiceTest.java
@@ -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