feat(iam): check API Gateway's routes by botocore's models (#8060)

API Gateway was the one REST service besides S3 that the registry
authorized by hand: seven rules gave every management route its HTTP
method's action, apigateway:GET, apigateway:POST and so on, with two
named exceptions written in. Its routes were vendored for the coverage
test only.

The developer guide gives the management API's actions as the HTTP
verbs, and the Service Reference lists most API Gateway operations the
action of their route's method beside permissions AWS checks only when
the request carries what they guard, such as UpdateRestApiPolicy for a
resource policy or iam:PassRole for a role. The authorized-actions
table now lists those operations, 55 of them, under authorizedByMethod,
and a request on such an operation's route is checked as the action its
own method names: TagResource is a PUT in v1 and a POST in v2. The
other 132 are the single-action renames the table already held,
RejectDomainNameAccessAssociation and PutRoutingRule among them, or
keep the action of their own name, as the portal, portal product and
routing rule operations do.

So the rules go and API Gateway leaves the hand-routed scopes. Every
route Floci serves is checked as before. Its v1 tag routes are the
shared tags controller's, so they take an ARN sent unencoded and keep
the bare /tags forms, whose tagging form is a POST although v1 tags
with a PUT. v2's tag routes take an unencoded ARN too, as its
controller does.

The routes Floci does not serve, those of portals, portal products and
routing rules, are now checked as the actions AWS names for them rather
than as their method. A path no route of either model has, such as a
deployed API's execute path signed for apigateway, is no longer checked
as a management action: AWS authorizes an invocation as
execute-api:Invoke, which the execute path checks itself.

Regenerating the authorized-actions table also brings in two Lake
Formation operations AWS has added since,
GetGlueFunctionSessionContext and GetTemporaryGlueFunctionCredentials,
both authorized as lakeformation:GetDataAccess. Floci serves neither.

The passed-role generator imports the authorized-actions one, so the
online IAM gate checks the passed-role table for this change too, and
the table no longer held: AWS now passes EMR StartSession's role to
managed-compute.elasticmapreduce alone. Syncing it had failed since AWS
listed iam:PassRole for three more operations the generator found no
role member on, and asks a reason for.

CloudWatch Logs StartQuery names no role at any depth, in the pinned
botocore or the newest, so it is not read for that reason. SSM
RegisterDefaultHostManagementConfiguration and Kinesis Analytics
ImportSnapshot are newer than the pinned botocore, so their requests
cannot be read yet. They get a reason the sync and the offline gate
both refuse once the pinned models carry the operation, so a bump
cannot leave their roles unread. Floci serves StartQuery and neither of
the others.

That refusal caught two entries the pin had already outgrown. ECS
CreateGateway and UpdateGateway were excused as operations botocore
does not model, from the day the table was generated, and the pin has
had both for a while, each naming the infrastructureRoleArn of "the IAM
role that the gateway assumes to create and manage infrastructure on
your behalf". The reference passes it to ecs.amazonaws.com, so the
table reads it for both now. StartSession's role goes where the
reference sends it, and the hand mapping that picked elasticmapreduce
out of its two services is gone. Floci serves neither ECS gateway
operation nor StartSession.
This commit is contained in:
Priamo Germosen authored and GitHub committed 2026-11-12 16:07:36 -04:00
1 parent ab794d914c
commit 81894c545d
18 files changed
+708 -122

No files matched your search

@@ -134,6 +134,34 @@ class ApiGatewayPathArnEnforcementIntegrationTest {
refused(get(user, "/v2/tags/" + encoded));
}
/**
* A tagging route is checked as the action its HTTP method names: v1 tags a REST API with a PUT on
* {@code /tags/<arn>}, the ARN sent encoded or not, the shared tags controller's bare {@code /tags} with a POST
* naming the ARN in its body, and v2 an HTTP API with a POST on {@code /v2/tags/<arn>}.
*/
@Test
void eachTaggingRouteIsCheckedAsTheActionItsMethodNames() {
String restApiId = createRestApi();
String restArn = "arn:aws:apigateway:us-east-1::/restapis/" + restApiId;
String encodedRestArn = "arn%3Aaws%3Aapigateway%3Aus-east-1%3A%3A%2Frestapis%2F" + restApiId;
String httpArn = "arn:aws:apigateway:us-east-1::/apis/" + createHttpApiWithDefaultStage();
String tags = "{\"tags\":{\"team\":\"a\"}}";
String bare = "{\"resourceArn\":\"" + restArn + "\",\"tags\":{\"team\":\"b\"}}";
String user = user("apigw-tagging");
policy(user, allow("apigateway:POST", "*"));
refused("apigateway:PUT", send(user, "PUT", "/tags/" + encodedRestArn, tags));
refused("apigateway:PUT", send(user, "PUT", "/tags/" + restArn, tags));
send(user, "POST", "/tags", bare).statusCode(200);
send(user, "POST", "/v2/tags/" + httpArn, tags).statusCode(201);
policy(user, allow("apigateway:PUT", "*"));
send(user, "PUT", "/tags/" + encodedRestArn, tags).statusCode(204);
send(user, "PUT", "/tags/" + restArn, tags).statusCode(204);
refused("apigateway:POST", send(user, "POST", "/tags", bare));
refused("apigateway:POST", send(user, "POST", "/v2/tags/" + httpArn, tags));
}
private String createHttpApiWithDefaultStage() {
String apiId = given()
.header("Authorization", auth(ADMIN, "apigateway"))
@@ -171,6 +199,13 @@ class ApiGatewayPathArnEnforcementIntegrationTest {
.header("Authorization", auth(keys.get(user), "apigateway")).get(path).then();
}
private ValidatableResponse send(String user, String method, String path, String body) {
return given().urlEncodingEnabled(false)
.header("Authorization", auth(keys.get(user), "apigateway"))
.contentType("application/json").body(body)
.request(method, path).then();
}
/** Sends {@code path} with its empty segments, which RestAssured collapses before sending. */
private HttpResponse<String> getAsWritten(String user, String path) throws Exception {
URI uri = URI.create(baseUri.getScheme() + "://" + baseUri.getRawAuthority() + path);
@@ -198,9 +233,13 @@ class ApiGatewayPathArnEnforcementIntegrationTest {
}
private static void refused(ValidatableResponse response) {
refused("apigateway:GET", response);
}
private static void refused(String action, ValidatableResponse response) {
response.statusCode(403)
.body(containsString("AccessDeniedException"))
.body(containsString("apigateway:GET"));
.body(containsString(action));
}
private static String allow(String action, String resource) {
@@ -115,6 +115,44 @@ class IamActionRegistryTest {
assertEquals(action, registry.resolveRoute(scope, mockCtx(method, path, new MultivaluedHashMap<>(), null, "")));
}
/**
* API Gateway's management routes, v1 and v2, are checked as the Service Reference gives their operations: the
* action their HTTP method names, {@code TagResource} a PUT in v1 and a POST in v2 and the shared tags
* controller's bare POST, with an ARN sent encoded or not; and the operations AWS authorizes by an action of
* their own name as that action, Floci serving none of them. A path no route of either model has, such as a
* deployed API's execute path, is no management call.
*/
@ParameterizedTest
@CsvSource({"GET,/restapis,apigateway:GET",
"PATCH,/restapis/abc,apigateway:PATCH",
"DELETE,/v2/apis/abc/stages/prod,apigateway:DELETE",
"GET,/v2/apis/abc/stages/prod,apigateway:GET",
"PUT,/tags/arn%3Aaws%3Aapigateway%3Aus-east-1%3A%3A%2Frestapis%2Fabc,apigateway:PUT",
"PUT,/tags/arn:aws:apigateway:us-east-1::/restapis/abc,apigateway:PUT",
"DELETE,/tags/arn:aws:apigateway:us-east-1::/restapis/abc,apigateway:DELETE",
"POST,/tags,apigateway:POST",
"POST,/v2/tags/arn:aws:apigateway:us-east-1::/apis/abc,apigateway:POST",
"GET,/v2/tags/arn%3Aaws%3Aapigateway%3Aus-east-1%3A%3A%2Fapis%2Fabc,apigateway:GET",
"POST,/rejectdomainnameaccessassociations,apigateway:RejectAccessAssociation",
"PUT,/v2/domainnames/example.com/routingrules/r1,apigateway:UpdateRoutingRule",
"POST,/v2/domainnames/example.com/routingrules,apigateway:CreateRoutingRule",
"POST,/v2/portals,apigateway:CreatePortal",
"PATCH,/v2/portals/p1,apigateway:UpdatePortal"})
void anApiGatewayRouteIsCheckedAsTheServiceReferenceGivesItsOperation(String method, String path, String action) {
assertEquals(action, apiGatewayAction(method, path));
}
@ParameterizedTest
@CsvSource({"GET,/execute-api/abc/prod/pets", "POST,/restapis/abc/prod/_user_request_/pets"})
void anApiGatewayPathNoModelRoutesIsNoManagementCall(String method, String path) {
assertNull(apiGatewayAction(method, path));
}
private String apiGatewayAction(String method, String path) {
return registry.resolveRoute("apigateway",
mockCtx(method, path, new MultivaluedHashMap<>(), MediaType.APPLICATION_JSON_TYPE, "{}"));
}
/**
* Access Analyzer's analyzer routes are checked as their operations, the vendored request resources reading the
* analyzer from the path or the body, and so are those of its archive rules, findings and access previews, which
@@ -48,10 +48,48 @@ class IamAuthorizedActionsTest {
void entriesAreKeyedByNamespaceAndOperation() throws IOException {
IamAuthorizedActions.Table parsed = IamAuthorizedActions.parse(json("""
{"authorizedActions": {"sqs": {"SendMessageBatch": "sqs:SendMessage"}},
"actionsWithoutResourceTypes": {"es": ["ListDomainNames"], "dsql": []}}
"actionsWithoutResourceTypes": {"es": ["ListDomainNames"], "dsql": []},
"authorizedByMethod": {"apigateway": ["GetStage", "TagResource"]}}
"""));
assertEquals(Map.of("sqs:SendMessageBatch", "sqs:SendMessage"), parsed.actions());
assertEquals(Set.of("es:listdomainnames"), parsed.withoutResourceTypes());
assertEquals(Set.of("apigateway:GetStage", "apigateway:TagResource"), parsed.byMethod());
}
/**
* A request on the route of an operation the file authorizes by method is checked as the action its method
* names: API Gateway's {@code TagResource} is a PUT in v1 and a POST in v2. An operation the file renames keeps
* that action, and one it names nowhere its own name, whatever the method.
*/
@Test
void anOperationAuthorizedByMethodIsTheActionItsRequestsMethodNames() {
assertEquals("apigateway:PUT", IamAuthorizedActions.actionFor("apigateway", "TagResource", "PUT"));
assertEquals("apigateway:POST", IamAuthorizedActions.actionFor("apigateway", "TagResource", "post"));
assertEquals("apigateway:DELETE", IamAuthorizedActions.actionFor("apigateway", "DeleteStage", "DELETE"));
assertEquals("apigateway:GET", IamAuthorizedActions.actionFor("apigateway", "GetRestApis", "GET"));
assertEquals("apigateway:RejectAccessAssociation",
IamAuthorizedActions.actionFor("apigateway", "RejectDomainNameAccessAssociation", "POST"));
assertEquals("apigateway:CreateRoutingRule",
IamAuthorizedActions.actionFor("apigateway", "CreateRoutingRule", "POST"));
assertEquals("lambda:InvokeFunction", IamAuthorizedActions.actionFor("lambda", "Invoke", "POST"));
// An operation named in a request rather than reached by its route keeps the two-argument answer.
assertEquals("apigateway:TagResource", IamAuthorizedActions.actionFor("apigateway", "TagResource"));
}
@Test
void aFileWithoutTheOperationsAuthorizedByMethodIsRefused() {
assertThrows(IllegalStateException.class, () -> IamAuthorizedActions.parse(json("""
{"authorizedActions": {"sqs": {"SendMessageBatch": "sqs:SendMessage"}},
"actionsWithoutResourceTypes": {}}
""")));
assertThrows(IllegalStateException.class, () -> IamAuthorizedActions.parse(json("""
{"authorizedActions": {"sqs": {"SendMessageBatch": "sqs:SendMessage"}},
"actionsWithoutResourceTypes": {}, "authorizedByMethod": {"apigateway": "TagResource"}}
""")));
assertThrows(IllegalStateException.class, () -> IamAuthorizedActions.parse(json("""
{"authorizedActions": {"sqs": {"SendMessageBatch": "sqs:SendMessage"}},
"actionsWithoutResourceTypes": {}, "authorizedByMethod": {"apigateway": [""]}}
""")));
}
/**
@@ -34,7 +34,8 @@ import static org.mockito.Mockito.when;
* 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.
* {@code iam-authorized-actions.json} names for the operation, or its route's method names for an operation it
* authorizes by method, or else the operation's own name.
*/
class IamRestRouteCoverageTest {
@@ -116,31 +117,45 @@ class IamRestRouteCoverageTest {
* 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.
* unchecked rather than checked on {@code *}, until the resources in its path are read. An operation the
* authorized actions list as authorized by method is the action its route's method names, and an alternative
* route a shared controller also serves it on is checked as the operation, by that route's own method.
*/
@TestFactory
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 authorizedActions = load("/aws/iam-authorized-actions.json");
JsonNode authorized = authorizedActions.path("authorizedActions");
JsonNode requestResources = load("/aws/iam-request-resources.json");
Set<String> handBuilt = new HashSet<>();
requestResources.path("handBuilt").forEach(namespace -> handBuilt.add(namespace.asText()));
Set<String> byMethod = new HashSet<>();
authorizedActions.path("authorizedByMethod").properties().forEach(scope ->
scope.getValue().forEach(operation -> byMethod.add(scope.getKey() + ":" + operation.asText())));
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());
String action = authorized.path(scope).path(operation.getKey()).asText(scope + ":" + operation.getKey());
String method = operation.getValue().path("method").asText();
List<Route> routes = new ArrayList<>(List.of(new Route(scope, model, operation.getKey(), method,
operation.getValue().path("requestUri").asText())));
operation.getValue().path("alternatives").forEach(alternative -> routes.add(new Route(scope, model,
operation.getKey(), alternative.path("method").asText(method),
alternative.path("requestUri").asText())));
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())));
for (Route route : routes) {
String action = byMethod.contains(scope + ":" + operation.getKey())
? scope + ":" + route.method()
: authorized.path(scope).path(operation.getKey()).asText(scope + ":" + operation.getKey());
String expected = handBuilt.contains(scope) || read
|| IamAuthorizedActions.actsOnNoResourceType(action)
? action : null;
tests.add(DynamicTest.dynamicTest(route.toString(),
() -> assertEquals(expected, resolve(route), route.toString())));
}
}
}
return tests.stream();
@@ -167,8 +182,9 @@ class IamRestRouteCoverageTest {
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());
assertEquals(IamAuthorizedActions.actionFor(scope, operation.getKey(), route.method()),
matched == null ? null : IamAuthorizedActions.actionFor(scope, matched, route.method()),
route.toString());
}));
}
}
@@ -62,6 +62,39 @@ class IamRestRoutesTest {
});
}
/**
* API Gateway v1 tags with a PUT on {@code /tags/{resource_arn}}, a label spanning the slashes of an ARN sent
* unencoded, and the shared tags controller's bare path tags with a POST naming the ARN in its body: that
* alternative is matched by its own method, never the operation's.
*/
@Test
void anAlternativeIsMatchedByItsOwnMethod() {
IamRestRoutes vendored = IamRestRoutes.vendored();
IamRestRoutes.Match bare = vendored.match("apigateway", "POST", "/tags", null).orElseThrow();
assertEquals("TagResource", bare.operation());
assertEquals(Map.of("resourceArn", "body"), bare.located());
assertEquals(Optional.empty(), vendored.operation("apigateway", "PUT", "/tags", null));
assertEquals(Optional.of("TagResource"),
vendored.operation("apigateway", "PUT", "/tags/arn:aws:apigateway:us-east-1::/restapis/abc", null));
assertEquals(Optional.of("GetTags"), vendored.operation("apigateway", "GET", "/tags", null));
assertEquals(Optional.of("TagResource"),
vendored.operation("apigateway", "POST", "/v2/tags/arn:aws:apigateway:us-east-1::/apis/abc", null));
IamRestRoutes own = routes(ROUTES.replace("\"requestUri\": \"/things/{ThingName}?tagging\"",
"\"requestUri\": \"/things/{ThingName}?tagging\", \"alternatives\": [{\"method\": \"PUT\", "
+ "\"requestUri\": \"/tagging\", \"located\": {\"ThingName\": \"body\"}}]"));
assertEquals(Optional.of("TagThing"), own.operation("svc", "PUT", "/tagging", null));
assertEquals(Optional.empty(), own.operation("svc", "POST", "/tagging", null));
}
@Test
void anAlternativeOfNoKnownMethodIsRejected() {
String alternative = ROUTES.replace("\"requestUri\": \"/things/\"",
"\"requestUri\": \"/things/\", \"alternatives\": [{\"method\": \"FETCH\", \"requestUri\": \"/other\", "
+ "\"located\": {\"member\": \"body\"}}]");
assertThrows(IllegalStateException.class, () -> routes(alternative));
}
@Test
void malformedAlternativeMemberSourceIsRejected() {
String alternative = ROUTES.replace("\"requestUri\": \"/things/\"",