Skip to content

armgit / floci

Public Imported from GitHub
0

Light, fluffy, and always free - The AWS Local Emulator alternative

fix(iam): page ListUsers, ListGroups and policy lists with MaxItems and Marker (#6267)

Allen Sanborn3212ce3c1565
diff --git a/Makefile b/Makefile
index eb9852837e..a0ca3494ea 100644
--- a/Makefile
+++ b/Makefile
@@ -34,6 +34,8 @@
# tools/aws/regen_emr_serverless_shapes.py.
# src/test/resources/aws/rest-routes.json, the REST routes IamRestRouteCoverageTest checks, is
# generated from botocore's models by tools/aws/regen_rest_routes.py.
+# src/main/resources/aws/iam-paginators.json, what each paged IAM list pages by, is generated
+# from botocore's IAM model and paginators by tools/aws/regen_iam_paginators.py.
PYTHON ?= python3
@@ -245,6 +247,7 @@ aws-data-sync: ## Regenerate src/main/resources/aws/*.json and the IAM managed-p
$(PYTHON) tools/aws/regen_emr_serverless_shapes.py
$(PYTHON) tools/aws/regen_query_services.py
$(PYTHON) tools/aws/regen_rest_routes.py
+ $(PYTHON) tools/aws/regen_iam_paginators.py
$(PYTHON) tools/aws/regen_managed_policies.py
aws-data-check: ## CI gate: the vendored AWS data must match a fresh generation
@@ -334,6 +337,12 @@ aws-data-check: ## CI gate: the vendored AWS data must match a fresh generation
echo " Run 'make aws-data-sync' and commit the result."; \
exit 1; \
}
+ @$(PYTHON) tools/aws/regen_iam_paginators.py --check || { \
+ echo ""; \
+ echo "error: src/main/resources/aws/iam-paginators.json is out of date."; \
+ echo " Run 'make aws-data-sync' and commit the result."; \
+ exit 1; \
+ }
@$(PYTHON) tools/aws/regen_managed_policies.py --check || { \
echo ""; \
echo "error: the IAM managed-policy catalog (src/main/resources/iam/managed-polic*) is out of date or malformed."; \
diff --git a/docs/services/iam.md b/docs/services/iam.md
index 92e3bd2e85..8ae460bb55 100644
--- a/docs/services/iam.md
+++ b/docs/services/iam.md
@@ -33,6 +33,44 @@ or at the AWS Sign-In host of a region in the deployment's partition; any other
## Supported Actions
+### Pagination
+
+Every IAM operation whose request models `Marker` pages through one path, driven by
+`src/main/resources/aws/iam-paginators.json`. That table is generated by
+`tools/aws/regen_iam_paginators.py` from botocore's IAM model: the 34 operations its
+`paginators-1.json` lists, with their tokens, limit key and result keys, plus the six that model
+`Marker` without a paginator (`GetServiceLastAccessedDetails`,
+`GetServiceLastAccessedDetailsWithEntities`, `GetOrganizationsAccessReport`,
+`ListServiceSpecificCredentials`, `ListDelegationRequests` and `ListPoliciesGrantingServiceAccess`).
+An operation AWS starts paging later needs `make aws-data-sync`, not new handler code.
+
+- `MaxItems` must be between 1 and 1000, as `maxItemsType` declares, and a `Marker` between 1 and
+ 320 characters of `markerType`'s pattern. Both are read from the model rather than from the table:
+ every paged operation is in the `IamRequestShapes` wave (`tools/aws/regen_iam_shapes.py`), so a
+ value outside either is a `ValidationError` before the operation runs. An omitted `MaxItems` is the default the reference documents ("the number of
+ items defaults to 100"), and the whole list where it documents none
+ (`ListServiceSpecificCredentials`). `ListPoliciesGrantingServiceAccess` models no `MaxItems`, so it
+ is never truncated.
+- A truncated page carries `IsTruncated=true` and a `Marker`; the last page carries no `Marker`.
+- A `Marker` is opaque and resumes only the listing that issued it. AWS documents it as "the value
+ of the `Marker` element in the response that you received", so any value Floci did not issue, a
+ bare number included, is `InvalidInput`. The marker is signed over the account, the operation and
+ every request member except `Marker` and `MaxItems`, so a marker from another operation, another
+ principal or filter, or another account is refused, while the page size may change between calls.
+ On the lists whose `UserName` defaults to the caller (`ListAccessKeys`, `ListMFADevices`,
+ `ListSSHPublicKeys`, `ListSigningCertificates`, `ListServiceSpecificCredentials`), the marker is
+ signed over the user the list was read for, so one user's marker does not resume another's when
+ both omit `UserName`. Markers are signed with a key generated at startup and do not survive a restart.
+- A marker names the last item of its page rather than a position, so the next page resumes after
+ that item wherever it now sits: an item created or deleted ahead of it neither repeats nor skips
+ anything. Each list is ordered by the key its marker names (users, groups, roles, instance profiles
+ and inline policies by name, attached policies by ARN, tags by key, policy versions by number).
+ `ListEntitiesForPolicy` and `GetAccountAuthorizationDetails` page their several lists as one, in
+ the paginator's order.
+- Every marker Floci issues fits `markerType`'s 320 characters. One whose key would not, an ARN with
+ a long path, carries a SHA-256 digest of the key instead, and Floci keeps the key the digest stands
+ for, so the marker still resumes after its item when that item has been deleted.
+
### Users
| Action | Description |
@@ -146,13 +184,11 @@ reads "Map value must satisfy constraint".
| ListPolicyTags | Lists tags stored for a managed policy. |
`ListEntitiesForPolicy` currently returns direct permissions-policy attachments. `EntityFilter`,
-`PathPrefix`, `PolicyUsageFilter`, and pagination are not yet applied; responses return
-`IsTruncated=false`.
+`PathPrefix` and `PolicyUsageFilter` are not yet applied.
-`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`.
+`PathPrefix` and `Scope` filter before paging (see [Pagination](#pagination)). `ListPolicies` lists
+customer managed policies by name, then the AWS managed catalog, and does not yet apply
+`OnlyAttached` or `PolicyUsageFilter`.
The declared constraints on the managed-policy family are read from the model rather than from a
hand-written check, `tools/aws/regen_iam_shapes.py` vendoring them for `GetPolicy`, `DeletePolicy`,
@@ -192,6 +228,14 @@ pattern were all answered with a 200. A number too large for a 64-bit integer is
same, so a `MaxItems` of `9223372036854775808` breaks the maximum rather than reading as no number
at all.
+Every other paged operation joined that wave (see [Pagination](#pagination)), most with their whole
+request. Six join with `MaxItems` and `Marker` alone and keep the reading they have for the rest:
+the three report readers, whose `JobId` is answered as one fixed length ("length equal to 36") and
+whose `SortKey` is held to its enum by hand, `ListPoliciesGrantingServiceAccess`, whose empty
+`ServiceNamespaces` is answered `InvalidInput`, and `SimulateCustomPolicy` and
+`SimulatePrincipalPolicy`, whose `ContextEntries` nest a list inside a list of structures, which the
+walk does not read.
+
### Permission Boundaries
| Action | Description |
@@ -617,9 +661,7 @@ completion timestamps are the same instant. Jobs are kept for the life of the st
no expiry for a `JobId`, so ageing them out would mean inventing a retention window and failing a
caller holding an ID that AWS would still answer.
-Both readers honour `MaxItems` and `Marker` and report `IsTruncated` truthfully, returning a
-`Marker` only when a page remains. This differs from the rest of this page, where pagination inputs
-are accepted and ignored; these actions apply them rather than inherit that gap.
+Both readers page as every IAM list does (see [Pagination](#pagination)).
`ListPoliciesGrantingServiceAccess` is not an Access Advisor job and needs no usage history: AWS
defines it purely over permissions-policy logic, so it is answered from real policy content. It
@@ -740,9 +782,7 @@ Request shapes are checked before the device is resolved, so a `SerialNumber` ou
9-to-256 range is a `ValidationError` rather than a `NoSuchEntity` for a device that could not have
existed. Note that `VirtualMFADeviceName` is the one IAM name type with no documented maximum
length: a name longer than the 128 characters other IAM names stop at is accepted here, as on AWS.
-`ListMFADeviceTags` honors `Marker` and `MaxItems`, sorting by tag key first as AWS documents, so a
-client can walk the result a page at a time. IAM's other tag readers in Floci still return every
-tag with `IsTruncated=false`.
+`ListMFADeviceTags`, like every IAM tag reader, pages in tag-key order, as AWS documents.
`VirtualMFADeviceName` has no maximum length, but the serial number it mints does: 256 characters.
A name long enough to overflow that is rejected at creation rather than producing a device whose
@@ -799,8 +839,8 @@ authorization means touching the request context and STS session shape, which is
| GenerateCredentialReport | Generates (or, within 4 hours of the last one, reuses) the account's credential report. |
| GetCredentialReport | Returns the most recently generated credential report as Base64-encoded CSV. |
-`Filter`, `MaxItems` and `Marker` are not honored: the response always includes everything, with
-`IsTruncated` always `false`. `AttachmentCount` and `PermissionsBoundaryUsageCount` are computed by
+`Filter` is not honored: the response includes every user, group, role and relevant policy, and
+`MaxItems` and `Marker` page the four lists as one. `AttachmentCount` and `PermissionsBoundaryUsageCount` are computed by
scanning the account's own users, groups and roles rather than read off a stored counter, so they
are correctly scoped to the calling account even for an AWS-managed policy (see the note on
`IamService.getAccountAuthorizationDetails` for why that distinction matters). Policy documents are
diff --git a/src/main/java/io/github/hectorvent/floci/core/common/SignedMarkers.java b/src/main/java/io/github/hectorvent/floci/core/common/SignedMarkers.java
index 31e5bd55a4..93139c1b66 100644
--- a/src/main/java/io/github/hectorvent/floci/core/common/SignedMarkers.java
+++ b/src/main/java/io/github/hectorvent/floci/core/common/SignedMarkers.java
@@ -5,7 +5,11 @@ import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.security.GeneralSecurityException;
import java.security.MessageDigest;
+import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
+import java.util.Collections;
+import java.util.LinkedHashMap;
+import java.util.Map;
/**
* Pagination markers that name a cursor, as AWS's opaque tokens do. Each marker is signed with a
@@ -15,15 +19,68 @@ import java.security.SecureRandom;
public final class SignedMarkers {
private static final char SEPARATOR = '.';
+ /** Opens a cursor that stands for a longer one by its digest. No key a list pages by holds a NUL. */
+ private static final String DIGEST_PREFIX = "\u0000#";
+ /** Long cursors held per instance; a marker whose digest was evicted is refused as unknown. */
+ static final int MAX_LONG_CURSORS = 10_000;
private final byte[] key = newKey();
+ private final int maxLength;
+ /**
+ * The cursors too long to carry, by the digest a marker carries instead. An entry is the key of
+ * an item a page ended on, so a marker resumes after that item even once it is deleted.
+ * Bounded with LRU-style eviction, as an expired AWS token would be refused.
+ */
+ private final Map<String, String> longCursors = Collections.synchronizedMap(
+ new LinkedHashMap<>(16, 0.75f, true) {
+ @Override
+ protected boolean removeEldestEntry(Map.Entry<String, String> eldest) {
+ return size() > MAX_LONG_CURSORS;
+ }
+ });
+
+ public SignedMarkers() {
+ this(Integer.MAX_VALUE);
+ }
+
+ /** Markers no longer than {@code maxLength}, however long the cursor they name. */
+ public SignedMarkers(int maxLength) {
+ this.maxLength = maxLength;
+ }
public String issue(String cursor) {
return Base64Url.encode(cursor + SEPARATOR + sign(cursor));
}
+ /**
+ * A marker for {@code cursor} that only {@link #cursorOf(String, String)} with the same
+ * {@code scope} recognises. The scope is signed rather than carried, so it costs the marker no
+ * length. A cursor that would make the marker longer than this instance's limit is carried as
+ * its digest instead and read back from the cursors this instance has issued.
+ */
+ public String issue(String scope, String cursor) {
+ if (!cursor.startsWith(DIGEST_PREFIX)) {
+ String marker = scopedMarker(scope, cursor);
+ if (marker.length() <= maxLength) {
+ return marker;
+ }
+ }
+ String digest = DIGEST_PREFIX + digest(cursor);
+ longCursors.put(digest, cursor);
+ return scopedMarker(scope, digest);
+ }
+
+ private String scopedMarker(String scope, String cursor) {
+ return Base64Url.encode(cursor + SEPARATOR + sign(scoped(scope, cursor)));
+ }
+
/** The cursor a marker names, or null when this instance did not issue it. */
public String cursorOf(String marker) {
+ return cursorOf(null, marker);
+ }
+
+ /** The cursor a marker names, or null when this instance did not issue it for {@code scope}. */
+ public String cursorOf(String scope, String marker) {
String decoded;
try {
decoded = Base64Url.decode(marker);
@@ -37,10 +94,25 @@ public final class SignedMarkers {
}
String cursor = decoded.substring(0, separator);
byte[] presented = decoded.substring(separator + 1).getBytes(StandardCharsets.UTF_8);
- if (!MessageDigest.isEqual(presented, sign(cursor).getBytes(StandardCharsets.UTF_8))) {
+ String signed = scope == null ? cursor : scoped(scope, cursor);
+ if (!MessageDigest.isEqual(presented, sign(signed).getBytes(StandardCharsets.UTF_8))) {
return null;
}
- return cursor;
+ return cursor.startsWith(DIGEST_PREFIX) ? longCursors.get(cursor) : cursor;
+ }
+
+ private static String digest(String cursor) {
+ try {
+ return Base64Url.encode(MessageDigest.getInstance("SHA-256")
+ .digest(cursor.getBytes(StandardCharsets.UTF_8)));
+ } catch (NoSuchAlgorithmException e) {
+ throw new IllegalStateException("SHA-256 is required to shorten pagination markers", e);
+ }
+ }
+
+ /** Length-prefixed, so no scope and cursor pair signs the same text as another. */
+ private static String scoped(String scope, String cursor) {
+ return scope.length() + ":" + scope + cursor;
}
private String sign(String cursor) {
diff --git a/src/main/java/io/github/hectorvent/floci/services/iam/IamPaginators.java b/src/main/java/io/github/hectorvent/floci/services/iam/IamPaginators.java
new file mode 100644
index 0000000000..ef032bbf31
--- /dev/null
+++ b/src/main/java/io/github/hectorvent/floci/services/iam/IamPaginators.java
@@ -0,0 +1,91 @@
+package io.github.hectorvent.floci.services.iam;
+
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import io.github.hectorvent.floci.core.common.VendoredResources;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.util.ArrayList;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+
+/**
+ * What every paged IAM operation pages by, read once from the vendored
+ * {@code aws/iam-paginators.json}. {@link IamQueryHandler} pages each list through one path that
+ * reads its operation's entry here.
+ *
+ * <p>The file is generated by {@code tools/aws/regen_iam_paginators.py} from botocore's IAM model:
+ * every operation whose request models {@code Marker}, with botocore's paginator where it has one.
+ * An operation AWS starts paging later needs a regeneration, not new handler code. {@code make
+ * aws-data-check} fails when it is stale against the pinned botocore.
+ *
+ * <p>A missing or malformed resource is a build defect, not a runtime condition, so loading fails
+ * with {@link IllegalStateException} rather than degrading to lists that never page.
+ */
+final class IamPaginators {
+
+ static final String RESOURCE_NAME = "aws/iam-paginators.json";
+
+ /**
+ * One operation's paging. {@code limitKey} is null where the request models no limit, and
+ * {@code defaultItems} is null where the reference documents no default page size, in which
+ * case an omitted limit returns the whole list. {@code resultKeys} is empty for an operation
+ * botocore has no paginator for.
+ *
+ * <p>No bound is carried: the limit's range and the marker's length are request constraints,
+ * which {@link IamRequestShapes} holds a request to before the operation runs.
+ */
+ record Paginator(String inputToken, String outputToken, String limitKey, String moreResults,
+ List<String> resultKeys, Integer defaultItems) {
+ }
+
+ private static final ObjectMapper MAPPER = new ObjectMapper();
+
+ private static final class Holder {
+ static final Map<String, Paginator> OPERATIONS = VendoredResources.read(RESOURCE_NAME,
+ "IAM paginator table", IamPaginators::parse);
+ }
+
+ private IamPaginators() {
+ }
+
+ /** The paging of {@code operation}; an operation the table lacks is a handler defect. */
+ static Paginator of(String operation) {
+ Paginator paginator = Holder.OPERATIONS.get(operation);
+ if (paginator == null) {
+ throw new IllegalStateException(RESOURCE_NAME + " has no paged operation " + operation);
+ }
+ return paginator;
+ }
+
+ static Map<String, Paginator> parse(InputStream in) throws IOException {
+ JsonNode operations = MAPPER.readTree(in).path("operations");
+ if (!operations.isObject() || operations.isEmpty()) {
+ throw new IllegalStateException(RESOURCE_NAME + " carries no operations");
+ }
+ Map<String, Paginator> parsed = new LinkedHashMap<>();
+ operations.properties().forEach(entry -> parsed.put(entry.getKey(), paginator(entry.getKey(), entry.getValue())));
+ return Map.copyOf(parsed);
+ }
+
+ private static Paginator paginator(String operation, JsonNode node) {
+ List<String> resultKeys = new ArrayList<>();
+ node.path("resultKeys").forEach(key -> resultKeys.add(key.asText()));
+ String inputToken = text(node, "inputToken");
+ String outputToken = text(node, "outputToken");
+ String moreResults = text(node, "moreResults");
+ if (inputToken == null || outputToken == null || moreResults == null) {
+ throw new IllegalStateException(RESOURCE_NAME + ": " + operation + " lacks a token");
+ }
+ JsonNode defaultItems = node.path("defaultItems");
+ return new Paginator(inputToken, outputToken, text(node, "limitKey"), moreResults,
+ List.copyOf(resultKeys), defaultItems.isInt() ? defaultItems.asInt() : null);
+ }
+
+ private static String text(JsonNode node, String field) {
+ JsonNode value = node.path(field);
+ return value.isTextual() ? value.asText() : null;
+ }
+}
diff --git a/src/main/java/io/github/hectorvent/floci/services/iam/IamQueryHandler.java b/src/main/java/io/github/hectorvent/floci/services/iam/IamQueryHandler.java
index 0a609781f9..f7710ed652 100644
--- a/src/main/java/io/github/hectorvent/floci/services/iam/IamQueryHandler.java
+++ b/src/main/java/io/github/hectorvent/floci/services/iam/IamQueryHandler.java
@@ -31,6 +31,7 @@ import io.github.hectorvent.floci.services.iam.model.VirtualMfaDevice;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.enterprise.inject.Instance;
import jakarta.inject.Inject;
+import jakarta.ws.rs.core.MultivaluedHashMap;
import jakarta.ws.rs.core.MultivaluedMap;
import jakarta.ws.rs.core.Response;
import org.jboss.logging.Logger;
@@ -50,6 +51,7 @@ import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.TreeMap;
+import java.util.function.BiConsumer;
import java.util.function.Function;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
@@ -65,9 +67,8 @@ public class IamQueryHandler {
private static final Logger LOG = Logger.getLogger(IamQueryHandler.class);
- /** {@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 markerType}'s maximum, which every marker issued has to fit to be accepted back. */
+ private static final int MARKER_MAX_LENGTH = 320;
/** {@code jobIDType} on every report reader: min 36 and max 36, which is a UUID string. */
private static final int JOB_ID_LENGTH = 36;
/** {@code arnType} on {@code PolicySourceArn} and {@code TemplateArn}: 20 to 2048, no pattern. */
@@ -117,7 +118,7 @@ public class IamQueryHandler {
private final RegionResolver regionResolver;
private final Instance<ServerCertificateReferenceProvider> serverCertificateReferenceProviders;
/** Signs each page's Marker, so only a marker this handler issued names an item. */
- private final SignedMarkers markers = new SignedMarkers();
+ private final SignedMarkers markers = new SignedMarkers(MARKER_MAX_LENGTH);
@Inject
public IamQueryHandler(IamService iamService, IamPolicyEvaluator policyEvaluator,
@@ -418,6 +419,20 @@ public class IamQueryHandler {
"The Access Key with id " + accessKeyId + " cannot be found.", 404));
}
+ /**
+ * The request with {@code UserName} set to the user it acts on, for a listing whose user may be
+ * the caller. A marker is signed over the request's members, so a listing paged from the raw
+ * request would give every caller who omits {@code UserName} the same scope, and one user's
+ * marker would resume another's listing. Paged from this, the marker is bound to the user the
+ * list was read for, whether named or resolved.
+ */
+ private MultivaluedMap<String, String> withResolvedUser(MultivaluedMap<String, String> params,
+ String authorization) {
+ MultivaluedMap<String, String> resolved = new MultivaluedHashMap<>(params);
+ resolved.putSingle("UserName", resolveUserName(params, authorization));
+ return resolved;
+ }
+
private Response handleGetUser(MultivaluedMap<String, String> params, String authorization) {
// UserName is optional per the IAM model: it defaults to the user owning the
// access key that signed the request.
@@ -433,14 +448,8 @@ public class IamQueryHandler {
}
private Response handleListUsers(MultivaluedMap<String, String> params) {
- String pathPrefix = getParam(params, "PathPrefix");
- List<IamUser> userList = iamService.listUsers(pathPrefix);
- XmlBuilder xml = new XmlBuilder().start("Users");
- for (IamUser u : userList) {
- xml.start("member").raw(userXml(u, false)).end("member");
- }
- xml.end("Users").elem("IsTruncated", false);
- return Response.ok(AwsQueryResponse.envelope("ListUsers", AwsNamespaces.IAM, xml.build())).build();
+ return pagedList("ListUsers", iamService.listUsers(getParam(params, "PathPrefix")), IamUser::getUserName,
+ params, (xml, u) -> xml.start("member").raw(userXml(u, false)).end("member"));
}
private Response handleUpdateUser(MultivaluedMap<String, String> params) {
@@ -464,11 +473,7 @@ public class IamQueryHandler {
}
private Response handleListUserTags(MultivaluedMap<String, String> params) {
- String userName = getParam(params, "UserName");
- Map<String, String> tags = iamService.listUserTags(userName);
- String result = new XmlBuilder().start("Tags").raw(tagsXml(tags)).end("Tags")
- .elem("IsTruncated", false).build();
- return Response.ok(AwsQueryResponse.envelope("ListUserTags", AwsNamespaces.IAM, result)).build();
+ return pagedTags("ListUserTags", iamService.listUserTags(getParam(params, "UserName")), params);
}
/**
@@ -500,11 +505,9 @@ public class IamQueryHandler {
* leak the shared secret of every device in the account.
*/
private Response handleListVirtualMFADevices(MultivaluedMap<String, String> params) {
- Page<VirtualMfaDevice> page = paginate(
+ return pagedList("ListVirtualMFADevices",
iamService.listVirtualMfaDevices(getParam(params, "AssignmentStatus")),
- VirtualMfaDevice::getSerialNumber, params);
- XmlBuilder xml = new XmlBuilder().start("VirtualMFADevices");
- for (VirtualMfaDevice device : page.items()) {
+ VirtualMfaDevice::getSerialNumber, params, (xml, device) -> {
xml.start("member").elem("SerialNumber", device.getSerialNumber());
if (device.isAssigned()) {
xml.elem("EnableDate", isoDate(device.getEnableDate()));
@@ -516,12 +519,7 @@ public class IamQueryHandler {
.ifPresent(user -> xml.start("User").raw(userXml(user, false)).end("User"));
}
xml.end("member");
- }
- xml.end("VirtualMFADevices").elem("IsTruncated", page.truncated());
- if (page.marker() != null) {
- xml.elem("Marker", page.marker());
- }
- return Response.ok(AwsQueryResponse.envelope("ListVirtualMFADevices", AwsNamespaces.IAM, xml.build())).build();
+ });
}
private Response handleDeleteVirtualMFADevice(MultivaluedMap<String, String> params) {
@@ -549,22 +547,14 @@ public class IamQueryHandler {
return Response.ok(AwsQueryResponse.envelopeNoResult("ResyncMFADevice", AwsNamespaces.IAM)).build();
}
- private Response handleListMFADevices(MultivaluedMap<String, String> params, String authorization) {
- String userName = resolveUserName(params, authorization);
- Page<VirtualMfaDevice> page = paginate(iamService.listMfaDevices(userName), VirtualMfaDevice::getSerialNumber, params);
- XmlBuilder xml = new XmlBuilder().start("MFADevices");
- for (VirtualMfaDevice device : page.items()) {
- xml.start("member")
- .elem("UserName", device.getUserName())
- .elem("SerialNumber", device.getSerialNumber())
- .elem("EnableDate", isoDate(device.getEnableDate()))
- .end("member");
- }
- xml.end("MFADevices").elem("IsTruncated", page.truncated());
- if (page.marker() != null) {
- xml.elem("Marker", page.marker());
- }
- return Response.ok(AwsQueryResponse.envelope("ListMFADevices", AwsNamespaces.IAM, xml.build())).build();
+ private Response handleListMFADevices(MultivaluedMap<String, String> request, String authorization) {
+ MultivaluedMap<String, String> params = withResolvedUser(request, authorization);
+ return pagedList("ListMFADevices", iamService.listMfaDevices(getParam(params, "UserName")),
+ VirtualMfaDevice::getSerialNumber, params, (xml, device) -> xml.start("member")
+ .elem("UserName", device.getUserName())
+ .elem("SerialNumber", device.getSerialNumber())
+ .elem("EnableDate", isoDate(device.getEnableDate()))
+ .end("member"));
}
private Response handleTagMFADevice(MultivaluedMap<String, String> params) {
@@ -577,24 +567,8 @@ public class IamQueryHandler {
return Response.ok(AwsQueryResponse.envelopeNoResult("UntagMFADevice", AwsNamespaces.IAM)).build();
}
- /**
- * Unlike IAM's other tag readers here, this one honours {@code Marker} and {@code MaxItems}:
- * AWS models both on ListMFADeviceTags, and a client asking for a one-item page should be able
- * to walk the result. Tags are sorted by key first, as AWS documents ("the returned list of
- * tags is sorted by tag key"), so the marker names a stable position.
- */
private Response handleListMFADeviceTags(MultivaluedMap<String, String> params) {
- Map<String, String> tags = new TreeMap<>(iamService.listMfaDeviceTags(getParam(params, "SerialNumber")));
- Page<Map.Entry<String, String>> page = paginate(List.copyOf(tags.entrySet()), Map.Entry::getKey, params);
- XmlBuilder xml = new XmlBuilder().start("Tags");
- for (Map.Entry<String, String> tag : page.items()) {
- xml.start("member").elem("Key", tag.getKey()).elem("Value", tag.getValue()).end("member");
- }
- xml.end("Tags").elem("IsTruncated", page.truncated());
- if (page.marker() != null) {
- xml.elem("Marker", page.marker());
- }
- return Response.ok(AwsQueryResponse.envelope("ListMFADeviceTags", AwsNamespaces.IAM, xml.build())).build();
+ return pagedTags("ListMFADeviceTags", iamService.listMfaDeviceTags(getParam(params, "SerialNumber")), params);
}
/**
@@ -767,11 +741,8 @@ public class IamQueryHandler {
private Response handleListSAMLProviderTags(MultivaluedMap<String, String> params, String authorization) {
String accountId = accountResolver.resolve(authorization);
- Map<String, String> tags = new TreeMap<>(
- samlProviderService.listTags(accountId, getParam(params, "SAMLProviderArn")));
- String result = new XmlBuilder().start("Tags").raw(tagsXml(tags)).end("Tags")
- .elem("IsTruncated", false).build();
- return Response.ok(AwsQueryResponse.envelope("ListSAMLProviderTags", AwsNamespaces.IAM, result)).build();
+ return pagedTags("ListSAMLProviderTags",
+ samlProviderService.listTags(accountId, getParam(params, "SAMLProviderArn")), params);
}
// ListOpenIDConnectProviders is not paginated and carries only ARNs — the client fetches
@@ -858,13 +829,8 @@ public class IamQueryHandler {
}
private Response handleListOpenIDConnectProviderTags(MultivaluedMap<String, String> params) {
- Map<String, String> providerTags =
- iamService.listOpenIDConnectProviderTags(getParam(params, "OpenIDConnectProviderArn"));
- String result = new XmlBuilder()
- .start("Tags").raw(tagsXml(providerTags)).end("Tags")
- .elem("IsTruncated", false)
- .build();
- return Response.ok(AwsQueryResponse.envelope("ListOpenIDConnectProviderTags", AwsNamespaces.IAM, result)).build();
+ return pagedTags("ListOpenIDConnectProviderTags",
+ iamService.listOpenIDConnectProviderTags(getParam(params, "OpenIDConnectProviderArn")), params);
}
private Response handleUploadServerCertificate(MultivaluedMap<String, String> params) {
@@ -915,18 +881,9 @@ public class IamQueryHandler {
* body, certificate chain, or private key".
*/
private Response handleListServerCertificates(MultivaluedMap<String, String> params) {
- Page<ServerCertificate> page = paginate(
- iamService.listServerCertificates(getParam(params, "PathPrefix")),
- ServerCertificate::getServerCertificateName, params);
- XmlBuilder xml = new XmlBuilder().start("ServerCertificateMetadataList");
- for (ServerCertificate certificate : page.items()) {
- xml.start("member").raw(serverCertificateMetadataXml(certificate)).end("member");
- }
- xml.end("ServerCertificateMetadataList").elem("IsTruncated", page.truncated());
- if (page.marker() != null) {
- xml.elem("Marker", page.marker());
- }
- return Response.ok(AwsQueryResponse.envelope("ListServerCertificates", AwsNamespaces.IAM, xml.build())).build();
+ return pagedList("ListServerCertificates", iamService.listServerCertificates(getParam(params, "PathPrefix")),
+ ServerCertificate::getServerCertificateName, params,
+ (xml, certificate) -> xml.start("member").raw(serverCertificateMetadataXml(certificate)).end("member"));
}
/**
@@ -951,14 +908,15 @@ public class IamQueryHandler {
* quietly winning.
*/
private Response handleListServiceSpecificCredentials(
- MultivaluedMap<String, String> params, String authorization) {
- boolean allUsers = "true".equalsIgnoreCase(getParam(params, "AllUsers"));
- if (allUsers && getParam(params, "UserName") != null) {
+ MultivaluedMap<String, String> request, String authorization) {
+ boolean allUsers = "true".equalsIgnoreCase(getParam(request, "AllUsers"));
+ if (allUsers && getParam(request, "UserName") != null) {
throw new AwsException("ValidationError",
"AllUsers cannot be specified together with UserName.", 400);
}
- String userName = allUsers ? null : resolveUserName(params, authorization);
- Page<ServiceSpecificCredential> page = paginate(
+ MultivaluedMap<String, String> params = allUsers ? request : withResolvedUser(request, authorization);
+ String userName = allUsers ? null : getParam(params, "UserName");
+ Page<ServiceSpecificCredential> page = paginate("ListServiceSpecificCredentials",
iamService.listServiceSpecificCredentials(
userName, getParam(params, "ServiceName"), allUsers),
ServiceSpecificCredential::getServiceSpecificCredentialId, params);
@@ -966,10 +924,8 @@ public class IamQueryHandler {
for (ServiceSpecificCredential credential : page.items()) {
xml.start("member").raw(serviceCredentialXml(credential, false)).end("member");
}
- xml.end("ServiceSpecificCredentials").elem("IsTruncated", page.truncated());
- if (page.marker() != null) {
- xml.elem("Marker", page.marker());
- }
+ xml.end("ServiceSpecificCredentials");
+ continuation(xml, page);
return Response.ok(AwsQueryResponse.envelope("ListServiceSpecificCredentials",
AwsNamespaces.IAM, xml.build())).build();
}
@@ -1081,26 +1037,16 @@ public class IamQueryHandler {
* The metadata list only. AWS documents SSHPublicKeyMetadata as carrying the key "without the
* key's body or fingerprint", so neither appears here even though both are stored.
*/
- private Response handleListSshPublicKeys(MultivaluedMap<String, String> params,
+ private Response handleListSshPublicKeys(MultivaluedMap<String, String> request,
String authorization) {
- Page<SshPublicKey> page = paginate(
- iamService.listSshPublicKeys(resolveUserName(params, authorization)),
- SshPublicKey::getSshPublicKeyId, params);
- XmlBuilder xml = new XmlBuilder().start("SSHPublicKeys");
- for (SshPublicKey key : page.items()) {
- xml.start("member")
- .elem("UserName", key.getUserName())
- .elem("SSHPublicKeyId", key.getSshPublicKeyId())
- .elem("Status", key.getStatus())
- .elem("UploadDate", isoDate(key.getUploadDate()))
- .end("member");
- }
- xml.end("SSHPublicKeys").elem("IsTruncated", page.truncated());
- if (page.marker() != null) {
- xml.elem("Marker", page.marker());
- }
- return Response.ok(AwsQueryResponse.envelope("ListSSHPublicKeys",
- AwsNamespaces.IAM, xml.build())).build();
+ MultivaluedMap<String, String> params = withResolvedUser(request, authorization);
+ return pagedList("ListSSHPublicKeys", iamService.listSshPublicKeys(getParam(params, "UserName")),
+ SshPublicKey::getSshPublicKeyId, params, (xml, key) -> xml.start("member")
+ .elem("UserName", key.getUserName())
+ .elem("SSHPublicKeyId", key.getSshPublicKeyId())
+ .elem("Status", key.getStatus())
+ .elem("UploadDate", isoDate(key.getUploadDate()))
+ .end("member"));
}
private Response handleUpdateSshPublicKey(MultivaluedMap<String, String> params) {
@@ -1143,21 +1089,13 @@ public class IamQueryHandler {
AwsNamespaces.IAM, xml.build())).build();
}
- private Response handleListSigningCertificates(MultivaluedMap<String, String> params,
+ private Response handleListSigningCertificates(MultivaluedMap<String, String> request,
String authorization) {
- Page<SigningCertificate> page = paginate(
- iamService.listSigningCertificates(resolveUserName(params, authorization)),
- SigningCertificate::getCertificateId, params);
- XmlBuilder xml = new XmlBuilder().start("Certificates");
- for (SigningCertificate certificate : page.items()) {
- xml.start("member").raw(signingCertificateXml(certificate)).end("member");
- }
- xml.end("Certificates").elem("IsTruncated", page.truncated());
- if (page.marker() != null) {
- xml.elem("Marker", page.marker());
- }
- return Response.ok(AwsQueryResponse.envelope("ListSigningCertificates",
- AwsNamespaces.IAM, xml.build())).build();
+ MultivaluedMap<String, String> params = withResolvedUser(request, authorization);
+ return pagedList("ListSigningCertificates",
+ iamService.listSigningCertificates(getParam(params, "UserName")),
+ SigningCertificate::getCertificateId, params,
+ (xml, certificate) -> xml.start("member").raw(signingCertificateXml(certificate)).end("member"));
}
private Response handleUpdateSigningCertificate(MultivaluedMap<String, String> params,
@@ -1198,18 +1136,8 @@ public class IamQueryHandler {
}
private Response handleListServerCertificateTags(MultivaluedMap<String, String> params) {
- Map<String, String> tags = new TreeMap<>(iamService.listServerCertificateTags(
- getParam(params, "ServerCertificateName")));
- Page<Map.Entry<String, String>> page = paginate(List.copyOf(tags.entrySet()), Map.Entry::getKey, params);
- XmlBuilder xml = new XmlBuilder().start("Tags");
- for (Map.Entry<String, String> tag : page.items()) {
- xml.start("member").elem("Key", tag.getKey()).elem("Value", tag.getValue()).end("member");
- }
- xml.end("Tags").elem("IsTruncated", page.truncated());
- if (page.marker() != null) {
- xml.elem("Marker", page.marker());
- }
- return Response.ok(AwsQueryResponse.envelope("ListServerCertificateTags", AwsNamespaces.IAM, xml.build())).build();
+ return pagedTags("ListServerCertificateTags",
+ iamService.listServerCertificateTags(getParam(params, "ServerCertificateName")), params);
}
private String serverCertificateMetadataXml(ServerCertificate certificate) {
@@ -1227,13 +1155,11 @@ public class IamQueryHandler {
// Account Aliases
// =========================================================================
- // ListAccountAliases is paginated on the wire (IsTruncated) even though an account can only
- // ever hold one alias, so the envelope carries the flag to match the AWS response shape.
+ // ListAccountAliases is paginated on the wire even though an account can only ever hold one
+ // alias, so it pages like every other list: its bounds hold, and it is never truncated.
private Response handleListAccountAliases(MultivaluedMap<String, String> params) {
- XmlBuilder xml = new XmlBuilder().start("AccountAliases");
- iamService.getAccountAlias().ifPresent(alias -> xml.elem("member", alias));
- xml.end("AccountAliases").elem("IsTruncated", false);
- return Response.ok(AwsQueryResponse.envelope("ListAccountAliases", AwsNamespaces.IAM, xml.build())).build();
+ return pagedList("ListAccountAliases", iamService.getAccountAlias().stream().toList(), Function.identity(),
+ params, (xml, alias) -> xml.elem("member", alias));
}
private Response handleCreateAccountAlias(MultivaluedMap<String, String> params) {
@@ -1383,14 +1309,17 @@ public class IamQueryHandler {
} catch (AwsException e) {
return Stream.empty();
}
- }).toList();
+ }).sorted(Comparator.comparing(IamUser::getUserName)).toList();
+ // Group is the one member that is not paged: it comes with every page.
+ Page<IamUser> page = paginate("GetGroup", members, IamUser::getUserName, params);
XmlBuilder xml = new XmlBuilder()
.start("Group").raw(groupXml(group)).end("Group")
.start("Users");
- for (IamUser u : members) {
+ for (IamUser u : page.items()) {
xml.start("member").raw(userXml(u, false)).end("member");
}
- xml.end("Users").elem("IsTruncated", false);
+ xml.end("Users");
+ continuation(xml, page);
return Response.ok(AwsQueryResponse.envelope("GetGroup", AwsNamespaces.IAM, xml.build())).build();
}
@@ -1406,13 +1335,8 @@ public class IamQueryHandler {
}
private Response handleListGroups(MultivaluedMap<String, String> params) {
- List<IamGroup> groupList = iamService.listGroups(getParam(params, "PathPrefix"));
- XmlBuilder xml = new XmlBuilder().start("Groups");
- for (IamGroup g : groupList) {
- xml.start("member").raw(groupXml(g)).end("member");
- }
- xml.end("Groups").elem("IsTruncated", false);
- return Response.ok(AwsQueryResponse.envelope("ListGroups", AwsNamespaces.IAM, xml.build())).build();
+ return pagedList("ListGroups", iamService.listGroups(getParam(params, "PathPrefix")), IamGroup::getGroupName,
+ params, (xml, g) -> xml.start("member").raw(groupXml(g)).end("member"));
}
private Response handleAddUserToGroup(MultivaluedMap<String, String> params) {
@@ -1426,13 +1350,9 @@ public class IamQueryHandler {
}
private Response handleListGroupsForUser(MultivaluedMap<String, String> params) {
- List<IamGroup> groupList = iamService.listGroupsForUser(getParam(params, "UserName"));
- XmlBuilder xml = new XmlBuilder().start("Groups");
- for (IamGroup g : groupList) {
- xml.start("member").raw(groupXml(g)).end("member");
- }
- xml.end("Groups").elem("IsTruncated", false);
- return Response.ok(AwsQueryResponse.envelope("ListGroupsForUser", AwsNamespaces.IAM, xml.build())).build();
+ return pagedList("ListGroupsForUser", iamService.listGroupsForUser(getParam(params, "UserName")).stream()
+ .sorted(Comparator.comparing(IamGroup::getGroupName)).toList(),
+ IamGroup::getGroupName, params, (xml, g) -> xml.start("member").raw(groupXml(g)).end("member"));
}
// =========================================================================
@@ -1485,16 +1405,8 @@ public class IamQueryHandler {
}
private Response handleListRoles(MultivaluedMap<String, String> params) {
- Page<IamRole> page = paginate(iamService.listRoles(getParam(params, "PathPrefix")), IamRole::getRoleName, params);
- XmlBuilder xml = new XmlBuilder().start("Roles");
- for (IamRole r : page.items()) {
- xml.start("member").raw(roleXml(r, false)).end("member");
- }
- 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();
+ return pagedList("ListRoles", iamService.listRoles(getParam(params, "PathPrefix")), IamRole::getRoleName,
+ params, (xml, r) -> xml.start("member").raw(roleXml(r, false)).end("member"));
}
private Response handleUpdateRole(MultivaluedMap<String, String> params) {
@@ -1539,10 +1451,7 @@ public class IamQueryHandler {
}
private Response handleListRoleTags(MultivaluedMap<String, String> params) {
- Map<String, String> tags = iamService.listRoleTags(getParam(params, "RoleName"));
- String result = new XmlBuilder().start("Tags").raw(tagsXml(tags)).end("Tags")
- .elem("IsTruncated", false).build();
- return Response.ok(AwsQueryResponse.envelope("ListRoleTags", AwsNamespaces.IAM, result)).build();
+ return pagedTags("ListRoleTags", iamService.listRoleTags(getParam(params, "RoleName")), params);
}
// =========================================================================
@@ -1677,38 +1586,28 @@ public class IamQueryHandler {
}
private Response handleListPolicies(MultivaluedMap<String, String> params) {
- Page<IamPolicy> page = paginate(iamService.listPolicies(
- getParam(params, "Scope"), getParam(params, "PathPrefix")), IamQueryHandler::policyKey, params);
- XmlBuilder xml = new XmlBuilder().start("Policies");
- for (IamPolicy p : page.items()) {
- xml.start("member").raw(policyXml(p, false)).end("member");
- }
- 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();
+ return pagedList("ListPolicies", iamService.listPolicies(getParam(params, "Scope"), getParam(params, "PathPrefix")),
+ IamQueryHandler::policyKey, params, (xml, p) -> xml.start("member").raw(policyXml(p, false)).end("member"));
}
private Response handleListEntitiesForPolicy(MultivaluedMap<String, String> params) {
IamService.PolicyEntities entities = iamService.listEntitiesForPolicy(getParam(params, "PolicyArn"));
- XmlBuilder xml = new XmlBuilder().start("PolicyGroups");
- for (IamGroup group : entities.groups()) {
- xml.start("member").elem("GroupName", group.getGroupName())
- .elem("GroupId", group.getGroupId()).end("member");
- }
- xml.end("PolicyGroups").start("PolicyUsers");
- for (IamUser user : entities.users()) {
- xml.start("member").elem("UserName", user.getUserName())
- .elem("UserId", user.getUserId()).end("member");
- }
- xml.end("PolicyUsers").start("PolicyRoles");
- for (IamRole role : entities.roles()) {
- xml.start("member").elem("RoleName", role.getRoleName())
- .elem("RoleId", role.getRoleId()).end("member");
- }
- xml.end("PolicyRoles").elem("IsTruncated", false);
- return Response.ok(AwsQueryResponse.envelope("ListEntitiesForPolicy", AwsNamespaces.IAM, xml.build())).build();
+ // The three lists page as one, in the paginator's order: groups, users, roles.
+ List<Listed> items = new ArrayList<>(Listed.of(0, entities.groups(), IamGroup::getGroupName));
+ items.addAll(Listed.of(1, entities.users(), IamUser::getUserName));
+ items.addAll(Listed.of(2, entities.roles(), IamRole::getRoleName));
+ return pagedLists("ListEntitiesForPolicy", items, params, (xml, listed) -> {
+ XmlBuilder member = switch (listed.item()) {
+ case IamGroup group -> new XmlBuilder().elem("GroupName", group.getGroupName())
+ .elem("GroupId", group.getGroupId());
+ case IamUser user -> new XmlBuilder().elem("UserName", user.getUserName())
+ .elem("UserId", user.getUserId());
+ case IamRole role -> new XmlBuilder().elem("RoleName", role.getRoleName())
+ .elem("RoleId", role.getRoleId());
+ default -> throw new IllegalStateException("not a policy entity: " + listed.item());
+ };
+ xml.start("member").raw(member.build()).end("member");
+ });
}
private Response handleGetAccountSummary(MultivaluedMap<String, String> params) {
@@ -1804,32 +1703,25 @@ public class IamQueryHandler {
return Response.ok(AwsQueryResponse.envelope("GetCredentialReport", AwsNamespaces.IAM, result)).build();
}
- // Filter, MaxItems and Marker are not honored: every user, group, role and relevant policy
- // is always returned in one response, matching this handler's general convention elsewhere
- // (ListInstanceProfiles, SimulatePrincipalPolicy, ...) of not implementing pagination.
+ // Filter is not honored: every user, group, role and relevant policy is listed. MaxItems and
+ // Marker page the four lists as one, in the paginator's order.
private Response handleGetAccountAuthorizationDetails(MultivaluedMap<String, String> params) {
IamService.AccountAuthorizationDetails details = iamService.getAccountAuthorizationDetails();
-
- XmlBuilder xml = new XmlBuilder().start("UserDetailList");
- for (IamUser user : details.users()) {
- xml.start("member").raw(userDetailXml(user)).end("member");
- }
- xml.end("UserDetailList").start("GroupDetailList");
- for (IamGroup group : details.groups()) {
- xml.start("member").raw(groupDetailXml(group)).end("member");
- }
- xml.end("GroupDetailList").start("RoleDetailList");
- for (IamRole role : details.roles()) {
- xml.start("member").raw(roleDetailXml(role)).end("member");
- }
- xml.end("RoleDetailList").start("Policies");
- for (IamPolicy policy : details.policies()) {
- xml.start("member")
- .raw(managedPolicyDetailXml(policy, details.attachmentCounts(), details.permissionsBoundaryUsageCounts()))
- .end("member");
- }
- xml.end("Policies").elem("IsTruncated", false);
- return Response.ok(AwsQueryResponse.envelope("GetAccountAuthorizationDetails", AwsNamespaces.IAM, xml.build())).build();
+ List<Listed> items = new ArrayList<>(Listed.of(0, details.users(), IamUser::getUserName));
+ items.addAll(Listed.of(1, details.groups(), IamGroup::getGroupName));
+ items.addAll(Listed.of(2, details.roles(), IamRole::getRoleName));
+ items.addAll(Listed.of(3, details.policies(), IamPolicy::getArn));
+ return pagedLists("GetAccountAuthorizationDetails", items, params, (xml, listed) -> {
+ String member = switch (listed.item()) {
+ case IamUser user -> userDetailXml(user);
+ case IamGroup group -> groupDetailXml(group);
+ case IamRole role -> roleDetailXml(role);
+ case IamPolicy policy -> managedPolicyDetailXml(policy, details.attachmentCounts(),
+ details.permissionsBoundaryUsageCounts());
+ default -> throw new IllegalStateException("not an authorization detail: " + listed.item());
+ };
+ xml.start("member").raw(member).end("member");
+ });
}
private String userDetailXml(IamUser u) {
@@ -1956,13 +1848,11 @@ public class IamQueryHandler {
}
private Response handleListPolicyVersions(MultivaluedMap<String, String> params) {
- List<PolicyVersion> versions = iamService.listPolicyVersions(getParam(params, "PolicyArn"));
- XmlBuilder xml = new XmlBuilder().start("Versions");
- for (PolicyVersion v : versions) {
- xml.start("member").raw(policyVersionXml(v)).end("member");
- }
- xml.end("Versions").elem("IsTruncated", false);
- return Response.ok(AwsQueryResponse.envelope("ListPolicyVersions", AwsNamespaces.IAM, xml.build())).build();
+ // Keyed by version number, so v10 sorts after v9 and a deleted version resumes in place.
+ Function<PolicyVersion, String> byNumber = v -> positionKey(Integer.parseInt(v.getVersionId().substring(1)));
+ return pagedList("ListPolicyVersions", iamService.listPolicyVersions(getParam(params, "PolicyArn")).stream()
+ .sorted(Comparator.comparing(byNumber)).toList(),
+ byNumber, params, (xml, v) -> xml.start("member").raw(policyVersionXml(v)).end("member"));
}
private Response handleSetDefaultPolicyVersion(MultivaluedMap<String, String> params) {
@@ -1981,10 +1871,7 @@ public class IamQueryHandler {
}
private Response handleListPolicyTags(MultivaluedMap<String, String> params) {
- Map<String, String> tags = iamService.listPolicyTags(getParam(params, "PolicyArn"));
- String result = new XmlBuilder().start("Tags").raw(tagsXml(tags)).end("Tags")
- .elem("IsTruncated", false).build();
- return Response.ok(AwsQueryResponse.envelope("ListPolicyTags", AwsNamespaces.IAM, result)).build();
+ return pagedTags("ListPolicyTags", iamService.listPolicyTags(getParam(params, "PolicyArn")), params);
}
// =========================================================================
@@ -2004,8 +1891,7 @@ public class IamQueryHandler {
private Response handleListAttachedUserPolicies(MultivaluedMap<String, String> params) {
List<IamPolicy> policyList = iamService.listAttachedUserPolicies(
getParam(params, "UserName"), getParam(params, "PathPrefix"));
- return Response.ok(AwsQueryResponse.envelope("ListAttachedUserPolicies", AwsNamespaces.IAM,
- attachedPoliciesXml(policyList))).build();
+ return attachedPolicies("ListAttachedUserPolicies", policyList, params);
}
// =========================================================================
@@ -2025,8 +1911,7 @@ public class IamQueryHandler {
private Response handleListAttachedGroupPolicies(MultivaluedMap<String, String> params) {
List<IamPolicy> policyList = iamService.listAttachedGroupPolicies(
getParam(params, "GroupName"), getParam(params, "PathPrefix"));
- return Response.ok(AwsQueryResponse.envelope("ListAttachedGroupPolicies", AwsNamespaces.IAM,
- attachedPoliciesXml(policyList))).build();
+ return attachedPolicies("ListAttachedGroupPolicies", policyList, params);
}
// =========================================================================
@@ -2046,8 +1931,7 @@ public class IamQueryHandler {
private Response handleListAttachedRolePolicies(MultivaluedMap<String, String> params) {
List<IamPolicy> policyList = iamService.listAttachedRolePolicies(
getParam(params, "RoleName"), getParam(params, "PathPrefix"));
- return Response.ok(AwsQueryResponse.envelope("ListAttachedRolePolicies", AwsNamespaces.IAM,
- attachedPoliciesXml(policyList))).build();
+ return attachedPolicies("ListAttachedRolePolicies", policyList, params);
}
// =========================================================================
@@ -2077,8 +1961,7 @@ public class IamQueryHandler {
private Response handleListUserPolicies(MultivaluedMap<String, String> params) {
List<String> names = iamService.listUserPolicies(getParam(params, "UserName"));
- return Response.ok(AwsQueryResponse.envelope("ListUserPolicies", AwsNamespaces.IAM,
- inlinePolicyNamesXml(names))).build();
+ return inlinePolicyNames("ListUserPolicies", names, params);
}
// =========================================================================
@@ -2108,8 +1991,7 @@ public class IamQueryHandler {
private Response handleListGroupPolicies(MultivaluedMap<String, String> params) {
List<String> names = iamService.listGroupPolicies(getParam(params, "GroupName"));
- return Response.ok(AwsQueryResponse.envelope("ListGroupPolicies", AwsNamespaces.IAM,
- inlinePolicyNamesXml(names))).build();
+ return inlinePolicyNames("ListGroupPolicies", names, params);
}
// =========================================================================
@@ -2139,8 +2021,7 @@ public class IamQueryHandler {
private Response handleListRolePolicies(MultivaluedMap<String, String> params) {
List<String> names = iamService.listRolePolicies(getParam(params, "RoleName"));
- return Response.ok(AwsQueryResponse.envelope("ListRolePolicies", AwsNamespaces.IAM,
- inlinePolicyNamesXml(names))).build();
+ return inlinePolicyNames("ListRolePolicies", names, params);
}
// =========================================================================
@@ -2158,14 +2039,11 @@ public class IamQueryHandler {
return Response.ok(AwsQueryResponse.envelopeNoResult("DeleteAccessKey", AwsNamespaces.IAM)).build();
}
- private Response handleListAccessKeys(MultivaluedMap<String, String> params, String authorization) {
- List<AccessKey> keys = iamService.listAccessKeys(resolveUserName(params, authorization));
- XmlBuilder xml = new XmlBuilder().start("AccessKeyMetadata");
- for (AccessKey k : keys) {
- xml.start("member").raw(accessKeyXml(k, false)).end("member");
- }
- xml.end("AccessKeyMetadata").elem("IsTruncated", false);
- return Response.ok(AwsQueryResponse.envelope("ListAccessKeys", AwsNamespaces.IAM, xml.build())).build();
+ private Response handleListAccessKeys(MultivaluedMap<String, String> request, String authorization) {
+ MultivaluedMap<String, String> params = withResolvedUser(request, authorization);
+ return pagedList("ListAccessKeys", iamService.listAccessKeys(getParam(params, "UserName")).stream()
+ .sorted(Comparator.comparing(AccessKey::getAccessKeyId)).toList(),
+ AccessKey::getAccessKeyId, params, (xml, k) -> xml.start("member").raw(accessKeyXml(k, false)).end("member"));
}
private Response handleUpdateAccessKey(MultivaluedMap<String, String> params, String authorization) {
@@ -2271,14 +2149,10 @@ public class IamQueryHandler {
}
private Response handleListInstanceProfiles(MultivaluedMap<String, String> params) {
- List<InstanceProfile> profiles = iamService.listInstanceProfiles(getParam(params, "PathPrefix"));
- XmlBuilder xml = new XmlBuilder().start("InstanceProfiles");
- for (InstanceProfile p : profiles) {
- // Documented listing subset: tags are omitted here, unlike GetInstanceProfile.
- xml.start("member").raw(instanceProfileXml(p, false)).end("member");
- }
- xml.end("InstanceProfiles").elem("IsTruncated", false);
- return Response.ok(AwsQueryResponse.envelope("ListInstanceProfiles", AwsNamespaces.IAM, xml.build())).build();
+ // Documented listing subset: tags are omitted here, unlike GetInstanceProfile.
+ return pagedList("ListInstanceProfiles", byProfileName(iamService.listInstanceProfiles(getParam(params, "PathPrefix"))),
+ InstanceProfile::getInstanceProfileName, params,
+ (xml, p) -> xml.start("member").raw(instanceProfileXml(p, false)).end("member"));
}
private Response handleAddRoleToInstanceProfile(MultivaluedMap<String, String> params) {
@@ -2292,13 +2166,13 @@ public class IamQueryHandler {
}
private Response handleListInstanceProfilesForRole(MultivaluedMap<String, String> params) {
- List<InstanceProfile> profiles = iamService.listInstanceProfilesForRole(getParam(params, "RoleName"));
- XmlBuilder xml = new XmlBuilder().start("InstanceProfiles");
- for (InstanceProfile p : profiles) {
- xml.start("member").raw(instanceProfileXml(p, true)).end("member");
- }
- xml.end("InstanceProfiles").elem("IsTruncated", false);
- return Response.ok(AwsQueryResponse.envelope("ListInstanceProfilesForRole", AwsNamespaces.IAM, xml.build())).build();
+ return pagedList("ListInstanceProfilesForRole", byProfileName(iamService.listInstanceProfilesForRole(getParam(params, "RoleName"))),
+ InstanceProfile::getInstanceProfileName, params,
+ (xml, p) -> xml.start("member").raw(instanceProfileXml(p, true)).end("member"));
+ }
+
+ private static List<InstanceProfile> byProfileName(List<InstanceProfile> profiles) {
+ return profiles.stream().sorted(Comparator.comparing(InstanceProfile::getInstanceProfileName)).toList();
}
// =========================================================================
@@ -2354,8 +2228,7 @@ public class IamQueryHandler {
}
populated.forEach(context::putIfAbsent);
});
- String result = simulationResultsXml(caller, actionNames, resourceArns, context);
- return Response.ok(AwsQueryResponse.envelope("SimulatePrincipalPolicy", AwsNamespaces.IAM, result)).build();
+ return simulationResults("SimulatePrincipalPolicy", params, caller, actionNames, resourceArns, context);
}
private Response handleSimulateCustomPolicy(MultivaluedMap<String, String> params) {
@@ -2368,8 +2241,7 @@ public class IamQueryHandler {
List<String> boundaryInputList = extractIndexedValues(params, "PermissionsBoundaryPolicyInputList.member");
String boundaryDocument = boundaryInputList.isEmpty() ? null : boundaryInputList.get(0);
CallerContext caller = new CallerContext(policyInputList, null, boundaryDocument);
- String result = simulationResultsXml(caller, actionNames, resourceArns, context);
- return Response.ok(AwsQueryResponse.envelope("SimulateCustomPolicy", AwsNamespaces.IAM, result)).build();
+ return simulationResults("SimulateCustomPolicy", params, caller, actionNames, resourceArns, context);
}
private List<String> requireActionNames(MultivaluedMap<String, String> params) {
@@ -2393,25 +2265,31 @@ public class IamQueryHandler {
return resourceArns.isEmpty() ? List.of("*") : resourceArns;
}
- private String simulationResultsXml(CallerContext caller, List<String> actionNames,
- List<String> resourceArns, Map<String, List<String>> context) {
- XmlBuilder results = new XmlBuilder().start("EvaluationResults");
+ /**
+ * One evaluation result per action and resource, in request order. A page is evaluated only
+ * for the pairs it carries, and keyed by position, since a simulation's inputs do not change
+ * between the calls that page it.
+ */
+ private Response simulationResults(String action, MultivaluedMap<String, String> params, CallerContext caller,
+ List<String> actionNames, List<String> resourceArns,
+ Map<String, List<String>> context) {
+ List<String[]> pairs = new ArrayList<>();
for (String actionName : actionNames) {
for (String resourceArn : resourceArns) {
- IamPolicyEvaluator.SimulationDecision decision =
- policyEvaluator.simulatePrincipalPolicy(caller, actionName, resourceArn, context);
- results.start("member")
- .elem("EvalActionName", actionName)
- .elem("EvalResourceName", resourceArn)
- .elem("EvalDecision", decision.awsValue())
- .start("MatchedStatements").end("MatchedStatements")
- .start("MissingContextValues").end("MissingContextValues")
- .end("member");
+ pairs.add(new String[] {positionKey(pairs.size()), actionName, resourceArn});
}
}
- return results.end("EvaluationResults")
- .elem("IsTruncated", false)
- .build();
+ return pagedList(action, pairs, pair -> pair[0], params, (xml, pair) -> {
+ IamPolicyEvaluator.SimulationDecision decision =
+ policyEvaluator.simulatePrincipalPolicy(caller, pair[1], pair[2], context);
+ xml.start("member")
+ .elem("EvalActionName", pair[1])
+ .elem("EvalResourceName", pair[2])
+ .elem("EvalDecision", decision.awsValue())
+ .start("MatchedStatements").end("MatchedStatements")
+ .start("MissingContextValues").end("MissingContextValues")
+ .end("member");
+ });
}
private Response handleGetContextKeysForCustomPolicy(MultivaluedMap<String, String> params) {
@@ -2471,10 +2349,10 @@ public class IamQueryHandler {
private Response handleGetServiceLastAccessedDetails(MultivaluedMap<String, String> params,
String authorization) {
String jobId = validatedJobId(params);
- validatePagingInputs(params);
+ validatePagingInputs("GetServiceLastAccessedDetails", params);
ServiceLastAccessedJob job = serviceLastAccessedService.get(
accountResolver.resolve(authorization), jobId);
- Page<String> page = paginate(job.getServiceNamespaces(), Function.identity(), params);
+ Page<String> page = paginate("GetServiceLastAccessedDetails", job.getServiceNamespaces(), Function.identity(), params);
XmlBuilder xml = new XmlBuilder()
.elem("JobStatus", "COMPLETED")
.elem("JobType", job.getGranularity())
@@ -2489,10 +2367,8 @@ public class IamQueryHandler {
.elem("ServiceNamespace", namespace)
.end("member");
}
- xml.end("ServicesLastAccessed").elem("IsTruncated", page.truncated());
- if (page.marker() != null) {
- xml.elem("Marker", page.marker());
- }
+ xml.end("ServicesLastAccessed");
+ continuation(xml, page);
return Response.ok(AwsQueryResponse.envelope("GetServiceLastAccessedDetails", AwsNamespaces.IAM,
xml.build())).build();
}
@@ -2534,7 +2410,7 @@ public class IamQueryHandler {
// Read before the lookup, because a value outside the enum is a bad request whether or not
// the job exists: validating it after would answer NoSuchEntity for a request AWS rejects.
String sortKey = validatedSortKey(params);
- validatePagingInputs(params);
+ validatePagingInputs("GetOrganizationsAccessReport", params);
OrganizationsAccessReportJob job = organizationsAccessReportService.get(
accountResolver.resolve(authorization), jobId);
XmlBuilder xml = new XmlBuilder()
@@ -2552,7 +2428,7 @@ public class IamQueryHandler {
.build())).build();
}
List<String> namespaces = sortedByKey(job.getServiceNamespaces(), sortKey);
- Page<String> page = paginate(namespaces, Function.identity(), params);
+ Page<String> page = paginate("GetOrganizationsAccessReport", namespaces, Function.identity(), params);
xml.elem("NumberOfServicesAccessible", namespaces.size())
.elem("NumberOfServicesNotAccessed", namespaces.size())
.start("AccessDetails");
@@ -2565,41 +2441,12 @@ public class IamQueryHandler {
.elem("TotalAuthenticatedEntities", 0)
.end("member");
}
- xml.end("AccessDetails").elem("IsTruncated", page.truncated());
- if (page.marker() != null) {
- xml.elem("Marker", page.marker());
- }
+ xml.end("AccessDetails");
+ continuation(xml, page);
return Response.ok(AwsQueryResponse.envelope("GetOrganizationsAccessReport",
AwsNamespaces.IAM, xml.build())).build();
}
- /**
- * {@code MaxItems} if the request carries one inside the range the reference publishes, null if
- * it carries none. Read without the list it will page, so a reader can check it before it looks
- * anything up.
- */
- private static Integer validatedMaxItems(MultivaluedMap<String, String> params) {
- String raw = params.getFirst("MaxItems");
- if (raw == null || raw.isBlank()) {
- return null;
- }
- int limit;
- try {
- limit = Integer.parseInt(raw.trim());
- } catch (NumberFormatException e) {
- throw new AwsException("InvalidInput",
- "The value " + raw + " at 'maxItems' is not a number.", 400);
- }
- if (limit < 1) {
- throw validationError(raw, "maxItems", "Member must have value greater than or equal to 1");
- }
- if (limit > MAX_MAX_ITEMS) {
- throw validationError(raw, "maxItems",
- "Member must have value less than or equal to " + MAX_MAX_ITEMS);
- }
- return limit;
- }
-
/**
* {@code JobId} held to the fixed 36 characters {@code jobIDType} declares, before the job is
* looked up. The order is the whole point: a value that breaks a declared constraint is a bad
@@ -2622,16 +2469,14 @@ public class IamQueryHandler {
/**
* The paging members, read ahead of the lookup whose result they page, for the reason
- * {@link #validatedJobId} is. {@link #paginate} reads them again when it runs: most of the
- * readers paged there look nothing up first, and a check only one caller performs is one the
- * next caller forgets.
+ * {@link #validatedJobId} is: the limit and the marker {@code action} issued, checked exactly
+ * as {@link #paginate} checks them when it runs over the list.
*/
- private void validatePagingInputs(MultivaluedMap<String, String> params) {
- validatedMaxItems(params);
- String marker = params.getFirst("Marker");
- if (marker != null && !marker.isBlank() && markers.cursorOf(marker.trim()) == null) {
- markerIndex(marker);
- }
+ private void validatePagingInputs(String action, MultivaluedMap<String, String> params) {
+ IamPaginators.Paginator paginator = IamPaginators.of(action);
+ limit(paginator, params, 0);
+ resumeIndex(List.of(), Function.identity(), params.getFirst(paginator.inputToken()),
+ markerScope(action, paginator, params));
}
/**
@@ -2718,13 +2563,14 @@ public class IamQueryHandler {
String authorization) {
String jobId = validatedJobId(params);
String namespace = requireParam(params, "ServiceNamespace");
- validatePagingInputs(params);
+ validatePagingInputs("GetServiceLastAccessedDetailsWithEntities", params);
ServiceLastAccessedJob job = serviceLastAccessedService.get(
accountResolver.resolve(authorization), jobId);
// The report named the services it covers, so an entity is only reported for one of those.
List<ServiceLastAccessedEntity> reported = job.getServiceNamespaces().contains(namespace)
? job.getEntities() : List.of();
- Page<ServiceLastAccessedEntity> page = paginate(reported, ServiceLastAccessedEntity::getArn, params);
+ Page<ServiceLastAccessedEntity> page = paginate("GetServiceLastAccessedDetailsWithEntities", reported,
+ ServiceLastAccessedEntity::getArn, params);
XmlBuilder xml = new XmlBuilder()
.elem("JobStatus", "COMPLETED")
.elem("JobCreationDate", isoDate(job.getJobCreationDate()))
@@ -2739,10 +2585,8 @@ public class IamQueryHandler {
.elem("Path", entity.getPath())
.end("EntityInfo").end("member");
}
- xml.end("EntityDetailsList").elem("IsTruncated", page.truncated());
- if (page.marker() != null) {
- xml.elem("Marker", page.marker());
- }
+ xml.end("EntityDetailsList");
+ continuation(xml, page);
return Response.ok(AwsQueryResponse.envelope("GetServiceLastAccessedDetailsWithEntities",
AwsNamespaces.IAM, xml.build())).build();
}
@@ -2764,8 +2608,9 @@ public class IamQueryHandler {
checkListLength(namespaces.size(), "serviceNamespaces", MAX_SERVICE_NAMESPACES);
List<GrantingPolicy> candidates = policiesForIdentity(accountId, arn);
// The response list carries one entry per requested namespace, so that is what a Marker
- // walks through.
- Page<String> page = paginateByMarker(namespaces, Function.identity(), params);
+ // walks through. The request models no MaxItems, so the table gives it no limit and the
+ // list is never cut.
+ Page<String> page = paginate("ListPoliciesGrantingServiceAccess", namespaces, Function.identity(), params);
XmlBuilder xml = new XmlBuilder().start("PoliciesGrantingServiceAccess");
for (String namespace : page.items()) {
xml.start("member").elem("ServiceNamespace", namespace).start("Policies");
@@ -2785,10 +2630,8 @@ public class IamQueryHandler {
}
xml.end("Policies").end("member");
}
- xml.end("PoliciesGrantingServiceAccess").elem("IsTruncated", page.truncated());
- if (page.marker() != null) {
- xml.elem("Marker", page.marker());
- }
+ xml.end("PoliciesGrantingServiceAccess");
+ continuation(xml, page);
return Response.ok(AwsQueryResponse.envelope("ListPoliciesGrantingServiceAccess",
AwsNamespaces.IAM, xml.build())).build();
}
@@ -2897,7 +2740,7 @@ public class IamQueryHandler {
}
private Response handleListDelegationRequests(MultivaluedMap<String, String> params) {
- Page<DelegationRequest> page = paginate(delegationRequestService.list(
+ Page<DelegationRequest> page = paginate("ListDelegationRequests", delegationRequestService.list(
regionResolver.getAccountId(), getParam(params, "OwnerId")),
DelegationRequest::getDelegationRequestId, params);
XmlBuilder xml = new XmlBuilder().start("DelegationRequests");
@@ -2905,11 +2748,9 @@ public class IamQueryHandler {
xml.start("member").raw(delegationRequestXml(request)).end("member");
}
// isTruncated is lower-cased on this one operation, where every other IAM list spells it
- // IsTruncated. The model names the member that way, so the wire follows the model.
- xml.end("DelegationRequests").elem("isTruncated", page.truncated());
- if (page.marker() != null) {
- xml.elem("Marker", page.marker());
- }
+ // IsTruncated. The model names the member that way, and the table carries the model's name.
+ xml.end("DelegationRequests");
+ continuation(xml, page);
return Response.ok(AwsQueryResponse.envelope("ListDelegationRequests",
AwsNamespaces.IAM, xml.build())).build();
}
@@ -3089,68 +2930,94 @@ public class IamQueryHandler {
+ "': Member must be a boolean", 400);
}
- /** One page of a response list, plus the marker that continues it. */
- private record Page<T>(List<T> items, boolean truncated, String marker) {}
+ /** One page of a response list, the paging it was cut by, and the marker that continues it. */
+ private record Page<T>(IamPaginators.Paginator paginator, List<T> items, boolean truncated, String marker) {}
- /**
- * Applies {@code MaxItems} and {@code Marker}. The marker names the last item of the page
- * before by {@code keyOf}, so the next page continues after that item wherever it now sits:
- * the API reference documents it as the place "where the next call should start", and an item
- * created or deleted ahead of it skips nothing and repeats nothing.
- */
- private <T> Page<T> paginate(List<T> items, Function<T, String> keyOf, MultivaluedMap<String, String> params) {
- return paginate(items, keyOf, params, true);
- }
+ /** Request members that name the call rather than the listing. A presigned request's X-Amz-* members are skipped too. */
+ private static final Set<String> NOT_LISTING_PARAMS = Set.of("Action", "Version");
/**
- * Marker-only pagination, for {@code ListPoliciesGrantingServiceAccess}: its request models
- * {@code Marker} but no {@code MaxItems}, and honouring a member AWS does not declare would be
- * inventing one.
+ * The one path every paged IAM list goes through, driven by {@code action}'s entry in the
+ * generated {@link IamPaginators} table: its limit's default and the request member that
+ * resumes it.
+ *
+ * <p>{@code MaxItems} and {@code Marker} reach here already held to the model's bounds, 1 to
+ * 1000 and 1 to 320 characters, by {@link IamRequestShapes}, which checks every paged operation
+ * before it runs. An omitted {@code MaxItems} is the documented default ("the number of items
+ * defaults to 100") where the reference states one and the whole list where it does not. An
+ * operation whose request models no limit is never cut.
+ *
+ * <p>A {@code Marker} resumes only the listing that issued it. AWS documents it as "the value
+ * of the Marker element in the response that you received", so it is opaque: a value this
+ * handler did not issue, a bare number included, is {@code InvalidInput}. The marker is signed
+ * over the request's account, the operation, and every request member but the marker and the
+ * limit, so one issued by another operation, for another principal or filter, or in another
+ * account is refused too (a list whose user defaults to the caller pages over
+ * {@link #withResolvedUser}, so that user is among those members), while the page size may change between calls. It names the last item
+ * of the page before by {@code keyOf}, so the next page continues after that item wherever it
+ * now sits: an item created or deleted ahead of it skips nothing and repeats nothing.
+ *
+ * <p>Every marker issued fits those 320 characters, however long the key it names: one whose
+ * key would not fit names it by digest, which {@link SignedMarkers} resolves back to the key.
*/
- private <T> Page<T> paginateByMarker(List<T> items, Function<T, String> keyOf,
- MultivaluedMap<String, String> params) {
- return paginate(items, keyOf, params, false);
- }
-
- private <T> Page<T> paginate(List<T> items, Function<T, String> keyOf, MultivaluedMap<String, String> params,
- boolean maxItemsModeled) {
- // Every input is validated before the bounds check, so a malformed request is rejected
- // rather than answered emptily just because the marker happens to sit past the end.
- int from = resumeIndex(items, keyOf, params);
- // An omitted MaxItems is not "no limit": the API reference states the count "defaults to
- // 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) {
- Integer asked = validatedMaxItems(params);
- if (asked != null) {
- limit = asked;
- }
- }
+ private <T> Page<T> paginate(String action, List<T> items, Function<T, String> keyOf,
+ MultivaluedMap<String, String> params) {
+ IamPaginators.Paginator paginator = IamPaginators.of(action);
+ int limit = limit(paginator, params, items.size());
+ String scope = markerScope(action, paginator, params);
+ int from = resumeIndex(items, keyOf, params.getFirst(paginator.inputToken()), scope);
if (from >= items.size()) {
- return new Page<>(List.of(), false, null);
+ return new Page<>(paginator, List.of(), false, null);
}
// Counted from the remaining items rather than added to the offset, so a large MaxItems
// cannot overflow into a negative index.
int to = from + Math.min(limit, items.size() - from);
boolean truncated = to < items.size();
- return new Page<>(List.copyOf(items.subList(from, to)), truncated,
- truncated ? markers.issue(keyOf.apply(items.get(to - 1))) : null);
+ return new Page<>(paginator, List.copyOf(items.subList(from, to)), truncated,
+ truncated ? markers.issue(scope, keyOf.apply(items.get(to - 1))) : null);
+ }
+
+ private static int limit(IamPaginators.Paginator paginator, MultivaluedMap<String, String> params, int size) {
+ if (paginator.limitKey() == null) {
+ return size;
+ }
+ String raw = params.getFirst(paginator.limitKey());
+ if (raw == null || raw.isBlank()) {
+ return paginator.defaultItems() != null ? paginator.defaultItems() : size;
+ }
+ // The range is the model's and was checked ahead of the operation; a value that is no
+ // number is left to the operation by that check, and answered here.
+ try {
+ return Integer.parseInt(raw.trim());
+ } catch (NumberFormatException e) {
+ throw new AwsException("InvalidInput", "The value " + raw + " at 'maxItems' is not a number.", 400);
+ }
+ }
+
+ /** What a marker is signed over: the account, the operation and the listing's own members. */
+ private String markerScope(String action, IamPaginators.Paginator paginator, MultivaluedMap<String, String> params) {
+ StringBuilder scope = new StringBuilder().append(iamService.requestAccountId()).append('\n').append(action);
+ new TreeMap<>(params).forEach((name, values) -> {
+ if (!name.equals(paginator.inputToken()) && !name.equals(paginator.limitKey())
+ && !NOT_LISTING_PARAMS.contains(name) && !name.startsWith("X-Amz-")) {
+ scope.append('\n').append(name).append('=').append(String.join("\u0000", values));
+ }
+ });
+ return scope.toString();
}
/**
- * Where a {@code Marker} resumes: after the item it names. When that item is gone, at the first
- * item whose key sorts after it, since every list whose items can be deleted is ordered by the
- * key its reader passes. A marker this handler did not issue is read as an index, as before.
+ * Where a marker resumes: after the item it names. When that item is gone, at the first item
+ * whose key sorts after it, since every list whose items can be deleted is ordered by the key
+ * its reader passes.
*/
- private <T> int resumeIndex(List<T> items, Function<T, String> keyOf, MultivaluedMap<String, String> params) {
- String marker = params.getFirst("Marker");
+ private <T> int resumeIndex(List<T> items, Function<T, String> keyOf, String marker, String scope) {
if (marker == null || marker.isBlank()) {
return 0;
}
- String anchor = markers.cursorOf(marker.trim());
+ String anchor = markers.cursorOf(scope, marker.trim());
if (anchor == null) {
- return markerIndex(marker);
+ throw new AwsException("InvalidInput", "The marker " + marker + " is not valid.", 400);
}
for (int i = 0; i < items.size(); i++) {
if (keyOf.apply(items.get(i)).equals(anchor)) {
@@ -3165,6 +3032,69 @@ public class IamQueryHandler {
return items.size();
}
+ /** The page's truncation flag and continuing marker, under the names the operation's response models. */
+ private static void continuation(XmlBuilder xml, Page<?> page) {
+ xml.elem(page.paginator().moreResults(), page.truncated());
+ if (page.marker() != null) {
+ xml.elem(page.paginator().outputToken(), page.marker());
+ }
+ }
+
+ /**
+ * A whole response for an operation that pages one list: the list under its result key, one
+ * {@code member} per item as {@code member} writes it, then the continuation.
+ */
+ private <T> Response pagedList(String action, List<T> items, Function<T, String> keyOf,
+ MultivaluedMap<String, String> params, BiConsumer<XmlBuilder, T> member) {
+ Page<T> page = paginate(action, items, keyOf, params);
+ List<String> resultKeys = page.paginator().resultKeys();
+ if (resultKeys.size() != 1) {
+ throw new IllegalStateException(action + " pages " + resultKeys + ", not one list");
+ }
+ XmlBuilder xml = new XmlBuilder().start(resultKeys.getFirst());
+ page.items().forEach(item -> member.accept(xml, item));
+ xml.end(resultKeys.getFirst());
+ continuation(xml, page);
+ return Response.ok(AwsQueryResponse.envelope(action, AwsNamespaces.IAM, xml.build())).build();
+ }
+
+ /** A tag list, paged in tag-key order, which is the order AWS documents tags are returned in. */
+ private Response pagedTags(String action, Map<String, String> tags, MultivaluedMap<String, String> params) {
+ return pagedList(action, List.copyOf(new TreeMap<>(tags).entrySet()), Map.Entry::getKey, params,
+ (xml, tag) -> xml.start("member").elem("Key", tag.getKey()).elem("Value", tag.getValue()).end("member"));
+ }
+
+ /**
+ * An item of one of the lists an operation pages as one ({@code ListEntitiesForPolicy},
+ * {@code GetAccountAuthorizationDetails}): the index of its result key, and its key within the
+ * whole, which leads with that index so the combined list stays ordered by key.
+ */
+ private record Listed(int list, String key, Object item) {
+ static <T> List<Listed> of(int list, List<T> items, Function<T, String> keyOf) {
+ return items.stream().map(item -> new Listed(list, list + keyOf.apply(item), item))
+ .sorted(Comparator.comparing(Listed::key)).toList();
+ }
+ }
+
+ /** Pages several lists as one and writes each under its own result key, in the table's order. */
+ private Response pagedLists(String action, List<Listed> items, MultivaluedMap<String, String> params,
+ BiConsumer<XmlBuilder, Listed> member) {
+ Page<Listed> page = paginate(action, items, Listed::key, params);
+ List<String> resultKeys = page.paginator().resultKeys();
+ XmlBuilder xml = new XmlBuilder();
+ for (int list = 0; list < resultKeys.size(); list++) {
+ xml.start(resultKeys.get(list));
+ for (Listed item : page.items()) {
+ if (item.list() == list) {
+ member.accept(xml, item);
+ }
+ }
+ xml.end(resultKeys.get(list));
+ }
+ continuation(xml, page);
+ return Response.ok(AwsQueryResponse.envelope(action, AwsNamespaces.IAM, xml.build())).build();
+ }
+
/**
* ListPolicies lists customer-managed policies by name, then the AWS-managed catalog, which
* never changes. The key keeps that order, so a deleted customer-managed policy resumes at the
@@ -3175,18 +3105,9 @@ public class IamQueryHandler {
? "1" + policy.getArn() : "0" + policy.getPolicyName();
}
- /** The index a marker this handler did not issue resumes at, as markers were read before. */
- private static int markerIndex(String marker) {
- int index;
- try {
- index = Integer.parseInt(marker.trim());
- } catch (NumberFormatException e) {
- throw new AwsException("InvalidInput", "The marker " + marker + " is not valid.", 400);
- }
- if (index < 0) {
- throw new AwsException("InvalidInput", "The marker " + marker + " is not valid.", 400);
- }
- return index;
+ /** A key that sorts as the position does, for a list ordered by position rather than by a name. */
+ private static String positionKey(int position) {
+ return String.format("%010d", position);
}
/**
@@ -3550,23 +3471,22 @@ public class IamQueryHandler {
return xml.raw(detailed ? tagsElement(p.getTags()) : "").build();
}
- private String attachedPoliciesXml(List<IamPolicy> policyList) {
- XmlBuilder xml = new XmlBuilder().start("AttachedPolicies");
- for (IamPolicy p : policyList) {
- xml.start("member")
- .elem("PolicyName", p.getPolicyName())
- .elem("PolicyArn", p.getArn())
- .end("member");
- }
- return xml.end("AttachedPolicies").elem("IsTruncated", false).build();
+ /**
+ * Pages the attached policies in ARN order, so a Marker resumes in the right place even when
+ * the policy it names was detached in between. The ARN, not the name, is the key: a
+ * customer-managed policy may share its name with an AWS-managed one.
+ */
+ private Response attachedPolicies(String action, List<IamPolicy> policyList, MultivaluedMap<String, String> params) {
+ return pagedList(action, policyList.stream().sorted(Comparator.comparing(IamPolicy::getArn)).toList(),
+ IamPolicy::getArn, params, (xml, p) -> xml.start("member")
+ .elem("PolicyName", p.getPolicyName())
+ .elem("PolicyArn", p.getArn())
+ .end("member"));
}
- private String inlinePolicyNamesXml(List<String> names) {
- XmlBuilder xml = new XmlBuilder().start("PolicyNames");
- for (String name : names) {
- xml.elem("member", name);
- }
- return xml.end("PolicyNames").elem("IsTruncated", false).build();
+ private Response inlinePolicyNames(String action, List<String> names, MultivaluedMap<String, String> params) {
+ return pagedList(action, names.stream().sorted().toList(), Function.identity(), params,
+ (xml, name) -> xml.elem("member", name));
}
/**
@@ -3856,11 +3776,7 @@ public class IamQueryHandler {
}
private Response handleListInstanceProfileTags(MultivaluedMap<String, String> params) {
- String instanceProfileName = getParam(params, "InstanceProfileName");
- // AWS documents the result as sorted by tag key.
- Map<String, String> tags = new TreeMap<>(iamService.listInstanceProfileTags(instanceProfileName));
- String result = new XmlBuilder().start("Tags").raw(tagsXml(tags)).end("Tags")
- .elem("IsTruncated", false).build();
- return Response.ok(AwsQueryResponse.envelope("ListInstanceProfileTags", AwsNamespaces.IAM, result)).build();
+ return pagedTags("ListInstanceProfileTags",
+ iamService.listInstanceProfileTags(getParam(params, "InstanceProfileName")), params);
}
}
diff --git a/src/main/java/io/github/hectorvent/floci/services/iam/IamRequestShapes.java b/src/main/java/io/github/hectorvent/floci/services/iam/IamRequestShapes.java
index e2b0a2693f..27d12a98c9 100644
--- a/src/main/java/io/github/hectorvent/floci/services/iam/IamRequestShapes.java
+++ b/src/main/java/io/github/hectorvent/floci/services/iam/IamRequestShapes.java
@@ -17,7 +17,10 @@ import jakarta.ws.rs.core.MultivaluedMap;
* came first, with {@code AttachRolePolicy} and {@code DetachRolePolicy} as the exception and the
* parity case, {@code IamService.validateRoleName} already answering {@code roleName} in the same
* form. {@code GetAccountAuthorizationDetails} is the first read through the list walk, its
- * {@code Filter}, {@code MaxItems} and {@code Marker} having been read by nothing at all.
+ * {@code Filter}, {@code MaxItems} and {@code Marker} having been read by nothing at all. Every
+ * other paged operation follows, so {@code MaxItems} and {@code Marker} are held to the model here
+ * rather than by the paging itself; six of them carry only those two members, the rest of their
+ * request being answered by hand or nested past what the walk reads.
*/
final class IamRequestShapes {
diff --git a/src/main/java/io/github/hectorvent/floci/services/iam/IamService.java b/src/main/java/io/github/hectorvent/floci/services/iam/IamService.java
index c9dbd3672e..ebb5d63f96 100644
--- a/src/main/java/io/github/hectorvent/floci/services/iam/IamService.java
+++ b/src/main/java/io/github/hectorvent/floci/services/iam/IamService.java
@@ -818,6 +818,11 @@ public class IamService implements SessionAccountLookup, ResourceProvider {
return accessKeys.get(accessKeyId).map(AccessKey::getUserName);
}
+ /** The account this request's IAM entities are read from, or null outside account-aware storage. */
+ public String requestAccountId() {
+ return users instanceof AccountAwareStorageBackend<IamUser> aware ? aware.accountId() : null;
+ }
+
/**
* The owner of a key in the calling account, for a read that is not the owner's own request.
* Unlike {@link #findUserNameByAccessKeyId}, this never migrates: an unprefixed
@@ -905,6 +910,7 @@ public class IamService implements SessionAccountLookup, ResourceProvider {
String prefix = pathPrefix != null ? pathPrefix : "/";
return users.scan(k -> true).stream()
.filter(u -> u.getPath().startsWith(prefix))
+ .sorted(Comparator.comparing(IamUser::getUserName))
.toList();
}
@@ -1126,6 +1132,7 @@ public class IamService implements SessionAccountLookup, ResourceProvider {
String prefix = pathPrefix != null ? pathPrefix : "/";
return groups.scan(k -> true).stream()
.filter(g -> g.getPath().startsWith(prefix))
+ .sorted(Comparator.comparing(IamGroup::getGroupName))
.toList();
}
diff --git a/src/main/resources/aws/iam-paginators.json b/src/main/resources/aws/iam-paginators.json
new file mode 100644
index 0000000000..cc06891c34
--- /dev/null
+++ b/src/main/resources/aws/iam-paginators.json
@@ -0,0 +1,440 @@
+{
+ "_source": {
+ "generator": "tools/aws/regen_iam_paginators.py",
+ "botocore": "botocore 1.43.113 (installed package)"
+ },
+ "operations": {
+ "GetAccountAuthorizationDetails": {
+ "paginator": true,
+ "inputToken": "Marker",
+ "outputToken": "Marker",
+ "limitKey": "MaxItems",
+ "moreResults": "IsTruncated",
+ "resultKeys": [
+ "UserDetailList",
+ "GroupDetailList",
+ "RoleDetailList",
+ "Policies"
+ ],
+ "defaultItems": 100
+ },
+ "GetGroup": {
+ "paginator": true,
+ "inputToken": "Marker",
+ "outputToken": "Marker",
+ "limitKey": "MaxItems",
+ "moreResults": "IsTruncated",
+ "resultKeys": [
+ "Users"
+ ],
+ "defaultItems": 100
+ },
+ "GetOrganizationsAccessReport": {
+ "paginator": false,
+ "inputToken": "Marker",
+ "outputToken": "Marker",
+ "limitKey": "MaxItems",
+ "moreResults": "IsTruncated",
+ "resultKeys": [],
+ "defaultItems": 100
+ },
+ "GetServiceLastAccessedDetails": {
+ "paginator": false,
+ "inputToken": "Marker",
+ "outputToken": "Marker",
+ "limitKey": "MaxItems",
+ "moreResults": "IsTruncated",
+ "resultKeys": [],
+ "defaultItems": 100
+ },
+ "GetServiceLastAccessedDetailsWithEntities": {
+ "paginator": false,
+ "inputToken": "Marker",
+ "outputToken": "Marker",
+ "limitKey": "MaxItems",
+ "moreResults": "IsTruncated",
+ "resultKeys": [],
+ "defaultItems": 100
+ },
+ "ListAccessKeys": {
+ "paginator": true,
+ "inputToken": "Marker",
+ "outputToken": "Marker",
+ "limitKey": "MaxItems",
+ "moreResults": "IsTruncated",
+ "resultKeys": [
+ "AccessKeyMetadata"
+ ],
+ "defaultItems": 100
+ },
+ "ListAccountAliases": {
+ "paginator": true,
+ "inputToken": "Marker",
+ "outputToken": "Marker",
+ "limitKey": "MaxItems",
+ "moreResults": "IsTruncated",
+ "resultKeys": [
+ "AccountAliases"
+ ],
+ "defaultItems": 100
+ },
+ "ListAttachedGroupPolicies": {
+ "paginator": true,
+ "inputToken": "Marker",
+ "outputToken": "Marker",
+ "limitKey": "MaxItems",
+ "moreResults": "IsTruncated",
+ "resultKeys": [
+ "AttachedPolicies"
+ ],
+ "defaultItems": 100
+ },
+ "ListAttachedRolePolicies": {
+ "paginator": true,
+ "inputToken": "Marker",
+ "outputToken": "Marker",
+ "limitKey": "MaxItems",
+ "moreResults": "IsTruncated",
+ "resultKeys": [
+ "AttachedPolicies"
+ ],
+ "defaultItems": 100
+ },
+ "ListAttachedUserPolicies": {
+ "paginator": true,
+ "inputToken": "Marker",
+ "outputToken": "Marker",
+ "limitKey": "MaxItems",
+ "moreResults": "IsTruncated",
+ "resultKeys": [
+ "AttachedPolicies"
+ ],
+ "defaultItems": 100
+ },
+ "ListDelegationRequests": {
+ "paginator": false,
+ "inputToken": "Marker",
+ "outputToken": "Marker",
+ "limitKey": "MaxItems",
+ "moreResults": "isTruncated",
+ "resultKeys": [],
+ "defaultItems": 100
+ },
+ "ListEntitiesForPolicy": {
+ "paginator": true,
+ "inputToken": "Marker",
+ "outputToken": "Marker",
+ "limitKey": "MaxItems",
+ "moreResults": "IsTruncated",
+ "resultKeys": [
+ "PolicyGroups",
+ "PolicyUsers",
+ "PolicyRoles"
+ ],
+ "defaultItems": 100
+ },
+ "ListGroupPolicies": {
+ "paginator": true,
+ "inputToken": "Marker",
+ "outputToken": "Marker",
+ "limitKey": "MaxItems",
+ "moreResults": "IsTruncated",
+ "resultKeys": [
+ "PolicyNames"
+ ],
+ "defaultItems": 100
+ },
+ "ListGroups": {
+ "paginator": true,
+ "inputToken": "Marker",
+ "outputToken": "Marker",
+ "limitKey": "MaxItems",
+ "moreResults": "IsTruncated",
+ "resultKeys": [
+ "Groups"
+ ],
+ "defaultItems": 100
+ },
+ "ListGroupsForUser": {
+ "paginator": true,
+ "inputToken": "Marker",
+ "outputToken": "Marker",
+ "limitKey": "MaxItems",
+ "moreResults": "IsTruncated",
+ "resultKeys": [
+ "Groups"
+ ],
+ "defaultItems": 100
+ },
+ "ListInstanceProfileTags": {
+ "paginator": true,
+ "inputToken": "Marker",
+ "outputToken": "Marker",
+ "limitKey": "MaxItems",
+ "moreResults": "IsTruncated",
+ "resultKeys": [
+ "Tags"
+ ],
+ "defaultItems": 100
+ },
+ "ListInstanceProfiles": {
+ "paginator": true,
+ "inputToken": "Marker",
+ "outputToken": "Marker",
+ "limitKey": "MaxItems",
+ "moreResults": "IsTruncated",
+ "resultKeys": [
+ "InstanceProfiles"
+ ],
+ "defaultItems": 100
+ },
+ "ListInstanceProfilesForRole": {
+ "paginator": true,
+ "inputToken": "Marker",
+ "outputToken": "Marker",
+ "limitKey": "MaxItems",
+ "moreResults": "IsTruncated",
+ "resultKeys": [
+ "InstanceProfiles"
+ ],
+ "defaultItems": 100
+ },
+ "ListMFADeviceTags": {
+ "paginator": true,
+ "inputToken": "Marker",
+ "outputToken": "Marker",
+ "limitKey": "MaxItems",
+ "moreResults": "IsTruncated",
+ "resultKeys": [
+ "Tags"
+ ],
+ "defaultItems": 100
+ },
+ "ListMFADevices": {
+ "paginator": true,
+ "inputToken": "Marker",
+ "outputToken": "Marker",
+ "limitKey": "MaxItems",
+ "moreResults": "IsTruncated",
+ "resultKeys": [
+ "MFADevices"
+ ],
+ "defaultItems": 100
+ },
+ "ListOpenIDConnectProviderTags": {
+ "paginator": true,
+ "inputToken": "Marker",
+ "outputToken": "Marker",
+ "limitKey": "MaxItems",
+ "moreResults": "IsTruncated",
+ "resultKeys": [
+ "Tags"
+ ],
+ "defaultItems": 100
+ },
+ "ListPolicies": {
+ "paginator": true,
+ "inputToken": "Marker",
+ "outputToken": "Marker",
+ "limitKey": "MaxItems",
+ "moreResults": "IsTruncated",
+ "resultKeys": [
+ "Policies"
+ ],
+ "defaultItems": 100
+ },
+ "ListPoliciesGrantingServiceAccess": {
+ "paginator": false,
+ "inputToken": "Marker",
+ "outputToken": "Marker",
+ "limitKey": null,
+ "moreResults": "IsTruncated",
+ "resultKeys": []
+ },
+ "ListPolicyTags": {
+ "paginator": true,
+ "inputToken": "Marker",
+ "outputToken": "Marker",
+ "limitKey": "MaxItems",
+ "moreResults": "IsTruncated",
+ "resultKeys": [
+ "Tags"
+ ],
+ "defaultItems": 100
+ },
+ "ListPolicyVersions": {
+ "paginator": true,
+ "inputToken": "Marker",
+ "outputToken": "Marker",
+ "limitKey": "MaxItems",
+ "moreResults": "IsTruncated",
+ "resultKeys": [
+ "Versions"
+ ],
+ "defaultItems": 100
+ },
+ "ListRolePolicies": {
+ "paginator": true,
+ "inputToken": "Marker",
+ "outputToken": "Marker",
+ "limitKey": "MaxItems",
+ "moreResults": "IsTruncated",
+ "resultKeys": [
+ "PolicyNames"
+ ],
+ "defaultItems": 100
+ },
+ "ListRoleTags": {
+ "paginator": true,
+ "inputToken": "Marker",
+ "outputToken": "Marker",
+ "limitKey": "MaxItems",
+ "moreResults": "IsTruncated",
+ "resultKeys": [
+ "Tags"
+ ],
+ "defaultItems": 100
+ },
+ "ListRoles": {
+ "paginator": true,
+ "inputToken": "Marker",
+ "outputToken": "Marker",
+ "limitKey": "MaxItems",
+ "moreResults": "IsTruncated",
+ "resultKeys": [
+ "Roles"
+ ],
+ "defaultItems": 100
+ },
+ "ListSAMLProviderTags": {
+ "paginator": true,
+ "inputToken": "Marker",
+ "outputToken": "Marker",
+ "limitKey": "MaxItems",
+ "moreResults": "IsTruncated",
+ "resultKeys": [
+ "Tags"
+ ],
+ "defaultItems": 100
+ },
+ "ListSSHPublicKeys": {
+ "paginator": true,
+ "inputToken": "Marker",
+ "outputToken": "Marker",
+ "limitKey": "MaxItems",
+ "moreResults": "IsTruncated",
+ "resultKeys": [
+ "SSHPublicKeys"
+ ],
+ "defaultItems": 100
+ },
+ "ListServerCertificateTags": {
+ "paginator": true,
+ "inputToken": "Marker",
+ "outputToken": "Marker",
+ "limitKey": "MaxItems",
+ "moreResults": "IsTruncated",
+ "resultKeys": [
+ "Tags"
+ ],
+ "defaultItems": 100
+ },
+ "ListServerCertificates": {
+ "paginator": true,
+ "inputToken": "Marker",
+ "outputToken": "Marker",
+ "limitKey": "MaxItems",
+ "moreResults": "IsTruncated",
+ "resultKeys": [
+ "ServerCertificateMetadataList"
+ ],
+ "defaultItems": 100
+ },
+ "ListServiceSpecificCredentials": {
+ "paginator": false,
+ "inputToken": "Marker",
+ "outputToken": "Marker",
+ "limitKey": "MaxItems",
+ "moreResults": "IsTruncated",
+ "resultKeys": [],
+ "defaultItems": null
+ },
+ "ListSigningCertificates": {
+ "paginator": true,
+ "inputToken": "Marker",
+ "outputToken": "Marker",
+ "limitKey": "MaxItems",
+ "moreResults": "IsTruncated",
+ "resultKeys": [
+ "Certificates"
+ ],
+ "defaultItems": 100
+ },
+ "ListUserPolicies": {
+ "paginator": true,
+ "inputToken": "Marker",
+ "outputToken": "Marker",
+ "limitKey": "MaxItems",
+ "moreResults": "IsTruncated",
+ "resultKeys": [
+ "PolicyNames"
+ ],
+ "defaultItems": 100
+ },
+ "ListUserTags": {
+ "paginator": true,
+ "inputToken": "Marker",
+ "outputToken": "Marker",
+ "limitKey": "MaxItems",
+ "moreResults": "IsTruncated",
+ "resultKeys": [
+ "Tags"
+ ],
+ "defaultItems": 100
+ },
+ "ListUsers": {
+ "paginator": true,
+ "inputToken": "Marker",
+ "outputToken": "Marker",
+ "limitKey": "MaxItems",
+ "moreResults": "IsTruncated",
+ "resultKeys": [
+ "Users"
+ ],
+ "defaultItems": 100
+ },
+ "ListVirtualMFADevices": {
+ "paginator": true,
+ "inputToken": "Marker",
+ "outputToken": "Marker",
+ "limitKey": "MaxItems",
+ "moreResults": "IsTruncated",
+ "resultKeys": [
+ "VirtualMFADevices"
+ ],
+ "defaultItems": 100
+ },
+ "SimulateCustomPolicy": {
+ "paginator": true,
+ "inputToken": "Marker",
+ "outputToken": "Marker",
+ "limitKey": "MaxItems",
+ "moreResults": "IsTruncated",
+ "resultKeys": [
+ "EvaluationResults"
+ ],
+ "defaultItems": 100
+ },
+ "SimulatePrincipalPolicy": {
+ "paginator": true,
+ "inputToken": "Marker",
+ "outputToken": "Marker",
+ "limitKey": "MaxItems",
+ "moreResults": "IsTruncated",
+ "resultKeys": [
+ "EvaluationResults"
+ ],
+ "defaultItems": 100
+ }
+ }
+}
diff --git a/src/main/resources/aws/iam-request-shapes.json b/src/main/resources/aws/iam-request-shapes.json
index 0885222f05..450ffd11f0 100644
--- a/src/main/resources/aws/iam-request-shapes.json
+++ b/src/main/resources/aws/iam-request-shapes.json
@@ -16,7 +16,46 @@
"GetPolicyVersion": "GetPolicyVersionRequest",
"DeletePolicyVersion": "DeletePolicyVersionRequest",
"SetDefaultPolicyVersion": "SetDefaultPolicyVersionRequest",
- "GetAccountAuthorizationDetails": "GetAccountAuthorizationDetailsRequest"
+ "GetAccountAuthorizationDetails": "GetAccountAuthorizationDetailsRequest",
+ "GetGroup": "GetGroupRequest",
+ "ListAccessKeys": "ListAccessKeysRequest",
+ "ListAccountAliases": "ListAccountAliasesRequest",
+ "ListAttachedGroupPolicies": "ListAttachedGroupPoliciesRequest",
+ "ListAttachedRolePolicies": "ListAttachedRolePoliciesRequest",
+ "ListAttachedUserPolicies": "ListAttachedUserPoliciesRequest",
+ "ListDelegationRequests": "ListDelegationRequestsRequest",
+ "ListEntitiesForPolicy": "ListEntitiesForPolicyRequest",
+ "ListGroupPolicies": "ListGroupPoliciesRequest",
+ "ListGroups": "ListGroupsRequest",
+ "ListGroupsForUser": "ListGroupsForUserRequest",
+ "ListInstanceProfileTags": "ListInstanceProfileTagsRequest",
+ "ListInstanceProfiles": "ListInstanceProfilesRequest",
+ "ListInstanceProfilesForRole": "ListInstanceProfilesForRoleRequest",
+ "ListMFADeviceTags": "ListMFADeviceTagsRequest",
+ "ListMFADevices": "ListMFADevicesRequest",
+ "ListOpenIDConnectProviderTags": "ListOpenIDConnectProviderTagsRequest",
+ "ListPolicies": "ListPoliciesRequest",
+ "ListPolicyTags": "ListPolicyTagsRequest",
+ "ListPolicyVersions": "ListPolicyVersionsRequest",
+ "ListRolePolicies": "ListRolePoliciesRequest",
+ "ListRoleTags": "ListRoleTagsRequest",
+ "ListRoles": "ListRolesRequest",
+ "ListSAMLProviderTags": "ListSAMLProviderTagsRequest",
+ "ListSSHPublicKeys": "ListSSHPublicKeysRequest",
+ "ListServerCertificateTags": "ListServerCertificateTagsRequest",
+ "ListServerCertificates": "ListServerCertificatesRequest",
+ "ListServiceSpecificCredentials": "ListServiceSpecificCredentialsRequest",
+ "ListSigningCertificates": "ListSigningCertificatesRequest",
+ "ListUserPolicies": "ListUserPoliciesRequest",
+ "ListUserTags": "ListUserTagsRequest",
+ "ListUsers": "ListUsersRequest",
+ "ListVirtualMFADevices": "ListVirtualMFADevicesRequest",
+ "GetOrganizationsAccessReport": "GetOrganizationsAccessReportRequest",
+ "GetServiceLastAccessedDetails": "GetServiceLastAccessedDetailsRequest",
+ "GetServiceLastAccessedDetailsWithEntities": "GetServiceLastAccessedDetailsWithEntitiesRequest",
+ "ListPoliciesGrantingServiceAccess": "ListPoliciesGrantingServiceAccessRequest",
+ "SimulateCustomPolicy": "SimulateCustomPolicyRequest",
+ "SimulatePrincipalPolicy": "SimulatePrincipalPolicyRequest"
},
"shapes": {
"AttachGroupPolicyRequest": {
@@ -135,6 +174,24 @@
"Marker": "markerType"
}
},
+ "GetGroupRequest": {
+ "type": "structure",
+ "required": [
+ "GroupName"
+ ],
+ "members": {
+ "GroupName": "groupNameType",
+ "Marker": "markerType",
+ "MaxItems": "maxItemsType"
+ }
+ },
+ "GetOrganizationsAccessReportRequest": {
+ "type": "structure",
+ "members": {
+ "MaxItems": "maxItemsType",
+ "Marker": "markerType"
+ }
+ },
"GetPolicyRequest": {
"type": "structure",
"required": [
@@ -155,6 +212,353 @@
"VersionId": "policyVersionIdType"
}
},
+ "GetServiceLastAccessedDetailsRequest": {
+ "type": "structure",
+ "members": {
+ "MaxItems": "maxItemsType",
+ "Marker": "markerType"
+ }
+ },
+ "GetServiceLastAccessedDetailsWithEntitiesRequest": {
+ "type": "structure",
+ "members": {
+ "MaxItems": "maxItemsType",
+ "Marker": "markerType"
+ }
+ },
+ "ListAccessKeysRequest": {
+ "type": "structure",
+ "members": {
+ "UserName": "existingUserNameType",
+ "Marker": "markerType",
+ "MaxItems": "maxItemsType"
+ }
+ },
+ "ListAccountAliasesRequest": {
+ "type": "structure",
+ "members": {
+ "Marker": "markerType",
+ "MaxItems": "maxItemsType"
+ }
+ },
+ "ListAttachedGroupPoliciesRequest": {
+ "type": "structure",
+ "required": [
+ "GroupName"
+ ],
+ "members": {
+ "GroupName": "groupNameType",
+ "PathPrefix": "policyPathType",
+ "Marker": "markerType",
+ "MaxItems": "maxItemsType"
+ }
+ },
+ "ListAttachedRolePoliciesRequest": {
+ "type": "structure",
+ "required": [
+ "RoleName"
+ ],
+ "members": {
+ "RoleName": "roleNameType",
+ "PathPrefix": "policyPathType",
+ "Marker": "markerType",
+ "MaxItems": "maxItemsType"
+ }
+ },
+ "ListAttachedUserPoliciesRequest": {
+ "type": "structure",
+ "required": [
+ "UserName"
+ ],
+ "members": {
+ "UserName": "userNameType",
+ "PathPrefix": "policyPathType",
+ "Marker": "markerType",
+ "MaxItems": "maxItemsType"
+ }
+ },
+ "ListDelegationRequestsRequest": {
+ "type": "structure",
+ "members": {
+ "OwnerId": "ownerIdType",
+ "Marker": "markerType",
+ "MaxItems": "maxItemsType"
+ }
+ },
+ "ListEntitiesForPolicyRequest": {
+ "type": "structure",
+ "required": [
+ "PolicyArn"
+ ],
+ "members": {
+ "PolicyArn": "arnType",
+ "EntityFilter": "EntityType",
+ "PathPrefix": "pathType",
+ "PolicyUsageFilter": "PolicyUsageType",
+ "Marker": "markerType",
+ "MaxItems": "maxItemsType"
+ }
+ },
+ "ListGroupPoliciesRequest": {
+ "type": "structure",
+ "required": [
+ "GroupName"
+ ],
+ "members": {
+ "GroupName": "groupNameType",
+ "Marker": "markerType",
+ "MaxItems": "maxItemsType"
+ }
+ },
+ "ListGroupsForUserRequest": {
+ "type": "structure",
+ "required": [
+ "UserName"
+ ],
+ "members": {
+ "UserName": "existingUserNameType",
+ "Marker": "markerType",
+ "MaxItems": "maxItemsType"
+ }
+ },
+ "ListGroupsRequest": {
+ "type": "structure",
+ "members": {
+ "PathPrefix": "pathPrefixType",
+ "Marker": "markerType",
+ "MaxItems": "maxItemsType"
+ }
+ },
+ "ListInstanceProfileTagsRequest": {
+ "type": "structure",
+ "required": [
+ "InstanceProfileName"
+ ],
+ "members": {
+ "InstanceProfileName": "instanceProfileNameType",
+ "Marker": "markerType",
+ "MaxItems": "maxItemsType"
+ }
+ },
+ "ListInstanceProfilesForRoleRequest": {
+ "type": "structure",
+ "required": [
+ "RoleName"
+ ],
+ "members": {
+ "RoleName": "roleNameType",
+ "Marker": "markerType",
+ "MaxItems": "maxItemsType"
+ }
+ },
+ "ListInstanceProfilesRequest": {
+ "type": "structure",
+ "members": {
+ "PathPrefix": "pathPrefixType",
+ "Marker": "markerType",
+ "MaxItems": "maxItemsType"
+ }
+ },
+ "ListMFADeviceTagsRequest": {
+ "type": "structure",
+ "required": [
+ "SerialNumber"
+ ],
+ "members": {
+ "SerialNumber": "serialNumberType",
+ "Marker": "markerType",
+ "MaxItems": "maxItemsType"
+ }
+ },
+ "ListMFADevicesRequest": {
+ "type": "structure",
+ "members": {
+ "UserName": "existingUserNameType",
+ "Marker": "markerType",
+ "MaxItems": "maxItemsType"
+ }
+ },
+ "ListOpenIDConnectProviderTagsRequest": {
+ "type": "structure",
+ "required": [
+ "OpenIDConnectProviderArn"
+ ],
+ "members": {
+ "OpenIDConnectProviderArn": "arnType",
+ "Marker": "markerType",
+ "MaxItems": "maxItemsType"
+ }
+ },
+ "ListPoliciesGrantingServiceAccessRequest": {
+ "type": "structure",
+ "members": {
+ "Marker": "markerType"
+ }
+ },
+ "ListPoliciesRequest": {
+ "type": "structure",
+ "members": {
+ "Scope": "policyScopeType",
+ "OnlyAttached": "booleanType",
+ "PathPrefix": "policyPathType",
+ "PolicyUsageFilter": "PolicyUsageType",
+ "Marker": "markerType",
+ "MaxItems": "maxItemsType"
+ }
+ },
+ "ListPolicyTagsRequest": {
+ "type": "structure",
+ "required": [
+ "PolicyArn"
+ ],
+ "members": {
+ "PolicyArn": "arnType",
+ "Marker": "markerType",
+ "MaxItems": "maxItemsType"
+ }
+ },
+ "ListPolicyVersionsRequest": {
+ "type": "structure",
+ "required": [
+ "PolicyArn"
+ ],
+ "members": {
+ "PolicyArn": "arnType",
+ "Marker": "markerType",
+ "MaxItems": "maxItemsType"
+ }
+ },
+ "ListRolePoliciesRequest": {
+ "type": "structure",
+ "required": [
+ "RoleName"
+ ],
+ "members": {
+ "RoleName": "roleNameType",
+ "Marker": "markerType",
+ "MaxItems": "maxItemsType"
+ }
+ },
+ "ListRoleTagsRequest": {
+ "type": "structure",
+ "required": [
+ "RoleName"
+ ],
+ "members": {
+ "RoleName": "roleNameType",
+ "Marker": "markerType",
+ "MaxItems": "maxItemsType"
+ }
+ },
+ "ListRolesRequest": {
+ "type": "structure",
+ "members": {
+ "PathPrefix": "pathPrefixType",
+ "Marker": "markerType",
+ "MaxItems": "maxItemsType"
+ }
+ },
+ "ListSAMLProviderTagsRequest": {
+ "type": "structure",
+ "required": [
+ "SAMLProviderArn"
+ ],
+ "members": {
+ "SAMLProviderArn": "arnType",
+ "Marker": "markerType",
+ "MaxItems": "maxItemsType"
+ }
+ },
+ "ListSSHPublicKeysRequest": {
+ "type": "structure",
+ "members": {
+ "UserName": "userNameType",
+ "Marker": "markerType",
+ "MaxItems": "maxItemsType"
+ }
+ },
+ "ListServerCertificateTagsRequest": {
+ "type": "structure",
+ "required": [
+ "ServerCertificateName"
+ ],
+ "members": {
+ "ServerCertificateName": "serverCertificateNameType",
+ "Marker": "markerType",
+ "MaxItems": "maxItemsType"
+ }
+ },
+ "ListServerCertificatesRequest": {
+ "type": "structure",
+ "members": {
+ "PathPrefix": "pathPrefixType",
+ "Marker": "markerType",
+ "MaxItems": "maxItemsType"
+ }
+ },
+ "ListServiceSpecificCredentialsRequest": {
+ "type": "structure",
+ "members": {
+ "UserName": "userNameType",
+ "ServiceName": "serviceName",
+ "AllUsers": "allUsers",
+ "Marker": "markerType",
+ "MaxItems": "maxItemsType"
+ }
+ },
+ "ListSigningCertificatesRequest": {
+ "type": "structure",
+ "members": {
+ "UserName": "existingUserNameType",
+ "Marker": "markerType",
+ "MaxItems": "maxItemsType"
+ }
+ },
+ "ListUserPoliciesRequest": {
+ "type": "structure",
+ "required": [
+ "UserName"
+ ],
+ "members": {
+ "UserName": "existingUserNameType",
+ "Marker": "markerType",
+ "MaxItems": "maxItemsType"
+ }
+ },
+ "ListUserTagsRequest": {
+ "type": "structure",
+ "required": [
+ "UserName"
+ ],
+ "members": {
+ "UserName": "existingUserNameType",
+ "Marker": "markerType",
+ "MaxItems": "maxItemsType"
+ }
+ },
+ "ListUsersRequest": {
+ "type": "structure",
+ "members": {
+ "PathPrefix": "pathPrefixType",
+ "Marker": "markerType",
+ "MaxItems": "maxItemsType"
+ }
+ },
+ "ListVirtualMFADevicesRequest": {
+ "type": "structure",
+ "members": {
+ "AssignmentStatus": "assignmentStatusType",
+ "Marker": "markerType",
+ "MaxItems": "maxItemsType"
+ }
+ },
+ "PolicyUsageType": {
+ "type": "string",
+ "enum": [
+ "PermissionsPolicy",
+ "PermissionsBoundary"
+ ]
+ },
"SetDefaultPolicyVersionRequest": {
"type": "structure",
"required": [
@@ -166,11 +570,36 @@
"VersionId": "policyVersionIdType"
}
},
+ "SimulateCustomPolicyRequest": {
+ "type": "structure",
+ "members": {
+ "MaxItems": "maxItemsType",
+ "Marker": "markerType"
+ }
+ },
+ "SimulatePrincipalPolicyRequest": {
+ "type": "structure",
+ "members": {
+ "MaxItems": "maxItemsType",
+ "Marker": "markerType"
+ }
+ },
+ "allUsers": {
+ "type": "boolean"
+ },
"arnType": {
"type": "string",
"min": 20,
"max": 2048
},
+ "assignmentStatusType": {
+ "type": "string",
+ "enum": [
+ "Assigned",
+ "Unassigned",
+ "Any"
+ ]
+ },
"booleanType": {
"type": "boolean"
},
@@ -178,12 +607,24 @@
"type": "list",
"member": "EntityType"
},
+ "existingUserNameType": {
+ "type": "string",
+ "min": 1,
+ "max": 128,
+ "pattern": "[\\w+=,.@-]+"
+ },
"groupNameType": {
"type": "string",
"min": 1,
"max": 128,
"pattern": "[\\w+=,.@-]+"
},
+ "instanceProfileNameType": {
+ "type": "string",
+ "min": 1,
+ "max": 128,
+ "pattern": "[\\w+=,.@-]+"
+ },
"markerType": {
"type": "string",
"min": 1,
@@ -195,12 +636,44 @@
"min": 1,
"max": 1000
},
+ "ownerIdType": {
+ "type": "string",
+ "min": 20,
+ "max": 2048,
+ "pattern": "^[a-zA-Z0-9:/+=,.@_-]+$"
+ },
+ "pathPrefixType": {
+ "type": "string",
+ "min": 1,
+ "max": 512,
+ "pattern": "\\u002F[\\u0021-\\u007F]*"
+ },
+ "pathType": {
+ "type": "string",
+ "min": 1,
+ "max": 512,
+ "pattern": "(\\u002F)|(\\u002F[\\u0021-\\u007E]+\\u002F)"
+ },
"policyDocumentType": {
"type": "string",
"min": 1,
"max": 131072,
"pattern": "[\\u0009\\u000A\\u000D\\u0020-\\u00FF]+"
},
+ "policyPathType": {
+ "type": "string",
+ "min": 1,
+ "max": 512,
+ "pattern": "((/[A-Za-z0-9\\.,\\+@=_-]+)*)/"
+ },
+ "policyScopeType": {
+ "type": "string",
+ "enum": [
+ "All",
+ "AWS",
+ "Local"
+ ]
+ },
"policyVersionIdType": {
"type": "string",
"pattern": "v[1-9][0-9]*(\\.[A-Za-z0-9-]*)?"
@@ -211,6 +684,21 @@
"max": 64,
"pattern": "[\\w+=,.@-]+"
},
+ "serialNumberType": {
+ "type": "string",
+ "min": 9,
+ "max": 256,
+ "pattern": "[\\w+=/:,.@-]+"
+ },
+ "serverCertificateNameType": {
+ "type": "string",
+ "min": 1,
+ "max": 128,
+ "pattern": "[\\w+=,.@-]+"
+ },
+ "serviceName": {
+ "type": "string"
+ },
"userNameType": {
"type": "string",
"min": 1,
diff --git a/src/test/java/io/github/hectorvent/floci/core/common/SignedMarkersTest.java b/src/test/java/io/github/hectorvent/floci/core/common/SignedMarkersTest.java
index 4181d8ebaf..1a34156aec 100644
--- a/src/test/java/io/github/hectorvent/floci/core/common/SignedMarkersTest.java
+++ b/src/test/java/io/github/hectorvent/floci/core/common/SignedMarkersTest.java
@@ -2,8 +2,11 @@ package io.github.hectorvent.floci.core.common;
import org.junit.jupiter.api.Test;
+import java.util.Base64;
+
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
+import static org.junit.jupiter.api.Assertions.assertTrue;
class SignedMarkersTest {
@@ -25,4 +28,56 @@ class SignedMarkersTest {
assertNull(markers.cursorOf(Base64Url.encode("role-b.forged")));
assertNull(markers.cursorOf("not base64!"));
}
+
+ @Test
+ void aScopedMarkerResumesOnlyItsOwnScope() {
+ String marker = markers.issue("account-a\nListUsers", "user-b");
+
+ assertEquals("user-b", markers.cursorOf("account-a\nListUsers", marker));
+ assertNull(markers.cursorOf("account-b\nListUsers", marker));
+ assertNull(markers.cursorOf("account-a\nListGroups", marker));
+ assertNull(markers.cursorOf(marker), "an unscoped read does not accept a scoped marker");
+ assertNull(markers.cursorOf("account-a\nListUsers", markers.issue("user-b")),
+ "a scoped read does not accept an unscoped marker");
+ }
+
+ /** The scope is length-prefixed, so moving characters between scope and cursor breaks the signature. */
+ @Test
+ void theScopeAndCursorCannotTradeCharacters() {
+ String marker = markers.issue("ab", "c");
+
+ assertNull(markers.cursorOf("a", Base64Url.encode(
+ new String(Base64.getUrlDecoder().decode(marker)).replaceFirst("^c", "bc"))));
+ }
+
+ /** A cursor too long for the limit is named by digest, and still resumes only its own scope. */
+ @Test
+ void aCursorTooLongForTheLimitStillFitsAndResolves() {
+ SignedMarkers bounded = new SignedMarkers(320);
+ String arn = "arn:aws:iam::000000000000:policy/" + "p/".repeat(250) + "name";
+ String marker = bounded.issue("account-a\nListAttachedRolePolicies", arn);
+
+ assertTrue(marker.length() <= 320, marker.length() + " characters");
+ assertEquals(arn, bounded.cursorOf("account-a\nListAttachedRolePolicies", marker));
+ assertNull(bounded.cursorOf("account-b\nListAttachedRolePolicies", marker));
+ assertNull(markers.cursorOf("account-a\nListAttachedRolePolicies", marker),
+ "another instance holds neither the key nor the cursor");
+ assertEquals("user-b", bounded.cursorOf("s", bounded.issue("s", "user-b")),
+ "a cursor that fits is carried as it is");
+ }
+
+ /** The long cursors an instance holds are bounded; the least recently used is forgotten. */
+ @Test
+ void anEvictedLongCursorIsNotRecognisedButARecentOneResumes() {
+ SignedMarkers bounded = new SignedMarkers(320);
+ String prefix = "arn:aws:iam::000000000000:policy/" + "p/".repeat(250);
+ String oldest = bounded.issue("s", prefix + "oldest");
+ for (int i = 0; i < SignedMarkers.MAX_LONG_CURSORS; i++) {
+ bounded.issue("s", prefix + i);
+ }
+ String recent = bounded.issue("s", prefix + "recent");
+
+ assertNull(bounded.cursorOf("s", oldest), "an evicted digest resolves like an unknown one");
+ assertEquals(prefix + "recent", bounded.cursorOf("s", recent));
+ }
}
diff --git a/src/test/java/io/github/hectorvent/floci/services/iam/IamListPaginationIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/iam/IamListPaginationIntegrationTest.java
index b0c08f6181..55514862dd 100644
--- a/src/test/java/io/github/hectorvent/floci/services/iam/IamListPaginationIntegrationTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/iam/IamListPaginationIntegrationTest.java
@@ -1,16 +1,43 @@
package io.github.hectorvent.floci.services.iam;
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import io.github.hectorvent.floci.core.common.SshPublicKeys;
+import io.github.hectorvent.floci.core.common.Totp;
+import io.github.hectorvent.floci.core.common.XmlParser;
+import io.github.hectorvent.floci.services.acm.CertificateGenerator;
+import io.github.hectorvent.floci.services.acm.model.KeyAlgorithm;
+import io.quarkus.test.common.http.TestHTTPResource;
import io.quarkus.test.junit.QuarkusTest;
import io.restassured.path.xml.XmlPath;
import io.restassured.specification.RequestSpecification;
import org.junit.jupiter.api.Test;
+import org.w3c.dom.Element;
+import org.w3c.dom.Node;
+import java.io.IOException;
+import java.io.InputStream;
+import java.net.URI;
+import java.net.URLEncoder;
+import java.net.http.HttpClient;
+import java.net.http.HttpRequest;
+import java.net.http.HttpResponse;
import java.nio.charset.StandardCharsets;
+import java.security.KeyPairGenerator;
+import java.security.interfaces.RSAPublicKey;
+import java.time.Instant;
import java.util.ArrayList;
import java.util.Base64;
+import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.TreeMap;
+import java.util.TreeSet;
+import java.util.concurrent.CompletableFuture;
import java.util.function.Function;
+import java.util.function.Supplier;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.equalTo;
@@ -21,8 +48,11 @@ 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".
+ * Every IAM operation that pages goes through {@code MaxItems} and {@code Marker} as the vendored
+ * {@code aws/iam-paginators.json} describes it, which {@link #everyPaginatedOperationHonoursMaxItemsAndMarker}
+ * checks operation by operation. The rest pin what that one path does on the lists where it is
+ * easiest to see: name order, a marker anchored to an item rather than a position, the default page
+ * of 100, and a marker that resumes only the listing and account that issued it.
*
* <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.
@@ -39,6 +69,35 @@ class IamListPaginationIntegrationTest {
{"Version":"2012-10-17","Statement":[{"Effect":"Allow","Action":"s3:GetObject",\
"Resource":"*"}]}""";
+ @TestHTTPResource("/")
+ URI endpoint;
+
+ private static final HttpClient BULK = HttpClient.newBuilder().version(HttpClient.Version.HTTP_1_1).build();
+
+ /**
+ * Sends one {@code action} per parameter set, concurrently and without RestAssured, whose
+ * per-request overhead is most of the cost of the hundred-item fixtures. Each must answer 200.
+ */
+ private void bulk(String action, List<List<String>> requests) {
+ List<CompletableFuture<HttpResponse<String>>> sent = new ArrayList<>();
+ for (List<String> pairs : requests) {
+ StringBuilder form = new StringBuilder("Action=").append(action);
+ for (int i = 0; i < pairs.size(); i += 2) {
+ form.append('&').append(pairs.get(i)).append('=')
+ .append(URLEncoder.encode(pairs.get(i + 1), StandardCharsets.UTF_8));
+ }
+ sent.add(BULK.sendAsync(HttpRequest.newBuilder(endpoint)
+ .header("Authorization", IAM_AUTH)
+ .header("Content-Type", "application/x-www-form-urlencoded")
+ .POST(HttpRequest.BodyPublishers.ofString(form.toString())).build(),
+ HttpResponse.BodyHandlers.ofString()));
+ }
+ for (CompletableFuture<HttpResponse<String>> response : sent) {
+ HttpResponse<String> answered = response.join();
+ assertEquals(200, answered.statusCode(), action + ": " + answered.body());
+ }
+ }
+
private static RequestSpecification iam(String action) {
return given().header("Authorization", IAM_AUTH).formParam("Action", action);
}
@@ -162,7 +221,8 @@ class IamListPaginationIntegrationTest {
for (int i = 0; i < 101; i++) {
names.add(String.format("pg-default-%s-%03d", tag, i));
}
- names.forEach(name -> createRole(name, path));
+ bulk("CreateRole", names.stream().map(name -> List.of("RoleName", name, "Path", path,
+ "AssumeRolePolicyDocument", TRUST_POLICY)).toList());
try {
Page first = rolePage(path, null, null);
assertEquals(100, first.names().size());
@@ -174,7 +234,7 @@ class IamListPaginationIntegrationTest {
assertFalse(second.truncated());
assertNull(second.marker());
} finally {
- names.forEach(IamListPaginationIntegrationTest::deleteRole);
+ bulk("DeleteRole", names.stream().map(name -> List.of("RoleName", name)).toList());
}
}
@@ -213,39 +273,6 @@ class IamListPaginationIntegrationTest {
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"));
- }
- }
-
/**
* The API reference documents Marker as the place "where the next call should start", so a
* continuation returns the roles after the ones already seen, whatever happened ahead of it.
@@ -343,6 +370,49 @@ class IamListPaginationIntegrationTest {
}
}
+ /**
+ * ListAttachedRolePolicies keys a page by policy ARN, and a long path makes that ARN longer than
+ * the 320 characters the model allows a Marker. The marker issued still fits, so the request
+ * carrying it clears the model check, and with the policy it ended on deleted before the next
+ * page it resumes at the next policy, skipping none and repeating none.
+ */
+ @Test
+ void aMarkerEndingOnALongPolicyArnFitsTheModelAndResumesPastItsDeletion() {
+ String tag = suffix();
+ String path = "/" + ("pg-long-path-" + tag + "/").repeat(15);
+ String role = "pg-long-" + tag;
+ createRole(role, "/");
+ List<String> arns = new ArrayList<>();
+ for (int i = 0; i < 3; i++) {
+ arns.add(createPolicy(role + "-" + i, path));
+ call("AttachRolePolicy", "RoleName", role, "PolicyArn", arns.getLast());
+ }
+ List<String> remaining = new ArrayList<>(arns);
+ try {
+ assertTrue(arns.getFirst().length() > 320, arns.getFirst().length() + " characters");
+ Page first = page("ListAttachedRolePolicies", "AttachedPolicies", "PolicyArn",
+ iam("ListAttachedRolePolicies").formParam("RoleName", role).formParam("MaxItems", "1"));
+ assertEquals(List.of(arns.getFirst()), first.names());
+ assertNotNull(first.marker());
+ assertTrue(first.marker().length() <= 320, first.marker().length() + " characters");
+
+ call("DetachRolePolicy", "RoleName", role, "PolicyArn", arns.getFirst());
+ deletePolicy(arns.getFirst());
+ remaining.remove(arns.getFirst());
+
+ Page rest = page("ListAttachedRolePolicies", "AttachedPolicies", "PolicyArn",
+ withMarker(iam("ListAttachedRolePolicies").formParam("RoleName", role), first.marker()));
+ assertEquals(arns.subList(1, 3), rest.names());
+ assertFalse(rest.truncated());
+ } finally {
+ remaining.forEach(arn -> {
+ call("DetachRolePolicy", "RoleName", role, "PolicyArn", arn);
+ deletePolicy(arn);
+ });
+ deleteRole(role);
+ }
+ }
+
/** A marker shaped like an issued one but never issued is refused, as any other unissued marker is. */
@Test
void listRolesRejectsAnAnchoredMarkerItDidNotIssue() {
@@ -362,4 +432,854 @@ class IamListPaginationIntegrationTest {
}
return names;
}
+
+ private static Page listPage(String action, String listElement, String nameElement,
+ String entityParam, String entity, String maxItems, String marker) {
+ RequestSpecification request = iam(action);
+ if (entityParam != null) {
+ request.formParam(entityParam, entity);
+ }
+ if (maxItems != null) {
+ request.formParam("MaxItems", maxItems);
+ }
+ if (marker != null) {
+ request.formParam("Marker", marker);
+ }
+ return page(action, listElement, nameElement, request);
+ }
+
+ private static void call(String action, String... pairs) {
+ RequestSpecification request = iam(action);
+ for (int i = 0; i < pairs.length; i += 2) {
+ request.formParam(pairs[i], pairs[i + 1]);
+ }
+ request.when().post("/").then().statusCode(200);
+ }
+
+ @Test
+ void listUsersAndListGroupsPageThroughThePathPrefixInNameOrder() {
+ String tag = suffix();
+ String path = "/pg-principals-" + tag + "/";
+ List<String> expected = new ArrayList<>();
+ for (int i = 0; i < 5; i++) {
+ expected.add("pg-principal-" + tag + "-" + i);
+ }
+ // Created out of name order, so the listing has to sort rather than echo creation order.
+ for (String name : expected.reversed()) {
+ call("CreateUser", "UserName", name, "Path", path);
+ call("CreateGroup", "GroupName", name, "Path", path);
+ }
+ try {
+ List<Page> users = walk(marker -> page("ListUsers", "Users", "UserName",
+ withMarker(iam("ListUsers").formParam("PathPrefix", path).formParam("MaxItems", "2"), marker)));
+ List<Page> groups = walk(marker -> page("ListGroups", "Groups", "GroupName",
+ withMarker(iam("ListGroups").formParam("PathPrefix", path).formParam("MaxItems", "2"), marker)));
+
+ for (List<Page> pages : List.of(users, groups)) {
+ 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 entry once, in name order");
+ }
+ assertEquals(expected, page("ListUsers", "Users", "UserName",
+ iam("ListUsers").formParam("PathPrefix", path)).names(), "no MaxItems lists them all");
+ } finally {
+ for (String name : expected) {
+ call("DeleteUser", "UserName", name);
+ call("DeleteGroup", "GroupName", name);
+ }
+ }
+ }
+
+ private static RequestSpecification withMarker(RequestSpecification request, String marker) {
+ return marker == null ? request : request.formParam("Marker", marker);
+ }
+
+ @Test
+ void attachedAndInlinePolicyListsPageThroughMaxItemsAndMarker() {
+ String tag = suffix();
+ String name = "pg-holder-" + tag;
+ createRole(name, "/");
+ call("CreateUser", "UserName", name);
+ call("CreateGroup", "GroupName", name);
+ List<String> arns = new ArrayList<>();
+ List<String> inline = new ArrayList<>();
+ for (int i = 0; i < 3; i++) {
+ arns.add(createPolicy("pg-attached-" + tag + "-" + i, "/"));
+ inline.add("pg-inline-" + tag + "-" + i);
+ }
+ List<String[]> holders = List.of(new String[]{"Role", "RoleName"},
+ new String[]{"User", "UserName"}, new String[]{"Group", "GroupName"});
+ try {
+ for (String[] h : holders) {
+ for (int i = 2; i >= 0; i--) {
+ call("Attach" + h[0] + "Policy", h[1], name, "PolicyArn", arns.get(i));
+ call("Put" + h[0] + "Policy", h[1], name, "PolicyName", inline.get(i),
+ "PolicyDocument", POLICY_DOCUMENT);
+ }
+ }
+ for (String[] h : holders) {
+ List<Page> attached = walk(marker -> listPage("ListAttached" + h[0] + "Policies",
+ "AttachedPolicies", "PolicyArn", h[1], name, "2", marker));
+ assertEquals(List.of(2, 1), attached.stream().map(p -> p.names().size()).toList(), h[0]);
+ assertEquals(arns, flatten(attached), h[0] + " attached policies, each once");
+
+ List<Page> names = walk(marker -> {
+ String action = "List" + h[0] + "Policies";
+ XmlPath xml = withMarker(iam(action).formParam(h[1], name).formParam("MaxItems", "2"), marker)
+ .when().post("/").then().statusCode(200).extract().xmlPath();
+ String result = action + "Response." + action + "Result.";
+ String next = xml.getString(result + "Marker");
+ return new Page(xml.getList(result + "PolicyNames.member", String.class),
+ Boolean.parseBoolean(xml.getString(result + "IsTruncated")),
+ next == null || next.isEmpty() ? null : next);
+ });
+ assertEquals(List.of(2, 1), names.stream().map(p -> p.names().size()).toList(), h[0]);
+ assertEquals(inline, flatten(names), h[0] + " inline policies, each once");
+ }
+
+ // The policy a marker names, detached before the next page, skips nothing after it.
+ Page first = listPage("ListAttachedRolePolicies", "AttachedPolicies", "PolicyArn",
+ "RoleName", name, "2", null);
+ call("DetachRolePolicy", "RoleName", name, "PolicyArn", arns.get(1));
+ assertEquals(List.of(arns.get(2)), listPage("ListAttachedRolePolicies", "AttachedPolicies",
+ "PolicyArn", "RoleName", name, "2", first.marker()).names());
+ call("AttachRolePolicy", "RoleName", name, "PolicyArn", arns.get(1));
+
+ iam("ListRolePolicies").formParam("RoleName", name).formParam("MaxItems", "1001")
+ .when().post("/").then()
+ .statusCode(400)
+ .body("ErrorResponse.Error.Code", equalTo("ValidationError"));
+ iam("ListAttachedRolePolicies").formParam("RoleName", name).formParam("Marker", "not-a-marker")
+ .when().post("/").then()
+ .statusCode(400)
+ .body("ErrorResponse.Error.Code", equalTo("InvalidInput"));
+ } finally {
+ for (String[] h : holders) {
+ for (int i = 0; i < 3; i++) {
+ call("Detach" + h[0] + "Policy", h[1], name, "PolicyArn", arns.get(i));
+ call("Delete" + h[0] + "Policy", h[1], name, "PolicyName", inline.get(i));
+ }
+ }
+ arns.forEach(IamListPaginationIntegrationTest::deletePolicy);
+ deleteRole(name);
+ call("DeleteUser", "UserName", name);
+ call("DeleteGroup", "GroupName", name);
+ }
+ }
+
+ /**
+ * Only the default page size: resuming after a default page is {@link #listRolesDefaultsToOneHundredItems},
+ * and resuming these two lists is {@link #everyPaginatedOperationHonoursMaxItemsAndMarker}.
+ */
+ @Test
+ void listUsersAndListGroupsDefaultToOneHundredItems() {
+ String tag = suffix();
+ String path = "/pg-principals-default-" + tag + "/";
+ List<String> names = new ArrayList<>();
+ for (int i = 0; i < 101; i++) {
+ names.add(String.format("pg-default-%s-%03d", tag, i));
+ }
+ bulk("CreateUser", names.stream().map(name -> List.of("UserName", name, "Path", path)).toList());
+ bulk("CreateGroup", names.stream().map(name -> List.of("GroupName", name, "Path", path)).toList());
+ try {
+ for (String[] list : List.of(new String[]{"ListUsers", "Users", "UserName"},
+ new String[]{"ListGroups", "Groups", "GroupName"})) {
+ Page first = page(list[0], list[1], list[2], iam(list[0]).formParam("PathPrefix", path));
+ assertEquals(names.subList(0, 100), first.names(), list[0]);
+ assertTrue(first.truncated(), list[0]);
+ assertNotNull(first.marker(), list[0]);
+ }
+ } finally {
+ bulk("DeleteUser", names.stream().map(name -> List.of("UserName", name)).toList());
+ bulk("DeleteGroup", names.stream().map(name -> List.of("GroupName", name)).toList());
+ }
+ }
+
+ /** A marker resumes only the listing that issued it: same action, same principal. */
+ @Test
+ void aMarkerFromAnotherListingIsRejected() {
+ String tag = suffix();
+ String roleA = "pg-scope-a-" + tag;
+ String roleB = "pg-scope-b-" + tag;
+ createRole(roleA, "/");
+ createRole(roleB, "/");
+ List<String> arns = new ArrayList<>();
+ List<String> users = List.of("pg-scope-u0-" + tag, "pg-scope-u1-" + tag);
+ for (int i = 0; i < 2; i++) {
+ arns.add(createPolicy("pg-scope-" + tag + "-" + i, "/"));
+ call("CreateUser", "UserName", users.get(i), "Path", "/pg-scope-" + tag + "/");
+ call("CreateGroup", "GroupName", users.get(i), "Path", "/pg-scope-" + tag + "/");
+ for (String role : List.of(roleA, roleB)) {
+ call("AttachRolePolicy", "RoleName", role, "PolicyArn", arns.get(i));
+ call("PutRolePolicy", "RoleName", role, "PolicyName", "pg-inline-" + i,
+ "PolicyDocument", POLICY_DOCUMENT);
+ }
+ }
+ try {
+ String attachedA = listPage("ListAttachedRolePolicies", "AttachedPolicies", "PolicyArn",
+ "RoleName", roleA, "1", null).marker();
+ assertNotNull(attachedA);
+ String usersMarker = page("ListUsers", "Users", "UserName", iam("ListUsers")
+ .formParam("PathPrefix", "/pg-scope-" + tag + "/").formParam("MaxItems", "1")).marker();
+ assertNotNull(usersMarker);
+
+ List<RequestSpecification> misuses = List.of(
+ iam("ListAttachedRolePolicies").formParam("RoleName", roleB).formParam("Marker", attachedA),
+ iam("ListRolePolicies").formParam("RoleName", roleA).formParam("Marker", attachedA),
+ iam("ListGroups").formParam("PathPrefix", "/pg-scope-" + tag + "/")
+ .formParam("Marker", usersMarker));
+ for (RequestSpecification misuse : misuses) {
+ misuse.when().post("/").then()
+ .statusCode(400)
+ .body("ErrorResponse.Error.Code", equalTo("InvalidInput"));
+ }
+ assertEquals(List.of(arns.get(1)), listPage("ListAttachedRolePolicies", "AttachedPolicies",
+ "PolicyArn", "RoleName", roleA, "1", attachedA).names(), "the issuing listing still resumes");
+ } finally {
+ for (int i = 0; i < 2; i++) {
+ for (String role : List.of(roleA, roleB)) {
+ call("DetachRolePolicy", "RoleName", role, "PolicyArn", arns.get(i));
+ call("DeleteRolePolicy", "RoleName", role, "PolicyName", "pg-inline-" + i);
+ }
+ call("DeleteUser", "UserName", users.get(i));
+ call("DeleteGroup", "GroupName", users.get(i));
+ }
+ arns.forEach(IamListPaginationIntegrationTest::deletePolicy);
+ deleteRole(roleA);
+ deleteRole(roleB);
+ }
+ }
+
+ /** IAM is per account, so a marker from one account's listing does not resume another's. */
+ @Test
+ void aMarkerFromAnotherAccountIsRejected() {
+ String accountA = "AWS4-HMAC-SHA256 Credential=111111111111/20260227/us-east-1/iam/aws4_request";
+ String accountB = "AWS4-HMAC-SHA256 Credential=222222222222/20260227/us-east-1/iam/aws4_request";
+ String tag = suffix();
+ String path = "/pg-account-" + tag + "/";
+ List<String> names = List.of("pg-account-" + tag + "-0", "pg-account-" + tag + "-1");
+ for (String account : List.of(accountA, accountB)) {
+ for (String name : names) {
+ given().header("Authorization", account).formParam("Action", "CreateUser")
+ .formParam("UserName", name).formParam("Path", path)
+ .when().post("/").then().statusCode(200);
+ given().header("Authorization", account).formParam("Action", "PutUserPolicy")
+ .formParam("UserName", names.getFirst()).formParam("PolicyName", name)
+ .formParam("PolicyDocument", POLICY_DOCUMENT)
+ .when().post("/").then().statusCode(200);
+ }
+ }
+ try {
+ String usersMarker = page("ListUsers", "Users", "UserName", given().header("Authorization", accountA)
+ .formParam("Action", "ListUsers").formParam("PathPrefix", path).formParam("MaxItems", "1")).marker();
+ String inlineMarker = given().header("Authorization", accountA).formParam("Action", "ListUserPolicies")
+ .formParam("UserName", names.getFirst()).formParam("MaxItems", "1")
+ .when().post("/").then().statusCode(200).extract()
+ .path("ListUserPoliciesResponse.ListUserPoliciesResult.Marker");
+ assertNotNull(usersMarker);
+ assertNotNull(inlineMarker);
+
+ given().header("Authorization", accountB).formParam("Action", "ListUsers")
+ .formParam("PathPrefix", path).formParam("Marker", usersMarker)
+ .when().post("/").then()
+ .statusCode(400)
+ .body("ErrorResponse.Error.Code", equalTo("InvalidInput"));
+ given().header("Authorization", accountB).formParam("Action", "ListUserPolicies")
+ .formParam("UserName", names.getFirst()).formParam("Marker", inlineMarker)
+ .when().post("/").then()
+ .statusCode(400)
+ .body("ErrorResponse.Error.Code", equalTo("InvalidInput"));
+ } finally {
+ for (String account : List.of(accountA, accountB)) {
+ for (String name : names) {
+ given().header("Authorization", account).formParam("Action", "DeleteUserPolicy")
+ .formParam("UserName", names.getFirst()).formParam("PolicyName", name)
+ .when().post("/").then().statusCode(200);
+ }
+ for (String name : names) {
+ given().header("Authorization", account).formParam("Action", "DeleteUser")
+ .formParam("UserName", name)
+ .when().post("/").then().statusCode(200);
+ }
+ }
+ }
+ }
+
+ /**
+ * A list that omits {@code UserName} is the caller's, so the marker is bound to the user it
+ * resolved to: another user in the same account, also omitting it, cannot resume it, while the
+ * same listing named explicitly still can.
+ */
+ @Test
+ void aMarkerFromAnotherCallersImplicitListingIsRejected() {
+ String tag = suffix();
+ List<String> users = List.of("pg-caller-a-" + tag, "pg-caller-b-" + tag);
+ Map<String, List<String>> keys = new HashMap<>();
+ Map<String, List<String>> sshKeys = new HashMap<>();
+ for (String user : users) {
+ createUser(user);
+ keys.put(user, new ArrayList<>());
+ sshKeys.put(user, new ArrayList<>());
+ for (int i = 0; i < 2; i++) {
+ keys.get(user).add(iam("CreateAccessKey").formParam("UserName", user).when().post("/").then()
+ .statusCode(200).extract().path("CreateAccessKeyResponse.CreateAccessKeyResult.AccessKey.AccessKeyId"));
+ sshKeys.get(user).add(iam("UploadSSHPublicKey").formParam("UserName", user)
+ .formParam("SSHPublicKeyBody", SSH_PUBLIC_KEYS.get(i)).when().post("/").then().statusCode(200).extract()
+ .path("UploadSSHPublicKeyResponse.UploadSSHPublicKeyResult.SSHPublicKey.SSHPublicKeyId"));
+ }
+ }
+ Function<String, String> as = user -> "AWS4-HMAC-SHA256 Credential=" + keys.get(user).getFirst()
+ + "/20260227/us-east-1/iam/aws4_request";
+ String a = users.get(0);
+ String b = users.get(1);
+ try {
+ for (String[] op : List.of(new String[]{"ListAccessKeys", "AccessKeyMetadata", "AccessKeyId"},
+ new String[]{"ListSSHPublicKeys", "SSHPublicKeys", "SSHPublicKeyId"})) {
+ Page first = page(op[0], op[1], op[2], given().header("Authorization", as.apply(a))
+ .formParam("Action", op[0]).formParam("MaxItems", "1"));
+ assertTrue(first.truncated(), op[0] + " as " + a + " is cut at one item");
+ assertNotNull(first.marker());
+
+ refused(given().header("Authorization", as.apply(b)).formParam("Action", op[0])
+ .formParam("Marker", first.marker()), "InvalidInput");
+
+ List<String> all = new ArrayList<>(first.names());
+ all.addAll(page(op[0], op[1], op[2], given().header("Authorization", as.apply(a))
+ .formParam("Action", op[0]).formParam("Marker", first.marker())).names());
+ List<String> owned = op[0].equals("ListAccessKeys") ? keys.get(a) : sshKeys.get(a);
+ assertEquals(new TreeSet<>(owned), new TreeSet<>(all), op[0] + " resumes for its own caller");
+ assertEquals(List.of(all.get(1)), page(op[0], op[1], op[2], given()
+ .header("Authorization", as.apply(b)).formParam("Action", op[0])
+ .formParam("UserName", a).formParam("Marker", first.marker())).names(),
+ op[0] + " named explicitly is the same listing");
+ }
+ } finally {
+ for (String user : users) {
+ sshKeys.get(user).forEach(id -> call("DeleteSSHPublicKey", "UserName", user, "SSHPublicKeyId", id));
+ keys.get(user).forEach(key -> call("DeleteAccessKey", "UserName", user, "AccessKeyId", key));
+ call("DeleteUser", "UserName", user);
+ }
+ }
+ }
+
+ // =========================================================================
+ // Every operation the generated table pages
+ // =========================================================================
+
+ /** Operations that cannot list two items: an account holds at most one alias. */
+ private static final Set<String> AT_MOST_ONE_ITEM = Set.of("ListAccountAliases");
+
+ private static final CertificateGenerator CERTIFICATES = new CertificateGenerator();
+ private static final String THUMBPRINT = "9e99a48a9960b14926bb7f3b02e22da2b0ab7280";
+
+ /** A request that lists at least two items of one operation, and what removes them again. */
+ private record Fixture(List<String> params, Runnable cleanup) {
+ static Fixture of(Runnable cleanup, String... params) {
+ return new Fixture(List.of(params), cleanup);
+ }
+ }
+
+ private record Listing(List<String> items, boolean truncated, String marker) {}
+
+ /** The paginated operations of the vendored table, each with its paging entry. */
+ private static Map<String, JsonNode> paginators() throws IOException {
+ try (InputStream in = Thread.currentThread().getContextClassLoader()
+ .getResourceAsStream("aws/iam-paginators.json")) {
+ Map<String, JsonNode> found = new TreeMap<>();
+ new ObjectMapper().readTree(in).path("operations").properties().forEach(entry -> {
+ if (entry.getValue().path("paginator").asBoolean()) {
+ found.put(entry.getKey(), entry.getValue());
+ }
+ });
+ return found;
+ }
+ }
+
+ private static RequestSpecification listRequest(String action, Fixture fixture, String maxItems, String marker) {
+ RequestSpecification request = iam(action);
+ for (int i = 0; i < fixture.params().size(); i += 2) {
+ request.formParam(fixture.params().get(i), fixture.params().get(i + 1));
+ }
+ if (maxItems != null) {
+ request.formParam("MaxItems", maxItems);
+ }
+ return withMarker(request, marker);
+ }
+
+ /** One page, its items read from every result key the table names for the operation. */
+ private static Listing listing(String action, JsonNode paginator, Fixture fixture, String maxItems, String marker) {
+ String body = listRequest(action, fixture, maxItems, marker).when().post("/")
+ .then().statusCode(200).extract().asString();
+ Element result;
+ try {
+ result = (Element) XmlParser.parseDocument(body).getDocumentElement()
+ .getElementsByTagName(action + "Result").item(0);
+ } catch (Exception e) {
+ throw new IllegalStateException(action + " answered unparseable XML: " + body, e);
+ }
+ List<String> items = new ArrayList<>();
+ for (JsonNode resultKey : paginator.path("resultKeys")) {
+ Element list = child(result, resultKey.asText());
+ for (Node item = list == null ? null : list.getFirstChild(); item != null; item = item.getNextSibling()) {
+ if (item instanceof Element member) {
+ items.add(resultKey.asText() + ":" + member.getTextContent());
+ }
+ }
+ }
+ Element next = child(result, paginator.path("outputToken").asText());
+ Element truncated = child(result, paginator.path("moreResults").asText());
+ return new Listing(items, truncated != null && Boolean.parseBoolean(truncated.getTextContent()),
+ next == null || next.getTextContent().isEmpty() ? null : next.getTextContent());
+ }
+
+ /** The direct child of {@code parent} named {@code name}, or null. */
+ private static Element child(Element parent, String name) {
+ for (Node node = parent.getFirstChild(); node != null; node = node.getNextSibling()) {
+ if (node instanceof Element element && element.getTagName().equals(name)) {
+ return element;
+ }
+ }
+ return null;
+ }
+
+ private static List<String> walkFrom(String action, JsonNode paginator, Fixture fixture, String maxItems, String marker) {
+ List<String> items = new ArrayList<>();
+ do {
+ Listing page = listing(action, paginator, fixture, maxItems, marker);
+ assertEquals(page.truncated(), page.marker() != null, action + ": a Marker exactly when truncated");
+ items.addAll(page.items());
+ marker = page.marker();
+ } while (marker != null);
+ return items;
+ }
+
+ private static void refused(RequestSpecification request, String code) {
+ request.when().post("/").then()
+ .statusCode(400)
+ .body("ErrorResponse.Error.Code", equalTo(code));
+ }
+
+ /**
+ * botocore's {@code paginators-1.json} lists every IAM operation that pages, and the vendored
+ * table carries each one. Each must hold {@code MaxItems} to the model's range, cut a page at
+ * it, resume from the {@code Marker} it issued without losing or repeating an item, default to
+ * the documented page size, and refuse a marker it did not issue. The fixture map has to name
+ * exactly the table's operations, so one AWS starts paging later fails here until it has one.
+ */
+ /** {@code maxItemsType}'s range, which {@link IamRequestShapes} holds every paged request to. */
+ private static final int MAX_ITEMS_MIN = 1;
+ private static final int MAX_ITEMS_MAX = 1000;
+
+ @Test
+ void everyPaginatedOperationHonoursMaxItemsAndMarker() throws IOException {
+ Map<String, JsonNode> paginators = paginators();
+ Map<String, Supplier<Fixture>> fixtures = fixtures();
+ assertEquals(paginators.keySet(), new TreeSet<>(fixtures.keySet()),
+ "every operation the table pages has a fixture, and nothing else does");
+
+ String foreignMarker = null;
+ for (Map.Entry<String, JsonNode> entry : paginators.entrySet()) {
+ String action = entry.getKey();
+ JsonNode paginator = entry.getValue();
+ int min = MAX_ITEMS_MIN;
+ int max = MAX_ITEMS_MAX;
+ Fixture fixture = fixtures.get(action).get();
+ try {
+ listRequest(action, fixture, Integer.toString(min - 1), null).when().post("/").then()
+ .statusCode(400)
+ .body("ErrorResponse.Error.Code", equalTo("ValidationError"))
+ .body("ErrorResponse.Error.Message", equalTo("1 validation error detected: Value '"
+ + (min - 1) + "' at 'maxItems' failed to satisfy constraint: "
+ + "Member must have value greater than or equal to " + min));
+ listRequest(action, fixture, Integer.toString(max + 1), null).when().post("/").then()
+ .statusCode(400)
+ .body("ErrorResponse.Error.Code", equalTo("ValidationError"))
+ .body("ErrorResponse.Error.Message", equalTo("1 validation error detected: Value '"
+ + (max + 1) + "' at 'maxItems' failed to satisfy constraint: "
+ + "Member must have value less than or equal to " + max));
+
+ List<String> all = walkFrom(action, paginator, fixture, Integer.toString(max), null);
+ assertEquals(all.size(), new HashSet<>(all).size(), action + ": no item twice");
+
+ Listing first = listing(action, paginator, fixture, "1", null);
+ if (AT_MOST_ONE_ITEM.contains(action)) {
+ assertTrue(all.size() <= 1, action);
+ assertFalse(first.truncated(), action);
+ } else {
+ assertTrue(all.size() >= 2, action + ": the fixture lists two items, not " + all);
+ assertEquals(1, first.items().size(), action + ": MaxItems=1 is one item");
+ assertTrue(first.truncated(), action + ": a cut page is truncated");
+ assertNotNull(first.marker(), action + ": a cut page carries a Marker");
+ List<String> resumed = new ArrayList<>(first.items());
+ resumed.addAll(walkFrom(action, paginator, fixture, Integer.toString(max), first.marker()));
+ assertEquals(all, resumed, action + ": the Marker resumes after the item it ended on");
+
+ if (foreignMarker != null) {
+ refused(listRequest(action, fixture, null, foreignMarker), "InvalidInput");
+ }
+ foreignMarker = first.marker();
+ }
+
+ Listing unlimited = listing(action, paginator, fixture, null, null);
+ int pageSize = paginator.path("defaultItems").asInt();
+ assertEquals(all.subList(0, Math.min(pageSize, all.size())), unlimited.items(),
+ action + ": an omitted MaxItems is the documented " + pageSize);
+ assertEquals(all.size() > pageSize, unlimited.truncated(), action);
+
+ refused(listRequest(action, fixture, null, "not-a-marker"), "InvalidInput");
+ refused(listRequest(action, fixture, null, "1"), "InvalidInput");
+ } catch (AssertionError e) {
+ throw new AssertionError(action + ": " + e.getMessage(), e);
+ } finally {
+ fixture.cleanup().run();
+ }
+ }
+ }
+
+ private static String createUser(String name) {
+ return iam("CreateUser").formParam("UserName", name).when().post("/").then().statusCode(200)
+ .extract().path("CreateUserResponse.CreateUserResult.User.Arn");
+ }
+
+ private static void tag(String action, String idParam, String id) {
+ call(action, idParam, id, "Tags.member.1.Key", "pg-a", "Tags.member.1.Value", "1",
+ "Tags.member.2.Key", "pg-b", "Tags.member.2.Value", "2");
+ }
+
+ private static String createVirtualMfaDevice(String name) {
+ return iam("CreateVirtualMFADevice").formParam("VirtualMFADeviceName", name).when().post("/").then()
+ .statusCode(200).extract()
+ .path("CreateVirtualMFADeviceResponse.CreateVirtualMFADeviceResult.VirtualMFADevice.SerialNumber");
+ }
+
+ private static void enableMfaDevice(String userName, String deviceName) {
+ XmlPath created = iam("CreateVirtualMFADevice").formParam("VirtualMFADeviceName", deviceName)
+ .when().post("/").then().statusCode(200).extract().xmlPath();
+ String base = "CreateVirtualMFADeviceResponse.CreateVirtualMFADeviceResult.VirtualMFADevice.";
+ String seed = new String(Base64.getDecoder().decode(created.getString(base + "Base32StringSeed").trim()),
+ StandardCharsets.UTF_8);
+ long step = Totp.stepAt(Instant.now());
+ call("EnableMFADevice", "UserName", userName, "SerialNumber", created.getString(base + "SerialNumber"),
+ "AuthenticationCode1", Totp.codeAt(seed, step - 1), "AuthenticationCode2", Totp.codeAt(seed, step));
+ }
+
+ /** Two distinct keys, since a user may not upload one twice; RSA generation is slow, so once per run. */
+ private static final List<String> SSH_PUBLIC_KEYS = List.of(sshPublicKey(), sshPublicKey());
+
+ private static String sshPublicKey() {
+ try {
+ KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA");
+ generator.initialize(2048);
+ return SshPublicKeys.toOpenSsh((RSAPublicKey) generator.generateKeyPair().getPublic());
+ } catch (Exception e) {
+ throw new IllegalStateException(e);
+ }
+ }
+
+ private static String samlMetadata(String entityId) {
+ return "<md:EntityDescriptor xmlns:md=\"urn:oasis:names:tc:SAML:2.0:metadata\" entityID=\""
+ + entityId + "\"><md:IDPSSODescriptor><md:KeyDescriptor use=\"signing\">"
+ + "<ds:KeyInfo xmlns:ds=\"http://www.w3.org/2000/09/xmldsig#\"><ds:X509Data>"
+ + "<ds:X509Certificate>cGFnaW5n</ds:X509Certificate></ds:X509Data></ds:KeyInfo>"
+ + "</md:KeyDescriptor></md:IDPSSODescriptor></md:EntityDescriptor>";
+ }
+
+ /** One fixture per paginated operation, each listing at least two items where it can. */
+ private static Map<String, Supplier<Fixture>> fixtures() {
+ Map<String, Supplier<Fixture>> fixtures = new HashMap<>();
+ fixtures.put("GetAccountAuthorizationDetails", () -> {
+ String a = "pg-gaad-a-" + suffix();
+ String b = "pg-gaad-b-" + suffix();
+ createUser(a);
+ createUser(b);
+ return Fixture.of(() -> {
+ call("DeleteUser", "UserName", a);
+ call("DeleteUser", "UserName", b);
+ });
+ });
+ fixtures.put("GetGroup", () -> {
+ String group = "pg-getgroup-" + suffix();
+ List<String> users = List.of(group + "-u0", group + "-u1");
+ call("CreateGroup", "GroupName", group);
+ users.forEach(user -> {
+ createUser(user);
+ call("AddUserToGroup", "GroupName", group, "UserName", user);
+ });
+ return Fixture.of(() -> {
+ users.forEach(user -> {
+ call("RemoveUserFromGroup", "GroupName", group, "UserName", user);
+ call("DeleteUser", "UserName", user);
+ });
+ call("DeleteGroup", "GroupName", group);
+ }, "GroupName", group);
+ });
+ fixtures.put("ListAccessKeys", () -> {
+ String user = "pg-keys-" + suffix();
+ createUser(user);
+ List<String> keys = new ArrayList<>();
+ for (int i = 0; i < 2; i++) {
+ keys.add(iam("CreateAccessKey").formParam("UserName", user).when().post("/").then().statusCode(200)
+ .extract().path("CreateAccessKeyResponse.CreateAccessKeyResult.AccessKey.AccessKeyId"));
+ }
+ return Fixture.of(() -> {
+ keys.forEach(key -> call("DeleteAccessKey", "UserName", user, "AccessKeyId", key));
+ call("DeleteUser", "UserName", user);
+ }, "UserName", user);
+ });
+ fixtures.put("ListAccountAliases", () -> Fixture.of(() -> { }));
+ for (String[] holder : List.of(new String[]{"User", "UserName"}, new String[]{"Group", "GroupName"},
+ new String[]{"Role", "RoleName"})) {
+ Function<String, Runnable> createHolder = name -> {
+ Runnable create = switch (holder[0]) {
+ case "User" -> () -> createUser(name);
+ case "Group" -> () -> call("CreateGroup", "GroupName", name);
+ default -> () -> createRole(name, "/");
+ };
+ create.run();
+ return () -> call("Delete" + holder[0], holder[1], name);
+ };
+ fixtures.put("ListAttached" + holder[0] + "Policies", () -> {
+ String name = "pg-attached-" + suffix();
+ Runnable deleteHolder = createHolder.apply(name);
+ List<String> arns = List.of(createPolicy(name + "-0", "/"), createPolicy(name + "-1", "/"));
+ arns.forEach(arn -> call("Attach" + holder[0] + "Policy", holder[1], name, "PolicyArn", arn));
+ return Fixture.of(() -> {
+ arns.forEach(arn -> {
+ call("Detach" + holder[0] + "Policy", holder[1], name, "PolicyArn", arn);
+ deletePolicy(arn);
+ });
+ deleteHolder.run();
+ }, holder[1], name);
+ });
+ fixtures.put("List" + holder[0] + "Policies", () -> {
+ String name = "pg-inline-" + suffix();
+ Runnable deleteHolder = createHolder.apply(name);
+ List<String> policies = List.of("pg-inline-0", "pg-inline-1");
+ policies.forEach(policy -> call("Put" + holder[0] + "Policy", holder[1], name,
+ "PolicyName", policy, "PolicyDocument", POLICY_DOCUMENT));
+ return Fixture.of(() -> {
+ policies.forEach(policy -> call("Delete" + holder[0] + "Policy", holder[1], name,
+ "PolicyName", policy));
+ deleteHolder.run();
+ }, holder[1], name);
+ });
+ }
+ fixtures.put("ListEntitiesForPolicy", () -> {
+ String name = "pg-entities-" + suffix();
+ String arn = createPolicy(name, "/");
+ createUser(name);
+ createRole(name, "/");
+ call("AttachUserPolicy", "UserName", name, "PolicyArn", arn);
+ call("AttachRolePolicy", "RoleName", name, "PolicyArn", arn);
+ return Fixture.of(() -> {
+ call("DetachUserPolicy", "UserName", name, "PolicyArn", arn);
+ call("DetachRolePolicy", "RoleName", name, "PolicyArn", arn);
+ call("DeleteUser", "UserName", name);
+ deleteRole(name);
+ deletePolicy(arn);
+ }, "PolicyArn", arn);
+ });
+ for (String[] principal : List.of(new String[]{"Users", "User", "UserName"},
+ new String[]{"Groups", "Group", "GroupName"}, new String[]{"Roles", "Role", "RoleName"})) {
+ fixtures.put("List" + principal[0], () -> {
+ String tag = suffix();
+ String path = "/pg-" + principal[0].toLowerCase() + "-" + tag + "/";
+ List<String> names = List.of("pg-" + tag + "-0", "pg-" + tag + "-1");
+ for (String name : names) {
+ if (principal[1].equals("Role")) {
+ createRole(name, path);
+ } else {
+ call("Create" + principal[1], principal[2], name, "Path", path);
+ }
+ }
+ return Fixture.of(() -> names.forEach(name -> call("Delete" + principal[1], principal[2], name)),
+ "PathPrefix", path);
+ });
+ }
+ fixtures.put("ListGroupsForUser", () -> {
+ String user = "pg-memberships-" + suffix();
+ List<String> groups = List.of(user + "-g0", user + "-g1");
+ createUser(user);
+ groups.forEach(group -> {
+ call("CreateGroup", "GroupName", group);
+ call("AddUserToGroup", "GroupName", group, "UserName", user);
+ });
+ return Fixture.of(() -> {
+ groups.forEach(group -> {
+ call("RemoveUserFromGroup", "GroupName", group, "UserName", user);
+ call("DeleteGroup", "GroupName", group);
+ });
+ call("DeleteUser", "UserName", user);
+ }, "UserName", user);
+ });
+ fixtures.put("ListInstanceProfiles", () -> {
+ String tag = suffix();
+ String path = "/pg-profiles-" + tag + "/";
+ List<String> profiles = List.of("pg-profile-" + tag + "-0", "pg-profile-" + tag + "-1");
+ profiles.forEach(profile -> call("CreateInstanceProfile", "InstanceProfileName", profile, "Path", path));
+ return Fixture.of(() -> profiles.forEach(profile -> call("DeleteInstanceProfile",
+ "InstanceProfileName", profile)), "PathPrefix", path);
+ });
+ fixtures.put("ListInstanceProfilesForRole", () -> {
+ String role = "pg-profiled-" + suffix();
+ List<String> profiles = List.of(role + "-0", role + "-1");
+ createRole(role, "/");
+ profiles.forEach(profile -> {
+ call("CreateInstanceProfile", "InstanceProfileName", profile);
+ call("AddRoleToInstanceProfile", "InstanceProfileName", profile, "RoleName", role);
+ });
+ return Fixture.of(() -> {
+ profiles.forEach(profile -> {
+ call("RemoveRoleFromInstanceProfile", "InstanceProfileName", profile, "RoleName", role);
+ call("DeleteInstanceProfile", "InstanceProfileName", profile);
+ });
+ deleteRole(role);
+ }, "RoleName", role);
+ });
+ fixtures.put("ListMFADevices", () -> {
+ String user = "pg-mfa-" + suffix();
+ createUser(user);
+ enableMfaDevice(user, user + "-0");
+ enableMfaDevice(user, user + "-1");
+ return Fixture.of(() -> {
+ List<String> serials = iam("ListMFADevices").formParam("UserName", user).when().post("/").then()
+ .statusCode(200).extract().xmlPath()
+ .getList("ListMFADevicesResponse.ListMFADevicesResult.MFADevices.member.SerialNumber", String.class);
+ serials.forEach(serial -> {
+ call("DeactivateMFADevice", "UserName", user, "SerialNumber", serial);
+ call("DeleteVirtualMFADevice", "SerialNumber", serial);
+ });
+ call("DeleteUser", "UserName", user);
+ }, "UserName", user);
+ });
+ fixtures.put("ListVirtualMFADevices", () -> {
+ String name = "pg-virtual-" + suffix();
+ List<String> serials = List.of(createVirtualMfaDevice(name + "-0"), createVirtualMfaDevice(name + "-1"));
+ return Fixture.of(() -> serials.forEach(serial -> call("DeleteVirtualMFADevice", "SerialNumber", serial)));
+ });
+ fixtures.put("ListPolicies", () -> {
+ String tag = suffix();
+ String path = "/pg-policies-" + tag + "/";
+ List<String> arns = List.of(createPolicy("pg-" + tag + "-0", path), createPolicy("pg-" + tag + "-1", path));
+ return Fixture.of(() -> arns.forEach(IamListPaginationIntegrationTest::deletePolicy),
+ "Scope", "Local", "PathPrefix", path);
+ });
+ fixtures.put("ListPolicyVersions", () -> {
+ String arn = createPolicy("pg-versions-" + suffix(), "/");
+ call("CreatePolicyVersion", "PolicyArn", arn, "PolicyDocument", POLICY_DOCUMENT);
+ return Fixture.of(() -> {
+ call("DeletePolicyVersion", "PolicyArn", arn, "VersionId", "v2");
+ deletePolicy(arn);
+ }, "PolicyArn", arn);
+ });
+ fixtures.put("ListServerCertificates", () -> {
+ String tag = suffix();
+ String path = "/pg-certs-" + tag + "/";
+ List<String> names = List.of("pg-cert-" + tag + "-0", "pg-cert-" + tag + "-1");
+ names.forEach(name -> uploadServerCertificate(name, path));
+ return Fixture.of(() -> names.forEach(name -> call("DeleteServerCertificate", "ServerCertificateName", name)),
+ "PathPrefix", path);
+ });
+ fixtures.put("ListSigningCertificates", () -> {
+ String user = "pg-signing-" + suffix();
+ createUser(user);
+ List<String> ids = new ArrayList<>();
+ for (int i = 0; i < 2; i++) {
+ ids.add(iam("UploadSigningCertificate").formParam("UserName", user)
+ .formParam("CertificateBody", CERTIFICATES.generateSelfSignedCertificate(
+ "signing.test.local", List.of(), KeyAlgorithm.EC_prime256v1).certificatePem())
+ .when().post("/").then().statusCode(200).extract()
+ .path("UploadSigningCertificateResponse.UploadSigningCertificateResult.Certificate.CertificateId"));
+ }
+ return Fixture.of(() -> {
+ ids.forEach(id -> call("DeleteSigningCertificate", "UserName", user, "CertificateId", id));
+ call("DeleteUser", "UserName", user);
+ }, "UserName", user);
+ });
+ fixtures.put("ListSSHPublicKeys", () -> {
+ String user = "pg-ssh-" + suffix();
+ createUser(user);
+ List<String> ids = new ArrayList<>();
+ for (int i = 0; i < 2; i++) {
+ ids.add(iam("UploadSSHPublicKey").formParam("UserName", user).formParam("SSHPublicKeyBody", SSH_PUBLIC_KEYS.get(i))
+ .when().post("/").then().statusCode(200).extract()
+ .path("UploadSSHPublicKeyResponse.UploadSSHPublicKeyResult.SSHPublicKey.SSHPublicKeyId"));
+ }
+ return Fixture.of(() -> {
+ ids.forEach(id -> call("DeleteSSHPublicKey", "UserName", user, "SSHPublicKeyId", id));
+ call("DeleteUser", "UserName", user);
+ }, "UserName", user);
+ });
+ fixtures.put("SimulateCustomPolicy", () -> Fixture.of(() -> { },
+ "PolicyInputList.member.1", POLICY_DOCUMENT,
+ "ActionNames.member.1", "s3:GetObject", "ActionNames.member.2", "s3:PutObject"));
+ fixtures.put("SimulatePrincipalPolicy", () -> {
+ String user = "pg-simulate-" + suffix();
+ String arn = createUser(user);
+ return Fixture.of(() -> call("DeleteUser", "UserName", user), "PolicySourceArn", arn,
+ "ActionNames.member.1", "s3:GetObject", "ActionNames.member.2", "s3:PutObject");
+ });
+ fixtures.put("ListUserTags", () -> {
+ String user = "pg-usertags-" + suffix();
+ createUser(user);
+ tag("TagUser", "UserName", user);
+ return Fixture.of(() -> call("DeleteUser", "UserName", user), "UserName", user);
+ });
+ fixtures.put("ListRoleTags", () -> {
+ String role = "pg-roletags-" + suffix();
+ createRole(role, "/");
+ tag("TagRole", "RoleName", role);
+ return Fixture.of(() -> deleteRole(role), "RoleName", role);
+ });
+ fixtures.put("ListPolicyTags", () -> {
+ String arn = createPolicy("pg-policytags-" + suffix(), "/");
+ tag("TagPolicy", "PolicyArn", arn);
+ return Fixture.of(() -> deletePolicy(arn), "PolicyArn", arn);
+ });
+ fixtures.put("ListInstanceProfileTags", () -> {
+ String profile = "pg-profiletags-" + suffix();
+ call("CreateInstanceProfile", "InstanceProfileName", profile);
+ tag("TagInstanceProfile", "InstanceProfileName", profile);
+ return Fixture.of(() -> call("DeleteInstanceProfile", "InstanceProfileName", profile),
+ "InstanceProfileName", profile);
+ });
+ fixtures.put("ListMFADeviceTags", () -> {
+ String serial = createVirtualMfaDevice("pg-mfatags-" + suffix());
+ tag("TagMFADevice", "SerialNumber", serial);
+ return Fixture.of(() -> call("DeleteVirtualMFADevice", "SerialNumber", serial), "SerialNumber", serial);
+ });
+ fixtures.put("ListOpenIDConnectProviderTags", () -> {
+ String arn = iam("CreateOpenIDConnectProvider").formParam("Url", "https://pg-" + suffix() + ".example.test")
+ .formParam("ThumbprintList.member.1", THUMBPRINT)
+ .when().post("/").then().statusCode(200).extract()
+ .path("CreateOpenIDConnectProviderResponse.CreateOpenIDConnectProviderResult.OpenIDConnectProviderArn");
+ tag("TagOpenIDConnectProvider", "OpenIDConnectProviderArn", arn);
+ return Fixture.of(() -> call("DeleteOpenIDConnectProvider", "OpenIDConnectProviderArn", arn),
+ "OpenIDConnectProviderArn", arn);
+ });
+ fixtures.put("ListSAMLProviderTags", () -> {
+ String name = "pg-saml-" + suffix();
+ String arn = iam("CreateSAMLProvider").formParam("Name", name)
+ .formParam("SAMLMetadataDocument", samlMetadata("https://idp.example.test/" + name))
+ .when().post("/").then().statusCode(200).extract()
+ .path("CreateSAMLProviderResponse.CreateSAMLProviderResult.SAMLProviderArn");
+ tag("TagSAMLProvider", "SAMLProviderArn", arn);
+ return Fixture.of(() -> call("DeleteSAMLProvider", "SAMLProviderArn", arn), "SAMLProviderArn", arn);
+ });
+ fixtures.put("ListServerCertificateTags", () -> {
+ String name = "pg-certtags-" + suffix();
+ uploadServerCertificate(name, "/");
+ tag("TagServerCertificate", "ServerCertificateName", name);
+ return Fixture.of(() -> call("DeleteServerCertificate", "ServerCertificateName", name),
+ "ServerCertificateName", name);
+ });
+ return fixtures;
+ }
+
+ private static void uploadServerCertificate(String name, String path) {
+ CertificateGenerator.GeneratedCertificate pair = CERTIFICATES.generateSelfSignedCertificate(
+ "certs.test.local", List.of(), KeyAlgorithm.EC_prime256v1);
+ call("UploadServerCertificate", "ServerCertificateName", name, "Path", path,
+ "CertificateBody", pair.certificatePem(), "PrivateKey", pair.privateKeyPem());
+ }
}
diff --git a/src/test/java/io/github/hectorvent/floci/services/iam/ServiceLastAccessedIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/iam/ServiceLastAccessedIntegrationTest.java
index fd67ddeae5..cc0841bace 100644
--- a/src/test/java/io/github/hectorvent/floci/services/iam/ServiceLastAccessedIntegrationTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/iam/ServiceLastAccessedIntegrationTest.java
@@ -794,7 +794,7 @@ class ServiceLastAccessedIntegrationTest {
.body(containsString("ValidationError"));
}
- /** A malformed request stays malformed even when the marker sits past the end of the list. */
+ /** MaxItems is held to its range before the marker is read, as AWS checks a request's shape first. */
@Test
void getServiceLastAccessedDetailsRejectsMaxItemsBelowOneEvenPastTheEnd() {
String arn = createUser("laa-maxitems-" + suffix());
@@ -821,19 +821,32 @@ class ServiceLastAccessedIntegrationTest {
.body("ErrorResponse.Error.Code", equalTo("InvalidInput"));
}
- /** ListPoliciesGrantingServiceAccess models a Marker, so it walks the namespace entries too. */
+ /**
+ * ListPoliciesGrantingServiceAccess models a Marker but no MaxItems, so its list is never cut
+ * and it never issues a marker: every namespace comes back in one page, and a marker, which can
+ * only be one it did not issue, is refused rather than read as an offset.
+ */
@Test
- void listPoliciesGrantingServiceAccessHonoursItsMarker() {
+ void listPoliciesGrantingServiceAccessIsOnePageAndRefusesAMarkerItNeverIssued() {
String arn = createUser("laa-list-marker-" + suffix());
iam("ListPoliciesGrantingServiceAccess").formParam("Arn", arn)
.formParam("ServiceNamespaces.member.1", "s3")
.formParam("ServiceNamespaces.member.2", "dynamodb")
- .formParam("Marker", "1")
.when().post("/").then()
.statusCode(200)
.body(containsString("<ServiceNamespace>dynamodb</ServiceNamespace>"))
- .body(not(containsString("<ServiceNamespace>s3</ServiceNamespace>")));
+ .body(containsString("<ServiceNamespace>s3</ServiceNamespace>"))
+ .body("ListPoliciesGrantingServiceAccessResponse.ListPoliciesGrantingServiceAccessResult.IsTruncated",
+ equalTo("false"));
+
+ iam("ListPoliciesGrantingServiceAccess").formParam("Arn", arn)
+ .formParam("ServiceNamespaces.member.1", "s3")
+ .formParam("ServiceNamespaces.member.2", "dynamodb")
+ .formParam("Marker", "1")
+ .when().post("/").then()
+ .statusCode(400)
+ .body("ErrorResponse.Error.Code", equalTo("InvalidInput"));
}
@Test
@@ -881,9 +894,14 @@ class ServiceLastAccessedIntegrationTest {
+ "\"Action\":[\"s3:GetObject\",\"dynamodb:GetItem\"],\"Resource\":\"*\"}]}")
.when().post("/").then().statusCode(200);
+ String jobId = generateJobFor(arn);
+ String marker = iam("GetServiceLastAccessedDetails").formParam("JobId", jobId).formParam("MaxItems", "1")
+ .when().post("/").then().statusCode(200)
+ .extract().path("GetServiceLastAccessedDetailsResponse.GetServiceLastAccessedDetailsResult.Marker");
+
iam("GetServiceLastAccessedDetails")
- .formParam("JobId", generateJobFor(arn))
- .formParam("Marker", "1")
+ .formParam("JobId", jobId)
+ .formParam("Marker", marker)
.formParam("MaxItems", "1000")
.when().post("/").then()
.statusCode(200)
diff --git a/tools/aws/regen_iam_paginators.py b/tools/aws/regen_iam_paginators.py
new file mode 100644
index 0000000000..b46c80ad05
--- /dev/null
+++ b/tools/aws/regen_iam_paginators.py
@@ -0,0 +1,154 @@
+#!/usr/bin/env python3
+"""Regenerate src/main/resources/aws/iam-paginators.json from botocore's IAM model.
+
+IAM pages its lists with a `Marker` request member and a `MaxItems` limit, and answers with
+`IsTruncated` and the `Marker` that continues the list. `IamQueryHandler` pages every such list
+through one path, which reads from this file what each operation pages by: the request member that
+resumes it, the member that limits it and that limit's default, the response members that say
+whether it was truncated and how to continue, and the lists it pages.
+
+Every IAM operation whose request models `Marker` is kept. For the operations botocore pages
+(`paginators-1.json`, 34 of them) the paginator names the tokens, the limit key and the result
+keys. The rest page on the wire without a paginator (the Access Advisor and Organizations reports,
+ListServiceSpecificCredentials, ListDelegationRequests, ListPoliciesGrantingServiceAccess), so
+their members are read from the request and response shapes and they carry no result keys:
+`"paginator": false` says so. ListPoliciesGrantingServiceAccess models no `MaxItems` at all, so
+its `limitKey` is null.
+
+No bound is kept here. `maxItemsType` (1 to 1000) and `markerType` (1 to 320 characters) are
+constraints of the request, so `regen_iam_shapes.py` vendors them with the rest of each paged
+operation's request and `IamRequestShapes` holds a request to them before it runs. The default page
+size is not a constraint the model encodes but a sentence in the limit member's documentation ("the
+number of items defaults to 100"), so it is read from there as `defaultItems`, null where the
+documentation states none.
+
+The model is botocore's `iam/2010-05-08/` (Apache-2.0, https://github.com/boto/botocore), located,
+in order, at `--botocore-data`, the `local/aws/botocore` checkout, then the installed `botocore`
+package, which `requirements.txt` pins so CI regenerates the same bytes.
+
+Run from anywhere in the repo:
+ python3 tools/aws/regen_iam_paginators.py # rewrite the vendored file in place
+ python3 tools/aws/regen_iam_paginators.py --check # exit 1 when the vendored file is stale
+"""
+from __future__ import annotations
+
+import argparse
+import json
+import re
+import sys
+from pathlib import Path
+
+from regen_partitions import resolve_botocore_data, strip_source
+from regen_query_services import load_model
+
+REPO_ROOT = Path(__file__).resolve().parents[2]
+OUTPUT = REPO_ROOT / "src/main/resources/aws/iam-paginators.json"
+MODEL_DIR = ("iam", "2010-05-08")
+INPUT_TOKEN = "Marker"
+
+DEFAULT_RE = re.compile(r"defaults to (\d+)")
+
+
+def load_paginators(directory: Path) -> dict:
+ path = directory / "paginators-1.json"
+ if not path.exists():
+ raise SystemExit(f"error: {path} not found")
+ return json.loads(path.read_text(encoding="utf-8"))["pagination"]
+
+
+def _as_list(value) -> list[str]:
+ return [value] if isinstance(value, str) else list(value)
+
+
+def operations_from(model: dict, paginators: dict) -> dict[str, dict]:
+ """Every operation whose request models Marker, and what it pages by."""
+ shapes = model["shapes"]
+ found: dict[str, dict] = {}
+ for name in sorted(model["operations"]):
+ operation = model["operations"][name]
+ request = shapes[operation["input"]["shape"]]["members"] if "input" in operation else {}
+ if INPUT_TOKEN not in request:
+ if name in paginators:
+ raise ValueError(f"{name} is paginated but its request has no {INPUT_TOKEN}")
+ continue
+ response = shapes[operation["output"]["shape"]]["members"] if "output" in operation else {}
+ paginator = paginators.get(name)
+ if paginator is not None:
+ input_token = paginator["input_token"]
+ output_token = paginator["output_token"]
+ limit_key = paginator.get("limit_key")
+ more_results = paginator.get("more_results")
+ result_keys = _as_list(paginator["result_key"])
+ else:
+ input_token = INPUT_TOKEN
+ output_token = INPUT_TOKEN if INPUT_TOKEN in response else None
+ limit_key = "MaxItems" if "MaxItems" in request else None
+ # ListDelegationRequests spells it isTruncated, so match without regard to case.
+ more_results = next((m for m in response if m.lower() == "istruncated"), None)
+ result_keys = []
+ problems = [f"request has no {key}" for key in (input_token, limit_key)
+ if key is not None and key not in request]
+ problems += [f"response has no {key}" for key in (output_token, more_results, *result_keys)
+ if key is not None and key not in response]
+ if output_token is None or more_results is None:
+ problems.append("response models no continuation")
+ if problems:
+ raise ValueError(f"{name}: " + "; ".join(problems))
+ entry = {
+ "paginator": paginator is not None,
+ "inputToken": input_token,
+ "outputToken": output_token,
+ "limitKey": limit_key,
+ "moreResults": more_results,
+ "resultKeys": result_keys,
+ }
+ if limit_key is not None:
+ documented = DEFAULT_RE.search(request[limit_key].get("documentation", ""))
+ entry["defaultItems"] = int(documented.group(1)) if documented else None
+ found[name] = entry
+ missing = sorted(set(paginators) - set(found))
+ if missing:
+ raise ValueError(f"paginated operations missing from the model: {', '.join(missing)}")
+ return found
+
+
+def build(model: dict, paginators: dict, provenance: str) -> dict:
+ return {
+ "_source": {
+ "generator": "tools/aws/regen_iam_paginators.py",
+ "botocore": provenance,
+ },
+ "operations": operations_from(model, paginators),
+ }
+
+
+def render(doc: dict) -> str:
+ return json.dumps(doc, indent=2, sort_keys=False) + "\n"
+
+
+def main(argv: list[str] | None = None) -> int:
+ parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
+ parser.add_argument("--check", action="store_true", help="exit 1 when the vendored file differs from a fresh generation")
+ parser.add_argument("--botocore-data", type=Path, help="botocore data directory")
+ parser.add_argument("--output", type=Path, default=OUTPUT, help=argparse.SUPPRESS)
+ args = parser.parse_args(argv)
+
+ data, provenance = resolve_botocore_data(args.botocore_data)
+ directory = data.joinpath(*MODEL_DIR)
+ fresh = render(build(load_model(directory), load_paginators(directory), provenance))
+
+ if args.check:
+ current = args.output.read_text(encoding="utf-8") if args.output.exists() else ""
+ if strip_source(current) != strip_source(fresh):
+ print(f"{args.output} is stale (generated from {provenance}).", file=sys.stderr)
+ return 1
+ return 0
+
+ args.output.write_text(fresh, encoding="utf-8")
+ shown = args.output.relative_to(REPO_ROOT) if args.output.is_relative_to(REPO_ROOT) else args.output
+ print(f"wrote {shown} from {provenance}")
+ return 0
+
+
+if __name__ == "__main__":
+ sys.exit(main())
diff --git a/tools/aws/regen_iam_shapes.py b/tools/aws/regen_iam_shapes.py
index 56f0a93258..df8770e26d 100644
--- a/tools/aws/regen_iam_shapes.py
+++ b/tools/aws/regen_iam_shapes.py
@@ -35,17 +35,55 @@ GENERATOR = "tools/aws/regen_iam_shapes.py"
# `GetAccountAuthorizationDetails` is the first operation read through the list walk. Its three
# members are declared and none of them is read at all today: `Filter` is a list of an enum,
# `MaxItems` a range and `Marker` a length and a pattern.
+#
+# The list operations follow it: every operation `aws/iam-paginators.json` pages, so `MaxItems`
+# (1 to 1000) and `Marker` (1 to 320 characters) are held to the model here and nowhere else.
OPERATIONS = (
"AttachGroupPolicy", "AttachRolePolicy", "AttachUserPolicy",
"DetachGroupPolicy", "DetachRolePolicy", "DetachUserPolicy",
"GetPolicy", "DeletePolicy",
"CreatePolicyVersion", "GetPolicyVersion", "DeletePolicyVersion", "SetDefaultPolicyVersion",
"GetAccountAuthorizationDetails",
+ "GetGroup",
+ "ListAccessKeys", "ListAccountAliases", "ListAttachedGroupPolicies", "ListAttachedRolePolicies",
+ "ListAttachedUserPolicies", "ListDelegationRequests", "ListEntitiesForPolicy",
+ "ListGroupPolicies", "ListGroups", "ListGroupsForUser", "ListInstanceProfileTags",
+ "ListInstanceProfiles", "ListInstanceProfilesForRole", "ListMFADeviceTags", "ListMFADevices",
+ "ListOpenIDConnectProviderTags", "ListPolicies",
+ "ListPolicyTags", "ListPolicyVersions", "ListRolePolicies", "ListRoleTags", "ListRoles",
+ "ListSAMLProviderTags", "ListSSHPublicKeys", "ListServerCertificateTags",
+ "ListServerCertificates", "ListServiceSpecificCredentials", "ListSigningCertificates",
+ "ListUserPolicies", "ListUserTags", "ListUsers", "ListVirtualMFADevices",
+)
+
+# Paged operations vendored with their paging members alone, so `MaxItems` and `Marker` are still
+# the model's while the rest of the request keeps the reading it has today.
+PAGING_MEMBERS = ("Marker", "MaxItems")
+PAGING_ONLY = (
+ # `JobId` is answered by hand as one fixed-length constraint ("length equal to 36"), which the
+ # walk would reword as a minimum; `SortKey` is held to its enum by hand too.
+ "GetOrganizationsAccessReport", "GetServiceLastAccessedDetails",
+ "GetServiceLastAccessedDetailsWithEntities",
+ # An empty `ServiceNamespaces` is answered by hand with `InvalidInput`, not the walk's null.
+ "ListPoliciesGrantingServiceAccess",
+ # `ContextEntries` nests a list inside a list of structures, which the walk refuses.
+ "SimulateCustomPolicy", "SimulatePrincipalPolicy",
)
+def paging_only(model: dict) -> dict:
+ """`model` with each `PAGING_ONLY` request reduced to its paging members."""
+ shapes = dict(model["shapes"])
+ for operation in PAGING_ONLY:
+ name = model["operations"][operation]["input"]["shape"]
+ request = shapes[name]
+ shapes[name] = {"type": request["type"],
+ "members": {k: v for k, v in request["members"].items() if k in PAGING_MEMBERS}}
+ return {**model, "shapes": shapes}
+
+
def build(model: dict, provenance: str) -> dict:
- return build_constraints(model, OPERATIONS, provenance, GENERATOR)
+ return build_constraints(paging_only(model), OPERATIONS + PAGING_ONLY, provenance, GENERATOR)
def render(doc: dict) -> str:
diff --git a/tools/aws/test_regen_iam_paginators.py b/tools/aws/test_regen_iam_paginators.py
new file mode 100644
index 0000000000..2de2c3a765
--- /dev/null
+++ b/tools/aws/test_regen_iam_paginators.py
@@ -0,0 +1,128 @@
+"""Tests for regen_iam_paginators.
+
+Run with: pytest tools/aws -q (or: make aws-data-test)
+"""
+from __future__ import annotations
+
+import json
+
+import pytest
+
+import regen_iam_paginators as r
+
+MAX_ITEMS_DOC = "<p>If you do not include this parameter, the number of items defaults to 100.</p>"
+
+
+def model(**operations: tuple[dict, dict]) -> dict:
+ """A model whose operations map to (request members, response members), each member naming
+ its shape."""
+ shapes = {
+ "maxItemsType": {"type": "integer", "min": 1, "max": 1000},
+ "markerType": {"type": "string", "min": 1, "max": 320, "pattern": "[\\u0020-\\u00FF]+"},
+ "booleanType": {"type": "boolean"},
+ "listType": {"type": "list"},
+ }
+ ops = {}
+ for name, (request, response) in operations.items():
+ shapes[f"{name}Request"] = {"type": "structure", "members": request}
+ shapes[f"{name}Response"] = {"type": "structure", "members": response}
+ ops[name] = {"input": {"shape": f"{name}Request"}, "output": {"shape": f"{name}Response"}}
+ return {"operations": ops, "shapes": shapes}
+
+
+PAGED_REQUEST = {"Marker": {"shape": "markerType"},
+ "MaxItems": {"shape": "maxItemsType", "documentation": MAX_ITEMS_DOC}}
+
+
+def paged_response(*lists: str) -> dict:
+ return {**{key: {"shape": "listType"} for key in lists},
+ "IsTruncated": {"shape": "booleanType"}, "Marker": {"shape": "markerType"}}
+
+
+def paginator(*result_keys: str) -> dict:
+ return {"input_token": "Marker", "output_token": "Marker", "limit_key": "MaxItems",
+ "more_results": "IsTruncated",
+ "result_key": result_keys[0] if len(result_keys) == 1 else list(result_keys)}
+
+
+def test_a_paginator_names_its_tokens_lists_and_default_but_no_bounds():
+ found = r.operations_from(model(ListRoles=(PAGED_REQUEST, paged_response("Roles"))),
+ {"ListRoles": paginator("Roles")})
+
+ assert found == {"ListRoles": {
+ "paginator": True, "inputToken": "Marker", "outputToken": "Marker", "limitKey": "MaxItems",
+ "moreResults": "IsTruncated", "resultKeys": ["Roles"], "defaultItems": 100,
+ }}
+
+
+def test_several_result_keys_are_kept_in_the_paginators_order():
+ found = r.operations_from(
+ model(ListEntitiesForPolicy=(PAGED_REQUEST, paged_response("PolicyGroups", "PolicyUsers"))),
+ {"ListEntitiesForPolicy": paginator("PolicyGroups", "PolicyUsers")})
+
+ assert found["ListEntitiesForPolicy"]["resultKeys"] == ["PolicyGroups", "PolicyUsers"]
+
+
+def test_an_operation_paged_without_a_paginator_is_read_from_its_shapes():
+ # ListDelegationRequests spells the flag isTruncated, and the table keeps the model's spelling.
+ response = {"DelegationRequests": {"shape": "listType"}, "Marker": {"shape": "markerType"},
+ "isTruncated": {"shape": "booleanType"}}
+ found = r.operations_from(model(ListDelegationRequests=(PAGED_REQUEST, response)), {})
+
+ entry = found["ListDelegationRequests"]
+ assert entry["paginator"] is False
+ assert entry["moreResults"] == "isTruncated"
+ assert entry["resultKeys"] == []
+
+
+def test_a_request_without_max_items_has_no_limit():
+ found = r.operations_from(model(ListPoliciesGrantingServiceAccess=(
+ {"Marker": {"shape": "markerType"}}, paged_response("PoliciesGrantingServiceAccess"))), {})
+
+ assert found["ListPoliciesGrantingServiceAccess"]["limitKey"] is None
+ assert "defaultItems" not in found["ListPoliciesGrantingServiceAccess"]
+
+
+def test_an_undocumented_default_is_null_rather_than_invented():
+ request = {"Marker": {"shape": "markerType"}, "MaxItems": {"shape": "maxItemsType"}}
+ found = r.operations_from(model(ListServiceSpecificCredentials=(request, paged_response("C"))), {})
+
+ assert found["ListServiceSpecificCredentials"]["defaultItems"] is None
+
+
+def test_an_operation_without_a_marker_is_left_out():
+ assert r.operations_from(model(GetUser=({}, {"User": {"shape": "listType"}})), {}) == {}
+
+
+def test_a_paginator_naming_a_member_the_shapes_lack_is_refused():
+ with pytest.raises(ValueError, match="response has no Users"):
+ r.operations_from(model(ListRoles=(PAGED_REQUEST, paged_response("Roles"))),
+ {"ListRoles": paginator("Users")})
+
+
+def test_a_paginator_for_an_operation_without_a_marker_is_refused():
+ with pytest.raises(ValueError, match="no Marker"):
+ r.operations_from(model(ListRoles=({}, paged_response("Roles"))), {"ListRoles": paginator("Roles")})
+
+
+def test_check_ignores_the_provenance_and_catches_a_changed_entry(tmp_path):
+ directory = tmp_path.joinpath("data", *r.MODEL_DIR)
+ directory.mkdir(parents=True)
+ (directory / "service-2.json").write_text(
+ json.dumps(model(ListRoles=(PAGED_REQUEST, paged_response("Roles")))), encoding="utf-8")
+ (directory / "paginators-1.json").write_text(
+ json.dumps({"pagination": {"ListRoles": paginator("Roles")}}), encoding="utf-8")
+ data = str(tmp_path / "data")
+ output = tmp_path / "iam-paginators.json"
+
+ assert r.main(["--botocore-data", data, "--output", str(output)]) == 0
+ assert r.main(["--check", "--botocore-data", data, "--output", str(output)]) == 0
+
+ stale = json.loads(output.read_text(encoding="utf-8"))
+ stale["_source"]["botocore"] = "another label"
+ output.write_text(json.dumps(stale), encoding="utf-8")
+ assert r.main(["--check", "--botocore-data", data, "--output", str(output)]) == 0
+
+ stale["operations"]["ListRoles"]["defaultItems"] = 10
+ output.write_text(json.dumps(stale), encoding="utf-8")
+ assert r.main(["--check", "--botocore-data", data, "--output", str(output)]) == 1
diff --git a/tools/aws/test_regen_iam_shapes.py b/tools/aws/test_regen_iam_shapes.py
index 79fe9d406a..059b5aa377 100644
--- a/tools/aws/test_regen_iam_shapes.py
+++ b/tools/aws/test_regen_iam_shapes.py
@@ -30,6 +30,7 @@ MODEL = {
def test_keeps_only_the_listed_operations_with_their_constraints(monkeypatch):
monkeypatch.setattr(r, "OPERATIONS", ("GetPolicy",))
+ monkeypatch.setattr(r, "PAGING_ONLY", ())
doc = r.build(MODEL, "botocore test")
@@ -44,6 +45,7 @@ def test_keeps_only_the_listed_operations_with_their_constraints(monkeypatch):
def test_a_misspelled_operation_is_refused_rather_than_skipped(monkeypatch):
monkeypatch.setattr(r, "OPERATIONS", ("GetPolciy",))
+ monkeypatch.setattr(r, "PAGING_ONLY", ())
with pytest.raises(KeyError):
r.build(MODEL, "botocore test")
@@ -52,13 +54,45 @@ def test_a_misspelled_operation_is_refused_rather_than_skipped(monkeypatch):
def test_the_vendored_file_carries_every_listed_operation():
doc = json.loads(r.OUTPUT.read_text(encoding="utf-8"))
- assert sorted(doc["operations"]) == sorted(r.OPERATIONS)
+ assert sorted(doc["operations"]) == sorted(r.OPERATIONS + r.PAGING_ONLY)
for operation, shape in doc["operations"].items():
assert shape in doc["shapes"], operation
+def test_every_paged_operation_is_held_to_the_model():
+ # IamQueryHandler checks no MaxItems or Marker bound of its own, so an operation the paginator
+ # table pages and this wave leaves out would take any limit and any marker length.
+ paged = json.loads((r.OUTPUT.parent / "iam-paginators.json").read_text(encoding="utf-8"))["operations"]
+
+ assert sorted(set(paged) - set(r.OPERATIONS + r.PAGING_ONLY)) == []
+
+
+def test_a_paging_only_operation_keeps_its_paging_members_alone(monkeypatch):
+ model = {
+ "operations": {"ListThings": {"input": {"shape": "ListThingsRequest"}}},
+ "shapes": {
+ "ListThingsRequest": {"type": "structure", "required": ["JobId"], "members": {
+ "JobId": {"shape": "jobIDType"}, "Marker": {"shape": "markerType"},
+ "MaxItems": {"shape": "maxItemsType"},
+ }},
+ "jobIDType": {"type": "string", "min": 36, "max": 36},
+ "markerType": {"type": "string", "min": 1, "max": 320},
+ "maxItemsType": {"type": "integer", "min": 1, "max": 1000},
+ },
+ }
+ monkeypatch.setattr(r, "OPERATIONS", ())
+ monkeypatch.setattr(r, "PAGING_ONLY", ("ListThings",))
+
+ doc = r.build(model, "botocore test")
+
+ assert doc["shapes"]["ListThingsRequest"] == {
+ "type": "structure", "members": {"Marker": "markerType", "MaxItems": "maxItemsType"}}
+ assert "jobIDType" not in doc["shapes"]
+
+
def test_check_ignores_provenance(tmp_path, monkeypatch):
monkeypatch.setattr(r, "OPERATIONS", ("GetPolicy",))
+ monkeypatch.setattr(r, "PAGING_ONLY", ())
output = tmp_path / "shapes.json"
output.write_text(r.render(r.build(MODEL, "botocore 0.0.1 (local/aws/botocore)")), encoding="utf-8")
monkeypatch.setattr(r, "resolve_botocore_data", lambda explicit: (tmp_path, "--botocore-data /elsewhere"))
@@ -69,6 +103,7 @@ def test_check_ignores_provenance(tmp_path, monkeypatch):
def test_check_reports_a_changed_constraint(tmp_path, monkeypatch):
monkeypatch.setattr(r, "OPERATIONS", ("GetPolicy",))
+ monkeypatch.setattr(r, "PAGING_ONLY", ())
output = tmp_path / "shapes.json"
changed = {**MODEL, "shapes": {**MODEL["shapes"], "arnType": {"type": "string", "min": 1, "max": 2048}}}
output.write_text(r.render(r.build(changed, "botocore test")), encoding="utf-8")
@@ -80,6 +115,7 @@ def test_check_reports_a_changed_constraint(tmp_path, monkeypatch):
def test_output_is_stable(monkeypatch):
monkeypatch.setattr(r, "OPERATIONS", ("GetPolicy", "ListPolicies"))
+ monkeypatch.setattr(r, "PAGING_ONLY", ())
first = r.render(r.build(MODEL, "botocore test"))
second = r.render(r.build(MODEL, "botocore test"))