feat(iam): read members clients locate apart, S3's key shape and unread bodies (#9151)

Four rules of the request-resources generator that S3 needs to be read from the table, which leave the
table as it is while S3 is still built by hand.

A member the clients of an operation carry in different places, a body the reader reads among them, is
recorded under each client locating it (locatedApart: S3's CreateBucket carries its Bucket as {Bucket},
S3 Control's as {name}), and the reader takes the members of the client whose vendored route the request
matched; a split by a client with no vendored routes is refused. A member whose botocore shape is named
as the type and Key fills the type's name (S3's Key, an ObjectKey, the object's ${ObjectName}). A type
named exactly as what an operation makes rules out one only ending with that name (PutObject makes an
object, not an accesspointobject). An operation of a REST-XML model naming what it acts on in its body
by such a key shape, which the reader does not read, is recorded unread (DeleteObjects'
Delete.Objects[].Key), and RequestResources.reads, of and ofBody leave it to its service.
This commit is contained in:
Priamo Germosen authored and GitHub committed 2026-11-21 15:37:05 -04:00
1 parent 27de6fd46e
commit 1a107f8f46
6 files changed
+360 -33

No files matched your search

@@ -7,6 +7,7 @@ import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
@@ -53,6 +54,11 @@ final class RequestResourceMembers {
/** A member a REST request carries outside its body, by its name, and where: a path label or a query parameter. */
private static final Pattern LOCATED_MEMBER = Pattern.compile("[A-Za-z][A-Za-z0-9_]*");
private static final Pattern LOCATION = Pattern.compile("\\{[A-Za-z0-9_]+}|\\?[A-Za-z0-9_.-]+");
// A botocore client, as the vendored routes name its model.
private static final Pattern CLIENT = Pattern.compile("[a-z0-9][a-z0-9-]*");
// A member of a request's body at any depth: Delete.Objects[].Key.
private static final Pattern BODY_PATH = Pattern.compile(
"[A-Za-z][A-Za-z0-9_]*(\\[])?(\\.[A-Za-z][A-Za-z0-9_]*(\\[])?)*");
/** The one id a child type's format appends to its parent's. */
private static final Pattern APPENDED_ID = Pattern.compile("[/:]\\$\\{\\w+}");
/** A word of a child type's own and one id, which its format appends to its parent's whole resource. */
@@ -326,9 +332,11 @@ final class RequestResourceMembers {
* {@code <namespace>:<Operation>}, the members a REST operation's request carries outside its body, each
* namespace's ARN formats, and the namespaces it reads, those built by hand, those not read yet, and the others
* with resource types. A located member is a label of the request's path, {@code {Label}}, or a parameter of its
* query, {@code ?name}, by the member's name. Each operation's {@code forwarded} requests are those its service
* makes to another as the caller, and its {@code statements} those it makes as the caller to run each statement its
* request may carry.
* query, {@code ?name}, by the member's name, and one the clients of an operation locate apart is under each
* client ({@code locatedApart}), whose vendored route tells a request's client. Each operation's {@code forwarded}
* requests are those its service makes to another as the caller, and its {@code statements} those it makes as the
* caller to run each statement its request may carry. An {@code unread} operation names what it acts on in a body
* the reader does not read.
*/
record Table(Map<String, List<Resource>> operations, Map<String, List<String>> types,
Map<String, List<Created>> creates, Map<String, List<Resource>> makes,
@@ -338,7 +346,8 @@ final class RequestResourceMembers {
Map<String, Map<String, List<String>>> resourceTagKeys,
Map<String, Map<String, Map<String, ResourceKey>>> resourceKeys,
Set<String> namespaces, Set<String> handBuilt, Set<String> notCovered, Set<String> otherNamespaces,
Map<String, List<Forwarded>> forwarded, Map<String, Map<String, List<StatementRequest>>> statements) {
Map<String, List<Forwarded>> forwarded, Map<String, Map<String, List<StatementRequest>>> statements,
Map<String, Map<String, Map<String, String>>> locatedApart, Set<String> unread) {
}
private static final class Holder {
@@ -443,6 +452,8 @@ final class RequestResourceMembers {
Map<String, Targets> targets = new LinkedHashMap<>();
Map<String, Map<Member, String>> ec2Query = new LinkedHashMap<>();
Map<String, Map<String, String>> located = new LinkedHashMap<>();
Map<String, Map<String, Map<String, String>>> locatedApart = new LinkedHashMap<>();
Set<String> unread = new LinkedHashSet<>();
Map<String, List<Forwarded>> forwarded = new LinkedHashMap<>();
JsonNode forwardedActions = document.path("forwardedActions");
operations.properties().forEach(operation -> {
@@ -530,6 +541,48 @@ final class RequestResourceMembers {
if (!where.isEmpty()) {
located.put(operation.getKey(), Map.copyOf(where));
}
JsonNode locatedApartNode = operation.getValue().path("locatedApart");
if (!locatedApartNode.isMissingNode() && (!locatedApartNode.isObject() || locatedApartNode.isEmpty())) {
throw new IllegalStateException(RESOURCE_NAME + " locates " + operation.getKey()
+ "'s members apart under no client");
}
Map<String, Map<String, String>> apart = new LinkedHashMap<>();
locatedApartNode.properties().forEach(client -> {
if (!client.getValue().isObject()) {
throw new IllegalStateException(RESOURCE_NAME + " locates " + operation.getKey() + "'s members for "
+ client.getKey() + " as " + client.getValue() + ", no members");
}
Map<String, String> members = new LinkedHashMap<>();
client.getValue().properties().forEach(member -> {
if (!CLIENT.matcher(client.getKey()).matches() || !LOCATED_MEMBER.matcher(member.getKey()).matches()
|| !LOCATION.matcher(member.getValue().asText("")).matches()) {
throw new IllegalStateException(RESOURCE_NAME + " locates " + operation.getKey() + "'s "
+ member.getKey() + " at " + member.getValue() + " for " + client.getKey()
+ ", no client's label of a path or query parameter");
}
members.put(member.getKey(), member.getValue().asText());
});
if (members.isEmpty()) {
throw new IllegalStateException(RESOURCE_NAME + " locates none of " + operation.getKey()
+ "'s members for " + client.getKey());
}
apart.put(client.getKey(), Map.copyOf(members));
});
if (!apart.isEmpty()) {
locatedApart.put(operation.getKey(), Map.copyOf(apart));
}
JsonNode unreadNode = operation.getValue().path("unread");
if (!unreadNode.isMissingNode() && (!unreadNode.isArray() || unreadNode.isEmpty())) {
throw new IllegalStateException(RESOURCE_NAME + " leaves " + operation.getKey()
+ " unread on no member of its body");
}
for (JsonNode member : unreadNode) {
if (!member.isTextual() || !BODY_PATH.matcher(member.asText()).matches()) {
throw new IllegalStateException(RESOURCE_NAME + " leaves " + operation.getKey() + "'s " + member
+ " unread, no member of a request's body");
}
unread.add(operation.getKey());
}
List<Forwarded> forwards = new ArrayList<>();
for (JsonNode use : operation.getValue().path("forwarded")) {
forwards.add(forwarded(operation.getKey(), use, types, formats.getOrDefault(namespace, Map.of()),
@@ -544,7 +597,8 @@ final class RequestResourceMembers {
Map.copyOf(resourceTagKeys), resourceKeys, namespaces,
names(document.path("handBuilt")),
Set.copyOf(document.path("notCovered").propertyStream().map(Map.Entry::getKey).toList()),
names(document.path("otherNamespaces")), Map.copyOf(forwarded), statements(document, formats));
names(document.path("otherNamespaces")), Map.copyOf(forwarded), statements(document, formats),
Map.copyOf(locatedApart), Set.copyOf(unread));
}
/**
@@ -65,9 +65,18 @@ public final class RequestResources {
private RequestResources() {
}
/** Whether the generated table owns this operation, including those of hand-built namespaces it reads. */
/**
* Whether the generated table owns this operation, including those of hand-built namespaces it reads. An operation
* naming what it acts on in a body the reader does not read ({@code unread}: S3's DeleteObjects, its keys in an XML
* body) is not read, as checked on the rest of its request it would be checked on none of what it names.
*/
public static boolean reads(String operation) {
return operation != null && RequestResourceMembers.table().operations().containsKey(operation);
return readable(RequestResourceMembers.table(), operation);
}
/** Whether {@code table} reads the operation's requests: it has an entry for it, and not an unread one. */
static boolean readable(RequestResourceMembers.Table table, String operation) {
return operation != null && table.operations().containsKey(operation) && !table.unread().contains(operation);
}
/** Whether {@code ResourceArnBuilder} builds the resources of this namespace's requests itself. */
@@ -175,7 +184,8 @@ public final class RequestResources {
return targetArns(targets, formats(table, operation), form,
form.isEmpty() ? PassedRoles.jsonBody(ctx) : null, partition, region, accountId);
}
List<RequestResourceMembers.Resource> resources = operation == null ? null
// An operation the table does not read, an unread one among them, names nothing from it.
List<RequestResourceMembers.Resource> resources = !readable(table, operation) ? null
: served(table.operations().get(operation), ctx);
if (resources == null) {
return List.of();
@@ -199,7 +209,8 @@ public final class RequestResources {
if (targets != null) {
return targetArns(targets, formats(table, operation), Map.of(), body, partition, region, accountId);
}
List<RequestResourceMembers.Resource> resources = operation == null ? null : table.operations().get(operation);
List<RequestResourceMembers.Resource> resources = !readable(table, operation) ? null
: table.operations().get(operation);
if (resources == null || resources.isEmpty()) {
return List.of();
}
@@ -509,12 +520,26 @@ public final class RequestResources {
private static Map<String, String> locatedMembers(RequestResourceMembers.Table table, String operation,
ContainerRequestContext ctx) {
IamActionRegistry.RouteMembers route = IamActionRegistry.routeMembers(operation, ctx);
return locatedMembers(table, operation, route.model(), route.located());
}
/**
* The members the table locates for a request of the operation whose route is the {@code model}'s: those every
* client locates alike, those it locates apart for that model ({@code locatedApart}: S3 Control's CreateBucket
* carries its {@code Bucket} as {@code {name}}, S3's as {@code {Bucket}}), and those a generated alternative route
* locates ({@code alternatives}), {@code body} for one its body carries there.
*/
static Map<String, String> locatedMembers(RequestResourceMembers.Table table, String operation, String model,
Map<String, String> alternatives) {
Map<String, String> located = table.located().getOrDefault(operation, Map.of());
Map<String, String> alternatives = IamActionRegistry.routeMemberLocations(operation, ctx);
if (alternatives.isEmpty()) {
Map<String, String> apart = model == null ? Map.of()
: table.locatedApart().getOrDefault(operation, Map.of()).getOrDefault(model, Map.of());
if (alternatives.isEmpty() && apart.isEmpty()) {
return located;
}
Map<String, String> merged = new HashMap<>(located);
merged.putAll(apart);
alternatives.forEach((member, source) -> {
if ("body".equals(source)) {
merged.remove(member);
@@ -792,18 +792,27 @@ public class IamActionRegistry {
.orElse(action);
}
/** Member locations of a generated alternative route; absent entries keep the operation's model locations. */
public static Map<String, String> routeMemberLocations(String operation, ContainerRequestContext ctx) {
/**
* The vendored route a request of an operation matched: the member locations of a generated alternative route
* ({@code located}; absent entries keep the operation's model locations) and the botocore model whose route it is
* ({@code model}), which tells apart the clients of an operation several serve.
*/
public record RouteMembers(Map<String, String> located, String model) {
static final RouteMembers NONE = new RouteMembers(Map.of(), null);
}
/** The route a request of the operation matches, {@link RouteMembers#NONE} for one it matches none of. */
public static RouteMembers routeMembers(String operation, ContainerRequestContext ctx) {
int separator = operation.indexOf(':');
if (separator < 0 || ctx.getMethod() == null || ctx.getUriInfo() == null
|| ctx.getUriInfo().getRequestUri() == null) {
return Map.of();
return RouteMembers.NONE;
}
return IamRestRoutes.vendored().match(operation.substring(0, separator), ctx.getMethod().toUpperCase(),
withoutInternalPrefix(ctx, routedPath(ctx)), ctx.getUriInfo().getQueryParameters(),
movedUnderPrefix(ctx), ctx.getHeaders())
.filter(match -> match.operation().equals(operation.substring(separator + 1)))
.map(IamRestRoutes.Match::located).orElse(Map.of());
.map(match -> new RouteMembers(match.located(), match.model())).orElse(RouteMembers.NONE);
}
/**
@@ -758,6 +758,51 @@ class RequestResourceMembersTest {
return new ArnFormat(format, RequestResourceMembers.pattern(format), false);
}
/**
* A member the clients of an operation locate apart is read for the client whose route a request matched, and an
* operation naming what it acts on in a body the reader does not read is recorded unread; a malformed entry of
* either is refused.
*/
@Test
void membersLocatedApartAreReadForTheRequestsClientAndUnreadOperationsAreRecorded() throws Exception {
String formats = "\"arnFormats\":{\"a\":{\"thing\":\"arn:${Partition}:a:::${ThingName}\"}}";
String operation = "{\"resources\":[{\"type\":\"thing\",\"fill\":{\"ThingName\":\"Bucket\"}}],"
+ "\"located\":{\"Marker\":\"?marker\"},"
+ "\"locatedApart\":{\"one\":{\"Bucket\":\"{Bucket}\"},\"two\":{\"Bucket\":\"{name}\"}},"
+ "\"unread\":[\"Delete.Objects[].Key\"]}";
RequestResourceMembers.Table table = parse("{\"namespaces\":{\"a\":[]}," + formats
+ ",\"operations\":{\"a:Op\":" + operation + "}}");
assertEquals(Map.of("one", Map.of("Bucket", "{Bucket}"), "two", Map.of("Bucket", "{name}")),
table.locatedApart().get("a:Op"));
assertEquals(Set.of("a:Op"), table.unread());
// An unread operation is one the table does not read: RequestResources.of names nothing from it.
assertFalse(RequestResources.readable(table, "a:Op"));
RequestResourceMembers.Table read = parse("{\"namespaces\":{\"a\":[]}," + formats
+ ",\"operations\":{\"a:Op\":{\"resources\":[]}}}");
assertTrue(RequestResources.readable(read, "a:Op"));
assertFalse(RequestResources.readable(read, "a:Other"));
assertEquals(Map.of("Marker", "?marker", "Bucket", "{Bucket}"),
RequestResources.locatedMembers(table, "a:Op", "one", Map.of()));
assertEquals(Map.of("Marker", "?marker", "Bucket", "{name}"),
RequestResources.locatedMembers(table, "a:Op", "two", Map.of()));
// A request no route of the operation matched, or one of a client locating nothing apart, reads only what every
// client locates alike.
assertEquals(Map.of("Marker", "?marker"), RequestResources.locatedMembers(table, "a:Op", null, Map.of()));
assertEquals(Map.of("Marker", "?marker"), RequestResources.locatedMembers(table, "a:Op", "three", Map.of()));
// A generated alternative route still says where its members are.
assertEquals(Map.of("Bucket", "{name}"),
RequestResources.locatedMembers(table, "a:Op", "two", Map.of("Marker", "body")));
for (String bad : List.of("\"locatedApart\":{\"One\":{\"Bucket\":\"{Bucket}\"}}",
"\"locatedApart\":{\"one\":{\"Bucket\":\"Bucket\"}}", "\"locatedApart\":{\"one\":{}}",
"\"locatedApart\":{}", "\"locatedApart\":[]", "\"locatedApart\":\"one\"",
"\"locatedApart\":{\"one\":\"{Bucket}\"}", "\"locatedApart\":{\"one\":[\"{Bucket}\"]}",
"\"unread\":[\"Delete..Key\"]", "\"unread\":[1]", "\"unread\":[]", "\"unread\":\"Delete.Key\"",
"\"unread\":{\"a\":\"Delete.Key\"}")) {
assertThrows(IllegalStateException.class, () -> parse("{\"namespaces\":{\"a\":[]}," + formats
+ ",\"operations\":{\"a:Op\":{\"resources\":[]," + bad + "}}}"), bad);
}
}
private static String document(String formats, String resource) {
return "{\"namespaces\":{\"a\":[]}," + formats + ",\"operations\":{\"a:Op\":{\"resources\":[" + resource + "]}}}";
}
+116 -15
View File
@@ -90,7 +90,12 @@ names none, is checked on `*`, as AWS checks it.
A REST request (`rest-json`) carries members in its path and its query as well as its body: a label of its path,
`{DomainName}`, and a parameter of its query, `?arn`, are members as its body's are, under their botocore names, and
the file records where each is (`located`), which the reader lays over the body from the path the request was routed
by and its query. A namespace read this way also takes the operations of each botocore model Floci reads REST routes
by and its query. A member the clients of an operation carry in different places is recorded under each client
(`locatedApart`: S3's CreateBucket carries its `Bucket` as `{Bucket}`, S3 Control's as `{name}`), the request's
vendored route telling its client. A REST-XML request's body is not read, so an operation naming what it acts on there
by a shape named as the type and `Key` (S3's DeleteObjects, `Delete.Objects[].Key`) is recorded `unread`, and the
reader leaves it to its service, as checked on the rest of its request it would be checked on none of what it names.
A namespace read this way also takes the operations of each botocore model Floci reads REST routes
for under it (`regen_rest_routes.MODELS`) that the reference lists for none of its clients, each checked as the action
of its own name with that action's resource types when the reference has that action, and left out when it does not:
the reference lists one client's operations per namespace, and
@@ -1450,23 +1455,48 @@ def only_arn(pattern: str | None) -> bool:
return True
def located_members(models: dict[str, dict], operation: str) -> dict[str, str]:
def located_members(models: dict[str, dict], operation: str) -> tuple[dict[str, str], dict[str, dict[str, str]]]:
"""The members of a REST request that its path or its query carries, holding a string, by name, with where:
`{Label}` for a label of its path, `?name` for a parameter of its query. The reader lays them over the request's
body under their names, so a resource reads them as it reads a member of the body."""
found: dict[str, str] = {}
body under their names, so a resource reads them as it reads a member of the body.
A member every client of the operation locates alike is in the first map; one its clients locate apart, or some
locate and another's read body carries, is in the second, under each client locating it, whose vendored route tells
a request's client (`locatedApart`: S3's CreateBucket carries its `Bucket` as `{Bucket}`, S3 Control's as
`{name}`); a request of another client is read from its body. One located apart by a client whose routes are not
vendored is refused, as no request would say where it is."""
per_client: dict[str, dict[str, str]] = {}
in_body: dict[str, set[str]] = {}
for client, model in sorted(models.items()):
spec = model["operations"].get(operation)
if spec is None or "input" not in spec or not ({"rest-json"} | LOCATED_ONLY_PROTOCOLS) & _protocols(model):
if spec is None or "input" not in spec:
continue
locating = bool(({"rest-json"} | LOCATED_ONLY_PROTOCOLS) & _protocols(model))
found: dict[str, str] = {}
for name, member in model["shapes"][spec["input"]["shape"]].get("members", {}).items():
where = _located(member)
if where is None and _reading(model) == "all" and member.get("location") in BODY_LOCATIONS:
in_body.setdefault(name, set()).add(client)
shape = model["shapes"][member["shape"]]
if where is None or (_strings(model, shape) != "" and shape["type"] not in ("integer", "long")):
if not locating or where is None or (_strings(model, shape) != "" and shape["type"] not in ("integer", "long")):
continue
if found.setdefault(name, where) != where:
raise ValueError(f"{operation}'s {name} is {found[name]} in one client and {where} in {client}")
return dict(sorted(found.items()))
found[name] = where
if locating:
per_client[client] = found
shared: dict[str, str] = {}
apart: dict[str, dict[str, str]] = {}
for name in sorted({name for found in per_client.values() for name in found}):
places = {client: found[name] for client, found in per_client.items() if name in found}
if len(set(places.values())) == 1 and not in_body.get(name):
shared[name] = next(iter(places.values()))
continue
unrouted = sorted(client for client in places if client not in REST_MODELS)
if unrouted:
raise ValueError(f"{operation}'s {name} is located apart by {', '.join(sorted(places))}, and "
f"{', '.join(unrouted)} has no vendored routes to tell its requests apart")
for client, where in places.items():
apart.setdefault(client, {})[name] = where
return shared, {client: dict(sorted(found.items())) for client, found in sorted(apart.items())}
def _located(member: dict) -> str | None:
@@ -1783,6 +1813,11 @@ def resources_for(operation: str, types: list[str], formats: dict[str, str], mem
filled: dict[str, dict[str, str]] = {}
used: dict[str, str] = {}
complete: dict[str, bool] = {}
# A type named exactly as what the operation makes is the one it makes, so another only ending with that name is
# not: PutObject makes an `object`, not an `accesspointobject`.
exactly_created = created is not None and any(
created in (stem(kind), stem(word.group(1)) if (word := RESOURCE_PART_RE.match(formats[kind])) else stem(kind))
for kind in types if kind in formats)
for kind in types:
if kind not in formats:
continue
@@ -1800,7 +1835,8 @@ def resources_for(operation: str, types: list[str], formats: dict[str, str], mem
variables = [v for v in VARIABLE_RE.findall(formats[kind]) if v not in KNOWN_VARIABLES]
# A create makes its own type, so a member holding whatever the action acts on does not hold that one:
# `CreateResourceShare`'s `resourceArns` are what the share it makes holds.
creates_it = created is not None and (related(created, kind_stem) or related(created, word_stem))
creates_it = created is not None and (created in (kind_stem, word_stem) if exactly_created
else related(created, kind_stem) or related(created, word_stem))
holding = [member for member in held if not (creates_it and stem(member) in ("", "resource"))]
# Its bare name then names what it makes, when the type's variables say they are a name or an id: a share's
# `${ResourcePath}`, which RAM mints, takes no name.
@@ -2019,7 +2055,8 @@ def _filling(variable: str, kind_stem: str, variables: int, names: dict[str, str
or, for the variable named after the type or a type's only one, a member named after the type, or a
bare `Name` or `Id` among those `bare` gives, of a compatible kind, or else a string or list member whose
botocore shape is named after the type, of a compatible kind (Parameter Store's `Path` and
`GetParameterHistory`'s `Name` hold a `PSParameterName`, Glue's `TablesToDelete` a `BatchDeleteTableNameList`);
`GetParameterHistory`'s `Name` hold a `PSParameterName`, Glue's `TablesToDelete` a `BatchDeleteTableNameList`, S3's
`Key` an `ObjectKey`, a shape named as the type and `Key`);
the closest of them, one qualified by the type's own name first (a snapshot's `SnapshotClusterIdentifier` before `ClusterIdentifier`), and a string before a list. A variable the
reference names `ResourceId` is the type's own id (`ingestion/${ResourceId}`)."""
# A `ResourceId` variable is filled by a member named so (CreateOpsMetadata's, `opsmetadata/${ResourceId}`) before
@@ -2045,7 +2082,8 @@ def _filling(variable: str, kind_stem: str, variables: int, names: dict[str, str
# not when it holds a name's shape.
candidates = [member for member in names if member in (shapes or {})
and (not names[member].endswith("[]") or shapes[member].endswith("List"))
and "." not in member and stem(shapes[member]) and related(stem(shapes[member]), kind_stem)
and "." not in member and stem(shapes[member])
and (related(stem(shapes[member]), kind_stem) or stem(shapes[member]) == kind_stem + "key")
and compatible(shapes[member], variable) and compatible(member, variable)]
if not candidates:
return None
@@ -2297,6 +2335,9 @@ def entry_for(operation: str, upstream: dict, formats: dict[str, str], models: d
if uses is not None and not (uses and all("action" in use for use in uses)):
resources = measured_resources(operation, types, formats, resources)
entry = {"action": upstream["action"], "types": types, "resources": resources}
unread = body_only_identifiers(types, formats, resources, models, operation.split(":", 1)[1])
if unread:
entry["unread"] = unread
creates = creates_for(operation, types, formats, members)
if creates:
entry["creates"] = creates
@@ -2309,15 +2350,60 @@ def entry_for(operation: str, upstream: dict, formats: dict[str, str], models: d
query_members = ec2_query_members(operation, models, named)
if query_members:
entry["ec2Query"] = query_members
located = {member: where for member, where in located_members(models, operation.split(":", 1)[1]).items()
if member in named}
shared, apart = located_members(models, operation.split(":", 1)[1])
located = {member: where for member, where in shared.items() if member in named}
if located:
entry["located"] = located
located_apart = {client: kept for client, found in apart.items()
if (kept := {member: where for member, where in found.items() if member in named})}
if located_apart:
entry["locatedApart"] = located_apart
if operation in measured_actions():
entry["forwarded"] = forwarded_for(operation, types, models, forwarded or {})
return entry
def body_only_identifiers(types: list[str], formats: dict[str, str], resources: list[dict], models: dict[str, dict],
name: str) -> list[str]:
"""The members of a request whose body the reader does not read (`LOCATED_ONLY_PROTOCOLS`) that name what a type
of the action acts on, by a shape named as the type and `Key`, where the members it does read leave the type's own
variable open: S3's DeleteObjects names each object it deletes in `Delete.Objects[].Key`, an `ObjectKey`. Read on
the rest of its request, such an operation would be checked on what it names in none of its body (`unread`)."""
found: list[str] = []
for model in (model for _, model in sorted(models.items())):
spec = model["operations"].get(name)
if spec is None or "input" not in spec or _reading(model) != "located":
continue
for kind in types:
variables = [variable for variable in VARIABLE_RE.findall(formats.get(kind, ""))
if variable not in KNOWN_VARIABLES and stem(variable) == stem(kind)]
if not variables or any(set(variables) <= set(resource.get("fill", {})) for resource in resources
if kind in _kinds(resource)):
continue
for path, shape in _body_members(model, spec["input"]["shape"]):
if stem(shape) == stem(kind) + "key" and path not in found:
found.append(path)
return found
def _body_members(model: dict, shape_name: str, prefix: str = "", depth: int = 0) -> list[tuple[str, str]]:
"""The members of a request's body, at any depth up to five, as `Outer.List[].Member` paths, with the shape each
holds."""
shape = model["shapes"][shape_name]
found: list[tuple[str, str]] = []
if depth > 4:
return found
if shape["type"] == "structure":
for member, ref in shape.get("members", {}).items():
if ref.get("location") in ("uri", "querystring", "header", "headers"):
continue
found.append((prefix + member, ref["shape"]))
found += _body_members(model, ref["shape"], prefix + member + ".", depth + 1)
elif shape["type"] == "list":
found += _body_members(model, shape["member"]["shape"], prefix.removesuffix(".") + "[].", depth + 1)
return found
def measured_resources(operation: str, types: list[str], formats: dict[str, str], derived: list[dict]) -> list[dict]:
"""The resources `MEASURED` gives the operation, refused unless its admission rules hold: its evidence links to
the measurement, the Service Reference lists none of its types for the action, each has an ARN format, and the
@@ -3511,6 +3597,8 @@ def render(document: dict) -> str:
# Gates
# --------------------------------------------------------------------------- #
PATH_RE = re.compile(r"^[A-Za-z][A-Za-z0-9_]*(\[])?$")
# A member of a request's body at any depth, as `body_only_identifiers` writes it: `Delete.Objects[].Key`.
BODY_PATH_RE = re.compile(r"^[A-Za-z][A-Za-z0-9_]*(\[])?(\.[A-Za-z][A-Za-z0-9_]*(\[])?)*$")
# A member filling a variable may also be a field of a structure, or of each element of a list of structures, one
# value for each.
FILL_PATH_RE = re.compile(r"^[A-Za-z][A-Za-z0-9_]*(\[]|\[]\.[A-Za-z][A-Za-z0-9_]*|\{}\.[A-Za-z][A-Za-z0-9_]*"
@@ -3620,7 +3708,8 @@ def validate(document: dict) -> list[str]:
problems.append(f"{operation!r} is not an operation of a namespace the file reads")
continue
if not isinstance(entry, dict) or not {"action", "types", "resources"} <= set(entry) <= {
"action", "types", "resources", "creates", "makes", "located", "targets", "forwarded", "ec2Query"}:
"action", "types", "resources", "creates", "makes", "located", "locatedApart", "targets", "forwarded",
"ec2Query", "unread"}:
problems.append(f"{operation} is not an action, its types and its resources")
continue
if not isinstance(entry["action"], str) or not OPERATION_RE.match(entry["action"]) \
@@ -3674,6 +3763,18 @@ def validate(document: dict) -> list[str]:
for member, where in located.items()):
problems.append(f"{operation} does not give each member it locates a label of its path or a parameter of "
f"its query")
apart = entry.get("locatedApart", {})
if not isinstance(apart, dict) or not apart and "locatedApart" in entry or not all(
client in REST_MODELS and isinstance(found, dict) and found and all(
isinstance(member, str) and PATH_RE.match(member) and isinstance(where, str)
and LOCATED_RE.match(where) for member, where in found.items())
for client, found in apart.items()):
problems.append(f"{operation} does not give each member it locates apart, under a client whose routes are "
f"vendored, a label of its path or a parameter of its query")
unread = entry.get("unread", [])
if not isinstance(unread, list) or not unread and "unread" in entry or not all(
isinstance(member, str) and BODY_PATH_RE.match(member) for member in unread):
problems.append(f"{operation} does not give each body member it leaves unread as a path")
forwarded = entry.get("forwarded", [])
if not isinstance(forwarded, list) or not forwarded and "forwarded" in entry or not all(
isinstance(use, dict) and set(use) == {"action", "of", "member", "endpoint"}
+96 -3
View File
@@ -222,7 +222,7 @@ def test_a_rest_xml_request_is_read_for_its_path_and_query_members_alone():
"shapes": shapes}}
assert r.request_members(models, "GetThing") == read, protocol
assert set(r.string_patterns(models, "GetThing")) == set(read), protocol
assert r.located_members(models, "GetThing") == {"Id": "{Id}", "Marker": "?Marker"}, protocol
assert r.located_members(models, "GetThing") == ({"Id": "{Id}", "Marker": "?Marker"}, {}), protocol
def test_an_arn_inside_a_structure_or_a_lists_structures_is_read_by_its_path():
@@ -1362,13 +1362,88 @@ def test_a_rest_request_reads_its_path_and_query_members_and_records_where_the_o
assert r.derive(document, tmp_path) == []
def test_a_member_two_clients_locate_apart_is_an_error():
def test_a_member_two_clients_locate_apart_is_read_under_each_client(monkeypatch):
# S3's CreateBucket carries its Bucket as {Bucket}, S3 Control's as {name}: a request's route tells which it is.
one = rest_model({"GetThing": {"ThingName": "String", "Marker": "String"}},
{"GetThing": {"ThingName": "uri:ThingName", "Marker": "querystring:marker"}})
two = rest_model({"GetThing": {"ThingName": "String", "Marker": "String"}},
{"GetThing": {"ThingName": "uri:name", "Marker": "querystring:marker"}})
monkeypatch.setattr(r, "REST_MODELS", {"one": "svc", "two": "svc"})
assert r.located_members({"one": one, "two": two}, "GetThing") == (
{"Marker": "?marker"}, {"one": {"ThingName": "{ThingName}"}, "two": {"ThingName": "{name}"}})
def test_a_member_one_client_locates_and_another_carries_in_a_body_it_reads_is_located_for_the_first_alone(monkeypatch):
# A request of the client carrying it in its body is read from its body, not from a path it has no label in.
one = rest_model({"GetThing": {"ThingName": "String"}}, {"GetThing": {"ThingName": "uri:ThingName"}})
two = model({"GetThing": {"ThingName": "String"}})
monkeypatch.setattr(r, "REST_MODELS", {"one": "svc"})
assert r.located_members({"one": one, "two": two}, "GetThing") == ({}, {"one": {"ThingName": "{ThingName}"}})
# A REST-XML body is not read, so a client carrying the member there leaves it shared.
xml = {**two, "metadata": {**two.get("metadata", {}), "protocol": "rest-xml"}}
assert r.located_members({"one": one, "two": xml}, "GetThing") == ({"ThingName": "{ThingName}"}, {})
monkeypatch.setattr(r, "REST_MODELS", {})
with pytest.raises(ValueError, match="one has no vendored routes"):
r.located_members({"one": one, "two": two}, "GetThing")
def test_a_member_located_apart_by_a_client_whose_routes_are_not_vendored_is_an_error(monkeypatch):
one = rest_model({"GetThing": {"ThingName": "String"}}, {"GetThing": {"ThingName": "uri:ThingName"}})
two = rest_model({"GetThing": {"ThingName": "String"}}, {"GetThing": {"ThingName": "querystring:thing"}})
with pytest.raises(ValueError, match="GetThing's ThingName is"):
monkeypatch.setattr(r, "REST_MODELS", {"one": "svc"})
with pytest.raises(ValueError, match="GetThing's ThingName is located apart by one, two, and two has no vendored"):
r.located_members({"one": one, "two": two}, "GetThing")
# S3's object types: an access point's object and a bucket's.
OBJECTS = {"accesspointobject": "arn:${Partition}:s3:${Region}:${Account}:accesspoint/${AccessPointName}/object/"
"${ObjectName}",
"object": "arn:${Partition}:s3:::${BucketName}/${ObjectName}"}
OBJECT_MEMBERS = {"Bucket": "Bucket", "Key": "Key", "ContentType": "ContentType"}
OBJECT_SHAPES = {"Bucket": "BucketName", "Key": "ObjectKey", "ContentType": "ContentType"}
def test_a_member_whose_shape_is_named_as_the_type_and_key_fills_the_types_name():
assert r._filling("ObjectName", "object", 2, {"Key": "Key", "Bucket": "Bucket"}, bare=set(),
shapes={"Key": "ObjectKey", "Bucket": "BucketName"}) == "Key"
assert r.resources_for("s3:GetObject", ["accesspointobject", "object"], OBJECTS, OBJECT_MEMBERS,
shapes=OBJECT_SHAPES) == [
{"type": "object", "fill": {"BucketName": "Bucket", "ObjectName": "Key"}}]
# A shape named as another type and Key names that one.
assert r._filling("ObjectName", "object", 2, {"Key": "Key"}, bare=set(), shapes={"Key": "BucketKey"}) is None
def test_a_type_named_exactly_as_what_the_operation_makes_rules_out_one_only_ending_with_it():
# PutObject makes an `object`, not an `accesspointobject`, whose access point the request does not name.
assert r.resources_for("s3:PutObject", ["accesspointobject", "object"], OBJECTS, OBJECT_MEMBERS,
shapes=OBJECT_SHAPES) == [
{"type": "object", "fill": {"BucketName": "Bucket", "ObjectName": "Key"}}]
# With no type named exactly so, one ending with the name is still what it makes.
assert r.resources_for("s3:PutObject", ["accesspointobject"], OBJECTS, OBJECT_MEMBERS, shapes=OBJECT_SHAPES) == [
{"type": "accesspointobject", "fill": {}}]
def test_a_type_a_body_the_reader_does_not_read_names_by_a_key_shape_is_left_unread():
# S3's DeleteObjects names each object it deletes in Delete.Objects[].Key, an ObjectKey, in a REST-XML body.
shapes = {"String": {"type": "string"}, "ObjectKey": {"type": "string"},
"Identifier": {"type": "structure", "members": {"Key": {"shape": "ObjectKey"}}},
"Identifiers": {"type": "list", "member": {"shape": "Identifier"}},
"Delete": {"type": "structure", "members": {"Objects": {"shape": "Identifiers"}}},
"In": {"type": "structure", "members": {
"Bucket": {"shape": "String", "location": "uri", "locationName": "Bucket"},
"Delete": {"shape": "Delete"}}}}
models = {"s3": {"metadata": {"protocol": "rest-xml"}, "operations": {"DeleteObjects": {"input": {"shape": "In"}}},
"shapes": shapes}}
bucket_only = [{"type": "object", "fill": {"BucketName": "Bucket"}}]
assert r.body_only_identifiers(["object"], OBJECTS, bucket_only, models, "DeleteObjects") == ["Delete.Objects[].Key"]
# The type's own variable filled by what the reader reads, nothing is left.
assert r.body_only_identifiers(["object"], OBJECTS, [{"type": "object", "fill": {
"BucketName": "Bucket", "ObjectName": "Key"}}], models, "DeleteObjects") == []
# A body the reader reads leaves nothing unread.
rest_json = {"s3": {**models["s3"], "metadata": {"protocol": "rest-json"}}}
assert r.body_only_identifiers(["object"], OBJECTS, bucket_only, rest_json, "DeleteObjects") == []
def test_a_located_member_must_be_a_path_label_or_a_query_parameter(isolated, tmp_path):
write_models(tmp_path, {"svc": rest_model({"GetThing": {"ThingName": "String"}, "ListThings": {}},
{"GetThing": {"ThingName": "uri:ThingName"}})})
@@ -1377,6 +1452,24 @@ def test_a_located_member_must_be_a_path_label_or_a_query_parameter(isolated, tm
assert any("does not give each member it locates" in problem for problem in r.validate(document))
def test_a_member_located_apart_names_a_client_whose_routes_are_vendored_and_an_unread_one_a_body_path(
isolated, tmp_path, monkeypatch):
write_models(tmp_path, {"svc": rest_model({"GetThing": {"ThingName": "String"}, "ListThings": {}},
{"GetThing": {"ThingName": "uri:ThingName"}})})
document = r.build(DOCUMENTS, "test", tmp_path, "botocore test")
monkeypatch.setattr(r, "REST_MODELS", {"one": "svc"})
entry = document["operations"]["svc:GetThing"]
entry.update(locatedApart={"one": {"ThingName": "{name}"}}, unread=["Delete.Objects[].Key"])
assert r.validate(document) == []
for broken in ({"locatedApart": {"two": {"ThingName": "{name}"}}}, {"locatedApart": {"one": {"ThingName": "x"}}},
{"locatedApart": {}}):
assert any("locates apart" in problem for problem in r.validate(
{**document, "operations": {**document["operations"], "svc:GetThing": {**entry, **broken}}}))
for broken in (["Delete..Key"], [], "Delete.Objects[].Key"):
assert any("leaves unread" in problem for problem in r.validate(
{**document, "operations": {**document["operations"], "svc:GetThing": {**entry, "unread": broken}}}))
SPLIT = [reference("svc", {"GetThing": ["thing"], "ListThings": []}, {"thing": FORMATS["thing"]}),
reference("other", {"Op": ["x"]}, {"x": "arn:${Partition}:other:::x"}),
reference("later", {"Op": ["y"]}, {"y": "arn:${Partition}:later:::y"})]