mirror of
https://github.com/floci-io/floci.git
synced 2026-12-02 09:47:56 -05:00
feat(iam): check REST routes no rule maps by botocore's models (#7461)
A REST request gets its IAM action from IamActionRegistry's hand-written rules, and a route no rule maps gets none, which the caller allows: under enforcement such a request runs unchecked. IamRestRoutes (#7085) reads botocore's routes at runtime, but only for the operations a hand-written list enrolls, ValidatePolicy alone, and only by literal paths. A request no rule maps is now the operation whose route in botocore's model it matches, and it is checked as that operation's action (IamAuthorizedActions), as a Query or JSON request naming its operation is, when Floci checks it on the resources AWS does: those its request names, which ResourceArnBuilder builds for its namespace or the vendored request resources read for the operation, or none, when the Service Reference gives the action no resource type, as AWS authorizes such an action on `*`. An action AWS checks on a resource Floci neither builds nor reads stays unchecked, as before: checked on `*`, a grant scoped to its resource would be refused. That is the reason #7085 gave for enrolling ValidatePolicy alone, now read from generated data instead of a list. - The actions of no resource type come from the Service Reference's Actions, through regen_iam_authorized_actions.py, into iam-authorized-actions.json, for each credential scope whose routes rest-routes.json reads: 88 over 7 scopes. They are read from Actions, not Operations, because the reference lists one SDK client's operations per namespace, OpenSearch's `es` client alone. --check fails until a scope rest-routes.json adds is listed, and --verify fails when AWS gives a listed action a resource type. - IamRestRoutes now matches every route of a model: literal segments, a label taking one segment, a greedy label the rest of the path, and the query a route names, which must be on the request. Of the routes a request matches, the most specific wins, segment by segment from the left a literal, then a segment mixing a literal and a label, then a label, then a greedy label; then the route naming more of the query. The path is the one the rules match, still percent-encoded and without a trailing slash, and a segment may still end in a matrix parameter, which the router ignores. - The rules come first, so nothing they map changes. S3 and API Gateway are listed as handRouted, with their reasons, and routed by their rules alone: S3 tells apart the operations of one route by their query and headers, and API Gateway is checked by HTTP method. The route generator fails when one route names two operations of any other scope. - OpenSearch Service's models, both API versions, are read under `es`: 59 of their 147 operations are checked by their routes (29 of the `es` model's 51, 30 of the `opensearch` model's 96), 53 of which ran unchecked, ListDomainNames and ListVersions among them. The other six are the VPC endpoint operations #7351 mapped by hand: their rules are removed, as their routes give the same actions. - Access Analyzer's 9 operations of no resource type are checked by their routes, ListAnalyzers among those Floci serves, where ValidatePolicy alone was; its analyzer operations are not. Lambda's, EKS's, Scheduler's, Pipes' and DSQL's resources are built by hand and their routes all mapped by their rules, so none is checked differently. IamRestRouteCoverageTest checks every route of a scope not hand-routed: by the vendored routes alone it is its own operation, and through the registry it is its action when its resources are built by hand or read, or its action has no resource type, and unmapped otherwise. iam.md and access-analyzer.md say which routes are checked.
This commit is contained in:
1 parent
5a4632229e
commit
251bb39375
18 files changed
+1178
-173
No files matched your search
@@ -55,6 +55,11 @@ public final class RequestResources {
|
||||
return operation != null && RequestResourceMembers.table().operations().containsKey(operation);
|
||||
}
|
||||
|
||||
/** Whether {@code ResourceArnBuilder} builds the resources of this namespace's requests itself. */
|
||||
public static boolean builtByHand(String namespace) {
|
||||
return namespace != null && RequestResourceMembers.table().handBuilt().contains(namespace);
|
||||
}
|
||||
|
||||
/**
|
||||
* The ARNs of the resources a request names, in the request's partition, Region and account: empty when the
|
||||
* table does not read the operation or its request names none, so it is checked on {@code *}. The operation,
|
||||
|
||||
@@ -4,6 +4,7 @@ import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import io.github.hectorvent.floci.core.common.AwsProtocolClaimFilter;
|
||||
import io.github.hectorvent.floci.core.common.AwsQueryServiceResolver;
|
||||
import io.github.hectorvent.floci.core.common.ProtocolClaim;
|
||||
import io.github.hectorvent.floci.core.common.RequestResources;
|
||||
import io.github.hectorvent.floci.core.common.WireProtocol;
|
||||
import io.github.hectorvent.floci.services.dynamodb.DynamoDbPartiQLParser;
|
||||
import io.github.hectorvent.floci.services.eks.EksController;
|
||||
@@ -23,6 +24,7 @@ import java.net.URLDecoder;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
/**
|
||||
@@ -32,7 +34,9 @@ import java.util.regex.Pattern;
|
||||
* parameter, or the controller's Operation fallback, is mapped directly to
|
||||
* {@code <service>:<Action>}.
|
||||
*
|
||||
* For REST-JSON services the first matching rule wins (specific before wildcard).
|
||||
* For REST-JSON services the first matching rule wins (specific before wildcard), and a request no
|
||||
* rule matches is the operation whose route in botocore's model it matches ({@link IamRestRoutes}),
|
||||
* when Floci can check that operation as AWS does.
|
||||
*/
|
||||
@ApplicationScoped
|
||||
public class IamActionRegistry {
|
||||
@@ -46,6 +50,16 @@ public class IamActionRegistry {
|
||||
private static final Logger LOG = Logger.getLogger(IamActionRegistry.class);
|
||||
private static final ObjectMapper MAPPER = new ObjectMapper();
|
||||
|
||||
private final IamRestRoutes restRoutes;
|
||||
|
||||
public IamActionRegistry() {
|
||||
this(IamRestRoutes.vendored());
|
||||
}
|
||||
|
||||
IamActionRegistry(IamRestRoutes restRoutes) {
|
||||
this.restRoutes = restRoutes;
|
||||
}
|
||||
|
||||
/**
|
||||
* A route and the action it is checked as. A rule naming a query parameter matches only a request
|
||||
* carrying it with that value, as {@code GET /layers?find=LayerVersion} is GetLayerVersionByArn
|
||||
@@ -558,15 +572,6 @@ public class IamActionRegistry {
|
||||
rule("ses", "POST", "^/v2/email/update-configuration-sets/?$", "ses:UpdateConfigurationSet"),
|
||||
rule("ses", "POST", "^/v2/email/vdm/recommendations/?$", "ses:ListRecommendations"),
|
||||
|
||||
// ── OpenSearch Service VPC endpoints ───────────────────────────────────
|
||||
rule("es", "POST", "^/2021-01-01/opensearch/vpcEndpoints/?$", "es:CreateVpcEndpoint"),
|
||||
rule("es", "GET", "^/2021-01-01/opensearch/vpcEndpoints/?$", "es:ListVpcEndpoints"),
|
||||
rule("es", "POST", "^/2021-01-01/opensearch/vpcEndpoints/describe/?$", "es:DescribeVpcEndpoints"),
|
||||
rule("es", "POST", "^/2021-01-01/opensearch/vpcEndpoints/update/?$", "es:UpdateVpcEndpoint"),
|
||||
rule("es", "DELETE", "^/2021-01-01/opensearch/vpcEndpoints/[^/]+/?$", "es:DeleteVpcEndpoint"),
|
||||
rule("es", "GET", "^/2021-01-01/opensearch/domain/[^/]+/vpcEndpoints/?$",
|
||||
"es:ListVpcEndpointsForDomain"),
|
||||
|
||||
// ── Resource Groups ─────────────────────────────────────────────────────
|
||||
rule("resource-groups", "POST", "^/_rg/groups/?$", "resource-groups:CreateGroup"),
|
||||
rule("resource-groups", "POST", "^/_rg/get-group/?$", "resource-groups:GetGroup"),
|
||||
@@ -626,7 +631,8 @@ public class IamActionRegistry {
|
||||
* For JSON 1.1 protocol the action comes from {@code X-Amz-Target}
|
||||
* (e.g. {@code DynamoDB_20120810.PutItem} → {@code dynamodb:PutItem}).
|
||||
*
|
||||
* For REST-JSON services the action is derived from the path rule table.
|
||||
* For REST-JSON services the action is derived from the path rule table, or else from the
|
||||
* operation whose botocore route the request matches.
|
||||
*
|
||||
* Returns {@code null} when the action is unknown (caller treats this as ALLOW).
|
||||
*/
|
||||
@@ -685,17 +691,19 @@ public class IamActionRegistry {
|
||||
* so the route's rule would not match and the call would pass as an unknown action. It is read
|
||||
* from the request URI because RESTEasy Reactive does not serve {@code UriInfo.getPath(false)}.
|
||||
*
|
||||
* <p>Returns {@code null} when no rule matches (caller treats this as ALLOW).
|
||||
* <p>A request no rule matches is the operation whose route, in botocore's model of its service, it
|
||||
* matches, and is checked as that operation's action ({@link IamAuthorizedActions#actionFor}), as a
|
||||
* request naming its operation is, when Floci can check it as AWS does ({@code checkedAsAws}). One it
|
||||
* cannot is left unmapped rather than checked on {@code *}, which would refuse a grant scoped to the
|
||||
* resource AWS checks it on. The scopes the vendored routes list as hand-routed, S3's and API Gateway's,
|
||||
* have their rules alone. Returns {@code null} when nothing maps the request (caller treats this as
|
||||
* ALLOW).
|
||||
*/
|
||||
public String resolveRoute(String credentialScope, ContainerRequestContext ctx) {
|
||||
String method = ctx.getMethod().toUpperCase();
|
||||
// An S3 key may end in a slash, PUT /bucket// writes the key "/", and S3's rules already take a
|
||||
// bucket's one trailing slash, so an S3 path is matched as sent.
|
||||
String path = "s3".equals(credentialScope) ? sentPath(ctx.getUriInfo()) : routedPath(ctx);
|
||||
String modeled = IamRestRoutes.actionFor(credentialScope, method, path);
|
||||
if (modeled != null) {
|
||||
return modeled;
|
||||
}
|
||||
|
||||
if ("s3".equals(credentialScope)) {
|
||||
// An S3 Control route is matched before the query overrides below, which would read the
|
||||
@@ -722,11 +730,32 @@ public class IamActionRegistry {
|
||||
return rule.action();
|
||||
}
|
||||
}
|
||||
Optional<String> operation = restRoutes.operation(credentialScope, method, path,
|
||||
ctx.getUriInfo() == null ? null : ctx.getUriInfo().getQueryParameters());
|
||||
if (operation.isPresent()) {
|
||||
String action = IamAuthorizedActions.actionFor(credentialScope, operation.get());
|
||||
if (checkedAsAws(credentialScope, operation.get(), action)) {
|
||||
return action;
|
||||
}
|
||||
}
|
||||
|
||||
LOG.debugv("No action mapping for {0} {1} {2} — defaulting to ALLOW", credentialScope, method, path);
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 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
|
||||
* {@code ResourceArnBuilder} builds for its namespace ({@link RequestResources#builtByHand}), or {@code *}
|
||||
* when AWS authorizes the action on no resource type ({@link IamAuthorizedActions#actsOnNoResourceType}), so
|
||||
* none of the resources in the request's path is needed.
|
||||
*/
|
||||
private static boolean checkedAsAws(String credentialScope, String operation, String action) {
|
||||
return RequestResources.reads(credentialScope + ":" + operation)
|
||||
|| RequestResources.builtByHand(credentialScope)
|
||||
|| IamAuthorizedActions.actsOnNoResourceType(action);
|
||||
}
|
||||
|
||||
/**
|
||||
* The path the router matched, relative to the application root. A request no filter rewrote is matched
|
||||
* on its normalized path, still percent-encoded but with encoded unreserved characters such as {@code %2E}
|
||||
@@ -781,11 +810,16 @@ public class IamActionRegistry {
|
||||
* unknown action.
|
||||
*/
|
||||
static String routedPath(ContainerRequestContext ctx) {
|
||||
String path = rawPath(ctx);
|
||||
while (path.length() > 1 && path.endsWith("/")) {
|
||||
path = path.substring(0, path.length() - 1);
|
||||
return withoutTrailingSlash(rawPath(ctx));
|
||||
}
|
||||
|
||||
/** The path without its trailing slashes, the root's own kept. */
|
||||
static String withoutTrailingSlash(String path) {
|
||||
String trimmed = path;
|
||||
while (trimmed.length() > 1 && trimmed.endsWith("/")) {
|
||||
trimmed = trimmed.substring(0, trimmed.length() - 1);
|
||||
}
|
||||
return path;
|
||||
return trimmed;
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -6,7 +6,9 @@ import io.github.hectorvent.floci.core.common.VendoredResources;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.util.HashSet;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.Locale;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
|
||||
@@ -34,6 +36,10 @@ import java.util.Set;
|
||||
* authorizes under a name other than the IAM namespace matches nothing here, and its operations keep
|
||||
* their own names.
|
||||
*
|
||||
* <p>The file also lists, for each credential scope whose REST routes {@code aws/rest-routes.json} reads, the
|
||||
* actions the Service Reference gives no resource type ({@link #actsOnNoResourceType}): AWS authorizes them on
|
||||
* {@code *}, which is what Floci checks a REST request on until it reads the resources in its path.
|
||||
*
|
||||
* <p>A missing or malformed resource is a build defect, not a runtime condition, so loading fails
|
||||
* with {@link IllegalStateException} rather than degrading to an empty map, which would silently put
|
||||
* every operation back on its own name.
|
||||
@@ -56,9 +62,16 @@ public final class IamAuthorizedActions {
|
||||
|
||||
private static final ObjectMapper MAPPER = new ObjectMapper();
|
||||
|
||||
/**
|
||||
* The file: the action of each operation it names, keyed by {@code <namespace>:<Operation>}, and the actions of
|
||||
* no resource type, as {@code <namespace>:<Action>} in lower case.
|
||||
*/
|
||||
record Table(Map<String, String> actions, Set<String> withoutResourceTypes) {
|
||||
}
|
||||
|
||||
private static final class Holder {
|
||||
static final Map<String, String> ACTIONS = VendoredResources.read(RESOURCE_NAME,
|
||||
"IAM authorized action map", IamAuthorizedActions::parse);
|
||||
static final Table TABLE = VendoredResources.read(RESOURCE_NAME, "IAM authorized action map",
|
||||
IamAuthorizedActions::parse);
|
||||
}
|
||||
|
||||
private IamAuthorizedActions() {
|
||||
@@ -73,12 +86,22 @@ public final class IamAuthorizedActions {
|
||||
if (KEPT_FOR_ITEM_CHECKS.contains(own)) {
|
||||
return own;
|
||||
}
|
||||
return Holder.ACTIONS.getOrDefault(own, own);
|
||||
return Holder.TABLE.actions().getOrDefault(own, own);
|
||||
}
|
||||
|
||||
/** The file's entries, keyed by {@code <namespace>:<Operation>}. */
|
||||
static Map<String, String> parse(InputStream in) throws IOException {
|
||||
JsonNode namespaces = MAPPER.readTree(in).path("authorizedActions");
|
||||
/**
|
||||
* Whether AWS authorizes {@code action}, as {@code <namespace>:<Action>}, on no resource type: one the file lists
|
||||
* for a credential scope whose REST routes are read, matched without regard to case, as IAM matches action
|
||||
* names. An action of any other scope is not known here, so is not one.
|
||||
*/
|
||||
public static boolean actsOnNoResourceType(String action) {
|
||||
return action != null && Holder.TABLE.withoutResourceTypes().contains(action.toLowerCase(Locale.ROOT));
|
||||
}
|
||||
|
||||
/** The file's entries. */
|
||||
static Table parse(InputStream in) throws IOException {
|
||||
JsonNode document = MAPPER.readTree(in);
|
||||
JsonNode namespaces = document.path("authorizedActions");
|
||||
if (!namespaces.isObject() || namespaces.isEmpty()) {
|
||||
throw new IllegalStateException(RESOURCE_NAME + " carries no authorizedActions");
|
||||
}
|
||||
@@ -99,6 +122,28 @@ public final class IamAuthorizedActions {
|
||||
actions.put(namespace.getKey() + ":" + operation.getKey(), action);
|
||||
});
|
||||
});
|
||||
return Map.copyOf(actions);
|
||||
return new Table(Map.copyOf(actions), withoutResourceTypes(document.path("actionsWithoutResourceTypes")));
|
||||
}
|
||||
|
||||
/** The actions of no resource type, each scope's a list of action names. */
|
||||
private static Set<String> withoutResourceTypes(JsonNode scopes) {
|
||||
if (!scopes.isObject()) {
|
||||
throw new IllegalStateException(RESOURCE_NAME + " carries no actionsWithoutResourceTypes");
|
||||
}
|
||||
Set<String> actions = new HashSet<>();
|
||||
scopes.properties().forEach(scope -> {
|
||||
if (!scope.getValue().isArray()) {
|
||||
throw new IllegalStateException(RESOURCE_NAME + " has actionsWithoutResourceTypes."
|
||||
+ scope.getKey() + " as something other than a list");
|
||||
}
|
||||
scope.getValue().forEach(action -> {
|
||||
if (!action.isTextual() || action.textValue().isBlank()) {
|
||||
throw new IllegalStateException(RESOURCE_NAME + " lists " + action + " among "
|
||||
+ scope.getKey() + "'s actions without resource types");
|
||||
}
|
||||
actions.add((scope.getKey() + ":" + action.textValue()).toLowerCase(Locale.ROOT));
|
||||
});
|
||||
});
|
||||
return Set.copyOf(actions);
|
||||
}
|
||||
}
|
||||
@@ -3,88 +3,185 @@ 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 jakarta.ws.rs.core.MultivaluedMap;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.HashMap;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.Set;
|
||||
import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
/** Runtime IAM routes read from the pinned botocore snapshot. */
|
||||
/**
|
||||
* The routes of the REST operations botocore models, read once from the vendored {@code aws/rest-routes.json}:
|
||||
* the operation a REST request is, from its method, its path and the query its route requires, for a request
|
||||
* {@link IamActionRegistry}'s rules give no action.
|
||||
*
|
||||
* <p>A route is its operation's {@code requestUri}: literal segments, a {@code {label}} taking one segment, and a
|
||||
* greedy {@code {label+}} taking the rest of the path, and a query it names ({@code ?tagging},
|
||||
* {@code ?list-type=2}) must be on the request, with that value when it gives one. A request is matched on its path
|
||||
* as the router matched it, still percent-encoded and without a trailing {@code /}, so an encoded {@code /} stays
|
||||
* inside its label. A segment may end in a matrix parameter ({@code ;name=value}), which the router ignores: the
|
||||
* path it routed carries none, and one read from the request URI still matches. Of the routes a request matches, it
|
||||
* is the most specific one's operation: compared segment by segment from the left, a literal before a segment mixing
|
||||
* a literal and a label, before a label, before a greedy label, then the route naming more of the query.
|
||||
*
|
||||
* <p>The file is generated by {@code tools/aws/regen_rest_routes.py}, which fails when one route names two
|
||||
* operations of a credential scope read here. The scopes it lists as {@code handRouted} are not read: the
|
||||
* registry's rules authorize them alone. A missing or malformed resource is a build defect, so loading fails with
|
||||
* {@link IllegalStateException} rather than leaving every route it holds unchecked.
|
||||
*/
|
||||
final class IamRestRoutes {
|
||||
private static final String RESOURCE = "aws/rest-routes.json";
|
||||
// Enroll operations independently of their HTTP spelling or IAM namespace. Analyzer CRUD
|
||||
// needs resource-ARN resolution before it can join this stateless operation.
|
||||
private static final Map<String, Set<String>> ENROLLED_OPERATIONS =
|
||||
Map.of("accessanalyzer", Set.of("ValidatePolicy"));
|
||||
private static final Set<String> METHODS = Set.of("GET", "POST", "PUT", "DELETE", "PATCH", "HEAD", "OPTIONS");
|
||||
private static final ObjectMapper MAPPER = new ObjectMapper();
|
||||
|
||||
private record Route(String scope, String method, Pattern path, String action) {}
|
||||
static final String RESOURCE_NAME = "aws/rest-routes.json";
|
||||
|
||||
private static final ObjectMapper MAPPER = new ObjectMapper();
|
||||
private static final Pattern LABEL = Pattern.compile("\\{[^}]+}");
|
||||
private static final Pattern GREEDY = Pattern.compile("\\{[^}]+\\+}");
|
||||
private static final String MATRIX = "(?:;[^/]*)?";
|
||||
private static final Set<String> METHODS = Set.of("GET", "POST", "PUT", "DELETE", "PATCH", "HEAD", "OPTIONS");
|
||||
|
||||
private static final int LITERAL = 3;
|
||||
private static final int MIXED = 2;
|
||||
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) {
|
||||
|
||||
boolean matches(String requestPath, MultivaluedMap<String, String> parameters) {
|
||||
if (!path.matcher(requestPath).matches()) {
|
||||
return false;
|
||||
}
|
||||
for (Map.Entry<String, String> parameter : query.entrySet()) {
|
||||
String value = parameters == null ? null : parameters.getFirst(parameter.getKey());
|
||||
if (value == null || !parameter.getValue().isEmpty() && !parameter.getValue().equals(value)) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
/** 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);
|
||||
return compared != 0 ? compared > 0 : query.size() > other.query.size();
|
||||
}
|
||||
}
|
||||
|
||||
private static final class Holder {
|
||||
static final IamRestRoutes TABLE = VendoredResources.read(RESOURCE, "IAM REST routes", IamRestRoutes::parse);
|
||||
static final IamRestRoutes VENDORED = VendoredResources.read(RESOURCE_NAME, "REST route table",
|
||||
IamRestRoutes::parse);
|
||||
}
|
||||
|
||||
private final List<Route> routes;
|
||||
/** Each credential scope's routes, by method. */
|
||||
private final Map<String, Map<String, List<Route>>> routes;
|
||||
|
||||
private IamRestRoutes(List<Route> routes) {
|
||||
this.routes = List.copyOf(routes);
|
||||
private IamRestRoutes(Map<String, Map<String, List<Route>>> routes) {
|
||||
this.routes = routes;
|
||||
}
|
||||
|
||||
static String actionFor(String scope, String method, String path) {
|
||||
return Holder.TABLE.resolve(scope, method, path);
|
||||
/** The vendored routes. */
|
||||
static IamRestRoutes vendored() {
|
||||
return Holder.VENDORED;
|
||||
}
|
||||
|
||||
String resolve(String scope, String method, String path) {
|
||||
for (Route route : routes) {
|
||||
if (route.scope().equals(scope) && route.method().equals(method) && route.path().matcher(path).matches()) {
|
||||
return route.action();
|
||||
/**
|
||||
* The operation whose route a request of the credential scope matches, the most specific one's when it
|
||||
* 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) {
|
||||
String requestPath = IamActionRegistry.withoutTrailingSlash(path);
|
||||
Route best = null;
|
||||
for (Route route : routes.getOrDefault(scope, Map.of()).getOrDefault(method, List.of())) {
|
||||
if (route.matches(requestPath, query) && (best == null || route.outranks(best))) {
|
||||
best = route;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
return best == null ? Optional.empty() : Optional.of(best.operation());
|
||||
}
|
||||
|
||||
static IamRestRoutes parse(InputStream in) throws IOException {
|
||||
JsonNode root = MAPPER.readTree(in);
|
||||
if (root == null || !root.path("models").isObject()) {
|
||||
throw new IOException("Missing REST route models");
|
||||
JsonNode document = MAPPER.readTree(in);
|
||||
JsonNode handRouted = document == null ? null : document.path("handRouted");
|
||||
JsonNode models = document == null ? null : document.path("models");
|
||||
if (handRouted == null || !handRouted.isObject() || !models.isObject() || models.isEmpty()) {
|
||||
throw new IllegalStateException(RESOURCE_NAME + " carries no handRouted scopes or no models");
|
||||
}
|
||||
List<Route> routes = new ArrayList<>();
|
||||
for (Map.Entry<String, Set<String>> enrolled : ENROLLED_OPERATIONS.entrySet()) {
|
||||
JsonNode model = root.path("models").path(enrolled.getKey());
|
||||
String scope = text(model, "credentialScope");
|
||||
for (String operation : enrolled.getValue()) {
|
||||
JsonNode http = model.path("operations").path(operation);
|
||||
String method = text(http, "method");
|
||||
String uri = text(http, "requestUri");
|
||||
if (!METHODS.contains(method) || !uri.startsWith("/") || uri.contains("{")
|
||||
|| uri.contains("}") || uri.contains("?") || uri.contains("#") || uri.contains(";")) {
|
||||
throw new IOException("Enrolled REST operation must have a supported method and literal path: "
|
||||
+ enrolled.getKey() + ":" + operation);
|
||||
Set<String> skipped = Set.copyOf(handRouted.propertyStream().map(Map.Entry::getKey).toList());
|
||||
Map<String, Map<String, List<Route>>> routes = new HashMap<>();
|
||||
models.properties().forEach(model -> {
|
||||
String scope = model.getValue().path("credentialScope").asText("");
|
||||
JsonNode operations = model.getValue().path("operations");
|
||||
if (scope.isEmpty() || !operations.isObject() || operations.isEmpty()) {
|
||||
throw new IllegalStateException(RESOURCE_NAME + " gives model " + model.getKey()
|
||||
+ " no credential scope or no operations");
|
||||
}
|
||||
if (skipped.contains(scope)) {
|
||||
return;
|
||||
}
|
||||
operations.properties().forEach(operation -> {
|
||||
String method = operation.getValue().path("method").asText("");
|
||||
String requestUri = operation.getValue().path("requestUri").asText("");
|
||||
if (!METHODS.contains(method) || !requestUri.startsWith("/")) {
|
||||
throw new IllegalStateException(RESOURCE_NAME + " gives " + model.getKey() + " "
|
||||
+ operation.getKey() + " no HTTP method or no request URI");
|
||||
}
|
||||
routes.add(new Route(scope, method, literalPath(uri), IamAuthorizedActions.actionFor(scope, operation)));
|
||||
routes.computeIfAbsent(scope, ignored -> new HashMap<>())
|
||||
.computeIfAbsent(method, ignored -> new ArrayList<>())
|
||||
.add(route(operation.getKey(), requestUri));
|
||||
});
|
||||
});
|
||||
Map<String, Map<String, List<Route>>> copied = new HashMap<>();
|
||||
routes.forEach((scope, byMethod) -> {
|
||||
Map<String, List<Route>> methods = new HashMap<>();
|
||||
byMethod.forEach((method, list) -> methods.put(method, List.copyOf(list)));
|
||||
copied.put(scope, Map.copyOf(methods));
|
||||
});
|
||||
return new IamRestRoutes(Map.copyOf(copied));
|
||||
}
|
||||
|
||||
/** A route of the operation from its request URI, its path's segments and the query after its {@code ?}. */
|
||||
private static Route route(String operation, String requestUri) {
|
||||
int question = requestUri.indexOf('?');
|
||||
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();
|
||||
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(".+");
|
||||
ranks[i] = REST_OF_PATH;
|
||||
continue;
|
||||
}
|
||||
Matcher label = LABEL.matcher(segment);
|
||||
int literalFrom = 0;
|
||||
boolean labelled = false;
|
||||
while (label.find()) {
|
||||
pattern.append(Pattern.quote(segment.substring(literalFrom, label.start()))).append("[^/]+");
|
||||
literalFrom = label.end();
|
||||
labelled = true;
|
||||
}
|
||||
pattern.append(Pattern.quote(segment.substring(literalFrom))).append(MATRIX);
|
||||
ranks[i] = !labelled ? LITERAL : LABEL.matcher(segment).matches() ? ONE_SEGMENT : MIXED;
|
||||
}
|
||||
Map<String, String> query = new LinkedHashMap<>();
|
||||
if (question >= 0) {
|
||||
for (String parameter : requestUri.substring(question + 1).split("&")) {
|
||||
int equals = parameter.indexOf('=');
|
||||
query.put(equals < 0 ? parameter : parameter.substring(0, equals),
|
||||
equals < 0 ? "" : parameter.substring(equals + 1));
|
||||
}
|
||||
}
|
||||
return new IamRestRoutes(routes);
|
||||
}
|
||||
|
||||
private static Pattern literalPath(String uri) {
|
||||
StringBuilder pattern = new StringBuilder("^");
|
||||
for (String segment : uri.substring(1).split("/", -1)) {
|
||||
// RESTEasy can retain ignored matrix suffixes in the path it matched.
|
||||
pattern.append('/').append(Pattern.quote(segment)).append("(?:;[^/]*)?");
|
||||
}
|
||||
return Pattern.compile(pattern.append('$').toString());
|
||||
}
|
||||
|
||||
private static String text(JsonNode node, String name) throws IOException {
|
||||
JsonNode value = node.path(name);
|
||||
if (!value.isTextual() || value.textValue().isBlank()) {
|
||||
throw new IOException("Missing REST route field: " + name);
|
||||
}
|
||||
return value.textValue();
|
||||
return new Route(operation, Pattern.compile(pattern.isEmpty() ? "/" : pattern.toString()), ranks,
|
||||
Map.copyOf(query));
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user