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

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

ListUsers, ListGroups, ListAttached{User,Group,Role}Policies and
List{User,Group,Role}Policies read neither MaxItems nor Marker and always
answered IsTruncated=false with every entry. They now go through the same
paginate helper ListRoles and ListPolicies use: an omitted MaxItems returns
100 items as the API reference documents, a MaxItems outside 1 to 1000 is a
ValidationError, a Marker the handler did not issue is InvalidInput, and a
Marker appears only on a truncated page.

Users, groups and inline policy names are listed in name order and attached
policies in ARN order, so a Marker keeps pointing at the same place between
calls even when the entry it names is removed in between.

* fix(iam): resume the newly paged IAM lists only from their own markers

ListUsers, ListGroups and the attached and inline policy lists read a
Marker they could not verify as a list offset, so Marker=1 silently
skipped the first entry, and a marker issued for one role's list resumed
another role's list after the same policy. These lists have only ever
issued signed markers, so their cursor now carries the action and, for a
per-principal list, the principal, and any other marker is InvalidInput.
ListRoles, ListPolicies and the other readers keep their existing marker
handling.

Also covers the omitted-MaxItems default on ListUsers and ListGroups with
101 entries: 100 on the first page, IsTruncated and a Marker that fetches
the last one.

* fix(iam): bind the newly paged IAM lists' markers to the request account

IAM entities are stored per account, but the marker cursor named only the
action and principal, so a marker issued in one account resumed the same
listing in another account after the same name and skipped its earlier
entries. The cursor now carries the account the request reads from, and a
marker from another account is InvalidInput.

* feat(iam): generate the IAM paginator table from botocore

tools/aws/regen_iam_paginators.py writes src/main/resources/aws/iam-paginators.json
from botocore's iam/2010-05-08 model, as the other tools/aws generators do: every
operation whose request models Marker, with its input and output token, limit
key, truncation flag and result keys, the MaxItems bounds of maxItemsType
(1 to 1000), the default page size the limit's documentation states ("defaults
to 100"), and markerType's bounds.

The 34 operations botocore's paginators-1.json lists take their tokens and
result keys from it. The six that model Marker without a paginator
(GetServiceLastAccessedDetails, GetServiceLastAccessedDetailsWithEntities,
GetOrganizationsAccessReport, ListServiceSpecificCredentials,
ListDelegationRequests, ListPoliciesGrantingServiceAccess) are read from
their request and response shapes and marked paginator: false.
ListServiceSpecificCredentials documents no default and
ListPoliciesGrantingServiceAccess models no MaxItems; the table records
both as such rather than inventing a value.

make aws-data-sync regenerates it and make aws-data-check fails when it is
stale against the pinned botocore.

* fix(iam): page every IAM list through one path driven by the paginator table

IamQueryHandler paged eight lists by hand through paginateScoped, a few more
through paginate, and left the rest (the tag readers, ListAccessKeys,
ListInstanceProfiles, ListPolicyVersions, GetGroup, ListGroupsForUser,
ListEntitiesForPolicy, GetAccountAuthorizationDetails, the simulations and
others) ignoring MaxItems and Marker with IsTruncated=false. Every operation
the generated aws/iam-paginators.json lists now pages through one paginate
path that reads its entry: the limit's bounds and default, the members that
resume and continue it, and the result keys pagedList and pagedLists write
under. paginateScoped, paginateByMarker and the hardcoded 100/1000 are gone.
ListEntitiesForPolicy and GetAccountAuthorizationDetails page their several
lists as one, in the paginator's order.

Marker semantics, chosen deliberately: a Marker is opaque and resumes only the
listing that issued it, on every paged operation. AWS documents it as "the
value of the Marker element in the response that you received", so a value
Floci did not issue, a bare number included, is InvalidInput; ListRoles,
ListPolicies and the report readers no longer read one as an index. The
marker names the last item of its page, so a deletion or creation ahead of
it skips nothing and repeats nothing, and it is signed (not prefixed) over
the account, the operation and every request member except Marker and
MaxItems, so a marker from another operation, principal, filter or account
is refused while the page size may change between calls. Signing the scope
instead of carrying it keeps issued markers short. markerType's 320-character
bound is not checked separately: every other value is refused as unissued,
and a long ARN key could otherwise push an issued marker past it.

MaxItems is now checked before Marker, as a malformed request is rejected
before anything is read from it. An omitted MaxItems is the documented 100;
ListServiceSpecificCredentials, which documents no default, returns its whole
list.

IamListPaginationIntegrationTest.everyPaginatedOperationHonoursMaxItemsAndMarker
iterates the table's 34 paginated operations, each with a fixture listing two
items, and checks the MaxItems bounds, a one-item page, resumption without
loss or repetition, the default page, and refusal of an unissued, bare-index
or other operation's marker. Its fixture map must name exactly the table's
operations, so one AWS starts paging later fails until it has one.
ListAccountAliases can hold one alias, so it is checked for everything but a
cut page. The tests the table test subsumes are removed; the ordering, anchor,
cross-listing and cross-account tests stay. Two ServiceLastAccessed tests
that walked by bare index now use issued markers.

* fix(iam): hold paged requests to the model through IamRequestShapes

MaxItems and Marker are request constraints, and main now checks a
request against the model before it runs. Every operation the paginator
table pages joins that wave in regen_iam_shapes.py, and the bounds leave
iam-paginators.json (which keeps only defaultItems, the documented page
size) and limit(), which now only parses the number and applies the
default. A pytest pins that every operation the paginator table carries
is in the wave, so a list AWS starts paging later cannot slip past the
bounds.

Six paged operations join with Marker and MaxItems alone: the three
report readers, whose JobId is answered by hand as "length equal to 36"
and whose SortKey enum is checked by hand; ListPoliciesGrantingServiceAccess,
whose empty ServiceNamespaces is answered InvalidInput; and the two
Simulate operations, whose ContextEntries nest a list inside a list of
structures, which the walk refuses. Vendoring their whole request would
reword answers main already settled; vendoring nothing would leave their
paging unbounded (SimulateCustomPolicy with MaxItems=0 was a 500).

Markers fit markerType's 320 characters. A marker embeds the key of the
item its page ended on, so a policy ARN with a long path produced one
of 610 characters, which the model check would now refuse on the way
back. SignedMarkers takes a maximum length: a cursor that would exceed
it is carried as a SHA-256 digest (119 characters once signed and
encoded), and the instance keeps the digest -> key mapping. That keeps
the existing resume semantics exactly: the marker still resolves to the
full key, so a deleted anchor resumes at the first key after it, and
the signature still binds account, operation and filter. Two stateless
alternatives were rejected: a truncated key prefix plus digest cannot
order a deleted anchor against items sharing the prefix, and a position
index skips or repeats when items ahead of it are deleted. The cost is
one map entry per distinct long key a page has ended on, never evicted
(marked ponytail in the code); markers already do not survive a
restart, as the signing key is per instance. Keys short enough to embed
are carried as before.

Checkstyle (./mvnw checkstyle:check) reported six errors in files this
PR touches: javax import order and two inline org.w3c.dom.Node in the
pagination test, and an inline java.util.Base64 in SignedMarkersTest.
The test now parses through XmlParser.parseDocument instead of its own
DocumentBuilderFactory. The switch statements in ListEntitiesForPolicy
and the test's holder fixture are switch expressions.

Tests: aMarkerEndingOnALongPolicyArnFitsTheModelAndResumesPastItsDeletion
attaches three policies under a 391-character path, pages with
MaxItems=1, deletes the anchor and resumes through the model check.
Constructing SignedMarkers without the limit fails it (610 characters);
restoring the pre-wave iam-request-shapes.json fails the table-driven
test (MaxItems=0 answered 500, MaxItems=1001 answered 200).

* fix(iam): bind a caller-resolved list's marker to the resolved user

ListAccessKeys, ListMFADevices, ListSSHPublicKeys, ListSigningCertificates
and ListServiceSpecificCredentials default an omitted UserName to the
caller. The marker was signed over the raw request members, so two users
in one account who both omitted UserName shared a scope and one's marker
resumed the other's listing. These handlers now page over the request
with UserName set to the resolved user, so the marker is bound to the
user the list was read for, named or implicit.

* fix(iam): bound the SignedMarkers digest map and trim the pagination test

SignedMarkers held every long cursor it had issued a digest for, in a map
that never shrank. It is now an access-ordered LinkedHashMap capped at
10,000 entries, the idiom CloudWatch Logs uses for its Insights queries. A
marker whose digest was evicted resolves to null, the same as an unknown
digest, so callers refuse it as an invalid marker.

IamListPaginationIntegrationTest spent most of its time in RestAssured's
per-request overhead on the hundred-item fixtures. Those creates and
deletes now go concurrently through java.net.http. The users and groups
default test keeps its first-page checks of the default of 100 and drops
the second page, which the roles default test and the every-operation test
already cover. The SSH public key fixture is generated once per run.
This commit is contained in:
Allen Sanborn authored and GitHub committed 2026-10-28 16:37:49 -04:00
1 parent d7763fff8e
commit 3212ce3c15
16 files changed
+2916 -501

No files matched your search

+9
View File
@@ -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."; \
+54 -14
View File
@@ -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
@@ -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) {
@@ -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;
}
}
File diff suppressed because it is too large. Load diff
@@ -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 {
@@ -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();
}
+440
View File
@@ -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
}
}
}
+489 -1
View File
@@ -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,
@@ -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));
}
}
@@ -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")
.when().post("/").then()
.statusCode(200)
.body(containsString("<ServiceNamespace>dynamodb</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(200)
.body(containsString("<ServiceNamespace>dynamodb</ServiceNamespace>"))
.body(not(containsString("<ServiceNamespace>s3</ServiceNamespace>")));
.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)
+154
View File
@@ -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())
+39 -1
View File
@@ -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:
+128
View File
@@ -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
+37 -1
View File
@@ -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"))