feat(iam): read a REST request's resources from its path and query (#7499)

The table of request resources read only a request's body or Query
form, so no REST namespace was read: a REST request names its
resources in its path and its query. An OpenSearch Service request
naming its domain, DescribeDomain on
/2021-01-01/opensearch/domain/{DomainName}, was left unchecked by the
routes the previous change reads, as Floci could not check it on the
domain AWS checks it on.

- The generator reads a rest-json request's members in its path and
  its query as members, under their botocore names, and records where
  each one a resource reads is (`located`): a path label, `{Label}`, or
  a query parameter, `?name`. RequestResources lays them over the body,
  a label's value from the route the request matched in the vendored
  routes (IamActionRegistry.pathLabels, IamRestRoutes now capturing
  each label), a query parameter's from the query, so every kind of
  resource reads them as it reads the body's. A located member is read
  from where it is alone, as its handler reads it: one the body also
  gives is dropped.
- A namespace read this way also takes the operations of each botocore
  model Floci reads routes for under it (regen_rest_routes.MODELS) that
  the reference lists for none of its clients, each the action of its
  own name with that action's resource types, when the reference has
  that action: the reference lists OpenSearch Service's `es` client
  alone, while the `opensearch` client's operations are named after
  `es` actions. --verify checks such an operation's action and types
  against the reference's Actions, and reports one whose action AWS no
  longer has.
- `es` moves from NOT_COVERED to NAMESPACES: 120 operations, both API
  versions', 1505 over 34 namespaces. Every domain route Floci serves
  reads its domain, from the path, the body or `?arn`, on
  `domain/<DomainName>`, the ARN Floci mints. Those whose resource the
  table does not find (outbound connections, applications, insights)
  are routes Floci does not serve.
- Reading rest-json would also have read the Payment Cryptography data
  plane's key from its path; Floci serves only the control plane, so
  `payment-cryptography-data` joins CLIENTS_NOT_READ with its reason
  and its operations stay as they were. No other entry changes.

With the domain operations in the table, the routes check them by the
resources-read half of the join rule. IamActionRegistryTest checks the
domain routes and the labels a request's path gives;
RequestResourcesTest reads a path label, a query parameter and a body
together; IamRestRouteEnforcementIntegrationTest checks DescribeDomain,
DescribeElasticsearchDomain and ListTags on the domain they name; the
generator tests cover the located members, a member two clients locate
apart, the REST models' operations and a round trip through --check and
--verify. iam.md says so.
This commit is contained in:
Priamo Germosen authored and GitHub committed 2026-11-04 08:05:50 -06:00
1 parent 8f69e81893
commit 9062572948
14 files changed
+637 -53

No files matched your search

@@ -1138,7 +1138,7 @@ public class IamEnforcementFilter implements ContainerRequestFilter {
String region, String accountId, String akid) {
// A create tags the resource it makes, not the parent it makes it in (see RequestResources.created).
List<String> created = RequestResources.created(operation, ctx, AwsRegions.partitionFor(region), region,
accountId);
accountId, IamActionRegistry.pathLabels(credentialScope, ctx));
List<String> made = created.isEmpty() ? resources : created;
for (TagOnCreate.TagSet set : tagging.checked()) {
Map<String, List<String>> context = TagOnCreate.conditionContext(tagging, set, operation);
@@ -45,6 +45,9 @@ final class RequestResourceMembers {
"^arn:\\$\\{Partition}:[^:]*:[^:]*:[^:]*:([A-Za-z][A-Za-z0-9-]*)(.*)$");
/** A format's resource that is a literal and one variable. */
private static final Pattern ONE_VARIABLE = Pattern.compile("[^$]*\\$\\{\\w+}");
/** 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_.-]+");
/** The one id a child type's format appends to its parent's. */
private static final Pattern APPENDED_ID = Pattern.compile("[/:]\\$\\{\\w+}");
/** The keys a resource found by members does not take: it is read no other way, in the caller's account. */
@@ -169,12 +172,14 @@ final class RequestResourceMembers {
/**
* The file: each operation's resources and the resources it creates under a parent, as
* {@code <namespace>:<Operation>}, each namespace's ARN formats, and the namespaces it reads, those built by
* hand, those not read yet, and the others with resource types.
* {@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.
*/
record Table(Map<String, List<Resource>> operations, Map<String, List<Created>> creates,
Map<String, Map<String, ArnFormat>> formats, Set<String> namespaces, Set<String> handBuilt,
Set<String> notCovered, Set<String> otherNamespaces) {
Map<String, Map<String, String>> located, Map<String, Map<String, ArnFormat>> formats,
Set<String> namespaces, Set<String> handBuilt, Set<String> notCovered, Set<String> otherNamespaces) {
}
private static final class Holder {
@@ -229,6 +234,7 @@ final class RequestResourceMembers {
});
Map<String, List<Resource>> entries = new LinkedHashMap<>();
Map<String, List<Created>> creates = new LinkedHashMap<>();
Map<String, Map<String, String>> located = new LinkedHashMap<>();
operations.properties().forEach(operation -> {
String namespace = operation.getKey().substring(0, Math.max(0, operation.getKey().indexOf(':')));
if (!namespaces.contains(namespace)) {
@@ -247,8 +253,20 @@ final class RequestResourceMembers {
if (!made.isEmpty()) {
creates.put(operation.getKey(), List.copyOf(made));
}
Map<String, String> where = new LinkedHashMap<>();
operation.getValue().path("located").properties().forEach(member -> {
if (!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() + ", no label of a path or query parameter");
}
where.put(member.getKey(), member.getValue().asText());
});
if (!where.isEmpty()) {
located.put(operation.getKey(), Map.copyOf(where));
}
});
return new Table(Map.copyOf(entries), Map.copyOf(creates), Map.copyOf(formats), namespaces,
return new Table(Map.copyOf(entries), Map.copyOf(creates), Map.copyOf(located), Map.copyOf(formats), namespaces,
names(document.path("handBuilt")),
Set.copyOf(document.path("notCovered").propertyStream().map(Map.Entry::getKey).toList()),
names(document.path("otherNamespaces")));
@@ -1,7 +1,10 @@
package io.github.hectorvent.floci.core.common;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.JsonNodeFactory;
import com.fasterxml.jackson.databind.node.ObjectNode;
import jakarta.ws.rs.container.ContainerRequestContext;
import jakarta.ws.rs.core.MultivaluedMap;
import java.util.ArrayList;
import java.util.HashMap;
@@ -79,6 +82,16 @@ public final class RequestResources {
*/
public static List<String> of(String operation, ContainerRequestContext ctx, String partition, String region,
String accountId, StoredResourceArns stored) {
return of(operation, ctx, partition, region, accountId, stored, Map.of());
}
/**
* As {@link #of(String, ContainerRequestContext, String, String, String, StoredResourceArns)}, a member the table
* locates in a REST request's path read from {@code labels}, the value the request's path gives each label of the
* route it was routed by, and one it locates in its query from the request's query parameters.
*/
public static List<String> of(String operation, ContainerRequestContext ctx, String partition, String region,
String accountId, StoredResourceArns stored, Map<String, String> labels) {
RequestResourceMembers.Table table = RequestResourceMembers.table();
List<RequestResourceMembers.Resource> resources = operation == null ? null
: served(table.operations().get(operation), ctx);
@@ -86,7 +99,7 @@ public final class RequestResources {
return List.of();
}
Map<String, String> form = IamConditionContextResolver.formParameters(ctx);
JsonNode body = form.isEmpty() ? PassedRoles.jsonBody(ctx) : null;
JsonNode body = form.isEmpty() ? located(table, operation, PassedRoles.jsonBody(ctx), ctx, labels) : null;
return named(resources, formats(table, operation), form, body, partition, region, accountId, stored);
}
@@ -128,6 +141,15 @@ public final class RequestResources {
*/
public static List<String> created(String operation, ContainerRequestContext ctx, String partition, String region,
String accountId) {
return created(operation, ctx, partition, region, accountId, Map.of());
}
/**
* As {@link #created(String, ContainerRequestContext, String, String, String)}, with the path's labels as for
* {@link #of(String, ContainerRequestContext, String, String, String, StoredResourceArns, Map)}.
*/
public static List<String> created(String operation, ContainerRequestContext ctx, String partition, String region,
String accountId, Map<String, String> labels) {
RequestResourceMembers.Table table = RequestResourceMembers.table();
List<RequestResourceMembers.Created> creates = operation == null ? null : table.creates().get(operation);
List<RequestResourceMembers.Resource> made = operation == null || creates != null ? List.of()
@@ -137,7 +159,7 @@ public final class RequestResources {
return List.of();
}
Map<String, String> form = IamConditionContextResolver.formParameters(ctx);
JsonNode body = form.isEmpty() ? PassedRoles.jsonBody(ctx) : null;
JsonNode body = form.isEmpty() ? located(table, operation, PassedRoles.jsonBody(ctx), ctx, labels) : null;
Map<String, RequestResourceMembers.ArnFormat> formats = formats(table, operation);
if (creates == null) {
return named(made, formats, form, body, partition, region, accountId, null);
@@ -163,6 +185,32 @@ public final class RequestResources {
return List.copyOf(arns);
}
/**
* The request's body with each member the table locates in a REST request's path or query laid over it under the
* member's name, so a resource reads it as it reads a member of the body: a path label's value from {@code labels},
* a query parameter's first value; the body itself when the operation locates none. A located member is read from
* where it is alone, as its handler reads it: one the body also gives is dropped, so a body naming a domain the
* query does not name names nothing.
*/
private static JsonNode located(RequestResourceMembers.Table table, String operation, JsonNode body,
ContainerRequestContext ctx, Map<String, String> labels) {
Map<String, String> located = table.located().getOrDefault(operation, Map.of());
if (located.isEmpty()) {
return body;
}
ObjectNode overlaid = body instanceof ObjectNode object ? object.deepCopy() : JsonNodeFactory.instance.objectNode();
MultivaluedMap<String, String> query = ctx.getUriInfo() == null ? null : ctx.getUriInfo().getQueryParameters();
located.forEach((member, where) -> {
overlaid.remove(member);
String value = where.startsWith("{") ? labels.get(where.substring(1, where.length() - 1))
: query == null ? null : query.getFirst(where.substring(1));
if (value != null) {
overlaid.put(member, value);
}
});
return overlaid;
}
/**
* The resources that apply to a request of the service serving it: one with an {@code endpoint} applies only to
* a request the service of that endpoint prefix serves, read from the claim of the service whose handler runs it
@@ -743,6 +743,21 @@ public class IamActionRegistry {
return null;
}
/**
* The value a REST request's path gives each label of the vendored route it matches, decoded, by the label's
* name; empty when it matches none. {@link RequestResources} reads a member the table of request resources
* locates in the path from them, as {@link #resolveRoute} matches the route.
*/
public static Map<String, String> pathLabels(String credentialScope, ContainerRequestContext ctx) {
IamRestRoutes routes = IamRestRoutes.vendored();
if (credentialScope == null || !routes.routes(credentialScope)) {
return Map.of();
}
return routes.match(credentialScope, ctx.getMethod().toUpperCase(), routedPath(ctx),
ctx.getUriInfo() == null ? null : ctx.getUriInfo().getQueryParameters())
.map(IamRestRoutes.Match::labels).orElse(Map.of());
}
/**
* Whether a request of the operation is checked on the resources AWS checks its action on: those its request
* names, which the vendored request resources read for the operation ({@link RequestResources#reads}) or
@@ -7,6 +7,8 @@ import jakarta.ws.rs.core.MultivaluedMap;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
@@ -52,8 +54,15 @@ final class IamRestRoutes {
private static final int ONE_SEGMENT = 1;
private static final int REST_OF_PATH = 0;
/** A route: its operation, its path as a pattern, each segment's rank, and the query it names. */
private record Route(String operation, Pattern path, int[] ranks, Map<String, String> query) {
/** A route a request matched: its operation, and the value its path gives each of the route's labels, decoded. */
record Match(String operation, Map<String, String> labels) {
}
/**
* A route: its operation, its path as a pattern capturing each label in turn, the labels' names, each segment's
* rank, and the query it names.
*/
private record Route(String operation, Pattern path, List<String> labels, int[] ranks, Map<String, String> query) {
boolean matches(String requestPath, MultivaluedMap<String, String> parameters) {
if (!path.matcher(requestPath).matches()) {
@@ -68,6 +77,20 @@ final class IamRestRoutes {
return true;
}
/** The value the path gives each label, decoded as the router decodes a path parameter. */
Map<String, String> labelValues(String requestPath) {
Matcher matcher = path.matcher(requestPath);
if (!matcher.matches()) {
return Map.of();
}
Map<String, String> values = new LinkedHashMap<>();
for (int i = 0; i < labels.size(); i++) {
values.put(labels.get(i), URLDecoder.decode(matcher.group(i + 1).replace("+", "%2B"),
StandardCharsets.UTF_8));
}
return Map.copyOf(values);
}
/** Whether this route is more specific than the other, as {@link IamRestRoutes} orders them. */
boolean outranks(Route other) {
int compared = Arrays.compare(ranks, other.ranks);
@@ -97,6 +120,11 @@ final class IamRestRoutes {
* matches several; empty when it matches none, or its scope is one the file does not route.
*/
Optional<String> operation(String scope, String method, String path, MultivaluedMap<String, String> query) {
return match(scope, method, path, query).map(Match::operation);
}
/** As {@link #operation}, with the values the request's path gives the route's labels. */
Optional<Match> match(String scope, String method, String path, MultivaluedMap<String, String> query) {
String requestPath = IamActionRegistry.withoutTrailingSlash(path);
Route best = null;
for (Route route : routes.getOrDefault(scope, Map.of()).getOrDefault(method, List.of())) {
@@ -104,7 +132,12 @@ final class IamRestRoutes {
best = route;
}
}
return best == null ? Optional.empty() : Optional.of(best.operation());
return best == null ? Optional.empty() : Optional.of(new Match(best.operation(), best.labelValues(requestPath)));
}
/** Whether the file routes any request of the credential scope. */
boolean routes(String scope) {
return routes.containsKey(scope);
}
static IamRestRoutes parse(InputStream in) throws IOException {
@@ -153,12 +186,14 @@ final class IamRestRoutes {
String path = IamActionRegistry.withoutTrailingSlash(question < 0 ? requestUri : requestUri.substring(0, question));
List<String> segments = path.equals("/") ? List.of() : List.of(path.substring(1).split("/", -1));
StringBuilder pattern = new StringBuilder();
List<String> labels = new ArrayList<>();
int[] ranks = new int[segments.size()];
for (int i = 0; i < segments.size(); i++) {
String segment = segments.get(i);
pattern.append('/');
if (GREEDY.matcher(segment).matches()) {
pattern.append(".+");
pattern.append("(.+)");
labels.add(segment.substring(1, segment.length() - 2));
ranks[i] = REST_OF_PATH;
continue;
}
@@ -166,7 +201,8 @@ final class IamRestRoutes {
int literalFrom = 0;
boolean labelled = false;
while (label.find()) {
pattern.append(Pattern.quote(segment.substring(literalFrom, label.start()))).append("[^/]+");
pattern.append(Pattern.quote(segment.substring(literalFrom, label.start()))).append("([^/]+)");
labels.add(segment.substring(label.start() + 1, label.end() - 1));
literalFrom = label.end();
labelled = true;
}
@@ -181,7 +217,7 @@ final class IamRestRoutes {
equals < 0 ? "" : parameter.substring(equals + 1));
}
}
return new Route(operation, Pattern.compile(pattern.isEmpty() ? "/" : pattern.toString()), ranks,
Map.copyOf(query));
return new Route(operation, Pattern.compile(pattern.isEmpty() ? "/" : pattern.toString()), List.copyOf(labels),
ranks, Map.copyOf(query));
}
}
@@ -229,7 +229,8 @@ public class ResourceArnBuilder {
private List<String> namedResources(String credentialScope, String operation, ContainerRequestContext ctx,
String region, String accountId, String partition) {
List<String> named = operation == null || !operation.startsWith(credentialScope + ":") ? List.of()
: RequestResources.of(operation, ctx, partition, region, accountId, storedResourceArns(credentialScope));
: RequestResources.of(operation, ctx, partition, region, accountId, storedResourceArns(credentialScope),
IamActionRegistry.pathLabels(credentialScope, ctx));
return named.isEmpty() ? List.of("*") : named;
}