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:
Priamo Germosen authored and GitHub committed 2026-11-03 23:18:31 -06:00
1 parent 5a4632229e
commit 251bb39375
18 files changed
+1178 -173

No files matched your search

@@ -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",
@@ -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
@@ -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<>();
@@ -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);
}
}
}