diff --git a/docs/services/iam.md b/docs/services/iam.md index 2c2dc77e9a..5ec5d567d5 100644 --- a/docs/services/iam.md +++ b/docs/services/iam.md @@ -486,6 +486,31 @@ is one character, so AWS's entity parse runs ahead of its length check for it. R through the same resolver and answers it the same way, which is a reading rather than a recording. A value that clears 20 characters and parses as no ARN keeps the sentence its own capture settled, `Invalid ARN provided in the request: `, and a value under 20 keeps the declared length. +### What a policy ARN that names nothing answers + +IAM answers two sentences for a managed policy ARN it cannot resolve, both 404 `NoSuchEntity`, and +they are not interchangeable: the operation decides which one it gives. `Policy was not +found.` says the ARN names nothing. `Policy does not exist or is not attachable.` says it +names nothing this call could attach, and AWS answers it for both of its own cases on purpose, so a +caller cannot tell an absent policy from an unattachable one. + +Recorded against a real account: `GetPolicy` and `TagPolicy` answer the first, on 2026-10-26, as do +`DetachUserPolicy`, `DetachGroupPolicy` and `DetachRolePolicy`, on 2026-10-29, including for a +policy that exists and is not attached, where this emulator used to add a clause naming the user, +group or role. `ListEntitiesForPolicy` answers the second, on 2026-10-25, and so do +`CreatePolicyVersion`, `GetPolicyVersion` and `ListPolicyVersions`, on 2026-10-29, with +`GetPolicyVersion` naming the version inside the same sentence: `Policy version does not +exist or is not attachable.` The attach operations answer the second as well, which is where an +AWS-managed name under the wrong path lands. + +The operations no recording covers answer with their own family, which is this emulator's reading +rather than a measurement. `UntagPolicy` and `ListPolicyTags` read with `TagPolicy`, and +`DeletePolicyVersion`, `SetDefaultPolicyVersion` and a permissions boundary that names no policy +read with the attach family. `DeletePolicy` reads with `GetPolicy`. One case stays as it was +because nothing records it and no family settles it: a version id that names nothing on a policy +that exists keeps `Policy version does not exist.`, which is about the version rather than the +ARN. A recording for any of those moves that operation alone, the sentences being sited per +operation in `IamService.PolicyNotFound`. ### Permission Boundaries 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 c3f199fcf4..05012912fa 100644 --- a/src/main/java/io/floci/aws/services/iam/IamService.java +++ b/src/main/java/io/floci/aws/services/iam/IamService.java @@ -919,7 +919,8 @@ public class IamService implements SessionAccountLookup, ResourceProvider { public IamUser createUser(String userName, String path, String permissionsBoundaryArn) { if (permissionsBoundaryArn != null) { - permissionsBoundaryArn = requirePolicy(permissionsBoundaryArn).getArn(); + permissionsBoundaryArn = + requirePolicy(permissionsBoundaryArn, PolicyNotFound.ATTACHABLE).getArn(); } synchronized (resourceNameLock) { if (containsNameIgnoreCase(users, IamUser::getUserName, userName)) { @@ -1824,10 +1825,53 @@ public class IamService implements SessionAccountLookup, ResourceProvider { return policy; } + /** + * The two sentences IAM answers for a managed policy ARN it cannot resolve. They are not + * interchangeable and the operation decides which it answers, each recorded against a real + * account: {@code GetPolicy} and {@code TagPolicy} answer {@link #PLAIN}, recorded 2026-10-26, + * as do the three detach operations, recorded 2026-10-29, while the attach family answers + * {@link #ATTACHABLE}, recorded on {@code ListEntitiesForPolicy} 2026-10-25 and on + * {@code CreatePolicyVersion}, {@code GetPolicyVersion} and {@code ListPolicyVersions} + * 2026-10-29. The clause is what tells the two apart: one says the ARN names nothing, the + * other that it names nothing this call could attach, and AWS answers the second for both of + * its own cases deliberately, so a caller cannot tell them apart either. + * + *

The operations no recording covers answer with their own family, which is this emulator's + * reading rather than a measurement: the tag readers with {@code TagPolicy}, the remaining + * version operations and a permissions boundary with the attach family. + * {@code docs/services/iam.md} records which is which and what a later recording moves. + */ + private enum PolicyNotFound { + + /** {@code Policy was not found.} */ + PLAIN("Policy %s was not found."), + + /** {@code Policy does not exist or is not attachable.} */ + ATTACHABLE("Policy %s does not exist or is not attachable."); + + private final String template; + + PolicyNotFound(String template) { + this.template = template; + } + + AwsException of(String policyArn) { + return new AwsException("NoSuchEntity", template.formatted(policyArn), 404); + } + + /** {@code GetPolicyVersion} names the version inside the same sentence. */ + AwsException of(String policyArn, String versionId) { + return new AwsException("NoSuchEntity", + template.formatted(policyArn + " version " + versionId), 404); + } + } + private IamPolicy requirePolicy(String policyArn) { - return resolvePolicy(policyArn) - .orElseThrow(() -> new AwsException("NoSuchEntity", - "Policy " + policyArn + " does not exist.", 404)); + return requirePolicy(policyArn, PolicyNotFound.PLAIN); + } + + private IamPolicy requirePolicy(String policyArn, PolicyNotFound notFound) { + return resolvePolicy(policyArn).orElseThrow(() -> notFound.of(policyArn)); } /** @@ -1878,7 +1922,8 @@ public class IamService implements SessionAccountLookup, ResourceProvider { */ private String requireBoundaryPolicy(String permissionsBoundaryArn) { return registeredPartnerBoundary(permissionsBoundaryArn) - ? permissionsBoundaryArn : requirePolicy(permissionsBoundaryArn).getArn(); + ? permissionsBoundaryArn + : requirePolicy(permissionsBoundaryArn, PolicyNotFound.ATTACHABLE).getArn(); } private int managedPolicyAttachmentCount(String policyArn) { @@ -1973,7 +2018,7 @@ public class IamService implements SessionAccountLookup, ResourceProvider { * succeed. Attachments are tracked on the principals, so this scans them for the given ARN. */ public PolicyEntities listEntitiesForPolicy(String policyArn) { - String canonicalArn = requirePolicy(policyArn).getArn(); + String canonicalArn = requirePolicy(policyArn, PolicyNotFound.ATTACHABLE).getArn(); List attachedRoles = roles.scan(k -> true).stream() .filter(r -> r.getAttachedPolicyArns().contains(canonicalArn)) .toList(); @@ -2117,7 +2162,7 @@ public class IamService implements SessionAccountLookup, ResourceProvider { IamPolicyDocuments.checkManagedPolicy(document); } rejectIfAwsManaged(policyArn); - IamPolicy policy = getPolicy(policyArn); + IamPolicy policy = requirePolicy(policyArn, PolicyNotFound.ATTACHABLE); Map versions = policy.getVersions(); PolicyVersion version; synchronized (versions) { @@ -2159,7 +2204,8 @@ public class IamService implements SessionAccountLookup, ResourceProvider { } public PolicyVersion getPolicyVersion(String policyArn, String versionId) { - IamPolicy policy = requirePolicy(policyArn); + IamPolicy policy = resolvePolicy(policyArn) + .orElseThrow(() -> PolicyNotFound.ATTACHABLE.of(policyArn, versionId)); PolicyVersion version = policy.getVersions().get(versionId); if (version == null) { throw new AwsException("NoSuchEntity", @@ -2170,7 +2216,7 @@ public class IamService implements SessionAccountLookup, ResourceProvider { public void deletePolicyVersion(String policyArn, String versionId) { rejectIfAwsManaged(policyArn); - IamPolicy policy = getPolicy(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); @@ -2187,7 +2233,8 @@ public class IamService implements SessionAccountLookup, ResourceProvider { } public List listPolicyVersions(String policyArn) { - Map versions = requirePolicy(policyArn).getVersions(); + Map versions = + requirePolicy(policyArn, PolicyNotFound.ATTACHABLE).getVersions(); synchronized (versions) { return new ArrayList<>(versions.values()); } @@ -2195,7 +2242,7 @@ public class IamService implements SessionAccountLookup, ResourceProvider { public void setDefaultPolicyVersion(String policyArn, String versionId) { rejectIfAwsManaged(policyArn); - IamPolicy policy = getPolicy(policyArn); + IamPolicy policy = requirePolicy(policyArn, PolicyNotFound.ATTACHABLE); Map versions = policy.getVersions(); synchronized (versions) { if (!versions.containsKey(versionId)) { @@ -2237,7 +2284,7 @@ public class IamService implements SessionAccountLookup, ResourceProvider { public void attachUserPolicy(String userName, String policyArn) { IamUser user = getUser(userName); - IamPolicy policy = requirePolicy(policyArn); + IamPolicy policy = requirePolicy(policyArn, PolicyNotFound.ATTACHABLE); if (!user.getAttachedPolicyArns().contains(policy.getArn())) { user.getAttachedPolicyArns().add(policy.getArn()); users.put(userName, user); @@ -2249,8 +2296,7 @@ public class IamService implements SessionAccountLookup, ResourceProvider { IamUser user = getUser(userName); String canonicalArn = canonicalPolicyArn(policyArn); if (!user.getAttachedPolicyArns().remove(canonicalArn)) { - throw new AwsException("NoSuchEntity", - "Policy " + policyArn + " is not attached to user " + userName + ".", 404); + throw PolicyNotFound.PLAIN.of(policyArn); } users.put(userName, user); decrementCustomerManagedPolicyAttachmentCount(canonicalArn); @@ -2269,7 +2315,7 @@ public class IamService implements SessionAccountLookup, ResourceProvider { public void attachGroupPolicy(String groupName, String policyArn) { IamGroup group = getGroup(groupName); - IamPolicy policy = requirePolicy(policyArn); + IamPolicy policy = requirePolicy(policyArn, PolicyNotFound.ATTACHABLE); if (!group.getAttachedPolicyArns().contains(policy.getArn())) { group.getAttachedPolicyArns().add(policy.getArn()); groups.put(groupName, group); @@ -2281,8 +2327,7 @@ public class IamService implements SessionAccountLookup, ResourceProvider { IamGroup group = getGroup(groupName); String canonicalArn = canonicalPolicyArn(policyArn); if (!group.getAttachedPolicyArns().remove(canonicalArn)) { - throw new AwsException("NoSuchEntity", - "Policy " + policyArn + " is not attached to group " + groupName + ".", 404); + throw PolicyNotFound.PLAIN.of(policyArn); } groups.put(groupName, group); decrementCustomerManagedPolicyAttachmentCount(canonicalArn); @@ -2304,7 +2349,7 @@ public class IamService implements SessionAccountLookup, ResourceProvider { validateRoleName(roleName); IamRole role = getRole(roleName); requireNotServiceLinked(role, roleName); - IamPolicy policy = requirePolicy(policyArn); + IamPolicy policy = requirePolicy(policyArn, PolicyNotFound.ATTACHABLE); if (!role.getAttachedPolicyArns().contains(policy.getArn())) { role.getAttachedPolicyArns().add(policy.getArn()); roles.put(roleName, role); @@ -2320,8 +2365,7 @@ public class IamService implements SessionAccountLookup, ResourceProvider { requireNotServiceLinked(role, roleName); String canonicalArn = canonicalPolicyArn(policyArn); if (!role.getAttachedPolicyArns().remove(canonicalArn)) { - throw new AwsException("NoSuchEntity", - "Policy " + policyArn + " is not attached to role " + roleName + ".", 404); + throw PolicyNotFound.PLAIN.of(policyArn); } roles.put(roleName, role); decrementCustomerManagedPolicyAttachmentCount(canonicalArn); @@ -2344,10 +2388,14 @@ public class IamService implements SessionAccountLookup, ResourceProvider { IamRole role = getRole(roleName); requireSameRole(role, roleName, expectedRoleId); requireNotServiceLinked(role, roleName); - List desired = policyArns.stream().map(this::requirePolicy) + // These are attachments, so they read with the attach family rather than with the + // default: a replacement that cannot find one of them is the same answer an attach + // would have given, which is what the boundary and the counts below already choose. + List desired = policyArns.stream() + .map(arn -> requirePolicy(arn, PolicyNotFound.ATTACHABLE)) .map(IamPolicy::getArn).distinct().toList(); if (boundaryArn != null) { - boundaryArn = requirePolicy(boundaryArn).getArn(); + boundaryArn = requirePolicy(boundaryArn, PolicyNotFound.ATTACHABLE).getArn(); } Map checkedInline = new LinkedHashMap<>(); for (Map.Entry entry : inlinePolicies.entrySet()) { @@ -2363,7 +2411,8 @@ public class IamService implements SessionAccountLookup, ResourceProvider { } for (String arn : desired) { if (!role.getAttachedPolicyArns().contains(arn)) { - incrementCustomerManagedPolicyAttachmentCount(requirePolicy(arn)); + incrementCustomerManagedPolicyAttachmentCount( + requirePolicy(arn, PolicyNotFound.ATTACHABLE)); } } Set changedInline = new HashSet<>(role.getInlinePolicies().keySet()); diff --git a/src/test/java/io/floci/aws/services/iam/IamPolicyNotFoundWordingIntegrationTest.java b/src/test/java/io/floci/aws/services/iam/IamPolicyNotFoundWordingIntegrationTest.java new file mode 100644 index 0000000000..010a0efb2c --- /dev/null +++ b/src/test/java/io/floci/aws/services/iam/IamPolicyNotFoundWordingIntegrationTest.java @@ -0,0 +1,178 @@ +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.equalTo; + +/** + * The two sentences IAM answers for a managed policy ARN it cannot resolve, one per operation: + * {@code was not found.} where the ARN names nothing, and {@code does not exist or is not + * attachable.} where it names nothing the call could attach. The recorded operations are pinned + * here with the ones that follow them, and so is the clause the detach paths used to add. + * + *

{@code docs/services/iam.md} carries the recordings and the readings. + */ +@QuarkusTest +class IamPolicyNotFoundWordingIntegrationTest { + + 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"; + + /** Well formed, this account's, and naming no policy. */ + private static final String ABSENT = "arn:aws:iam::000000000000:policy/not-found-wording"; + + private static final String PLAIN = "Policy " + ABSENT + " was not found."; + + private static final String ATTACHABLE = + "Policy " + ABSENT + " does not exist or is not attachable."; + + private static final String DOCUMENT = "{\"Version\":\"2012-10-17\",\"Statement\":" + + "[{\"Effect\":\"Allow\",\"Action\":\"s3:GetObject\",\"Resource\":\"*\"}]}"; + + @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 + "-" + System.nanoTime(); + } + + private static void expectNotFound(RequestSpecification request, String message) { + request.when().post("/").then().statusCode(404) + .body(CODE, equalTo("NoSuchEntity")) + .body(MESSAGE, equalTo(message)); + } + + private String createUser() { + String userName = unique("not-found-user"); + iam("CreateUser").formParam("UserName", userName).when().post("/").then().statusCode(200); + cleanup.register(() -> iam("DeleteUser").formParam("UserName", userName) + .when().post("/").then().statusCode(200)); + return userName; + } + + private String createPolicy() { + String policyName = unique("not-found-policy"); + String arn = iam("CreatePolicy").formParam("PolicyName", policyName) + .formParam("PolicyDocument", DOCUMENT) + .when().post("/").then().statusCode(200) + .extract().path("CreatePolicyResponse.CreatePolicyResult.Policy.Arn"); + cleanup.register(() -> iam("DeletePolicy").formParam("PolicyArn", arn) + .when().post("/").then().statusCode(200)); + return arn; + } + + /** The two reads the plain sentence is recorded on, and the delete that reads with them. */ + @Test + void thePolicyReadsAnswerTheSentenceThatNamesNothingElse() { + expectNotFound(iam("GetPolicy").formParam("PolicyArn", ABSENT), PLAIN); + expectNotFound(iam("TagPolicy").formParam("PolicyArn", ABSENT) + .formParam("Tags.member.1.Key", "team") + .formParam("Tags.member.1.Value", "iam"), PLAIN); + expectNotFound(iam("DeletePolicy").formParam("PolicyArn", ABSENT), PLAIN); + expectNotFound(iam("ListPolicyTags").formParam("PolicyArn", ABSENT), PLAIN); + } + + /** The attachment family, and the version operations that read with it. */ + @Test + void theAttachmentFamilyAnswersTheSentenceCarryingTheClause() { + expectNotFound(iam("AttachUserPolicy").formParam("UserName", createUser()) + .formParam("PolicyArn", ABSENT), ATTACHABLE); + expectNotFound(iam("ListEntitiesForPolicy").formParam("PolicyArn", ABSENT), ATTACHABLE); + expectNotFound(iam("ListPolicyVersions").formParam("PolicyArn", ABSENT), ATTACHABLE); + expectNotFound(iam("CreatePolicyVersion").formParam("PolicyArn", ABSENT) + .formParam("PolicyDocument", DOCUMENT), ATTACHABLE); + expectNotFound(iam("SetDefaultPolicyVersion").formParam("PolicyArn", ABSENT) + .formParam("VersionId", "v1"), ATTACHABLE); + } + + /** {@code GetPolicyVersion} names the version inside the same sentence. */ + @Test + void theVersionReadNamesTheVersionInsideTheSentence() { + expectNotFound(iam("GetPolicyVersion").formParam("PolicyArn", ABSENT) + .formParam("VersionId", "v1"), + "Policy " + ABSENT + " version v1 does not exist or is not attachable."); + } + + /** + * Detaching a policy that exists and is not attached is the plain sentence, with no clause + * naming the user, group or role: AWS emits none, and the three paths used to. + */ + @Test + void detachingAPolicyThatIsNotAttachedNamesNoEntity() { + String arn = createPolicy(); + String userName = createUser(); + expectNotFound(iam("DetachUserPolicy").formParam("UserName", userName) + .formParam("PolicyArn", arn), "Policy " + arn + " was not found."); + + String groupName = unique("not-found-group"); + iam("CreateGroup").formParam("GroupName", groupName).when().post("/").then().statusCode(200); + cleanup.register(() -> iam("DeleteGroup").formParam("GroupName", groupName) + .when().post("/").then().statusCode(200)); + expectNotFound(iam("DetachGroupPolicy").formParam("GroupName", groupName) + .formParam("PolicyArn", arn), "Policy " + arn + " was not found."); + + String roleName = unique("not-found-role"); + iam("CreateRole").formParam("RoleName", roleName) + .formParam("AssumeRolePolicyDocument", "{\"Version\":\"2012-10-17\",\"Statement\":" + + "[{\"Effect\":\"Allow\",\"Principal\":{\"Service\":\"ec2.amazonaws.com\"}," + + "\"Action\":\"sts:AssumeRole\"}]}") + .when().post("/").then().statusCode(200); + cleanup.register(() -> iam("DeleteRole").formParam("RoleName", roleName) + .when().post("/").then().statusCode(200)); + expectNotFound(iam("DetachRolePolicy").formParam("RoleName", roleName) + .formParam("PolicyArn", arn), "Policy " + arn + " was not found."); + } + + /** Detaching an ARN that names nothing at all answers the same sentence. */ + @Test + void detachingAnAbsentPolicyAnswersTheSameSentence() { + expectNotFound(iam("DetachUserPolicy").formParam("UserName", createUser()) + .formParam("PolicyArn", ABSENT), PLAIN); + } + + /** + * A permissions boundary that names no policy reads with the attach family, which is the + * reading rather than a recording. + */ + @Test + void aPermissionsBoundaryThatNamesNoPolicyReadsWithTheAttachFamily() { + expectNotFound(iam("CreateUser").formParam("UserName", unique("boundary-user")) + .formParam("PermissionsBoundary", ABSENT), ATTACHABLE); + } + + /** + * The one case left as it was: a version id that names nothing on a policy that exists is + * about the version rather than the ARN, and nothing records it. + */ + @Test + void aVersionThatNamesNothingOnAPolicyThatExistsIsUnchanged() { + expectNotFound(iam("GetPolicyVersion").formParam("PolicyArn", createPolicy()) + .formParam("VersionId", "v7"), "Policy version v7 does not exist."); + } + + /** The control: a policy that exists still reads, attaches and detaches. */ + @Test + void aPolicyThatExistsIsUntouched() { + String arn = createPolicy(); + String userName = createUser(); + iam("GetPolicy").formParam("PolicyArn", arn).when().post("/").then().statusCode(200); + iam("AttachUserPolicy").formParam("UserName", userName).formParam("PolicyArn", arn) + .when().post("/").then().statusCode(200); + iam("DetachUserPolicy").formParam("UserName", userName).formParam("PolicyArn", arn) + .when().post("/").then().statusCode(200); + iam("ListEntitiesForPolicy").formParam("PolicyArn", arn) + .when().post("/").then().statusCode(200); + } +}