fix(iam): page ListRoles and ListPolicies through MaxItems and Marker (#5515)

Both actions returned every match in one response with IsTruncated false.
They now use the existing paginate helper, so an omitted MaxItems returns
100 items, a MaxItems outside 1 to 1000 is a ValidationError, and Marker
appears only on a truncated page. PathPrefix and Scope filter first.

Roles and customer managed policies are listed in name order so a marker
keeps pointing at the same place between calls.
This commit is contained in:
lex00 authored and GitHub committed 2026-10-12 15:40:59 -04:00
1 parent c5feab635a
commit 72a4cc5515
6 files changed
+355 -18

No files matched your search

@@ -73,6 +73,7 @@ import software.amazon.awssdk.services.iam.model.ListInstanceProfilesResponse;
import software.amazon.awssdk.services.iam.model.ListPoliciesGrantingServiceAccessEntry;
import software.amazon.awssdk.services.iam.model.ListPoliciesGrantingServiceAccessRequest;
import software.amazon.awssdk.services.iam.model.ListPoliciesGrantingServiceAccessResponse;
import software.amazon.awssdk.services.iam.model.ListPoliciesResponse;
import software.amazon.awssdk.services.iam.model.ListRolePoliciesRequest;
import software.amazon.awssdk.services.iam.model.ListRolePoliciesResponse;
import software.amazon.awssdk.services.iam.model.ListRolesResponse;
@@ -83,10 +84,12 @@ import software.amazon.awssdk.services.iam.model.ListUserTagsRequest;
import software.amazon.awssdk.services.iam.model.ListUserTagsResponse;
import software.amazon.awssdk.services.iam.model.ListUsersResponse;
import software.amazon.awssdk.services.iam.model.NoSuchEntityException;
import software.amazon.awssdk.services.iam.model.Policy;
import software.amazon.awssdk.services.iam.model.PolicyScopeType;
import software.amazon.awssdk.services.iam.model.PutRolePolicyRequest;
import software.amazon.awssdk.services.iam.model.RemoveRoleFromInstanceProfileRequest;
import software.amazon.awssdk.services.iam.model.RemoveUserFromGroupRequest;
import software.amazon.awssdk.services.iam.model.Role;
import software.amazon.awssdk.services.iam.model.SimulatePrincipalPolicyRequest;
import software.amazon.awssdk.services.iam.model.SimulatePrincipalPolicyResponse;
import software.amazon.awssdk.services.iam.model.StatusType;
@@ -104,6 +107,7 @@ import software.amazon.awssdk.services.iam.model.UpdateSamlProviderRequest;
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import static org.assertj.core.api.Assertions.*;
@@ -372,12 +376,71 @@ class IamTest {
@Test
@Order(17)
void listRoles() {
ListRolesResponse response = iam.listRoles();
assertThat(response.roles())
assertThat(iam.listRolesPaginator().roles())
.anyMatch(r -> ROLE_NAME.equals(r.roleName()));
}
@Test
@Order(17)
void listRolesPagesThroughMaxItemsAndMarker() {
String suffix = Long.toString(System.nanoTime(), 36);
String path = "/sdk-page-roles-" + suffix + "/";
List<String> names = List.of("sdk-page-" + suffix + "-a", "sdk-page-" + suffix + "-b",
"sdk-page-" + suffix + "-c");
names.forEach(name -> iam.createRole(CreateRoleRequest.builder()
.roleName(name).path(path).assumeRolePolicyDocument(TRUST_POLICY).build()));
try {
List<ListRolesResponse> pages = iam.listRolesPaginator(request -> request
.pathPrefix(path).maxItems(2)).stream().toList();
assertThat(pages).hasSize(2);
assertThat(pages.get(0).isTruncated()).isTrue();
assertThat(pages.get(0).marker()).isNotBlank();
assertThat(pages.get(1).isTruncated()).isFalse();
assertThat(pages.get(1).marker()).isNull();
assertThat(pages.stream().flatMap(page -> page.roles().stream()).map(Role::roleName).toList())
.containsExactlyElementsOf(names);
} finally {
names.forEach(name -> iam.deleteRole(DeleteRoleRequest.builder().roleName(name).build()));
}
}
@Test
@Order(17)
void listPoliciesPagesThroughMaxItemsAndMarker() {
String suffix = Long.toString(System.nanoTime(), 36);
String path = "/sdk-page-policies-" + suffix + "/";
List<String> arns = new ArrayList<>();
for (String letter : List.of("a", "b", "c")) {
arns.add(iam.createPolicy(CreatePolicyRequest.builder().policyName("sdk-page-" + suffix + "-" + letter)
.path(path).policyDocument(POLICY_DOCUMENT).build()).policy().arn());
}
try {
List<ListPoliciesResponse> pages = iam.listPoliciesPaginator(request -> request
.scope(PolicyScopeType.LOCAL).pathPrefix(path).maxItems(2)).stream().toList();
assertThat(pages).hasSize(2);
assertThat(pages.get(0).isTruncated()).isTrue();
assertThat(pages.get(0).marker()).isNotBlank();
assertThat(pages.get(1).isTruncated()).isFalse();
assertThat(pages.get(1).marker()).isNull();
assertThat(pages.stream().flatMap(page -> page.policies().stream()).map(Policy::arn).toList())
.containsExactlyElementsOf(arns);
} finally {
arns.forEach(arn -> iam.deletePolicy(DeletePolicyRequest.builder().policyArn(arn).build()));
}
}
@Test
@Order(17)
void listPoliciesReturnsOneHundredWhenMaxItemsIsOmitted() {
ListPoliciesResponse response = iam.listPolicies(request -> request.scope(PolicyScopeType.AWS));
assertThat(response.policies()).hasSize(100);
assertThat(response.isTruncated()).isTrue();
assertThat(response.marker()).isNotBlank();
}
// ── Managed Policies ───────────────────────────────────────────────
@Test
+7 -2
View File
@@ -55,7 +55,7 @@ type.
| CreateRole | Creates an IAM role with an assume-role policy. |
| GetRole | Returns a stored IAM role. |
| DeleteRole | Deletes an IAM role from the local IAM store. |
| ListRoles | Lists IAM roles in the local account. |
| ListRoles | Lists IAM roles in the local account, with `Marker` and `MaxItems` paging. |
| UpdateRole | Updates mutable IAM role fields. |
| CreateServiceLinkedRole | Creates a role under /aws-service-role/ for a service principal. |
| DeleteServiceLinkedRole | Deletes a service-linked role and returns a deletion task id. |
@@ -74,7 +74,7 @@ type.
| CreatePolicy | Creates a customer-managed IAM policy. |
| GetPolicy | Returns metadata for a managed IAM policy. |
| DeletePolicy | Deletes a managed IAM policy. |
| ListPolicies | Lists managed IAM policies, including seeded AWS managed policies. |
| ListPolicies | Lists managed IAM policies, including seeded AWS managed policies, with `Marker` and `MaxItems` paging. |
| ListEntitiesForPolicy | Lists roles, users, and groups with a direct managed-policy attachment. |
| CreatePolicyVersion | Creates a new version of a managed policy. |
| GetPolicyVersion | Returns a managed policy version document. |
@@ -89,6 +89,11 @@ type.
`PathPrefix`, `PolicyUsageFilter`, and pagination are not yet applied; responses return
`IsTruncated=false`.
`ListRoles` and `ListPolicies` return 100 items when `MaxItems` is omitted and reject a value
outside 1 to 1000. `PathPrefix` and `Scope` filter before paging, and roles and customer managed
policies are listed in name order so a `Marker` resumes where the previous page stopped.
`ListPolicies` does not yet apply `OnlyAttached` or `PolicyUsageFilter`.
### Permission Boundaries
| Action | Description |
@@ -57,7 +57,7 @@ public class IamQueryHandler {
private static final Logger LOG = Logger.getLogger(IamQueryHandler.class);
/** {@code MaxItems} on the last-accessed readers: "defaults to 100", valid range 1 to 1000. */
/** {@code MaxItems} on the readers that page through {@link #paginate}: "defaults to 100", range 1 to 1000. */
private static final int DEFAULT_MAX_ITEMS = 100;
private static final int MAX_MAX_ITEMS = 1000;
/** {@code sortKeyType} on {@code GetOrganizationsAccessReport}. */
@@ -1351,12 +1351,15 @@ public class IamQueryHandler {
}
private Response handleListRoles(MultivaluedMap<String, String> params) {
List<IamRole> roleList = iamService.listRoles(getParam(params, "PathPrefix"));
Page<IamRole> page = paginate(iamService.listRoles(getParam(params, "PathPrefix")), params);
XmlBuilder xml = new XmlBuilder().start("Roles");
for (IamRole r : roleList) {
for (IamRole r : page.items()) {
xml.start("member").raw(roleXml(r, false)).end("member");
}
xml.end("Roles").elem("IsTruncated", false);
xml.end("Roles").elem("IsTruncated", page.truncated());
if (page.marker() != null) {
xml.elem("Marker", page.marker());
}
return Response.ok(AwsQueryResponse.envelope("ListRoles", AwsNamespaces.IAM, xml.build())).build();
}
@@ -1417,13 +1420,16 @@ public class IamQueryHandler {
}
private Response handleListPolicies(MultivaluedMap<String, String> params) {
List<IamPolicy> policyList = iamService.listPolicies(
getParam(params, "Scope"), getParam(params, "PathPrefix"));
Page<IamPolicy> page = paginate(iamService.listPolicies(
getParam(params, "Scope"), getParam(params, "PathPrefix")), params);
XmlBuilder xml = new XmlBuilder().start("Policies");
for (IamPolicy p : policyList) {
for (IamPolicy p : page.items()) {
xml.start("member").raw(policyXml(p, false)).end("member");
}
xml.end("Policies").elem("IsTruncated", false);
xml.end("Policies").elem("IsTruncated", page.truncated());
if (page.marker() != null) {
xml.elem("Marker", page.marker());
}
return Response.ok(AwsQueryResponse.envelope("ListPolicies", AwsNamespaces.IAM, xml.build())).build();
}
@@ -2418,7 +2424,7 @@ public class IamQueryHandler {
// rather than answered emptily just because the marker happens to sit past the end.
int from = markerIndex(params);
// An omitted MaxItems is not "no limit": the API reference states the count "defaults to
// 100" on both readers, so a report wider than that is truncated with a Marker exactly as
// 100" on each reader paged here, so a list wider than that is truncated with a Marker as
// it would be against AWS. Operations that model no MaxItems at all pass through whole.
int limit = maxItemsModeled ? DEFAULT_MAX_ITEMS : items.size();
if (maxItemsModeled) {
@@ -1319,6 +1319,7 @@ public class IamService implements SessionAccountLookup, ResourceProvider {
String prefix = pathPrefix != null ? pathPrefix : "/";
return roles.scan(k -> true).stream()
.filter(r -> r.getPath().startsWith(prefix))
.sorted(Comparator.comparing(IamRole::getRoleName))
.toList();
}
@@ -1561,6 +1562,7 @@ public class IamService implements SessionAccountLookup, ResourceProvider {
policies.scan(k -> true).stream()
.filter(p -> !AwsManagedPolicies.isManagedPolicyArn(p.getArn()))
.filter(p -> p.getPath().startsWith(prefix))
.sorted(Comparator.comparing(IamPolicy::getPolicyName))
.forEach(result::add);
}
if (includeAws) {
@@ -0,0 +1,246 @@
package io.github.hectorvent.floci.services.iam;
import io.quarkus.test.junit.QuarkusTest;
import io.restassured.path.xml.XmlPath;
import io.restassured.specification.RequestSpecification;
import org.junit.jupiter.api.Test;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.function.Function;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.equalTo;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* ListRoles and ListPolicies page through {@code MaxItems} and {@code Marker}. Both requests model
* {@code MaxItems} with a range of 1 to 1000 and document that an omitted value "defaults to 100".
*
* <p>IAM state is shared across the suite, so each test scopes its listing to a path of its own
* and removes what it created.
*/
@QuarkusTest
class IamListPaginationIntegrationTest {
private static final String IAM_AUTH =
"AWS4-HMAC-SHA256 Credential=test/20260227/us-east-1/iam/aws4_request";
private static final String TRUST_POLICY = """
{"Version":"2012-10-17","Statement":[{"Effect":"Allow",\
"Principal":{"Service":"lambda.amazonaws.com"},"Action":"sts:AssumeRole"}]}""";
private static final String POLICY_DOCUMENT = """
{"Version":"2012-10-17","Statement":[{"Effect":"Allow","Action":"s3:GetObject",\
"Resource":"*"}]}""";
private static RequestSpecification iam(String action) {
return given().header("Authorization", IAM_AUTH).formParam("Action", action);
}
private static String suffix() {
return Long.toString(System.nanoTime(), 36);
}
private record Page(List<String> names, boolean truncated, String marker) {}
private static Page page(String action, String listElement, String nameElement,
RequestSpecification request) {
String result = action + "Response." + action + "Result.";
XmlPath xml = request.when().post("/").then().statusCode(200).extract().xmlPath();
String marker = xml.getString(result + "Marker");
return new Page(xml.getList(result + listElement + ".member." + nameElement, String.class),
Boolean.parseBoolean(xml.getString(result + "IsTruncated")),
marker == null || marker.isEmpty() ? null : marker);
}
private static Page rolePage(String pathPrefix, String maxItems, String marker) {
RequestSpecification request = iam("ListRoles").formParam("PathPrefix", pathPrefix);
if (maxItems != null) {
request.formParam("MaxItems", maxItems);
}
if (marker != null) {
request.formParam("Marker", marker);
}
return page("ListRoles", "Roles", "RoleName", request);
}
private static Page policyPage(String scope, String pathPrefix, String maxItems, String marker) {
RequestSpecification request = iam("ListPolicies").formParam("Scope", scope);
if (pathPrefix != null) {
request.formParam("PathPrefix", pathPrefix);
}
if (maxItems != null) {
request.formParam("MaxItems", maxItems);
}
if (marker != null) {
request.formParam("Marker", marker);
}
return page("ListPolicies", "Policies", "Arn", request);
}
/**
* Follows {@code Marker} until {@code IsTruncated} is false, checking on every page that a
* marker is present exactly when the page is truncated.
*/
private static List<Page> walk(Function<String, Page> next) {
List<Page> pages = new ArrayList<>();
String marker = null;
do {
Page current = next.apply(marker);
if (current.truncated()) {
assertNotNull(current.marker(), "a truncated page carries a Marker");
} else {
assertNull(current.marker(), "the last page carries no Marker");
}
pages.add(current);
marker = current.marker();
} while (marker != null);
return pages;
}
private static List<String> flatten(List<Page> pages) {
List<String> all = new ArrayList<>();
pages.forEach(p -> all.addAll(p.names()));
return all;
}
private static void createRole(String name, String path) {
iam("CreateRole").formParam("RoleName", name).formParam("Path", path)
.formParam("AssumeRolePolicyDocument", TRUST_POLICY)
.when().post("/").then().statusCode(200);
}
private static void deleteRole(String name) {
iam("DeleteRole").formParam("RoleName", name).when().post("/").then().statusCode(200);
}
private static String createPolicy(String name, String path) {
return iam("CreatePolicy").formParam("PolicyName", name).formParam("Path", path)
.formParam("PolicyDocument", POLICY_DOCUMENT)
.when().post("/").then().statusCode(200)
.extract().path("CreatePolicyResponse.CreatePolicyResult.Policy.Arn");
}
private static void deletePolicy(String arn) {
iam("DeletePolicy").formParam("PolicyArn", arn).when().post("/").then().statusCode(200);
}
@Test
void listRolesPagesThroughThePathPrefixInNameOrder() {
String tag = suffix();
String path = "/pg-roles-" + tag + "/";
List<String> expected = new ArrayList<>();
for (int i = 0; i < 5; i++) {
expected.add("pg-role-" + tag + "-" + i);
}
String outside = "pg-role-" + tag + "-outside";
expected.forEach(name -> createRole(name, path));
createRole(outside, "/pg-roles-other-" + tag + "/");
try {
List<Page> pages = walk(marker -> rolePage(path, "2", marker));
assertEquals(List.of(2, 2, 1), pages.stream().map(p -> p.names().size()).toList());
assertEquals(List.of(true, true, false), pages.stream().map(Page::truncated).toList());
assertEquals(expected, flatten(pages), "every role once, in name order, nothing outside the prefix");
} finally {
expected.forEach(IamListPaginationIntegrationTest::deleteRole);
deleteRole(outside);
}
}
@Test
void listRolesDefaultsToOneHundredItems() {
String tag = suffix();
String path = "/pg-roles-default-" + tag + "/";
List<String> names = new ArrayList<>();
for (int i = 0; i < 101; i++) {
names.add(String.format("pg-default-%s-%03d", tag, i));
}
names.forEach(name -> createRole(name, path));
try {
Page first = rolePage(path, null, null);
assertEquals(100, first.names().size());
assertTrue(first.truncated());
assertNotNull(first.marker());
Page second = rolePage(path, null, first.marker());
assertEquals(List.of(names.get(100)), second.names());
assertFalse(second.truncated());
assertNull(second.marker());
} finally {
names.forEach(IamListPaginationIntegrationTest::deleteRole);
}
}
@Test
void listPoliciesPagesThroughScopeAndPathPrefix() {
String tag = suffix();
String path = "/pg-policies-" + tag + "/";
List<String> expected = new ArrayList<>();
for (int i = 0; i < 5; i++) {
expected.add(createPolicy("pg-policy-" + tag + "-" + i, path));
}
String outside = createPolicy("pg-policy-" + tag + "-outside", "/pg-policies-other-" + tag + "/");
try {
List<Page> pages = walk(marker -> policyPage("Local", path, "2", marker));
assertEquals(List.of(2, 2, 1), pages.stream().map(p -> p.names().size()).toList());
assertEquals(List.of(true, true, false), pages.stream().map(Page::truncated).toList());
assertEquals(expected, flatten(pages), "every policy once, in name order, nothing outside the prefix");
} finally {
expected.forEach(IamListPaginationIntegrationTest::deletePolicy);
deletePolicy(outside);
}
}
@Test
void listPoliciesDefaultsToOneHundredAndWalksTheWholeCatalog() {
Page first = policyPage("AWS", null, null, null);
assertEquals(100, first.names().size(), "an omitted MaxItems defaults to 100");
assertTrue(first.truncated());
List<String> byDefault = flatten(walk(marker -> policyPage("AWS", null, null, marker)));
List<String> byLargest = flatten(walk(marker -> policyPage("AWS", null, "1000", marker)));
assertTrue(byDefault.size() > 100, "the AWS managed catalog is wider than one default page");
assertEquals(byDefault.size(), new HashSet<>(byDefault).size(), "no policy repeats across pages");
assertEquals(byLargest, byDefault, "the page size changes where pages split, not what they hold");
}
@Test
void listRolesAndListPoliciesRejectMaxItemsOutsideOneToOneThousand() {
for (String action : List.of("ListRoles", "ListPolicies")) {
iam(action).formParam("MaxItems", "0")
.when().post("/").then()
.statusCode(400)
.body("ErrorResponse.Error.Code", equalTo("ValidationError"))
.body("ErrorResponse.Error.Message", equalTo(
"1 validation error detected: Value '0' at 'maxItems' failed to satisfy "
+ "constraint: Member must have value greater than or equal to 1"));
iam(action).formParam("MaxItems", "1001")
.when().post("/").then()
.statusCode(400)
.body("ErrorResponse.Error.Code", equalTo("ValidationError"))
.body("ErrorResponse.Error.Message", equalTo(
"1 validation error detected: Value '1001' at 'maxItems' failed to satisfy "
+ "constraint: Member must have value less than or equal to 1000"));
iam(action).formParam("MaxItems", "1000").when().post("/").then().statusCode(200);
}
}
@Test
void listRolesAndListPoliciesRejectAMarkerTheyDidNotIssue() {
for (String action : List.of("ListRoles", "ListPolicies")) {
iam(action).formParam("Marker", "not-a-marker")
.when().post("/").then()
.statusCode(400)
.body("ErrorResponse.Error.Code", equalTo("InvalidInput"));
}
}
}
@@ -2,6 +2,7 @@ package io.github.hectorvent.floci.services.iam;
import io.github.hectorvent.floci.core.common.XmlParser;
import io.quarkus.test.junit.QuarkusTest;
import io.restassured.path.xml.XmlPath;
import io.restassured.response.Response;
import org.junit.jupiter.api.Test;
@@ -81,10 +82,24 @@ class IamManagedPolicyAttachmentCountIntegrationTest {
iam(accountId, "GetPolicy", Map.of("PolicyArn", POLICY_ARN)).then().statusCode(200)
.body("GetPolicyResponse.GetPolicyResult.Policy.AttachmentCount",
equalTo(Integer.toString(expectedCount)));
iam(accountId, "ListPolicies", Map.of("Scope", "AWS")).then().statusCode(200)
.body("ListPoliciesResponse.ListPoliciesResult.Policies.member.find { it.Arn == '"
+ POLICY_ARN + "' }.AttachmentCount",
equalTo(Integer.toString(expectedCount)));
assertEquals(Integer.toString(expectedCount), listedAttachmentCount(accountId));
}
/** ListPolicies pages the AWS managed catalog, so this follows the Marker to the policy. */
private String listedAttachmentCount(String accountId) {
String result = "ListPoliciesResponse.ListPoliciesResult.";
Map<String, String> parameters = Map.of("Scope", "AWS", "MaxItems", "1000");
while (true) {
XmlPath page = iam(accountId, "ListPolicies", parameters).then().statusCode(200)
.extract().xmlPath();
String count = page.getString(result + "Policies.member.find { it.Arn == '"
+ POLICY_ARN + "' }.AttachmentCount");
if (!count.isEmpty()) {
return count;
}
assertEquals("true", page.getString(result + "IsTruncated"), POLICY_ARN + " was never listed");
parameters = Map.of("Scope", "AWS", "MaxItems", "1000", "Marker", page.getString(result + "Marker"));
}
}
private void changeAttachment(String accountId, String action, String entityType, String name) {