diff --git a/docs/services/iam.md b/docs/services/iam.md index a31594ef38..80d28f2560 100644 --- a/docs/services/iam.md +++ b/docs/services/iam.md @@ -639,6 +639,27 @@ returned object", even though the `InstanceProfile` shape itself carries no such Tags on a role embedded in `InstanceProfileList` are always omitted, matching `GetInstanceProfile`'s own documented role subset. +### What the instance profile pair refuses + +An instance profile holds one role, and both halves of that are recorded against a real account on +2026-10-29. + +Adding a second role is `LimitExceeded` 409 with `Cannot exceed quota for +InstanceSessionsPerInstanceProfile: 1`. The quota name is what tells an operator or a quota-aware +client which of the operation's limits fired, and it is that one: AWS publishes no +roles-per-instance-profile quota by any name, and this package used to answer prose instead of the +`Cannot exceed quota for : ` form it already writes for nine other quotas. + +Removing a role the profile does not hold is `NoSuchEntity` 404 with `Role in Instance +Profile 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. + +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. + ### Access Keys | Action | Description | diff --git a/src/main/java/io/floci/aws/services/cloudformation/provisioners/IamInstanceProfileCfnProvisioner.java b/src/main/java/io/floci/aws/services/cloudformation/provisioners/IamInstanceProfileCfnProvisioner.java index 6c79a476e3..04eac76fd8 100644 --- a/src/main/java/io/floci/aws/services/cloudformation/provisioners/IamInstanceProfileCfnProvisioner.java +++ b/src/main/java/io/floci/aws/services/cloudformation/provisioners/IamInstanceProfileCfnProvisioner.java @@ -147,7 +147,7 @@ public class IamInstanceProfileCfnProvisioner implements CfnResourceProvisioner private void reconcileRoles(String name, List current, List desired) { for (String roleName : new ArrayList<>(current)) { if (!desired.contains(roleName)) { - iamService.removeRoleFromInstanceProfile(name, roleName); + detachPairing(name, roleName); } } for (String roleName : desired) { @@ -157,6 +157,23 @@ public class IamInstanceProfileCfnProvisioner implements CfnResourceProvisioner } } + /** + * Detaches one role, tolerating a pairing that is already gone: the operation refuses a role + * the profile does not hold, and a caller outside the stack can detach between the list being + * read here and this call, which must not leave a deletion or a reconcile part way through. A + * profile that has itself gone is a different case and still propagates, so the deletion ends + * where it always did rather than carrying on against a profile that is not there. + */ + private void detachPairing(String name, String roleName) { + try { + iamService.removeRoleFromInstanceProfile(name, roleName); + } catch (AwsException e) { + if (!"NoSuchEntity".equals(e.getErrorCode()) || findProfile(name) == null) { + throw e; + } + } + } + private static String normalizePath(String path) { if (path == null || path.isEmpty()) { return "/"; @@ -197,7 +214,7 @@ public class IamInstanceProfileCfnProvisioner implements CfnResourceProvisioner CfnDeletes.safeDelete("IAM instance profile", physicalId, () -> { InstanceProfile profile = iamService.getInstanceProfile(physicalId); for (String roleName : new ArrayList<>(profile.getRoleNames())) { - iamService.removeRoleFromInstanceProfile(physicalId, roleName); + detachPairing(physicalId, roleName); } iamService.deleteInstanceProfile(physicalId); }, "NoSuchEntity"); 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 b4e225b0c1..f61bff75f5 100644 --- a/src/main/java/io/floci/aws/services/iam/IamService.java +++ b/src/main/java/io/floci/aws/services/iam/IamService.java @@ -2919,8 +2919,10 @@ public class IamService implements SessionAccountLookup, ResourceProvider { 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", - "An instance profile can contain at most 1 role.", 409); + "Cannot exceed quota for InstanceSessionsPerInstanceProfile: 1", 409); } roleNames.add(roleName); instanceProfiles.put(instanceProfileName, profile); @@ -2931,10 +2933,19 @@ public class IamService implements SessionAccountLookup, ResourceProvider { public void removeRoleFromInstanceProfile(String instanceProfileName, String roleName) { validateRoleName(roleName); InstanceProfile profile = getInstanceProfile(instanceProfileName); - // Tolerates an already-deleted role, so guard only what is still there. + // 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)); - profile.getRoleNames().remove(roleName); - instanceProfiles.put(instanceProfileName, profile); + List 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); + } } public List listInstanceProfilesForRole(String roleName) { diff --git a/src/test/java/io/floci/aws/services/cloudformation/provisioners/IamInstanceProfileCfnProvisionerTest.java b/src/test/java/io/floci/aws/services/cloudformation/provisioners/IamInstanceProfileCfnProvisionerTest.java index 833075a60e..cf0c0f3e01 100644 --- a/src/test/java/io/floci/aws/services/cloudformation/provisioners/IamInstanceProfileCfnProvisionerTest.java +++ b/src/test/java/io/floci/aws/services/cloudformation/provisioners/IamInstanceProfileCfnProvisionerTest.java @@ -35,7 +35,8 @@ import static org.mockito.Mockito.when; * and Roles are applied, a role swap reconciles in place, a createOnly change (name, or path on an * auto-named profile, or a dropped name) replaces the profile and marks the old one for cleanup, a * path change that keeps an explicit name collides with EntityAlreadyExists, a missing Roles is - * rejected, and delete detaches roles before removing the profile. + * rejected, and delete detaches roles before removing the profile, tolerating a pairing another + * caller detached first while still stopping where the profile itself has gone. */ class IamInstanceProfileCfnProvisionerTest { @@ -287,6 +288,54 @@ class IamInstanceProfileCfnProvisionerTest { assertEquals("DeleteConflict", failure.getErrorCode()); } + @Test + void deleteToleratesAPairingDetachedWhileTheProfileStands() { + InstanceProfile withRole = profile("web", "/"); + withRole.getRoleNames().add("app-role"); + when(iam.getInstanceProfile("web")).thenReturn(withRole); + doThrow(new AwsException("NoSuchEntity", + "Role app-role in Instance Profile web cannot be found.", 404)) + .when(iam).removeRoleFromInstanceProfile("web", "app-role"); + + assertDoesNotThrow(() -> provisioner.delete(TYPE, "web", "us-east-1")); + + verify(iam).deleteInstanceProfile("web"); + } + + @Test + void deleteStopsWhereTheProfileWentWithThePairing() { + InstanceProfile withRole = profile("web", "/"); + withRole.getRoleNames().add("app-role"); + when(iam.getInstanceProfile("web")).thenReturn(withRole) + .thenThrow(new AwsException("NoSuchEntity", "gone", 404)); + doThrow(new AwsException("NoSuchEntity", "gone", 404)) + .when(iam).removeRoleFromInstanceProfile("web", "app-role"); + + assertDoesNotThrow(() -> provisioner.delete(TYPE, "web", "us-east-1")); + + verify(iam, never()).deleteInstanceProfile("web"); + } + + @Test + void aPairingDetachedDuringAnUpdateDoesNotStopTheReconcile() throws Exception { + InstanceProfile existing = profile("web", "/"); + existing.getRoleNames().add("old-role"); + when(iam.createInstanceProfile("web", "/")) + .thenThrow(new AwsException("EntityAlreadyExists", "exists", 409)); + when(iam.getInstanceProfile("web")).thenReturn(existing); + doThrow(new AwsException("NoSuchEntity", + "Role old-role in Instance Profile web cannot be found.", 404)) + .when(iam).removeRoleFromInstanceProfile("web", "old-role"); + + StackResource r = resource(); + r.setPhysicalId("web"); + provisioner.provision(r, props(""" + {"InstanceProfileName": "web", "Roles": ["new-role"]} + """), ctx("web")); + + verify(iam).addRoleToInstanceProfile("web", "new-role"); + } + private ProvisionContext ctx(String priorPhysicalId) { return ctx("my-stack", priorPhysicalId); } diff --git a/src/test/java/io/floci/aws/services/iam/IamInstanceProfileRefusalIntegrationTest.java b/src/test/java/io/floci/aws/services/iam/IamInstanceProfileRefusalIntegrationTest.java new file mode 100644 index 0000000000..0f5ab41806 --- /dev/null +++ b/src/test/java/io/floci/aws/services/iam/IamInstanceProfileRefusalIntegrationTest.java @@ -0,0 +1,134 @@ +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; + +/** + * 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. + * + *

{@code docs/services/iam.md} carries the recordings. + */ +@QuarkusTest +class IamInstanceProfileRefusalIntegrationTest { + + private static final String IAM_AUTH = + "AWS4-HMAC-SHA256 Credential=test/20261118/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 TRUST_POLICY = "{\"Version\":\"2012-10-17\",\"Statement\":" + + "[{\"Effect\":\"Allow\",\"Principal\":{\"Service\":\"ec2.amazonaws.com\"}," + + "\"Action\":\"sts:AssumeRole\"}]}"; + + @RegisterExtension + final PartitionCleanup cleanup = new PartitionCleanup(); + + 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("profile-role"); + iam("CreateRole").formParam("RoleName", roleName) + .formParam("AssumeRolePolicyDocument", TRUST_POLICY) + .when().post("/").then().statusCode(200); + cleanup.register(() -> iam("DeleteRole").formParam("RoleName", roleName) + .when().post("/").then().statusCode(200)); + return roleName; + } + + private String createProfile() { + String profileName = unique("profile"); + iam("CreateInstanceProfile").formParam("InstanceProfileName", profileName) + .when().post("/").then().statusCode(200); + cleanup.register(() -> iam("DeleteInstanceProfile") + .formParam("InstanceProfileName", profileName) + .when().post("/").then().statusCode(200)); + return profileName; + } + + private void addRole(String profileName, String roleName) { + iam("AddRoleToInstanceProfile").formParam("InstanceProfileName", profileName) + .formParam("RoleName", roleName).when().post("/").then().statusCode(200); + cleanup.register(() -> iam("RemoveRoleFromInstanceProfile") + .formParam("InstanceProfileName", profileName) + .formParam("RoleName", roleName).when().post("/").then().statusCode(200)); + } + + /** The second role names the quota that fired, in the form the other nine quotas use. */ + @Test + void aSecondRoleNamesTheQuotaThatFired() { + String profileName = createProfile(); + addRole(profileName, createRole()); + iam("AddRoleToInstanceProfile").formParam("InstanceProfileName", profileName) + .formParam("RoleName", createRole()) + .when().post("/").then().statusCode(409) + .body(CODE, equalTo("LimitExceeded")) + .body(MESSAGE, equalTo( + "Cannot exceed quota for InstanceSessionsPerInstanceProfile: 1")); + } + + /** Removing a role the profile never held is refused rather than answered 200. */ + @Test + void removingARoleTheProfileNeverHeldIsRefused() { + String profileName = createProfile(); + String roleName = createRole(); + iam("RemoveRoleFromInstanceProfile").formParam("InstanceProfileName", profileName) + .formParam("RoleName", roleName) + .when().post("/").then().statusCode(404) + .body(CODE, equalTo("NoSuchEntity")) + .body(MESSAGE, equalTo("Role " + roleName + " in Instance Profile " + + profileName + " cannot be found.")); + } + + /** + * 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. + */ + @Test + void aRoleDeletedWhileStillListedStaysRemovable() { + String profileName = createProfile(); + String roleName = unique("profile-ghost-role"); + iam("CreateRole").formParam("RoleName", roleName) + .formParam("AssumeRolePolicyDocument", TRUST_POLICY) + .when().post("/").then().statusCode(200); + cleanup.register(() -> iam("DeleteRole").formParam("RoleName", roleName) + .when().post("/").then().statusCode(anyOf(is(200), is(404)))); + iam("AddRoleToInstanceProfile").formParam("InstanceProfileName", profileName) + .formParam("RoleName", roleName).when().post("/").then().statusCode(200); + cleanup.register(() -> iam("RemoveRoleFromInstanceProfile") + .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("RemoveRoleFromInstanceProfile").formParam("InstanceProfileName", profileName) + .formParam("RoleName", roleName).when().post("/").then().statusCode(200); + } + + /** The control: the first role still attaches, and removing it still succeeds. */ + @Test + void theFirstRoleStillAttachesAndDetaches() { + String profileName = createProfile(); + String roleName = createRole(); + iam("AddRoleToInstanceProfile").formParam("InstanceProfileName", profileName) + .formParam("RoleName", roleName).when().post("/").then().statusCode(200); + iam("RemoveRoleFromInstanceProfile").formParam("InstanceProfileName", profileName) + .formParam("RoleName", roleName).when().post("/").then().statusCode(200); + } +}