mirror of
https://github.com/floci-io/floci.git
synced 2026-11-22 21:50:46 -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
@@ -37,8 +37,10 @@
|
||||
# src/main/resources/aws/emr-serverless-shapes.json, the shapes the Step Functions emr-serverless
|
||||
# integrations recase against, is generated from botocore's EMR Serverless model by
|
||||
# tools/aws/regen_emr_serverless_shapes.py.
|
||||
# src/main/resources/aws/rest-routes.json, the routes read by runtime IAM authorization and
|
||||
# IamRestRouteCoverageTest, is generated from botocore's models by tools/aws/regen_rest_routes.py.
|
||||
# src/main/resources/aws/rest-routes.json, the REST routes IamActionRegistry checks a request no rule
|
||||
# maps by, and IamRestRouteCoverageTest checks the rules against, is generated from botocore's models
|
||||
# by tools/aws/regen_rest_routes.py. A model it adds also needs make iam-authorized-actions-sync, whose
|
||||
# check fails until the actions of no resource type list the model's scope.
|
||||
# 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.
|
||||
|
||||
@@ -478,7 +480,8 @@ IAM_NAMESPACES_PATHS := src/main/resources/aws/iam-service-namespaces.json \
|
||||
IAM_ACTION_RESOURCES_PATHS := src/main/resources/aws/iam-action-resources.json \
|
||||
tools/aws/regen_iam_action_resources.py tools/aws/test_regen_iam_action_resources.py
|
||||
IAM_AUTHORIZED_ACTIONS_PATHS := src/main/resources/aws/iam-authorized-actions.json \
|
||||
tools/aws/regen_iam_authorized_actions.py tools/aws/test_regen_iam_authorized_actions.py
|
||||
tools/aws/regen_iam_authorized_actions.py tools/aws/test_regen_iam_authorized_actions.py \
|
||||
src/main/resources/aws/rest-routes.json
|
||||
IAM_PASSED_ROLES_PATHS := src/main/resources/aws/iam-passed-roles.json $(IAM_PASSED_ROLES_GENERATOR) \
|
||||
tools/aws/test_regen_iam_passed_roles.py
|
||||
IAM_PASSED_NETWORK_CONNECTORS_PATHS := src/main/resources/aws/iam-passed-network-connectors.json \
|
||||
|
||||
@@ -22,7 +22,7 @@ Analyzer state is account and Region scoped and persisted through `StorageFactor
|
||||
|
||||
## Policy validation
|
||||
|
||||
`ValidatePolicy` accepts a JSON policy string at `POST /policy/validation`. It does not require an analyzer, persist the submitted policy, or change permissions. It supports `IDENTITY_POLICY`, `RESOURCE_POLICY`, `SERVICE_CONTROL_POLICY`, and `RESOURCE_CONTROL_POLICY` requests. With IAM enforcement enabled, callers need `access-analyzer:ValidatePolicy` on `Resource: "*"`.
|
||||
`ValidatePolicy` accepts a JSON policy string at `POST /policy/validation`. It does not require an analyzer, persist the submitted policy, or change permissions. It supports `IDENTITY_POLICY`, `RESOURCE_POLICY`, `SERVICE_CONTROL_POLICY`, and `RESOURCE_CONTROL_POLICY` requests. With IAM enforcement enabled, callers need `access-analyzer:ValidatePolicy` on `Resource: "*"`, and `ListAnalyzers` needs `access-analyzer:ListAnalyzers` the same way, both actions AWS authorizes on no resource. The analyzer operations, which AWS authorizes on the analyzer, are not checked yet.
|
||||
|
||||
The local checks cover malformed JSON, repeated object keys, document and statement shapes, required elements, mutually exclusive elements, policy versions, duplicate statement identifiers, principal key names, condition operator names, and selected empty-value suggestions. Resource policies accept the API's supported `validatePolicyResourceType` values; the IAM trust-policy type permits statements without a resource element. Generic resource policies containing trust actions use the same trust-policy context. `BinaryEquals` is recognized as policy syntax, but Floci's IAM evaluator does not execute it.
|
||||
|
||||
|
||||
+19
-2
@@ -1851,8 +1851,25 @@ it is signed with. The ARN is
|
||||
the one after `/tags/` or `/v1/tags/`, the body's `resourceArn` on `POST /tags`, and the
|
||||
`resourceArn` query parameter on the other bare routes.
|
||||
|
||||
A route no rule maps is not checked, as an unsigned REST request is not; the other REST services'
|
||||
routes are not mapped yet.
|
||||
A route no rule maps is the operation whose route it matches in botocore's model of its service,
|
||||
vendored in `src/main/resources/aws/rest-routes.json` (`make aws-data-sync` regenerates it): of the
|
||||
routes it matches, the most specific, segment by segment from the left a literal before a label and a
|
||||
label before a greedy one, then the route naming more of the query. It is checked as that operation's
|
||||
action, the way a request naming its operation is, when Floci checks it on the resources AWS does:
|
||||
those its request names, which Floci builds for the service itself or reads from the request, or none,
|
||||
when the Service Reference gives the action no resource type, as AWS authorizes such an action on `*`.
|
||||
The actions of no resource type are vendored in `src/main/resources/aws/iam-authorized-actions.json`
|
||||
for each scope whose routes are read (`make iam-authorized-actions-sync` regenerates them). So
|
||||
OpenSearch Service's `ListDomainNames`, `ListVersions` and VPC endpoint operations, in both API
|
||||
versions, and Access Analyzer's `ListAnalyzers` and `ValidatePolicy` are checked by their routes. A
|
||||
route whose action AWS checks on a resource Floci neither builds nor reads, OpenSearch's domain
|
||||
operations and Access Analyzer's analyzer operations among them, is not checked: checked on `*`, a
|
||||
grant scoped to the domain or analyzer would be refused. The routes of
|
||||
Lambda, EKS, EventBridge Scheduler, EventBridge Pipes and Aurora DSQL are all mapped by their rules,
|
||||
so none is checked differently. S3 and API Gateway are 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. A route
|
||||
matching nothing is not checked, as an unsigned REST request is not; the other REST services' routes
|
||||
are not vendored yet.
|
||||
|
||||
An S3 `CreateBucket` is checked as `s3:CreateBucket`, and also needs one action for each header
|
||||
that configures the new bucket, as the CreateBucket API reference lists them:
|
||||
|
||||
@@ -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));
|
||||
}
|
||||
}
|
||||
@@ -2,7 +2,7 @@
|
||||
"_source": {
|
||||
"generator": "tools/aws/regen_iam_authorized_actions.py",
|
||||
"reference": "https://servicereference.us-east-1.amazonaws.com/",
|
||||
"retrieved": "2026-10-31",
|
||||
"retrieved": "2026-11-03",
|
||||
"note": "make iam-authorized-actions-verify checks every entry against AWS."
|
||||
},
|
||||
"authorizedActions": {
|
||||
@@ -326,5 +326,109 @@
|
||||
"vpc-lattice": {
|
||||
"BatchUpdateRule": "vpc-lattice:UpdateRule"
|
||||
}
|
||||
},
|
||||
"actionsWithoutResourceTypes": {
|
||||
"access-analyzer": [
|
||||
"CancelPolicyGeneration",
|
||||
"CheckAccessNotGranted",
|
||||
"CheckNoNewAccess",
|
||||
"CheckNoPublicAccess",
|
||||
"GetGeneratedPolicy",
|
||||
"ListAnalyzers",
|
||||
"ListPolicyGenerations",
|
||||
"StartPolicyGeneration",
|
||||
"ValidatePolicy"
|
||||
],
|
||||
"dsql": [
|
||||
"InjectError",
|
||||
"ListClusters"
|
||||
],
|
||||
"eks": [
|
||||
"CreateCluster",
|
||||
"CreateEksAnywhereSubscription",
|
||||
"DescribeAddonConfiguration",
|
||||
"DescribeAddonVersions",
|
||||
"DescribeClusterVersions",
|
||||
"ListAccessPolicies",
|
||||
"ListClusters",
|
||||
"ListEksAnywhereSubscriptions",
|
||||
"RegisterCluster"
|
||||
],
|
||||
"es": [
|
||||
"AcceptInboundConnection",
|
||||
"AcceptInboundCrossClusterSearchConnection",
|
||||
"AuthorizeVpcEndpointAccess",
|
||||
"CreateApplication",
|
||||
"CreateElasticsearchServiceRole",
|
||||
"CreatePackage",
|
||||
"CreateServiceRole",
|
||||
"CreateVpcEndpoint",
|
||||
"DeleteElasticsearchServiceRole",
|
||||
"DeleteInboundConnection",
|
||||
"DeleteInboundCrossClusterSearchConnection",
|
||||
"DeleteOutboundConnection",
|
||||
"DeleteOutboundCrossClusterSearchConnection",
|
||||
"DeletePackage",
|
||||
"DeleteVpcEndpoint",
|
||||
"DescribeElasticsearchInstanceTypeLimits",
|
||||
"DescribeInboundConnections",
|
||||
"DescribeInboundCrossClusterSearchConnections",
|
||||
"DescribeInstanceTypeLimits",
|
||||
"DescribeOutboundConnections",
|
||||
"DescribeOutboundCrossClusterSearchConnections",
|
||||
"DescribePackages",
|
||||
"DescribeReservedElasticsearchInstanceOfferings",
|
||||
"DescribeReservedElasticsearchInstances",
|
||||
"DescribeReservedInstanceOfferings",
|
||||
"DescribeReservedInstances",
|
||||
"DescribeVpcEndpoints",
|
||||
"GetPackageVersionHistory",
|
||||
"ListDomainNames",
|
||||
"ListDomainsForPackage",
|
||||
"ListElasticsearchInstanceTypeDetails",
|
||||
"ListElasticsearchInstanceTypes",
|
||||
"ListElasticsearchVersions",
|
||||
"ListInstanceTypeDetails",
|
||||
"ListVersions",
|
||||
"ListVpcEndpointAccess",
|
||||
"ListVpcEndpoints",
|
||||
"ListVpcEndpointsForDomain",
|
||||
"PurchaseReservedElasticsearchInstanceOffering",
|
||||
"PurchaseReservedInstanceOffering",
|
||||
"RejectInboundConnection",
|
||||
"RejectInboundCrossClusterSearchConnection",
|
||||
"RevokeVpcEndpointAccess",
|
||||
"UpdatePackage",
|
||||
"UpdatePackageScope",
|
||||
"UpdateVpcEndpoint"
|
||||
],
|
||||
"lambda": [
|
||||
"ConnectMicrovm",
|
||||
"CreateCodeSigningConfig",
|
||||
"CreateEventSourceMapping",
|
||||
"CreateMicrovmImage",
|
||||
"GetAccountSettings",
|
||||
"GetWebAccountSettings",
|
||||
"ListCapacityProviders",
|
||||
"ListCodeSigningConfigs",
|
||||
"ListEventSourceMappings",
|
||||
"ListFunctions",
|
||||
"ListLayerVersions",
|
||||
"ListLayers",
|
||||
"ListManagedMicrovmImages",
|
||||
"ListMicrovmImages",
|
||||
"ListMicrovms",
|
||||
"ListNetworkConnectors",
|
||||
"ListWebFunctions",
|
||||
"PassNetworkConnector"
|
||||
],
|
||||
"pipes": [
|
||||
"ListPipes"
|
||||
],
|
||||
"scheduler": [
|
||||
"ListScheduleGroups",
|
||||
"ListSchedules",
|
||||
"ListSchedulesByTarget"
|
||||
]
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,9 @@
|
||||
{
|
||||
"_source": {"generator": "tools/aws/regen_rest_routes.py", "botocore": "botocore 1.43.118 (local/aws/botocore)"},
|
||||
"handRouted": {
|
||||
"apigateway": "API Gateway's management API is authorized by HTTP method, apigateway:GET, apigateway:POST and so on, on the resource path a route names, not by its operations' names, and the registry's rules give every route its method's action",
|
||||
"s3": "S3 tells apart the operations it serves on one route by their query parameters and headers, which the registry's S3 rules and sub-resource overrides read, and an S3 Control route Floci does not serve runs as the S3 data plane, checked as the bucket or object operation that runs"
|
||||
},
|
||||
"models": {
|
||||
"accessanalyzer": {
|
||||
"credentialScope": "access-analyzer",
|
||||
@@ -383,6 +387,63 @@
|
||||
"UpdatePodIdentityAssociation": {"method": "POST", "requestUri": "/clusters/{name}/pod-identity-associations/{associationId}"}
|
||||
}
|
||||
},
|
||||
"es": {
|
||||
"credentialScope": "es",
|
||||
"apiVersion": "2015-01-01",
|
||||
"operations": {
|
||||
"AcceptInboundCrossClusterSearchConnection": {"method": "PUT", "requestUri": "/2015-01-01/es/ccs/inboundConnection/{ConnectionId}/accept"},
|
||||
"AddTags": {"method": "POST", "requestUri": "/2015-01-01/tags"},
|
||||
"AssociatePackage": {"method": "POST", "requestUri": "/2015-01-01/packages/associate/{PackageID}/{DomainName}"},
|
||||
"AuthorizeVpcEndpointAccess": {"method": "POST", "requestUri": "/2015-01-01/es/domain/{DomainName}/authorizeVpcEndpointAccess"},
|
||||
"CancelDomainConfigChange": {"method": "POST", "requestUri": "/2015-01-01/es/domain/{DomainName}/config/cancel"},
|
||||
"CancelElasticsearchServiceSoftwareUpdate": {"method": "POST", "requestUri": "/2015-01-01/es/serviceSoftwareUpdate/cancel"},
|
||||
"CreateElasticsearchDomain": {"method": "POST", "requestUri": "/2015-01-01/es/domain"},
|
||||
"CreateOutboundCrossClusterSearchConnection": {"method": "POST", "requestUri": "/2015-01-01/es/ccs/outboundConnection"},
|
||||
"CreatePackage": {"method": "POST", "requestUri": "/2015-01-01/packages"},
|
||||
"CreateVpcEndpoint": {"method": "POST", "requestUri": "/2015-01-01/es/vpcEndpoints"},
|
||||
"DeleteElasticsearchDomain": {"method": "DELETE", "requestUri": "/2015-01-01/es/domain/{DomainName}"},
|
||||
"DeleteElasticsearchServiceRole": {"method": "DELETE", "requestUri": "/2015-01-01/es/role"},
|
||||
"DeleteInboundCrossClusterSearchConnection": {"method": "DELETE", "requestUri": "/2015-01-01/es/ccs/inboundConnection/{ConnectionId}"},
|
||||
"DeleteOutboundCrossClusterSearchConnection": {"method": "DELETE", "requestUri": "/2015-01-01/es/ccs/outboundConnection/{ConnectionId}"},
|
||||
"DeletePackage": {"method": "DELETE", "requestUri": "/2015-01-01/packages/{PackageID}"},
|
||||
"DeleteVpcEndpoint": {"method": "DELETE", "requestUri": "/2015-01-01/es/vpcEndpoints/{VpcEndpointId}"},
|
||||
"DescribeDomainAutoTunes": {"method": "GET", "requestUri": "/2015-01-01/es/domain/{DomainName}/autoTunes"},
|
||||
"DescribeDomainChangeProgress": {"method": "GET", "requestUri": "/2015-01-01/es/domain/{DomainName}/progress"},
|
||||
"DescribeElasticsearchDomain": {"method": "GET", "requestUri": "/2015-01-01/es/domain/{DomainName}"},
|
||||
"DescribeElasticsearchDomainConfig": {"method": "GET", "requestUri": "/2015-01-01/es/domain/{DomainName}/config"},
|
||||
"DescribeElasticsearchDomains": {"method": "POST", "requestUri": "/2015-01-01/es/domain-info"},
|
||||
"DescribeElasticsearchInstanceTypeLimits": {"method": "GET", "requestUri": "/2015-01-01/es/instanceTypeLimits/{ElasticsearchVersion}/{InstanceType}"},
|
||||
"DescribeInboundCrossClusterSearchConnections": {"method": "POST", "requestUri": "/2015-01-01/es/ccs/inboundConnection/search"},
|
||||
"DescribeOutboundCrossClusterSearchConnections": {"method": "POST", "requestUri": "/2015-01-01/es/ccs/outboundConnection/search"},
|
||||
"DescribePackages": {"method": "POST", "requestUri": "/2015-01-01/packages/describe"},
|
||||
"DescribeReservedElasticsearchInstanceOfferings": {"method": "GET", "requestUri": "/2015-01-01/es/reservedInstanceOfferings"},
|
||||
"DescribeReservedElasticsearchInstances": {"method": "GET", "requestUri": "/2015-01-01/es/reservedInstances"},
|
||||
"DescribeVpcEndpoints": {"method": "POST", "requestUri": "/2015-01-01/es/vpcEndpoints/describe"},
|
||||
"DissociatePackage": {"method": "POST", "requestUri": "/2015-01-01/packages/dissociate/{PackageID}/{DomainName}"},
|
||||
"GetCompatibleElasticsearchVersions": {"method": "GET", "requestUri": "/2015-01-01/es/compatibleVersions"},
|
||||
"GetPackageVersionHistory": {"method": "GET", "requestUri": "/2015-01-01/packages/{PackageID}/history"},
|
||||
"GetUpgradeHistory": {"method": "GET", "requestUri": "/2015-01-01/es/upgradeDomain/{DomainName}/history"},
|
||||
"GetUpgradeStatus": {"method": "GET", "requestUri": "/2015-01-01/es/upgradeDomain/{DomainName}/status"},
|
||||
"ListDomainNames": {"method": "GET", "requestUri": "/2015-01-01/domain"},
|
||||
"ListDomainsForPackage": {"method": "GET", "requestUri": "/2015-01-01/packages/{PackageID}/domains"},
|
||||
"ListElasticsearchInstanceTypes": {"method": "GET", "requestUri": "/2015-01-01/es/instanceTypes/{ElasticsearchVersion}"},
|
||||
"ListElasticsearchVersions": {"method": "GET", "requestUri": "/2015-01-01/es/versions"},
|
||||
"ListPackagesForDomain": {"method": "GET", "requestUri": "/2015-01-01/domain/{DomainName}/packages"},
|
||||
"ListTags": {"method": "GET", "requestUri": "/2015-01-01/tags/"},
|
||||
"ListVpcEndpointAccess": {"method": "GET", "requestUri": "/2015-01-01/es/domain/{DomainName}/listVpcEndpointAccess"},
|
||||
"ListVpcEndpoints": {"method": "GET", "requestUri": "/2015-01-01/es/vpcEndpoints"},
|
||||
"ListVpcEndpointsForDomain": {"method": "GET", "requestUri": "/2015-01-01/es/domain/{DomainName}/vpcEndpoints"},
|
||||
"PurchaseReservedElasticsearchInstanceOffering": {"method": "POST", "requestUri": "/2015-01-01/es/purchaseReservedInstanceOffering"},
|
||||
"RejectInboundCrossClusterSearchConnection": {"method": "PUT", "requestUri": "/2015-01-01/es/ccs/inboundConnection/{ConnectionId}/reject"},
|
||||
"RemoveTags": {"method": "POST", "requestUri": "/2015-01-01/tags-removal"},
|
||||
"RevokeVpcEndpointAccess": {"method": "POST", "requestUri": "/2015-01-01/es/domain/{DomainName}/revokeVpcEndpointAccess"},
|
||||
"StartElasticsearchServiceSoftwareUpdate": {"method": "POST", "requestUri": "/2015-01-01/es/serviceSoftwareUpdate/start"},
|
||||
"UpdateElasticsearchDomainConfig": {"method": "POST", "requestUri": "/2015-01-01/es/domain/{DomainName}/config"},
|
||||
"UpdatePackage": {"method": "POST", "requestUri": "/2015-01-01/packages/update"},
|
||||
"UpdateVpcEndpoint": {"method": "POST", "requestUri": "/2015-01-01/es/vpcEndpoints/update"},
|
||||
"UpgradeElasticsearchDomain": {"method": "POST", "requestUri": "/2015-01-01/es/upgradeDomain"}
|
||||
}
|
||||
},
|
||||
"lambda": {
|
||||
"credentialScope": "lambda",
|
||||
"apiVersion": "2015-03-31",
|
||||
@@ -519,6 +580,108 @@
|
||||
"UpdateMicrovmImageVersion": {"method": "PATCH", "requestUri": "/2025-09-09/microvm-images/{imageIdentifier}/versions/{imageVersion}"}
|
||||
}
|
||||
},
|
||||
"opensearch": {
|
||||
"credentialScope": "es",
|
||||
"apiVersion": "2021-01-01",
|
||||
"operations": {
|
||||
"AcceptInboundConnection": {"method": "PUT", "requestUri": "/2021-01-01/opensearch/cc/inboundConnection/{ConnectionId}/accept"},
|
||||
"AddDataSource": {"method": "POST", "requestUri": "/2021-01-01/opensearch/domain/{DomainName}/dataSource"},
|
||||
"AddDirectQueryDataSource": {"method": "POST", "requestUri": "/2021-01-01/opensearch/directQueryDataSource"},
|
||||
"AddTags": {"method": "POST", "requestUri": "/2021-01-01/tags"},
|
||||
"AssociatePackage": {"method": "POST", "requestUri": "/2021-01-01/packages/associate/{PackageID}/{DomainName}"},
|
||||
"AssociatePackages": {"method": "POST", "requestUri": "/2021-01-01/packages/associateMultiple"},
|
||||
"AttachDataSource": {"method": "POST", "requestUri": "/2021-01-01/opensearch/application/{id}/attachDataSource"},
|
||||
"AuthorizeVpcEndpointAccess": {"method": "POST", "requestUri": "/2021-01-01/opensearch/domain/{DomainName}/authorizeVpcEndpointAccess"},
|
||||
"CancelDomainConfigChange": {"method": "POST", "requestUri": "/2021-01-01/opensearch/domain/{DomainName}/config/cancel"},
|
||||
"CancelServiceSoftwareUpdate": {"method": "POST", "requestUri": "/2021-01-01/opensearch/serviceSoftwareUpdate/cancel"},
|
||||
"CreateApplication": {"method": "POST", "requestUri": "/2021-01-01/opensearch/application"},
|
||||
"CreateDomain": {"method": "POST", "requestUri": "/2021-01-01/opensearch/domain"},
|
||||
"CreateIndex": {"method": "POST", "requestUri": "/2021-01-01/opensearch/domain/{DomainName}/index"},
|
||||
"CreateOutboundConnection": {"method": "POST", "requestUri": "/2021-01-01/opensearch/cc/outboundConnection"},
|
||||
"CreatePackage": {"method": "POST", "requestUri": "/2021-01-01/packages"},
|
||||
"CreateVpcEndpoint": {"method": "POST", "requestUri": "/2021-01-01/opensearch/vpcEndpoints"},
|
||||
"DeleteApplication": {"method": "DELETE", "requestUri": "/2021-01-01/opensearch/application/{id}"},
|
||||
"DeleteDataSource": {"method": "DELETE", "requestUri": "/2021-01-01/opensearch/domain/{DomainName}/dataSource/{DataSourceName}"},
|
||||
"DeleteDirectQueryDataSource": {"method": "DELETE", "requestUri": "/2021-01-01/opensearch/directQueryDataSource/{DataSourceName}"},
|
||||
"DeleteDomain": {"method": "DELETE", "requestUri": "/2021-01-01/opensearch/domain/{DomainName}"},
|
||||
"DeleteInboundConnection": {"method": "DELETE", "requestUri": "/2021-01-01/opensearch/cc/inboundConnection/{ConnectionId}"},
|
||||
"DeleteIndex": {"method": "DELETE", "requestUri": "/2021-01-01/opensearch/domain/{DomainName}/index/{IndexName}"},
|
||||
"DeleteOutboundConnection": {"method": "DELETE", "requestUri": "/2021-01-01/opensearch/cc/outboundConnection/{ConnectionId}"},
|
||||
"DeletePackage": {"method": "DELETE", "requestUri": "/2021-01-01/packages/{PackageID}"},
|
||||
"DeleteVpcEndpoint": {"method": "DELETE", "requestUri": "/2021-01-01/opensearch/vpcEndpoints/{VpcEndpointId}"},
|
||||
"DeregisterCapability": {"method": "DELETE", "requestUri": "/2021-01-01/opensearch/application/{ApplicationId}/capability/deregister/{CapabilityName}"},
|
||||
"DescribeDataSourceAttachment": {"method": "POST", "requestUri": "/2021-01-01/opensearch/application/{id}/describeDataSourceAttachment"},
|
||||
"DescribeDomain": {"method": "GET", "requestUri": "/2021-01-01/opensearch/domain/{DomainName}"},
|
||||
"DescribeDomainAutoTunes": {"method": "GET", "requestUri": "/2021-01-01/opensearch/domain/{DomainName}/autoTunes"},
|
||||
"DescribeDomainChangeProgress": {"method": "GET", "requestUri": "/2021-01-01/opensearch/domain/{DomainName}/progress"},
|
||||
"DescribeDomainConfig": {"method": "GET", "requestUri": "/2021-01-01/opensearch/domain/{DomainName}/config"},
|
||||
"DescribeDomainHealth": {"method": "GET", "requestUri": "/2021-01-01/opensearch/domain/{DomainName}/health"},
|
||||
"DescribeDomainNodes": {"method": "GET", "requestUri": "/2021-01-01/opensearch/domain/{DomainName}/nodes"},
|
||||
"DescribeDomains": {"method": "POST", "requestUri": "/2021-01-01/opensearch/domain-info"},
|
||||
"DescribeDryRunProgress": {"method": "GET", "requestUri": "/2021-01-01/opensearch/domain/{DomainName}/dryRun"},
|
||||
"DescribeInboundConnections": {"method": "POST", "requestUri": "/2021-01-01/opensearch/cc/inboundConnection/search"},
|
||||
"DescribeInsightDetails": {"method": "POST", "requestUri": "/2021-01-01/opensearch/insight-details"},
|
||||
"DescribeInstanceTypeLimits": {"method": "GET", "requestUri": "/2021-01-01/opensearch/instanceTypeLimits/{EngineVersion}/{InstanceType}"},
|
||||
"DescribeOutboundConnections": {"method": "POST", "requestUri": "/2021-01-01/opensearch/cc/outboundConnection/search"},
|
||||
"DescribePackages": {"method": "POST", "requestUri": "/2021-01-01/packages/describe"},
|
||||
"DescribeReservedInstanceOfferings": {"method": "GET", "requestUri": "/2021-01-01/opensearch/reservedInstanceOfferings"},
|
||||
"DescribeReservedInstances": {"method": "GET", "requestUri": "/2021-01-01/opensearch/reservedInstances"},
|
||||
"DescribeVpcEndpoints": {"method": "POST", "requestUri": "/2021-01-01/opensearch/vpcEndpoints/describe"},
|
||||
"DetachDataSource": {"method": "POST", "requestUri": "/2021-01-01/opensearch/application/{id}/detachDataSource"},
|
||||
"DissociatePackage": {"method": "POST", "requestUri": "/2021-01-01/packages/dissociate/{PackageID}/{DomainName}"},
|
||||
"DissociatePackages": {"method": "POST", "requestUri": "/2021-01-01/packages/dissociateMultiple"},
|
||||
"GetApplication": {"method": "GET", "requestUri": "/2021-01-01/opensearch/application/{id}"},
|
||||
"GetCapability": {"method": "GET", "requestUri": "/2021-01-01/opensearch/application/{ApplicationId}/capability/{CapabilityName}"},
|
||||
"GetCompatibleVersions": {"method": "GET", "requestUri": "/2021-01-01/opensearch/compatibleVersions"},
|
||||
"GetDataSource": {"method": "GET", "requestUri": "/2021-01-01/opensearch/domain/{DomainName}/dataSource/{DataSourceName}"},
|
||||
"GetDefaultApplicationSetting": {"method": "GET", "requestUri": "/2021-01-01/opensearch/defaultApplicationSetting"},
|
||||
"GetDirectQueryDataSource": {"method": "GET", "requestUri": "/2021-01-01/opensearch/directQueryDataSource/{DataSourceName}"},
|
||||
"GetDomainMaintenanceStatus": {"method": "GET", "requestUri": "/2021-01-01/opensearch/domain/{DomainName}/domainMaintenance"},
|
||||
"GetIndex": {"method": "GET", "requestUri": "/2021-01-01/opensearch/domain/{DomainName}/index/{IndexName}"},
|
||||
"GetMigration": {"method": "GET", "requestUri": "/2021-01-01/opensearch/app-migrations/{migrationId}"},
|
||||
"GetPackageVersionHistory": {"method": "GET", "requestUri": "/2021-01-01/packages/{PackageID}/history"},
|
||||
"GetUpgradeHistory": {"method": "GET", "requestUri": "/2021-01-01/opensearch/upgradeDomain/{DomainName}/history"},
|
||||
"GetUpgradeStatus": {"method": "GET", "requestUri": "/2021-01-01/opensearch/upgradeDomain/{DomainName}/status"},
|
||||
"InsightFeedback": {"method": "POST", "requestUri": "/2021-01-01/opensearch/insight-feedback"},
|
||||
"ListApplications": {"method": "GET", "requestUri": "/2021-01-01/opensearch/list-applications"},
|
||||
"ListDataSourceAttachments": {"method": "POST", "requestUri": "/2021-01-01/opensearch/application/{id}/listDataSourceAttachments"},
|
||||
"ListDataSources": {"method": "GET", "requestUri": "/2021-01-01/opensearch/domain/{DomainName}/dataSource"},
|
||||
"ListDirectQueryDataSources": {"method": "GET", "requestUri": "/2021-01-01/opensearch/directQueryDataSource"},
|
||||
"ListDomainMaintenances": {"method": "GET", "requestUri": "/2021-01-01/opensearch/domain/{DomainName}/domainMaintenances"},
|
||||
"ListDomainNames": {"method": "GET", "requestUri": "/2021-01-01/domain"},
|
||||
"ListDomainsForPackage": {"method": "GET", "requestUri": "/2021-01-01/packages/{PackageID}/domains"},
|
||||
"ListInsights": {"method": "POST", "requestUri": "/2021-01-01/opensearch/insights"},
|
||||
"ListInstanceTypeDetails": {"method": "GET", "requestUri": "/2021-01-01/opensearch/instanceTypeDetails/{EngineVersion}"},
|
||||
"ListMigrations": {"method": "GET", "requestUri": "/2021-01-01/opensearch/app-migrations"},
|
||||
"ListPackagesForDomain": {"method": "GET", "requestUri": "/2021-01-01/domain/{DomainName}/packages"},
|
||||
"ListScheduledActions": {"method": "GET", "requestUri": "/2021-01-01/opensearch/domain/{DomainName}/scheduledActions"},
|
||||
"ListTags": {"method": "GET", "requestUri": "/2021-01-01/tags/"},
|
||||
"ListVersions": {"method": "GET", "requestUri": "/2021-01-01/opensearch/versions"},
|
||||
"ListVpcEndpointAccess": {"method": "GET", "requestUri": "/2021-01-01/opensearch/domain/{DomainName}/listVpcEndpointAccess"},
|
||||
"ListVpcEndpoints": {"method": "GET", "requestUri": "/2021-01-01/opensearch/vpcEndpoints"},
|
||||
"ListVpcEndpointsForDomain": {"method": "GET", "requestUri": "/2021-01-01/opensearch/domain/{DomainName}/vpcEndpoints"},
|
||||
"PurchaseReservedInstanceOffering": {"method": "POST", "requestUri": "/2021-01-01/opensearch/purchaseReservedInstanceOffering"},
|
||||
"PutDefaultApplicationSetting": {"method": "PUT", "requestUri": "/2021-01-01/opensearch/defaultApplicationSetting"},
|
||||
"RegisterCapability": {"method": "POST", "requestUri": "/2021-01-01/opensearch/application/{ApplicationId}/capability/register"},
|
||||
"RejectInboundConnection": {"method": "PUT", "requestUri": "/2021-01-01/opensearch/cc/inboundConnection/{ConnectionId}/reject"},
|
||||
"RemoveTags": {"method": "POST", "requestUri": "/2021-01-01/tags-removal"},
|
||||
"RevokeVpcEndpointAccess": {"method": "POST", "requestUri": "/2021-01-01/opensearch/domain/{DomainName}/revokeVpcEndpointAccess"},
|
||||
"RollbackServiceSoftwareUpdate": {"method": "POST", "requestUri": "/2021-01-01/opensearch/serviceSoftwareUpdate/rollback"},
|
||||
"StartDomainMaintenance": {"method": "POST", "requestUri": "/2021-01-01/opensearch/domain/{DomainName}/domainMaintenance"},
|
||||
"StartMigration": {"method": "POST", "requestUri": "/2021-01-01/opensearch/app-migrations"},
|
||||
"StartServiceSoftwareUpdate": {"method": "POST", "requestUri": "/2021-01-01/opensearch/serviceSoftwareUpdate/start"},
|
||||
"UpdateApplication": {"method": "PUT", "requestUri": "/2021-01-01/opensearch/application/{id}"},
|
||||
"UpdateDataSource": {"method": "PUT", "requestUri": "/2021-01-01/opensearch/domain/{DomainName}/dataSource/{DataSourceName}"},
|
||||
"UpdateDirectQueryDataSource": {"method": "PUT", "requestUri": "/2021-01-01/opensearch/directQueryDataSource/{DataSourceName}"},
|
||||
"UpdateDomainConfig": {"method": "POST", "requestUri": "/2021-01-01/opensearch/domain/{DomainName}/config"},
|
||||
"UpdateIndex": {"method": "PUT", "requestUri": "/2021-01-01/opensearch/domain/{DomainName}/index/{IndexName}"},
|
||||
"UpdatePackage": {"method": "POST", "requestUri": "/2021-01-01/packages/update"},
|
||||
"UpdatePackageScope": {"method": "POST", "requestUri": "/2021-01-01/packages/updateScope"},
|
||||
"UpdateScheduledAction": {"method": "PUT", "requestUri": "/2021-01-01/opensearch/domain/{DomainName}/scheduledAction/update"},
|
||||
"UpdateVpcEndpoint": {"method": "POST", "requestUri": "/2021-01-01/opensearch/vpcEndpoints/update"},
|
||||
"UpgradeDomain": {"method": "POST", "requestUri": "/2021-01-01/opensearch/upgradeDomain"}
|
||||
}
|
||||
},
|
||||
"pipes": {
|
||||
"credentialScope": "pipes",
|
||||
"apiVersion": "2015-10-07",
|
||||
|
||||
@@ -19,6 +19,7 @@ import org.junit.jupiter.params.provider.CsvSource;
|
||||
import org.mockito.Mockito;
|
||||
|
||||
import java.io.ByteArrayInputStream;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.net.URI;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
@@ -43,6 +44,76 @@ class IamActionRegistryTest {
|
||||
|
||||
private final IamActionRegistry registry = new IamActionRegistry();
|
||||
|
||||
/**
|
||||
* A REST request no rule maps is checked as the operation whose vendored route it matches, as that operation's
|
||||
* action, when Floci checks it on the resources AWS does: built by hand for its namespace ({@code Invoke} as
|
||||
* {@code lambda:InvokeFunction}), read by the vendored request resources ({@code DescribeRepositories}), or
|
||||
* none, AWS authorizing its action on no resource type ({@code ListDomainNames}). One AWS checks on a resource
|
||||
* Floci does not read stays unmapped ({@code DescribeDomain}), as does a request matching no route, and a rule
|
||||
* still decides a route it maps.
|
||||
*/
|
||||
@Test
|
||||
void aRouteNoRuleMapsIsCheckedAsItsOperationWhenFlociChecksItAsAwsDoes() throws IOException {
|
||||
IamRestRoutes routes = IamRestRoutes.parse(new ByteArrayInputStream("""
|
||||
{"handRouted": {},
|
||||
"models": {
|
||||
"opensearch": {"credentialScope": "es", "operations": {
|
||||
"ListDomainNames": {"method": "GET", "requestUri": "/unmapped/domain"},
|
||||
"DescribeDomain": {"method": "GET", "requestUri": "/unmapped/domain/{DomainName}"}
|
||||
}},
|
||||
"ecr": {"credentialScope": "ecr", "operations": {
|
||||
"DescribeRepositories": {"method": "GET", "requestUri": "/unmapped/repositories"}
|
||||
}},
|
||||
"lambda": {"credentialScope": "lambda", "operations": {
|
||||
"Invoke": {"method": "POST", "requestUri": "/unmapped/{FunctionName}/invocations"},
|
||||
"ListFunctions": {"method": "GET", "requestUri": "/2015-03-31/functions/{FunctionName}"}
|
||||
}}
|
||||
}}""".getBytes(StandardCharsets.UTF_8)));
|
||||
IamActionRegistry routed = new IamActionRegistry(routes);
|
||||
MultivaluedMap<String, String> none = new MultivaluedHashMap<>();
|
||||
assertEquals("es:ListDomainNames", routed.resolveRoute("es", mockCtx("GET", "/unmapped/domain", none, null, "")));
|
||||
assertNull(routed.resolveRoute("es", mockCtx("GET", "/unmapped/domain/logs", none, null, "")));
|
||||
assertNull(routed.resolveRoute("es", mockCtx("GET", "/other/domain", none, null, "")));
|
||||
assertNull(routed.resolveRoute("other", mockCtx("GET", "/unmapped/domain", none, null, "")));
|
||||
assertEquals("lambda:InvokeFunction", routed.resolveRoute("lambda",
|
||||
mockCtx("POST", "/unmapped/fn/invocations", none, null, "")));
|
||||
assertEquals("ecr:DescribeRepositories", routed.resolveRoute("ecr",
|
||||
mockCtx("GET", "/unmapped/repositories", none, null, "")));
|
||||
assertEquals("lambda:GetFunction", routed.resolveRoute("lambda",
|
||||
mockCtx("GET", "/2015-03-31/functions/fn", none, null, "")));
|
||||
}
|
||||
|
||||
/**
|
||||
* With the vendored routes, OpenSearch's and Access Analyzer's requests whose actions act on no resource type
|
||||
* are checked as their operations, the OpenSearch VPC endpoint operations among them, in both API versions;
|
||||
* those AWS checks on a domain or an analyzer stay unmapped, so a grant scoped to one is not refused.
|
||||
*/
|
||||
@ParameterizedTest
|
||||
@CsvSource({"es,GET,/2021-01-01/domain,es:ListDomainNames",
|
||||
"es,GET,/2015-01-01/domain,es:ListDomainNames",
|
||||
"es,GET,/2021-01-01/opensearch/versions,es:ListVersions",
|
||||
"es,POST,/2021-01-01/opensearch/vpcEndpoints,es:CreateVpcEndpoint",
|
||||
"es,GET,/2021-01-01/opensearch/vpcEndpoints,es:ListVpcEndpoints",
|
||||
"es,POST,/2021-01-01/opensearch/vpcEndpoints/describe,es:DescribeVpcEndpoints",
|
||||
"es,POST,/2021-01-01/opensearch/vpcEndpoints/update,es:UpdateVpcEndpoint",
|
||||
"es,DELETE,/2021-01-01/opensearch/vpcEndpoints/aos-123,es:DeleteVpcEndpoint",
|
||||
"es,GET,/2021-01-01/opensearch/domain/logs/vpcEndpoints,es:ListVpcEndpointsForDomain",
|
||||
"es,GET,/2015-01-01/es/vpcEndpoints,es:ListVpcEndpoints",
|
||||
"access-analyzer,GET,/analyzer,access-analyzer:ListAnalyzers",
|
||||
"access-analyzer,POST,/policy/validation,access-analyzer:ValidatePolicy"})
|
||||
void aVendoredRouteOfNoResourceTypeIsCheckedAsItsOperation(String scope, String method, String path,
|
||||
String action) {
|
||||
assertEquals(action, registry.resolveRoute(scope, mockCtx(method, path, new MultivaluedHashMap<>(), null, "")));
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@CsvSource({"es,GET,/2021-01-01/opensearch/domain/logs", "es,POST,/2021-01-01/opensearch/domain",
|
||||
"es,GET,/2015-01-01/es/domain/logs", "access-analyzer,PUT,/analyzer",
|
||||
"access-analyzer,GET,/analyzer/default", "access-analyzer,DELETE,/analyzer/default"})
|
||||
void aVendoredRouteAwsChecksOnAResourceStaysUnmapped(String scope, String method, String path) {
|
||||
assertNull(registry.resolveRoute(scope, mockCtx(method, path, new MultivaluedHashMap<>(), null, "")));
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@CsvSource({"/policy/validation", "/%70olicy/validation", "/policy/%76alidation",
|
||||
"/policy;ignored=yes/validation", "/policy/validation;ignored=yes",
|
||||
|
||||
+39
-3
@@ -7,9 +7,12 @@ import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
class IamAuthorizedActionsTest {
|
||||
|
||||
@@ -43,10 +46,43 @@ class IamAuthorizedActionsTest {
|
||||
|
||||
@Test
|
||||
void entriesAreKeyedByNamespaceAndOperation() throws IOException {
|
||||
Map<String, String> parsed = IamAuthorizedActions.parse(json("""
|
||||
{"authorizedActions": {"sqs": {"SendMessageBatch": "sqs:SendMessage"}}}
|
||||
IamAuthorizedActions.Table parsed = IamAuthorizedActions.parse(json("""
|
||||
{"authorizedActions": {"sqs": {"SendMessageBatch": "sqs:SendMessage"}},
|
||||
"actionsWithoutResourceTypes": {"es": ["ListDomainNames"], "dsql": []}}
|
||||
"""));
|
||||
assertEquals(Map.of("sqs:SendMessageBatch", "sqs:SendMessage"), parsed);
|
||||
assertEquals(Map.of("sqs:SendMessageBatch", "sqs:SendMessage"), parsed.actions());
|
||||
assertEquals(Set.of("es:listdomainnames"), parsed.withoutResourceTypes());
|
||||
}
|
||||
|
||||
/**
|
||||
* The actions of a routed REST scope that AWS authorizes on no resource type are known, matched as IAM matches
|
||||
* action names; one acting on a resource, or of a scope whose routes are not read, is not one of them.
|
||||
*/
|
||||
@Test
|
||||
void anActionOfNoResourceTypeIsKnownWhateverTheCaseOfItsName() {
|
||||
assertTrue(IamAuthorizedActions.actsOnNoResourceType("es:ListDomainNames"));
|
||||
assertTrue(IamAuthorizedActions.actsOnNoResourceType("ES:listdomainnames"));
|
||||
assertTrue(IamAuthorizedActions.actsOnNoResourceType("es:CreateVpcEndpoint"));
|
||||
assertTrue(IamAuthorizedActions.actsOnNoResourceType("access-analyzer:ValidatePolicy"));
|
||||
assertFalse(IamAuthorizedActions.actsOnNoResourceType("es:DescribeDomain"));
|
||||
assertFalse(IamAuthorizedActions.actsOnNoResourceType("access-analyzer:CreateAnalyzer"));
|
||||
assertFalse(IamAuthorizedActions.actsOnNoResourceType("sqs:ListQueues"));
|
||||
assertFalse(IamAuthorizedActions.actsOnNoResourceType(null));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aFileWithoutTheActionsOfNoResourceTypeIsRefused() {
|
||||
assertThrows(IllegalStateException.class, () -> IamAuthorizedActions.parse(json("""
|
||||
{"authorizedActions": {"sqs": {"SendMessageBatch": "sqs:SendMessage"}}}
|
||||
""")));
|
||||
assertThrows(IllegalStateException.class, () -> IamAuthorizedActions.parse(json("""
|
||||
{"authorizedActions": {"sqs": {"SendMessageBatch": "sqs:SendMessage"}},
|
||||
"actionsWithoutResourceTypes": {"es": "ListDomainNames"}}
|
||||
""")));
|
||||
assertThrows(IllegalStateException.class, () -> IamAuthorizedActions.parse(json("""
|
||||
{"authorizedActions": {"sqs": {"SendMessageBatch": "sqs:SendMessage"}},
|
||||
"actionsWithoutResourceTypes": {"es": [""]}}
|
||||
""")));
|
||||
}
|
||||
|
||||
@Test
|
||||
|
||||
+63
-10
@@ -14,6 +14,7 @@ import java.io.InputStream;
|
||||
import java.net.URI;
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.HashSet;
|
||||
import java.util.Iterator;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
@@ -29,8 +30,9 @@ import static org.mockito.Mockito.when;
|
||||
|
||||
/**
|
||||
* A REST request is authorized by its route, so an operation is checked as the IAM action AWS checks
|
||||
* for it only if a rule in {@link IamActionRegistry} maps its route to that action. This builds a
|
||||
* request on each operation's route, as botocore's model gives it ({@code rest-routes.json}, from
|
||||
* for it only if a rule in {@link IamActionRegistry} maps its route to that action, or, for an action AWS
|
||||
* authorizes on no resource type, the vendored route it matches is its own. This builds a request on each
|
||||
* operation's route, as botocore's model gives it ({@code rest-routes.json}, from
|
||||
* {@code tools/aws/regen_rest_routes.py}), and compares the action the registry resolves with the one
|
||||
* {@code iam-authorized-actions.json} names for the operation, or else the operation's own name.
|
||||
*/
|
||||
@@ -52,10 +54,6 @@ class IamRestRouteCoverageTest {
|
||||
"GetBucketMetadataConfiguration", "s3:ListBucket",
|
||||
"DeleteBucketMetadataConfiguration", "s3:DeleteBucket");
|
||||
|
||||
/** Models every operation of which is checked: the services whose routes the registry maps in full. */
|
||||
private static final Set<String> FULLY_ROUTED_MODELS =
|
||||
Set.of("scheduler", "pipes", "eks", "lambda", "lambda-microvms", "lambda-core", "dsql");
|
||||
|
||||
/**
|
||||
* The S3 Control operations Floci serves, the rest-routes entry of which is a route the
|
||||
* registry maps. Every other operation of the s3control model has no route in Floci: the
|
||||
@@ -123,20 +121,33 @@ class IamRestRouteCoverageTest {
|
||||
return tests.stream();
|
||||
}
|
||||
|
||||
/**
|
||||
* Every operation of a scope the vendored routes do not leave to the rules alone resolves to its action when
|
||||
* Floci can check it as AWS does: its resources built by hand for its namespace or read by the vendored request
|
||||
* resources, or none, AWS authorizing its action on no resource type. Any other operation stays unmapped,
|
||||
* unchecked rather than checked on {@code *}, until the resources in its path are read.
|
||||
*/
|
||||
@TestFactory
|
||||
Stream<DynamicTest> everyOperationOfAFullyRoutedServiceResolvesToItsAction() throws IOException {
|
||||
JsonNode models = load("/aws/rest-routes.json").path("models");
|
||||
Stream<DynamicTest> everyOperationOfARoutedScopeResolvesToItsActionWhenFlociCanCheckIt() throws IOException {
|
||||
JsonNode document = load("/aws/rest-routes.json");
|
||||
JsonNode models = document.path("models");
|
||||
JsonNode authorized = load("/aws/iam-authorized-actions.json").path("authorizedActions");
|
||||
JsonNode requestResources = load("/aws/iam-request-resources.json");
|
||||
Set<String> handBuilt = new HashSet<>();
|
||||
requestResources.path("handBuilt").forEach(namespace -> handBuilt.add(namespace.asText()));
|
||||
List<DynamicTest> tests = new ArrayList<>();
|
||||
for (String model : FULLY_ROUTED_MODELS) {
|
||||
for (String model : routedModels(document)) {
|
||||
String scope = models.path(model).path("credentialScope").asText();
|
||||
Iterator<Map.Entry<String, JsonNode>> operations = models.path(model).path("operations").fields();
|
||||
while (operations.hasNext()) {
|
||||
Map.Entry<String, JsonNode> operation = operations.next();
|
||||
Route route = new Route(scope, model, operation.getKey(), operation.getValue().path("method").asText(),
|
||||
operation.getValue().path("requestUri").asText());
|
||||
String expected = RUN_AS_ANOTHER_OPERATION.getOrDefault(operation.getKey(),
|
||||
String action = RUN_AS_ANOTHER_OPERATION.getOrDefault(operation.getKey(),
|
||||
authorized.path(scope).path(operation.getKey()).asText(scope + ":" + operation.getKey()));
|
||||
boolean read = requestResources.path("operations").has(scope + ":" + operation.getKey());
|
||||
String expected = handBuilt.contains(scope) || read || IamAuthorizedActions.actsOnNoResourceType(action)
|
||||
? action : null;
|
||||
tests.add(DynamicTest.dynamicTest(model + " " + operation.getKey(),
|
||||
() -> assertEquals(expected, resolve(route), route.toString())));
|
||||
}
|
||||
@@ -144,6 +155,35 @@ class IamRestRouteCoverageTest {
|
||||
return tests.stream();
|
||||
}
|
||||
|
||||
/**
|
||||
* Every route of a scope the vendored routes do not leave to the rules alone is, by those routes alone, an
|
||||
* operation checked as its own operation's action: the most specific route a request on it matches is its own,
|
||||
* or a sibling model's of the same scope and action (Lambda's and Lambda MicroVMs' tagging routes).
|
||||
*/
|
||||
@TestFactory
|
||||
Stream<DynamicTest> everyRouteOfARoutedScopeIsItsOperationByTheVendoredRoutesAlone() throws IOException {
|
||||
JsonNode document = load("/aws/rest-routes.json");
|
||||
JsonNode models = document.path("models");
|
||||
List<DynamicTest> tests = new ArrayList<>();
|
||||
for (String model : routedModels(document)) {
|
||||
String scope = models.path(model).path("credentialScope").asText();
|
||||
Iterator<Map.Entry<String, JsonNode>> operations = models.path(model).path("operations").fields();
|
||||
while (operations.hasNext()) {
|
||||
Map.Entry<String, JsonNode> operation = operations.next();
|
||||
Route route = new Route(scope, model, operation.getKey(), operation.getValue().path("method").asText(),
|
||||
operation.getValue().path("requestUri").asText());
|
||||
tests.add(DynamicTest.dynamicTest(model + " " + operation.getKey(), () -> {
|
||||
ContainerRequestContext request = route.request();
|
||||
String matched = IamRestRoutes.vendored().operation(scope, route.method(),
|
||||
request.getUriInfo().getPath(), request.getUriInfo().getQueryParameters()).orElse(null);
|
||||
assertEquals(IamAuthorizedActions.actionFor(scope, operation.getKey()),
|
||||
matched == null ? null : IamAuthorizedActions.actionFor(scope, matched), route.toString());
|
||||
}));
|
||||
}
|
||||
}
|
||||
return tests.stream();
|
||||
}
|
||||
|
||||
/**
|
||||
* Every route of the s3control model, which signs with the s3 scope. A route Floci serves is
|
||||
* checked as the action the Service Reference gives the operation, with the account-level
|
||||
@@ -177,6 +217,19 @@ class IamRestRouteCoverageTest {
|
||||
return tests.stream();
|
||||
}
|
||||
|
||||
/** The models of every credential scope the vendored routes do not list as hand-routed. */
|
||||
private static List<String> routedModels(JsonNode document) {
|
||||
List<String> models = new ArrayList<>();
|
||||
Iterator<Map.Entry<String, JsonNode>> all = document.path("models").fields();
|
||||
while (all.hasNext()) {
|
||||
Map.Entry<String, JsonNode> model = all.next();
|
||||
if (!document.path("handRouted").has(model.getValue().path("credentialScope").asText())) {
|
||||
models.add(model.getKey());
|
||||
}
|
||||
}
|
||||
return models;
|
||||
}
|
||||
|
||||
/** Every model route of {@code operation} among the models Floci authorizes under {@code scope}. */
|
||||
private static List<Route> routesOf(JsonNode models, String scope, String operation) {
|
||||
List<Route> routes = new ArrayList<>();
|
||||
|
||||
+46
@@ -492,6 +492,52 @@ class IamRestRouteEnforcementIntegrationTest {
|
||||
admin().get("/2017-03-31/tags/" + image).then().statusCode(200).body("Tags.size()", equalTo(0));
|
||||
}
|
||||
|
||||
/**
|
||||
* A route no rule maps is checked as the operation of its vendored route when AWS authorizes that operation's
|
||||
* action on no resource type, in both OpenSearch API versions and for Access Analyzer; one AWS checks on a domain
|
||||
* stays unchecked, so a grant scoped to the domain is not refused for want of reading it.
|
||||
*/
|
||||
@Test
|
||||
void aVendoredRouteIsCheckedWhenAwsAuthorizesItsActionOnNoResourceType() {
|
||||
String user = user("route-vendored");
|
||||
|
||||
policy(user, allow("es:ListVpcEndpoints", "*"));
|
||||
refused(as(user, "es").get("/2021-01-01/domain").then(), "es:ListDomainNames");
|
||||
refused(as(user, "es").get("/2015-01-01/domain").then(), "es:ListDomainNames");
|
||||
refused(as(user, "es").get("/2021-01-01/opensearch/versions").then(), "es:ListVersions");
|
||||
refused(as(user, "access-analyzer").get("/analyzer").then(), "access-analyzer:ListAnalyzers");
|
||||
as(user, "es").get("/2021-01-01/opensearch/domain/route-missing-" + suffix()).then().statusCode(409)
|
||||
.body(containsString("ResourceNotFoundException"));
|
||||
|
||||
policy(user, allow("es:ListDomainNames", "*"));
|
||||
as(user, "es").get("/2021-01-01/domain").then().statusCode(200);
|
||||
as(user, "es").get("/2015-01-01/domain").then().statusCode(200);
|
||||
}
|
||||
|
||||
/**
|
||||
* A segment ending in a matrix parameter, which the router ignores, is checked as the route it reaches, on the
|
||||
* resource its path names: the routed path carries no matrix parameter, so the rule matches and the ARN is the
|
||||
* named resource's, and a grant scoped to it lets the request through while a caller with none is refused.
|
||||
*/
|
||||
@Test
|
||||
void aMatrixParameterLeavesARouteCheckedOnTheResourceItNames() {
|
||||
String scheduler = user("route-matrix-scheduler");
|
||||
String lambda = user("route-matrix-lambda");
|
||||
String nobody = user("route-matrix-nobody");
|
||||
policy(scheduler, allow("scheduler:GetScheduleGroup",
|
||||
"arn:aws:scheduler:us-east-1:" + ACCOUNT + ":schedule-group/default"));
|
||||
policy(lambda, allow("lambda:GetFunction", "arn:aws:lambda:us-east-1:" + ACCOUNT + ":function:route-matrix-fn"));
|
||||
for (String path : new String[]{"/schedule-groups;ignored=yes/default", "/schedule-groups/default;ignored=yes"}) {
|
||||
as(scheduler, "scheduler").urlEncodingEnabled(false).get(path).then().statusCode(200);
|
||||
refused(as(nobody, "scheduler").urlEncodingEnabled(false).get(path).then(), "scheduler:GetScheduleGroup");
|
||||
}
|
||||
for (String path : new String[]{"/2015-03-31/functions;ignored=yes/route-matrix-fn",
|
||||
"/2015-03-31/functions/route-matrix-fn;ignored=yes"}) {
|
||||
as(lambda, "lambda").urlEncodingEnabled(false).get(path).then().statusCode(404);
|
||||
refused(as(nobody, "lambda").urlEncodingEnabled(false).get(path).then(), "lambda:GetFunction");
|
||||
}
|
||||
}
|
||||
|
||||
/** Creates a MicroVM image as the account's admin, removed afterwards, and returns its ARN. */
|
||||
private String microvmImage(String name) {
|
||||
admin().body("""
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
package io.github.hectorvent.floci.services.iam;
|
||||
|
||||
import jakarta.ws.rs.core.MultivaluedHashMap;
|
||||
import jakarta.ws.rs.core.MultivaluedMap;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.ValueSource;
|
||||
@@ -10,13 +12,39 @@ import java.io.InputStream;
|
||||
import java.net.URL;
|
||||
import java.net.URLClassLoader;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertNotNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
|
||||
class IamRestRoutesTest {
|
||||
|
||||
private static final String ROUTES = """
|
||||
{"handRouted": {"hand": "the rules route it alone"},
|
||||
"models": {
|
||||
"svc": {"credentialScope": "svc", "operations": {
|
||||
"ListThings": {"method": "GET", "requestUri": "/things/"},
|
||||
"GetThing": {"method": "GET", "requestUri": "/things/{ThingName}"},
|
||||
"GetThingPolicy": {"method": "GET", "requestUri": "/things/policy"},
|
||||
"GetThingVersion": {"method": "GET", "requestUri": "/things/{ThingName}:{Version}"},
|
||||
"GetPart": {"method": "GET", "requestUri": "/things/{ThingName}/parts/{PartPath+}"},
|
||||
"ListParts": {"method": "GET", "requestUri": "/things/{ThingName}/parts/list"},
|
||||
"UpdateThing": {"method": "POST", "requestUri": "/things/{ThingName}"},
|
||||
"TagThing": {"method": "POST", "requestUri": "/things/{ThingName}?tagging"},
|
||||
"ListVersions": {"method": "GET", "requestUri": "/versions"},
|
||||
"ListVersionsV2": {"method": "GET", "requestUri": "/versions?list-type=2"},
|
||||
"ValidateThing": {"method": "GET", "requestUri": "/from.data/validation"},
|
||||
"GetRoot": {"method": "GET", "requestUri": "/"}
|
||||
}},
|
||||
"hand": {"credentialScope": "hand", "operations": {
|
||||
"Ping": {"method": "GET", "requestUri": "/ping"}
|
||||
}}
|
||||
}}""";
|
||||
|
||||
private final IamRestRoutes routes = routes(ROUTES);
|
||||
|
||||
@Test
|
||||
void routeDataIsBundledWithTheApplicationRatherThanOnlyWithTests() throws Exception {
|
||||
URL application = IamActionRegistry.class.getProtectionDomain().getCodeSource().getLocation();
|
||||
@@ -27,58 +55,117 @@ class IamRestRoutesTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
void methodPathAndNamespaceComeFromTheModelAndLiteralSegmentsKeepMatrixHandling() throws IOException {
|
||||
IamRestRoutes table = parse(snapshot("from-data", "GET", "/from.data/validation"));
|
||||
assertEquals("from-data:ValidatePolicy", table.resolve("from-data", "GET", "/from.data/validation"));
|
||||
assertEquals("from-data:ValidatePolicy",
|
||||
table.resolve("from-data", "GET", "/from.data;ignored=yes/validation;ignored=yes"));
|
||||
assertNull(table.resolve("from-data", "GET", "/fromXdata/validation"));
|
||||
assertNull(table.resolve("from-data", "POST", "/from.data/validation"));
|
||||
assertNull(table.resolve("other", "GET", "/from.data/validation"));
|
||||
assertNull(table.resolve("from-data", "POST", "/policy/validation"));
|
||||
void aLiteralSegmentOutranksALabel() {
|
||||
assertEquals(Optional.of("GetThingPolicy"), get("/things/policy"));
|
||||
assertEquals(Optional.of("GetThing"), get("/things/web"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void operationsWithoutResourceArnSupportAreNotEnrolledBySharingTheModel() throws IOException {
|
||||
String document = snapshot("from-data", "GET", "/from.data/validation")
|
||||
.replace("\"ValidatePolicy\":", "\"CreateAnalyzer\": {\"method\":\"PUT\",\"requestUri\":\"/analyzer\"},"
|
||||
+ "\"ValidatePolicy\":");
|
||||
IamRestRoutes table = parse(document);
|
||||
assertNull(table.resolve("from-data", "PUT", "/analyzer"));
|
||||
void aSegmentMixingALiteralAndALabelOutranksALabel() {
|
||||
assertEquals(Optional.of("GetThingVersion"), get("/things/web:3"));
|
||||
}
|
||||
|
||||
/** A greedy label takes the rest of the path, one segment or more, and ranks below a literal there. */
|
||||
@Test
|
||||
void aGreedyLabelTakesTheRestOfThePath() {
|
||||
assertEquals(Optional.of("GetPart"), get("/things/web/parts/a/b/c"));
|
||||
assertEquals(Optional.of("GetPart"), get("/things/web/parts/a"));
|
||||
assertEquals(Optional.of("ListParts"), get("/things/web/parts/list"));
|
||||
assertEquals(Optional.empty(), get("/things/web/parts"));
|
||||
}
|
||||
|
||||
/** A query the route names must be on the request, with the value it gives, if any. */
|
||||
@Test
|
||||
void aQueryTheRouteNamesMustBeOnTheRequest() {
|
||||
assertEquals(Optional.of("TagThing"), routes.operation("svc", "POST", "/things/web", query("tagging", "")));
|
||||
assertEquals(Optional.of("UpdateThing"), routes.operation("svc", "POST", "/things/web", query("other", "")));
|
||||
assertEquals(Optional.of("UpdateThing"), routes.operation("svc", "POST", "/things/web", null));
|
||||
assertEquals(Optional.of("ListVersionsV2"), routes.operation("svc", "GET", "/versions",
|
||||
query("list-type", "2")));
|
||||
assertEquals(Optional.of("ListVersions"), routes.operation("svc", "GET", "/versions",
|
||||
query("list-type", "1")));
|
||||
}
|
||||
|
||||
/** A trailing slash is dropped, as the router drops it, and an encoded slash stays inside its label. */
|
||||
@Test
|
||||
void aPathIsReadAsTheRouterMatchedIt() {
|
||||
assertEquals(Optional.of("ListThings"), get("/things"));
|
||||
assertEquals(Optional.of("ListThings"), get("/things/"));
|
||||
assertEquals(Optional.of("GetThing"), get("/things/web%2Fpart"));
|
||||
assertEquals(Optional.of("GetRoot"), get("/"));
|
||||
}
|
||||
|
||||
/**
|
||||
* A literal segment matches itself alone, a dot in it no other character, and may end in a matrix parameter,
|
||||
* which RESTEasy keeps in the path it matched.
|
||||
*/
|
||||
@Test
|
||||
void aLiteralSegmentKeepsItsMatrixParameters() {
|
||||
assertEquals(Optional.of("ValidateThing"), get("/from.data/validation"));
|
||||
assertEquals(Optional.of("ValidateThing"), get("/from.data;ignored=yes/validation;ignored=yes"));
|
||||
assertEquals(Optional.empty(), get("/fromXdata/validation"));
|
||||
assertEquals(Optional.empty(), get("/from.data%3Bignored/validation"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aRequestOfAnotherMethodOrScopeOrOfAHandRoutedScopeMatchesNothing() {
|
||||
assertEquals(Optional.empty(), routes.operation("svc", "DELETE", "/things/web", null));
|
||||
assertEquals(Optional.empty(), routes.operation("other", "GET", "/things/web", null));
|
||||
assertEquals(Optional.empty(), routes.operation("hand", "GET", "/ping", null));
|
||||
assertEquals(Optional.empty(), get("/nothing"));
|
||||
}
|
||||
|
||||
/** The vendored routes load, a model routed under the scope it signs with, and S3 is left to its rules. */
|
||||
@Test
|
||||
void theVendoredRoutesAreRead() {
|
||||
assertEquals(Optional.of("GetFunction"),
|
||||
IamRestRoutes.vendored().operation("lambda", "GET", "/2015-03-31/functions/fn", null));
|
||||
assertEquals(Optional.of("ListNetworkConnectors"),
|
||||
IamRestRoutes.vendored().operation("lambda", "GET", "/2026-04-04/network-connectors", null));
|
||||
assertEquals(Optional.of("DescribeDomain"),
|
||||
IamRestRoutes.vendored().operation("es", "GET", "/2021-01-01/opensearch/domain/logs", null));
|
||||
assertEquals(Optional.of("DescribeElasticsearchDomain"),
|
||||
IamRestRoutes.vendored().operation("es", "GET", "/2015-01-01/es/domain/logs", null));
|
||||
assertEquals(Optional.empty(), IamRestRoutes.vendored().operation("s3", "GET", "/bucket", null));
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(strings = {"", "{}", "{\"models\":[]}", "{\"models\":{}}"})
|
||||
@ValueSource(strings = {"", "{}", "{\"models\":[]}", "{\"handRouted\": {}, \"models\":{}}"})
|
||||
void missingRouteDataFailsRatherThanProvidingAnEmptyAuthorizationTable(String document) {
|
||||
assertThrows(IOException.class, () -> parse(document));
|
||||
assertThrows(IllegalStateException.class, () -> routes(document));
|
||||
}
|
||||
|
||||
@Test
|
||||
void theSelectedOperationAndItsRequiredFieldsMustExist() {
|
||||
assertThrows(IOException.class,
|
||||
() -> parse(snapshot("from-data", "GET", "/path").replace("ValidatePolicy", "OtherOperation")));
|
||||
assertThrows(IOException.class, () -> parse(snapshot("", "GET", "/path")));
|
||||
assertThrows(IOException.class, () -> parse(snapshot("from-data", "INVALID", "/path")));
|
||||
assertThrows(IOException.class, () -> parse(snapshot("from-data", "GET", "")));
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(strings = {"/path/{id}", "/path?query=1", "/path#fragment", "/path;matrix=x", "no-leading-slash"})
|
||||
void unsupportedEnrolledPathShapesFailRatherThanSilentlyMissingTheRoute(String path) {
|
||||
assertThrows(IOException.class, () -> parse(snapshot("from-data", "GET", path)));
|
||||
}
|
||||
|
||||
private static IamRestRoutes parse(String document) throws IOException {
|
||||
try (InputStream in = new ByteArrayInputStream(document.getBytes(StandardCharsets.UTF_8))) {
|
||||
return IamRestRoutes.parse(in);
|
||||
void aMalformedFileFailsToLoad() {
|
||||
for (String bad : List.of("{\"models\": {\"svc\": {\"credentialScope\": \"svc\", \"operations\": {}}}}",
|
||||
"{\"handRouted\": {}, \"models\": {\"svc\": {\"credentialScope\": \"svc\", \"operations\": {}}}}",
|
||||
"{\"handRouted\": {}, \"models\": {\"svc\": {\"operations\": {}}}}",
|
||||
"{\"handRouted\": {}, \"models\": {\"svc\": {\"credentialScope\": \"svc\"}}}",
|
||||
"{\"handRouted\": {}, \"models\": {\"svc\": {\"credentialScope\": \"svc\", \"operations\": "
|
||||
+ "{\"Op\": {\"requestUri\": \"/op\"}}}}}",
|
||||
"{\"handRouted\": {}, \"models\": {\"svc\": {\"credentialScope\": \"svc\", \"operations\": "
|
||||
+ "{\"Op\": {\"method\": \"INVALID\", \"requestUri\": \"/op\"}}}}}",
|
||||
"{\"handRouted\": {}, \"models\": {\"svc\": {\"credentialScope\": \"svc\", \"operations\": "
|
||||
+ "{\"Op\": {\"method\": \"GET\", \"requestUri\": \"op\"}}}}}")) {
|
||||
assertThrows(IllegalStateException.class, () -> routes(bad), bad);
|
||||
}
|
||||
}
|
||||
|
||||
private static String snapshot(String scope, String method, String path) {
|
||||
return """
|
||||
{"models":{"accessanalyzer":{"credentialScope":"%s","operations":{
|
||||
"ValidatePolicy":{"method":"%s","requestUri":"%s"}
|
||||
}}}}
|
||||
""".formatted(scope, method, path);
|
||||
private Optional<String> get(String path) {
|
||||
return routes.operation("svc", "GET", path, null);
|
||||
}
|
||||
|
||||
private static MultivaluedMap<String, String> query(String name, String value) {
|
||||
MultivaluedMap<String, String> query = new MultivaluedHashMap<>();
|
||||
query.add(name, value);
|
||||
return query;
|
||||
}
|
||||
|
||||
private static IamRestRoutes routes(String json) {
|
||||
try {
|
||||
return IamRestRoutes.parse(new ByteArrayInputStream(json.getBytes(StandardCharsets.UTF_8)));
|
||||
} catch (IOException e) {
|
||||
throw new IllegalStateException(e);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -50,14 +50,27 @@ Two kinds of listed action do not count towards "exactly one":
|
||||
and modify budgets", adding "Creating a budget with tags also requires the 'budgets:TagResource'
|
||||
permission".
|
||||
|
||||
The file also lists, for each credential scope whose REST routes `rest-routes.json` reads (the
|
||||
scopes it leaves to the registry's rules, `handRouted`, aside), the actions of that namespace the
|
||||
reference gives no resource type, from its `Actions`. A REST request no rule of `IamActionRegistry`
|
||||
maps is checked as the operation whose route it matches only when that operation's action is one of
|
||||
them. Floci checks a REST request on `*` until it reads the resources in its path, and AWS authorizes
|
||||
such an action on `*` too, so the check is the one AWS makes. An action AWS authorizes on a resource
|
||||
stays unchecked instead: checked on `*`, a grant scoped to its resource would be refused. These are
|
||||
read from `Actions`, not `Operations`, because the reference lists the operations of one SDK client
|
||||
per namespace: OpenSearch's are the `es` client's alone, none of the `opensearch` client's, whose
|
||||
operations are named after `es` actions all the same.
|
||||
|
||||
The endpoint is live rather than a pinned dependency, so a fresh generation is not byte-identical.
|
||||
As with `regen_iam_action_resources.py`, what must hold is that nothing here is invented:
|
||||
|
||||
- `--check` is offline and structural: sorted, every name usable, every action in its own
|
||||
namespace and differing from the operation, and the anchor cases still present.
|
||||
namespace and differing from the operation, and the anchor cases still present; and the actions
|
||||
without resource types are listed for exactly the scopes `rest-routes.json` reads routes for.
|
||||
- `--verify` is the real gate and needs the network. Every vendored entry must still be what AWS
|
||||
publishes for that operation. An entry AWS has added is reported without failing: being behind
|
||||
leaves that operation authorized as its own name, which is where it was before this existed.
|
||||
publishes for that operation, and every action listed without resource types must still have
|
||||
none. An entry AWS has added is reported without failing: being behind leaves that operation
|
||||
authorized as its own name, or that route unchecked, which is where it was before this existed.
|
||||
|
||||
Run from anywhere in the repo:
|
||||
python3 tools/aws/regen_iam_authorized_actions.py # rewrite the vendored file in place
|
||||
@@ -78,6 +91,7 @@ from pathlib import Path
|
||||
|
||||
REPO_ROOT = Path(__file__).resolve().parents[2]
|
||||
OUTPUT = REPO_ROOT / "src/main/resources/aws/iam-authorized-actions.json"
|
||||
ROUTES = REPO_ROOT / "src/main/resources/aws/rest-routes.json"
|
||||
INDEX_URL = "https://servicereference.us-east-1.amazonaws.com/"
|
||||
FETCH_TIMEOUT_SECONDS = 30
|
||||
FETCH_WORKERS = 8
|
||||
@@ -199,7 +213,31 @@ def _sdk_clients(namespace: str, operation: dict) -> set[str]:
|
||||
return {sdk["Name"] for sdk in sdks}
|
||||
|
||||
|
||||
def build(documents: list[dict], provenance: str) -> dict:
|
||||
def routed_namespaces(routes: dict) -> list[str]:
|
||||
"""The credential scopes whose REST routes the vendored routes read: every model's but those the registry's
|
||||
rules authorize alone."""
|
||||
hand_routed = routes.get("handRouted") or {}
|
||||
return sorted({model["credentialScope"] for model in (routes.get("models") or {}).values()
|
||||
if model["credentialScope"] not in hand_routed})
|
||||
|
||||
|
||||
def actions_without_resource_types(documents: list[dict], namespaces: list[str]) -> dict[str, list[str]]:
|
||||
"""Each of the namespaces' actions the reference gives no resource type, sorted."""
|
||||
by_name = {document.get("Name"): document for document in documents}
|
||||
missing = [namespace for namespace in namespaces if namespace not in by_name]
|
||||
if missing:
|
||||
raise ValueError(f"the Service Reference has no namespace {', '.join(missing)}, whose REST routes "
|
||||
f"rest-routes.json reads")
|
||||
found = {}
|
||||
for namespace in namespaces:
|
||||
actions = by_name[namespace].get("Actions") or []
|
||||
if not all(isinstance(action, dict) and isinstance(action.get("Name"), str) for action in actions):
|
||||
raise ValueError(f"{namespace}: 'Actions' is not a list of objects with a string 'Name'")
|
||||
found[namespace] = sorted(action["Name"] for action in actions if not action.get("Resources"))
|
||||
return found
|
||||
|
||||
|
||||
def build(documents: list[dict], provenance: str, routed: list[str]) -> dict:
|
||||
return {
|
||||
"_source": {
|
||||
"generator": "tools/aws/regen_iam_authorized_actions.py",
|
||||
@@ -208,6 +246,7 @@ def build(documents: list[dict], provenance: str) -> dict:
|
||||
"note": "make iam-authorized-actions-verify checks every entry against AWS.",
|
||||
},
|
||||
"authorizedActions": authorized_actions_from(documents),
|
||||
"actionsWithoutResourceTypes": actions_without_resource_types(documents, routed),
|
||||
}
|
||||
|
||||
|
||||
@@ -215,9 +254,9 @@ def render(document: dict) -> str:
|
||||
return json.dumps(document, indent=2) + "\n"
|
||||
|
||||
|
||||
def validate(document: dict) -> list[str]:
|
||||
def validate(document: dict, routed: list[str]) -> list[str]:
|
||||
"""Problems that make the vendored file unusable, rather than merely out of date."""
|
||||
problems: list[str] = []
|
||||
problems = _unscoped_problems(document.get("actionsWithoutResourceTypes"), routed)
|
||||
namespaces = document.get("authorizedActions")
|
||||
if not isinstance(namespaces, dict) or not namespaces:
|
||||
return ["authorizedActions is missing or empty"]
|
||||
@@ -248,6 +287,24 @@ def validate(document: dict) -> list[str]:
|
||||
return problems
|
||||
|
||||
|
||||
def _unscoped_problems(unscoped: object, routed: list[str]) -> list[str]:
|
||||
"""Problems with the actions without resource types: one sorted list of usable names for each scope whose
|
||||
routes are read, and for no other."""
|
||||
if not isinstance(unscoped, dict):
|
||||
return ["actionsWithoutResourceTypes is missing"]
|
||||
problems = []
|
||||
if list(unscoped) != routed:
|
||||
problems.append(f"actionsWithoutResourceTypes lists {list(unscoped)}, not the scopes rest-routes.json reads "
|
||||
f"routes for, {routed}")
|
||||
for namespace, actions in unscoped.items():
|
||||
if not isinstance(actions, list) or not all(isinstance(action, str) and NAME_RE.match(action)
|
||||
for action in actions):
|
||||
problems.append(f"actionsWithoutResourceTypes.{namespace} is not a list of action names")
|
||||
elif actions != sorted(set(actions)):
|
||||
problems.append(f"actionsWithoutResourceTypes.{namespace} is not sorted, or repeats an action")
|
||||
return problems
|
||||
|
||||
|
||||
def verify_against(vendored: dict[str, dict[str, str]],
|
||||
upstream: dict[str, dict[str, str]]) -> tuple[list[str], list[str]]:
|
||||
"""What the vendored file claims and AWS does not, and what AWS has since added.
|
||||
@@ -270,6 +327,34 @@ def verify_against(vendored: dict[str, dict[str, str]],
|
||||
return untrue, sorted(added)
|
||||
|
||||
|
||||
def verify_unscoped_against(vendored: dict[str, list[str]],
|
||||
upstream: dict[str, list[str]]) -> tuple[list[str], list[str]]:
|
||||
"""The actions the vendored file lists without resource types that AWS gives one or no longer has, and those
|
||||
AWS has since added without one.
|
||||
|
||||
A listed action AWS gives a resource type is a failure: a request would be checked on `*` where AWS checks
|
||||
the resource. One AWS has added only leaves its route unchecked until the next sync.
|
||||
"""
|
||||
untrue = [f"AWS gives {namespace}:{action} a resource type, or no longer has it"
|
||||
for namespace, actions in vendored.items() for action in actions
|
||||
if action not in upstream.get(namespace, [])]
|
||||
added = sorted(f"{namespace}:{action}" for namespace, actions in upstream.items() for action in actions
|
||||
if action not in vendored.get(namespace, []))
|
||||
return untrue, added
|
||||
|
||||
|
||||
def _unscoped_count(document: dict) -> str:
|
||||
"""How many actions without resource types the document lists, over how many scopes."""
|
||||
unscoped = document["actionsWithoutResourceTypes"]
|
||||
return (f"{sum(len(actions) for actions in unscoped.values())} actions without resource types over "
|
||||
f"{len(unscoped)} routed scopes")
|
||||
|
||||
|
||||
def _routed(routes: Path) -> list[str]:
|
||||
"""The scopes the vendored REST routes read routes for."""
|
||||
return routed_namespaces(json.loads(routes.read_text(encoding="utf-8")))
|
||||
|
||||
|
||||
def _shown(path: Path) -> Path:
|
||||
"""The path relative to the repository when it is inside it, as the messages print it."""
|
||||
try:
|
||||
@@ -288,6 +373,7 @@ def main(argv: list[str] | None = None) -> int:
|
||||
parser.add_argument("--source-dir", type=Path, default=None,
|
||||
help="read saved <service>.json reference files instead of fetching them")
|
||||
parser.add_argument("--output", type=Path, default=OUTPUT, help=argparse.SUPPRESS)
|
||||
parser.add_argument("--routes", type=Path, default=ROUTES, help=argparse.SUPPRESS)
|
||||
args = parser.parse_args(argv)
|
||||
|
||||
if args.check:
|
||||
@@ -295,36 +381,44 @@ def main(argv: list[str] | None = None) -> int:
|
||||
print(f"error: {args.output} does not exist", file=sys.stderr)
|
||||
return 1
|
||||
document = json.loads(args.output.read_text(encoding="utf-8"))
|
||||
problems = validate(document)
|
||||
problems = validate(document, _routed(args.routes))
|
||||
for problem in problems:
|
||||
print(f"error: {problem}", file=sys.stderr)
|
||||
if problems:
|
||||
return 1
|
||||
entries = sum(len(operations) for operations in document["authorizedActions"].values())
|
||||
print(f"{_shown(args.output)} is well-formed "
|
||||
f"({entries} operations over {len(document['authorizedActions'])} namespaces)")
|
||||
f"({entries} operations over {len(document['authorizedActions'])} namespaces, "
|
||||
f"{_unscoped_count(document)})")
|
||||
return 0
|
||||
|
||||
if args.verify:
|
||||
if not args.output.exists():
|
||||
print(f"error: {args.output} does not exist", file=sys.stderr)
|
||||
return 1
|
||||
vendored = json.loads(args.output.read_text(encoding="utf-8"))["authorizedActions"]
|
||||
vendored_document = json.loads(args.output.read_text(encoding="utf-8"))
|
||||
vendored = vendored_document["authorizedActions"]
|
||||
unscoped = vendored_document.get("actionsWithoutResourceTypes") or {}
|
||||
try:
|
||||
documents, provenance = fetch_references(args.source_dir)
|
||||
upstream = authorized_actions_from(documents)
|
||||
upstream_unscoped = actions_without_resource_types(documents, list(unscoped))
|
||||
except (OSError, ValueError) as e:
|
||||
# The gate could not run, which CI has to tell apart from having found something
|
||||
# invented. ValueError covers a malformed or truncated response as well.
|
||||
print(f"error: could not read the Service Reference ({e})", file=sys.stderr)
|
||||
return 2
|
||||
untrue, added = verify_against(vendored, upstream)
|
||||
untrue_unscoped, added_unscoped = verify_unscoped_against(unscoped, upstream_unscoped)
|
||||
untrue += untrue_unscoped
|
||||
added += added_unscoped
|
||||
for claim in untrue:
|
||||
print(f"error: {claim}", file=sys.stderr)
|
||||
entries = sum(len(operations) for operations in vendored.values())
|
||||
if untrue:
|
||||
print(f"error: {len(untrue)} vendored claim(s) do not hold upstream; those operations "
|
||||
f"would be authorized as an action AWS does not check.", file=sys.stderr)
|
||||
f"would be authorized as an action AWS does not check, or on a resource it does not.",
|
||||
file=sys.stderr)
|
||||
return 1
|
||||
if added:
|
||||
print(f"{_shown(args.output)}: all {entries} entries verified. AWS has "
|
||||
@@ -337,11 +431,12 @@ def main(argv: list[str] | None = None) -> int:
|
||||
|
||||
try:
|
||||
documents, provenance = fetch_references(args.source_dir)
|
||||
document = build(documents, provenance)
|
||||
routed = _routed(args.routes)
|
||||
document = build(documents, provenance, routed)
|
||||
except (OSError, ValueError) as e:
|
||||
print(f"error: could not read the Service Reference ({e})", file=sys.stderr)
|
||||
return 2
|
||||
problems = validate(document)
|
||||
problems = validate(document, routed)
|
||||
for problem in problems:
|
||||
print(f"error: {problem}", file=sys.stderr)
|
||||
if problems:
|
||||
@@ -349,7 +444,7 @@ def main(argv: list[str] | None = None) -> int:
|
||||
args.output.write_text(render(document), encoding="utf-8")
|
||||
entries = sum(len(operations) for operations in document["authorizedActions"].values())
|
||||
print(f"wrote {_shown(args.output)} ({entries} operations over "
|
||||
f"{len(document['authorizedActions'])} namespaces, from {provenance})")
|
||||
f"{len(document['authorizedActions'])} namespaces, {_unscoped_count(document)}, from {provenance})")
|
||||
return 0
|
||||
|
||||
|
||||
|
||||
@@ -2,11 +2,16 @@
|
||||
"""Regenerate src/main/resources/aws/rest-routes.json from botocore's models.
|
||||
|
||||
A REST request is authorized by its route: `IamActionRegistry` maps the HTTP method and path to the
|
||||
IAM action, and a route no rule maps is left unchecked. Whether every operation of a service reaches
|
||||
the action AWS checks for it can only be tested against the operation's real route, which is what
|
||||
this vendors: for each operation of the models below, its HTTP method and request URI exactly as
|
||||
the SDKs send them. `IamRestRouteCoverageTest` builds a request on each route and compares the
|
||||
action the registry gives with the one `iam-authorized-actions.json` names, or the operation's own.
|
||||
IAM action, by its rules first and then by these routes, and a route neither maps is left unchecked.
|
||||
This vendors, for each operation of the models below, its HTTP method and request URI exactly as the
|
||||
SDKs send them. A request no rule maps is the operation whose route it matches, checked as the action
|
||||
`iam-authorized-actions.json` names for it, or as its own; `IamRestRouteCoverageTest` builds a
|
||||
request on each route and compares the action the registry gives with that one.
|
||||
|
||||
The credential scopes in `HAND_ROUTED` are authorized by the registry's rules alone, each for its
|
||||
reason, and their routes are vendored for the coverage test only. Within any other scope, two
|
||||
operations on one route would leave a request matching it no single operation, so the generation
|
||||
fails on them.
|
||||
|
||||
The models are botocore's `<model>/<apiVersion>/service-2.json` (Apache-2.0,
|
||||
https://github.com/boto/botocore), the latest API version of each, located as
|
||||
@@ -21,6 +26,7 @@ from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import json
|
||||
import re
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
@@ -30,6 +36,16 @@ from regen_query_services import latest_model_dir, load_model
|
||||
REPO_ROOT = Path(__file__).resolve().parents[2]
|
||||
OUTPUT = REPO_ROOT / "src/main/resources/aws/rest-routes.json"
|
||||
|
||||
# Credential scopes the registry's rules authorize alone, and why.
|
||||
HAND_ROUTED: dict[str, str] = {
|
||||
"apigateway": "API Gateway's management API is authorized by HTTP method, apigateway:GET, apigateway:POST "
|
||||
"and so on, on the resource path a route names, not by its operations' names, and the "
|
||||
"registry's rules give every route its method's action",
|
||||
"s3": "S3 tells apart the operations it serves on one route by their query parameters and headers, which the "
|
||||
"registry's S3 rules and sub-resource overrides read, and an S3 Control route Floci does not serve "
|
||||
"runs as the S3 data plane, checked as the bucket or object operation that runs",
|
||||
}
|
||||
|
||||
# botocore model -> the credential scope Floci authorizes its requests under.
|
||||
MODELS: dict[str, str] = {
|
||||
"accessanalyzer": "access-analyzer",
|
||||
@@ -37,9 +53,11 @@ MODELS: dict[str, str] = {
|
||||
"apigatewayv2": "apigateway",
|
||||
"dsql": "dsql",
|
||||
"eks": "eks",
|
||||
"es": "es",
|
||||
"lambda": "lambda",
|
||||
"lambda-core": "lambda",
|
||||
"lambda-microvms": "lambda",
|
||||
"opensearch": "es",
|
||||
"pipes": "pipes",
|
||||
"s3": "s3",
|
||||
"s3control": "s3",
|
||||
@@ -63,22 +81,52 @@ def build(models: dict[str, dict], provenance: str) -> dict:
|
||||
"apiVersion": model["metadata"]["apiVersion"],
|
||||
"operations": operations,
|
||||
}
|
||||
shared = shared_routes(routes)
|
||||
if shared:
|
||||
raise SystemExit("error: one route names more than one operation in a scope the rules do not route alone: "
|
||||
+ "; ".join(shared))
|
||||
return {
|
||||
"_source": {
|
||||
"generator": "tools/aws/regen_rest_routes.py",
|
||||
"botocore": provenance,
|
||||
},
|
||||
"handRouted": dict(sorted(HAND_ROUTED.items())),
|
||||
"models": routes,
|
||||
}
|
||||
|
||||
|
||||
def route_key(method: str, request_uri: str) -> tuple:
|
||||
"""A route as a request matches it: its method, its path's segments with every label alike, and its query."""
|
||||
path, _, query = request_uri.partition("?")
|
||||
segments = tuple("{+}" if re.fullmatch(r"\{[^}]+\+}", segment) else re.sub(r"\{[^}]+}", "{}", segment)
|
||||
for segment in path.strip("/").split("/"))
|
||||
return method, segments, tuple(sorted(query.split("&"))) if query else ()
|
||||
|
||||
|
||||
def shared_routes(routes: dict[str, dict]) -> list[str]:
|
||||
"""The routes that name more than one operation within a scope `HAND_ROUTED` does not name."""
|
||||
named: dict[tuple, set[str]] = {}
|
||||
for name, model in routes.items():
|
||||
if model["credentialScope"] in HAND_ROUTED:
|
||||
continue
|
||||
for operation, route in model["operations"].items():
|
||||
key = (model["credentialScope"],) + route_key(route["method"], route["requestUri"])
|
||||
named.setdefault(key, set()).add(operation)
|
||||
return [f"{key[0]} {key[1]} {'/'.join(key[2])}: {', '.join(sorted(operations))}"
|
||||
for key, operations in sorted(named.items()) if len(operations) > 1]
|
||||
|
||||
|
||||
def load_models(data: Path) -> dict[str, dict]:
|
||||
return {name: load_model(latest_model_dir(data, name)) for name in MODELS}
|
||||
|
||||
|
||||
def render(doc: dict) -> str:
|
||||
"""The document with one operation to a line, so a model's routes read as a table."""
|
||||
lines = ["{", f' "_source": {json.dumps(doc["_source"])},', ' "models": {']
|
||||
lines = ["{", f' "_source": {json.dumps(doc["_source"])},', ' "handRouted": {']
|
||||
hand = list(doc["handRouted"].items())
|
||||
for position, (scope, reason) in enumerate(hand):
|
||||
lines.append(f" {json.dumps(scope)}: {json.dumps(reason)}" + ("," if position < len(hand) - 1 else ""))
|
||||
lines += [" },", ' "models": {']
|
||||
models = list(doc["models"].items())
|
||||
for index, (name, model) in enumerate(models):
|
||||
lines.append(f" {json.dumps(name)}: {{")
|
||||
|
||||
@@ -209,7 +209,7 @@ def test_a_malformed_sdk_list_is_a_malformed_response():
|
||||
# validate: the offline --check gate
|
||||
# --------------------------------------------------------------------------- #
|
||||
def anchored(extra: dict[str, dict[str, str]] | None = None) -> dict:
|
||||
document = r.build(ANCHOR_SERVICES, "a test")
|
||||
document = r.build(ANCHOR_SERVICES, "a test", [])
|
||||
for namespace, operations in (extra or {}).items():
|
||||
document["authorizedActions"].setdefault(namespace, {}).update(operations)
|
||||
document["authorizedActions"] = {
|
||||
@@ -219,39 +219,39 @@ def anchored(extra: dict[str, dict[str, str]] | None = None) -> dict:
|
||||
|
||||
|
||||
def test_a_freshly_built_document_validates():
|
||||
assert r.validate(anchored()) == []
|
||||
assert r.validate(anchored(), []) == []
|
||||
|
||||
|
||||
def test_an_action_in_another_namespace_is_rejected():
|
||||
problems = r.validate(anchored({"sqs": {"PurgeQueueBatch": "sns:Publish"}}))
|
||||
problems = r.validate(anchored({"sqs": {"PurgeQueueBatch": "sns:Publish"}}), [])
|
||||
assert any("not an action of sqs" in problem for problem in problems)
|
||||
|
||||
|
||||
def test_an_operation_mapped_to_its_own_name_is_rejected():
|
||||
problems = r.validate(anchored({"sqs": {"Purgequeue": "sqs:PurgeQueue"}}))
|
||||
problems = r.validate(anchored({"sqs": {"Purgequeue": "sqs:PurgeQueue"}}), [])
|
||||
assert any("its own name" in problem for problem in problems)
|
||||
|
||||
|
||||
def test_a_missing_anchor_is_rejected():
|
||||
document = anchored()
|
||||
del document["authorizedActions"]["sns"]
|
||||
assert any("sns:PublishBatch" in problem for problem in r.validate(document))
|
||||
assert any("sns:PublishBatch" in problem for problem in r.validate(document, []))
|
||||
|
||||
|
||||
def test_an_anchor_mapped_elsewhere_is_rejected():
|
||||
document = anchored()
|
||||
document["authorizedActions"]["sqs"]["SendMessageBatch"] = "sqs:ReceiveMessage"
|
||||
assert any("sqs:SendMessageBatch" in problem for problem in r.validate(document))
|
||||
assert any("sqs:SendMessageBatch" in problem for problem in r.validate(document, []))
|
||||
|
||||
|
||||
def test_an_unsorted_namespace_map_is_rejected():
|
||||
document = anchored()
|
||||
document["authorizedActions"] = dict(reversed(list(document["authorizedActions"].items())))
|
||||
assert "authorizedActions is not sorted by namespace" in r.validate(document)
|
||||
assert "authorizedActions is not sorted by namespace" in r.validate(document, [])
|
||||
|
||||
|
||||
def test_an_empty_map_is_rejected():
|
||||
assert r.validate({"authorizedActions": {}}) == ["authorizedActions is missing or empty"]
|
||||
assert r.validate({"authorizedActions": {}}, []) == ["authorizedActions is missing or empty"]
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
@@ -289,11 +289,19 @@ def test_generating_from_saved_files_writes_a_file_check_accepts(tmp_path):
|
||||
for document in ANCHOR_SERVICES:
|
||||
(sources / f"{document['Name']}.json").write_text(json.dumps(document), encoding="utf-8")
|
||||
output = tmp_path / "iam-authorized-actions.json"
|
||||
assert r.main(["--source-dir", str(sources), "--output", str(output)]) == 0
|
||||
assert r.main(["--check", "--output", str(output)]) == 0
|
||||
routes = no_routes(tmp_path)
|
||||
assert r.main(["--source-dir", str(sources), "--output", str(output), "--routes", routes]) == 0
|
||||
assert r.main(["--check", "--output", str(output), "--routes", routes]) == 0
|
||||
assert r.main(["--verify", "--source-dir", str(sources), "--output", str(output)]) == 0
|
||||
|
||||
|
||||
def no_routes(tmp_path) -> str:
|
||||
"""A routes file reading no scope's routes."""
|
||||
routes = tmp_path / "rest-routes.json"
|
||||
routes.write_text(json.dumps({"handRouted": {}, "models": {}}), encoding="utf-8")
|
||||
return str(routes)
|
||||
|
||||
|
||||
def saved_sources(tmp_path, documents: list[dict]):
|
||||
sources = tmp_path / "reference"
|
||||
sources.mkdir()
|
||||
@@ -309,16 +317,84 @@ MALFORMED = {"Name": "sqs", "Operations": [
|
||||
def test_a_malformed_record_makes_generation_write_nothing(tmp_path):
|
||||
sources = saved_sources(tmp_path, ANCHOR_SERVICES + [MALFORMED])
|
||||
output = tmp_path / "iam-authorized-actions.json"
|
||||
assert r.main(["--source-dir", str(sources), "--output", str(output)]) == 2
|
||||
assert r.main(["--source-dir", str(sources), "--output", str(output), "--routes", no_routes(tmp_path)]) == 2
|
||||
assert not output.exists()
|
||||
|
||||
|
||||
def test_verify_reports_a_malformed_record_as_an_unreadable_reference(tmp_path):
|
||||
# Status 2 tells CI the reference could not be read, rather than that the vendored map is wrong.
|
||||
output = tmp_path / "iam-authorized-actions.json"
|
||||
assert r.main(["--source-dir", str(saved_sources(tmp_path, ANCHOR_SERVICES)), "--output", str(output)]) == 0
|
||||
assert r.main(["--source-dir", str(saved_sources(tmp_path, ANCHOR_SERVICES)), "--output", str(output),
|
||||
"--routes", no_routes(tmp_path)]) == 0
|
||||
malformed = tmp_path / "malformed"
|
||||
malformed.mkdir()
|
||||
(malformed / "sqs.json").write_text(json.dumps({"Name": "sqs", "Operations": [
|
||||
{"Name": "SendMessageBatch", "AuthorizedActions": [None]}]}), encoding="utf-8")
|
||||
assert r.main(["--verify", "--source-dir", str(malformed), "--output", str(output)]) == 2
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# actionsWithoutResourceTypes: the actions a route no rule maps may be checked as
|
||||
# --------------------------------------------------------------------------- #
|
||||
def typed(namespace: str, actions: dict[str, list[str]]) -> dict:
|
||||
"""A reference document whose actions act on the resource types given."""
|
||||
return {"Name": namespace, "Operations": [],
|
||||
"Actions": [{"Name": name, "Resources": [{"Name": kind} for kind in kinds]}
|
||||
for name, kinds in actions.items()]}
|
||||
|
||||
|
||||
ROUTES = {"handRouted": {"hand": "the rules route it alone"},
|
||||
"models": {"svc": {"credentialScope": "svc"}, "svc-v2": {"credentialScope": "svc"},
|
||||
"other": {"credentialScope": "other"}, "hand": {"credentialScope": "hand"}}}
|
||||
|
||||
|
||||
def test_the_routed_scopes_are_every_models_but_the_hand_routed_ones():
|
||||
assert r.routed_namespaces(ROUTES) == ["other", "svc"]
|
||||
|
||||
|
||||
def test_each_routed_scope_lists_its_actions_of_no_resource_type():
|
||||
documents = [typed("svc", {"ListThings": [], "GetThing": ["thing"], "CreateThing": ["thing", "tag"]}),
|
||||
typed("other", {"GetOther": ["other"]}), typed("unrouted", {"ListUnrouted": []})]
|
||||
assert r.actions_without_resource_types(documents, ["other", "svc"]) == {"other": [], "svc": ["ListThings"]}
|
||||
built = r.build(ANCHOR_SERVICES + documents, "a test", ["other", "svc"])
|
||||
assert built["actionsWithoutResourceTypes"] == {"other": [], "svc": ["ListThings"]}
|
||||
assert r.validate(built, ["other", "svc"]) == []
|
||||
|
||||
|
||||
def test_a_routed_scope_the_reference_does_not_have_is_an_error():
|
||||
with pytest.raises(ValueError, match="no namespace svc"):
|
||||
r.actions_without_resource_types([typed("other", {})], ["other", "svc"])
|
||||
|
||||
|
||||
def test_the_listed_scopes_must_be_the_routed_ones_each_sorted():
|
||||
document = r.build(ANCHOR_SERVICES + [typed("svc", {"ListThings": [], "ListMore": []})], "a test", ["svc"])
|
||||
assert r.validate(document, ["svc"]) == []
|
||||
assert any("not the scopes rest-routes.json reads" in problem for problem in r.validate(document, ["other", "svc"]))
|
||||
document["actionsWithoutResourceTypes"]["svc"].reverse()
|
||||
assert "actionsWithoutResourceTypes.svc is not sorted, or repeats an action" in r.validate(document, ["svc"])
|
||||
del document["actionsWithoutResourceTypes"]
|
||||
assert "actionsWithoutResourceTypes is missing" in r.validate(document, ["svc"])
|
||||
|
||||
|
||||
def test_verify_fails_on_a_listed_action_aws_gives_a_resource_type_and_reports_one_it_added():
|
||||
untrue, added = r.verify_unscoped_against({"svc": ["GetThing", "ListThings"]},
|
||||
{"svc": ["ListThings", "ListMore"]})
|
||||
assert untrue == ["AWS gives svc:GetThing a resource type, or no longer has it"]
|
||||
assert added == ["svc:ListMore"]
|
||||
assert r.verify_unscoped_against({"svc": ["ListThings"]}, {"svc": ["ListThings"]}) == ([], [])
|
||||
|
||||
|
||||
def test_the_round_trip_lists_the_routed_scopes_actions(tmp_path):
|
||||
documents = ANCHOR_SERVICES + [typed("svc", {"ListThings": [], "GetThing": ["thing"]}), typed("other", {})]
|
||||
sources = saved_sources(tmp_path, documents)
|
||||
routes = tmp_path / "rest-routes.json"
|
||||
routes.write_text(json.dumps(ROUTES), encoding="utf-8")
|
||||
output = tmp_path / "iam-authorized-actions.json"
|
||||
assert r.main(["--source-dir", str(sources), "--output", str(output), "--routes", str(routes)]) == 0
|
||||
assert json.loads(output.read_text())["actionsWithoutResourceTypes"] == {"other": [], "svc": ["ListThings"]}
|
||||
assert r.main(["--check", "--output", str(output), "--routes", str(routes)]) == 0
|
||||
assert r.main(["--verify", "--source-dir", str(sources), "--output", str(output)]) == 0
|
||||
(tmp_path / "later").mkdir()
|
||||
given = saved_sources(tmp_path / "later", ANCHOR_SERVICES + [typed("svc", {"ListThings": ["thing"]}),
|
||||
typed("other", {})])
|
||||
assert r.main(["--verify", "--source-dir", str(given), "--output", str(output)]) == 1
|
||||
@@ -67,3 +67,28 @@ def test_check_passes_on_a_fresh_generation_and_fails_on_a_stale_one(tmp_path):
|
||||
assert r.main(data + ["--check"]) == 0
|
||||
output.write_text(output.read_text(encoding="utf-8").replace("/ping", "/pong"), encoding="utf-8")
|
||||
assert r.main(data + ["--check"]) == 1
|
||||
|
||||
|
||||
def test_a_route_naming_two_operations_of_a_scope_the_rules_do_not_route_alone_is_refused():
|
||||
with pytest.raises(SystemExit):
|
||||
r.build({"lambda": model("rest-json", "2015-03-31", GetByName=("GET", "/things/{Name}"),
|
||||
GetById=("GET", "/things/{Id}/"))}, "botocore test")
|
||||
# One operation in two models of a scope, two routes a query tells apart, and two operations on one route of a
|
||||
# scope the rules route alone, all pass.
|
||||
doc = r.build({
|
||||
"lambda": model("rest-json", "2015-03-31", ListTags=("GET", "/tags/{ARN}"), GetThing=("GET", "/things/{Name}"),
|
||||
ListThingTags=("GET", "/things/{Name}?tagging")),
|
||||
"lambda-microvms": model("rest-json", "2025-01-01", ListTags=("GET", "/tags/{Resource}")),
|
||||
"s3": model("rest-xml", "2006-03-01", PutObject=("PUT", "/{Bucket}/{Key+}"),
|
||||
UploadPart=("PUT", "/{Bucket}/{Key+}")),
|
||||
}, "botocore test")
|
||||
assert doc["handRouted"] == dict(sorted(r.HAND_ROUTED.items()))
|
||||
assert set(doc["handRouted"]) == {"apigateway", "s3"}
|
||||
|
||||
|
||||
def test_the_hand_routed_scopes_are_rendered_with_their_reasons():
|
||||
text = r.render(r.build({"s3": model("rest-xml", "2006-03-01", HeadBucket=("HEAD", "/{Bucket}"))},
|
||||
"botocore test"))
|
||||
|
||||
assert json.loads(text)["handRouted"] == dict(sorted(r.HAND_ROUTED.items()))
|
||||
assert text.splitlines()[2] == ' "handRouted": {'
|
||||
Reference in new issue
Block a user