mirror of
https://github.com/floci-io/floci.git
synced 2026-11-22 21:50:46 -05:00
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:
1 parent
ab794d914c
commit
81894c545d
18 files changed
+708
-122
No files matched your search
+32
-21
@@ -1959,11 +1959,17 @@ Functions routes, each checked as the action of its own name except `InvokeWithR
|
||||
(checked as `lambda:InvokeFunction`) and `GetLayerVersionByArn` (`lambda:GetLayerVersion`). AWS also
|
||||
checks `lambda:AddPermission`, `lambda:GetPolicy` or `lambda:RemovePermission` for the resource
|
||||
policy operations, which Floci does not serve; their routes are checked as their own action alone.
|
||||
API Gateway's management API, v1 and v2, is checked as `apigateway:` and the HTTP
|
||||
method, `apigateway:GET`, `apigateway:POST` and so on, except `RejectDomainNameAccessAssociation`
|
||||
(`apigateway:RejectAccessAssociation`) and `PutRoutingRule` (`apigateway:UpdateRoutingRule`); the
|
||||
v2 routing rule, portal and portal product operations, which AWS checks as actions of their own
|
||||
names, are not served. A management call is checked against the path it names, in the request's
|
||||
API Gateway's management API, v1 and v2, is checked by the routes of botocore's two models, each
|
||||
operation as the Service Reference gives it: as `apigateway:` and the HTTP method, `apigateway:GET`,
|
||||
`apigateway:POST` and so on, `TagResource` a `PUT` in v1 and a `POST` in v2, except
|
||||
`RejectDomainNameAccessAssociation` (`apigateway:RejectAccessAssociation`), `PutRoutingRule`
|
||||
(`apigateway:UpdateRoutingRule`) and the v2 routing rule, portal and portal product operations,
|
||||
which AWS checks as actions of their own names and Floci does not serve. A v1 resource's tags are
|
||||
also set on the shared bare `/tags` path, a `POST` naming the ARN in its body, checked as `apigateway:POST`.
|
||||
AWS also checks `apigateway:UpdateRestApiPolicy` for a request carrying a resource policy,
|
||||
`apigateway:AddCertificateToDomain` and `apigateway:RemoveCertificateFromDomain` for a domain's
|
||||
mutual TLS certificate, `apigateway:PATCH` on a resource whose tags change, and `iam:PassRole` for
|
||||
a role; Floci checks the method's action alone. A management call is checked against the path it names, in the request's
|
||||
Region and partition and with no account, as the
|
||||
[API Gateway ARN reference](https://docs.aws.amazon.com/apigateway/latest/developerguide/arn-format-reference.html)
|
||||
gives it: `GET /restapis/<id>/stages` against `arn:aws:apigateway:<region>::/restapis/<id>/stages`.
|
||||
@@ -2058,12 +2064,14 @@ Analyzer's analyzer operations, Security Hub's hub operations and GuardDuty's de
|
||||
table of request resources reading the resource they name. Every route Floci serves of AWS Lake
|
||||
Formation and Amazon Inspector is one AWS authorizes on no resource type, as is every one of Amazon Macie's but
|
||||
`CreateMember`, so those are checked by their routes alone. `CreateMember`, on `POST /members`, is checked on the
|
||||
member its `account.accountId` names, and needs `macie2:TagResource` when it carries tags. A route whose action AWS checks on a
|
||||
member its `account.accountId` names, and needs `macie2:TagResource` when it carries tags. API Gateway's
|
||||
routes are checked by their routes alone too, on the path Floci builds the ARN from, and the authorized
|
||||
actions list the operations AWS checks as the action their HTTP method names (above). A route whose action AWS checks on a
|
||||
resource Floci neither builds nor reads would not be checked, since checked on `*` a grant scoped to
|
||||
the resource would be refused; no vendored route is one now. 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
|
||||
so none is checked differently. S3 is routed by its rules alone, since it tells apart the
|
||||
operations of one route by their query and headers. A route
|
||||
matching nothing is not checked, as an unsigned REST request is not; the other REST services' routes
|
||||
are not vendored yet.
|
||||
|
||||
@@ -2174,10 +2182,10 @@ role each passes:
|
||||
`CreateTaskSet` pass the roles of the task definition they name. The infrastructure roles go to
|
||||
`ecs.amazonaws.com`: a managed EBS volume's `roleArn` (`RunTask`, `StartTask`, `CreateService`,
|
||||
`UpdateService`), the service's `role` and the load balancer, lifecycle hook, Service Connect TLS
|
||||
and VPC Lattice roles (`CreateService`, `UpdateService`), and a Managed Instances provider's
|
||||
`infrastructureRoleArn` (`CreateCapacityProvider`, `UpdateCapacityProvider`). A role given by its
|
||||
name is the role of that name in the caller's account, and a task definition that does not exist
|
||||
passes nothing.
|
||||
and VPC Lattice roles (`CreateService`, `UpdateService`), and the `infrastructureRoleArn` of a
|
||||
Managed Instances provider (`CreateCapacityProvider`, `UpdateCapacityProvider`) and of a gateway
|
||||
(`CreateGateway`, `UpdateGateway`). A role given by its name is the role of that name in the
|
||||
caller's account, and a task definition that does not exist passes nothing.
|
||||
- **Step Functions:** `CreateStateMachine` and `UpdateStateMachine` pass `roleArn` to
|
||||
`states.amazonaws.com`, in a JSON or a CBOR body.
|
||||
- **EventBridge:** `PutRule` passes `RoleArn`, and `PutTargets` each target's `RoleArn`, to
|
||||
@@ -2293,15 +2301,18 @@ when the caller may not pass the role.
|
||||
`LocalRoleName`, which is checked on the ARN IAM holds the role under, and an update goes by the
|
||||
type of the constraint it changes. The type is matched in any case, since Floci keeps it as given.
|
||||
An SWF decision is read from the attributes its `decisionType` names.
|
||||
- Not read: an operation whose request names no role (SSM `CreateDocument`, for one); one whose role
|
||||
is a parameter of the runbook it runs (SSM `StartAutomationExecution`, Config
|
||||
`PutRemediationConfigurations`); one the Service Reference passes roles from to several services
|
||||
without saying which member goes where (EMR `RunJobFlow`, whose `JobFlowRole` also names an
|
||||
instance profile, EKS `UpdateClusterConfig`, CloudWatch Logs `CreateImportTask`, SageMaker
|
||||
`CreateTrainingSession`); and one whose body is XML (S3 `PutBucketReplication`). EC2's
|
||||
`RequestSpotFleet` names its roles in EC2's own protocol, one of them as an instance profile. The
|
||||
REST services whose routes no rule maps yet, and API Gateway, which is authorized by HTTP method,
|
||||
are not read either.
|
||||
- Not read: an operation whose request names no role (SSM `CreateDocument` and CloudWatch Logs
|
||||
`StartQuery`, for two); one whose role is a parameter of the runbook it runs (SSM
|
||||
`StartAutomationExecution`, Config `PutRemediationConfigurations`); one the Service Reference
|
||||
passes roles from to several services without saying which member goes where (EMR `RunJobFlow`,
|
||||
whose `JobFlowRole` also names an instance profile, EKS `UpdateClusterConfig`, CloudWatch Logs
|
||||
`CreateImportTask`, SageMaker `CreateTrainingSession`); one whose body is XML (S3
|
||||
`PutBucketReplication`); and one the botocore models Floci is pinned to do not have yet (SSM
|
||||
`RegisterDefaultHostManagementConfiguration`, Kinesis Analytics `ImportSnapshot`), whose role is
|
||||
read as soon as a release that has it is pinned, since the generator and its offline gate refuse
|
||||
that reason once the models carry the operation. EC2's `RequestSpotFleet` names its roles in
|
||||
EC2's own protocol, one of them as an instance profile. The REST services whose routes no rule
|
||||
maps yet, and API Gateway, which is authorized by HTTP method, are not read either.
|
||||
|
||||
A request that names a Lambda network connector also needs `lambda:PassNetworkConnector` on it. The
|
||||
Lambda developer guide has "The caller must have `lambda:PassNetworkConnector` on the referenced
|
||||
|
||||
@@ -290,19 +290,6 @@ public class IamActionRegistry {
|
||||
rule("rds-data", "POST", "^/CommitTransaction/?$", "rds-data:CommitTransaction"),
|
||||
rule("rds-data", "POST", "^/RollbackTransaction/?$", "rds-data:RollbackTransaction"),
|
||||
|
||||
// ── API Gateway ────────────────────────────────────────────────────────
|
||||
// The management API, v1 and v2, is authorized by HTTP method on the resource path:
|
||||
// apigateway:GET, POST, PUT, PATCH or DELETE. Two operations have an action of their own. The
|
||||
// others AWS authorizes only by an action of their own name, the v2 routing rules, portals and
|
||||
// portal products, are not served by Floci and need their own rules when they are.
|
||||
rule("apigateway", "POST", "^/rejectdomainnameaccessassociations$", "apigateway:RejectAccessAssociation"),
|
||||
rule("apigateway", "PUT", "^/v2/domainnames/[^/]+/routingrules/[^/]+$", "apigateway:UpdateRoutingRule"),
|
||||
rule("apigateway", "GET", ".*", "apigateway:GET"),
|
||||
rule("apigateway", "POST", ".*", "apigateway:POST"),
|
||||
rule("apigateway", "PUT", ".*", "apigateway:PUT"),
|
||||
rule("apigateway", "PATCH", ".*", "apigateway:PATCH"),
|
||||
rule("apigateway", "DELETE", ".*", "apigateway:DELETE"),
|
||||
|
||||
// ── EventBridge Scheduler ──────────────────────────────────────────────
|
||||
rule("scheduler", "GET", "^/schedules/[^/]+$", "scheduler:GetSchedule"),
|
||||
rule("scheduler", "POST", "^/schedules/[^/]+$", "scheduler:CreateSchedule"),
|
||||
@@ -694,13 +681,15 @@ public class IamActionRegistry {
|
||||
* from the request URI because RESTEasy Reactive does not serve {@code UriInfo.getPath(false)}.
|
||||
*
|
||||
* <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
|
||||
* matches, and is checked as that operation's action for the request's method
|
||||
* ({@link IamAuthorizedActions#actionFor(String, String, String)}): the one a request naming the operation
|
||||
* is checked as, or, for an operation AWS authorizes by method as it does API Gateway's management API,
|
||||
* {@code apigateway:PUT} for a PUT. That 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. A request a route filter moved under an internal prefix is matched on its
|
||||
* path without the prefix ({@link #withoutInternalPrefix}), the path the model gives it. 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).
|
||||
* path without the prefix ({@link #withoutInternalPrefix}), the path the model gives it. S3, the scope the
|
||||
* vendored routes list as hand-routed, has its 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();
|
||||
@@ -736,7 +725,7 @@ public class IamActionRegistry {
|
||||
Optional<String> operation = restRoutes.operation(credentialScope, method, withoutInternalPrefix(ctx, path),
|
||||
ctx.getUriInfo() == null ? null : ctx.getUriInfo().getQueryParameters(), movedUnderPrefix(ctx));
|
||||
if (operation.isPresent()) {
|
||||
String action = IamAuthorizedActions.actionFor(credentialScope, operation.get());
|
||||
String action = IamAuthorizedActions.actionFor(credentialScope, operation.get(), method);
|
||||
if (checkedAsAws(credentialScope, operation.get(), action)) {
|
||||
return action;
|
||||
}
|
||||
|
||||
@@ -38,7 +38,10 @@ import java.util.Set;
|
||||
*
|
||||
* <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.
|
||||
* {@code *}, which is what Floci checks a REST request on until it reads the resources in its path. And it lists
|
||||
* the operations of those scopes a request on whose route is checked as the action its HTTP method names
|
||||
* ({@link #actionFor(String, String, String)}): API Gateway's management API is authorized as
|
||||
* {@code apigateway:GET}, {@code apigateway:POST} and so on, and {@code TagResource} is a PUT in v1 and a POST in v2.
|
||||
*
|
||||
* <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
|
||||
@@ -63,10 +66,11 @@ 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.
|
||||
* The file: the action of each operation it names, keyed by {@code <namespace>:<Operation>}, the actions of
|
||||
* no resource type, as {@code <namespace>:<Action>} in lower case, and the operations authorized by method, as
|
||||
* {@code <namespace>:<Operation>}.
|
||||
*/
|
||||
record Table(Map<String, String> actions, Set<String> withoutResourceTypes) {
|
||||
record Table(Map<String, String> actions, Set<String> withoutResourceTypes, Set<String> byMethod) {
|
||||
}
|
||||
|
||||
private static final class Holder {
|
||||
@@ -89,6 +93,17 @@ public final class IamAuthorizedActions {
|
||||
return Holder.TABLE.actions().getOrDefault(own, own);
|
||||
}
|
||||
|
||||
/**
|
||||
* The action AWS checks for a request of {@code method} on a route of {@code operation} under {@code namespace}:
|
||||
* the one that method names, {@code <namespace>:<METHOD>}, for an operation the file lists as authorized by
|
||||
* method, or else {@link #actionFor(String, String)}'s.
|
||||
*/
|
||||
public static String actionFor(String namespace, String operation, String method) {
|
||||
return Holder.TABLE.byMethod().contains(namespace + ":" + operation)
|
||||
? namespace + ":" + method.toUpperCase(Locale.ROOT)
|
||||
: actionFor(namespace, operation);
|
||||
}
|
||||
|
||||
/**
|
||||
* 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
|
||||
@@ -122,7 +137,30 @@ public final class IamAuthorizedActions {
|
||||
actions.put(namespace.getKey() + ":" + operation.getKey(), action);
|
||||
});
|
||||
});
|
||||
return new Table(Map.copyOf(actions), withoutResourceTypes(document.path("actionsWithoutResourceTypes")));
|
||||
return new Table(Map.copyOf(actions), withoutResourceTypes(document.path("actionsWithoutResourceTypes")),
|
||||
byMethod(document.path("authorizedByMethod")));
|
||||
}
|
||||
|
||||
/** The operations authorized by method, each scope's a list of operation names. */
|
||||
private static Set<String> byMethod(JsonNode scopes) {
|
||||
if (!scopes.isObject()) {
|
||||
throw new IllegalStateException(RESOURCE_NAME + " carries no authorizedByMethod");
|
||||
}
|
||||
Set<String> operations = new HashSet<>();
|
||||
scopes.properties().forEach(scope -> {
|
||||
if (!scope.getValue().isArray()) {
|
||||
throw new IllegalStateException(RESOURCE_NAME + " has authorizedByMethod."
|
||||
+ scope.getKey() + " as something other than a list");
|
||||
}
|
||||
scope.getValue().forEach(operation -> {
|
||||
if (!operation.isTextual() || operation.textValue().isBlank()) {
|
||||
throw new IllegalStateException(RESOURCE_NAME + " lists " + operation + " among "
|
||||
+ scope.getKey() + "'s operations authorized by method");
|
||||
}
|
||||
operations.add(scope.getKey() + ":" + operation.textValue());
|
||||
});
|
||||
});
|
||||
return Set.copyOf(operations);
|
||||
}
|
||||
|
||||
/** The actions of no resource type, each scope's a list of action names. */
|
||||
|
||||
@@ -40,6 +40,10 @@ import java.util.regex.Pattern;
|
||||
* route takes them: a path that matches no route with each label taking one segment is matched again with each
|
||||
* label taking as many as its value spans.
|
||||
*
|
||||
* <p>An operation may have alternative routes, the bare paths a shared controller also serves it on, with where
|
||||
* the request carries the members the path no longer holds, and the alternative's own method when it is not the
|
||||
* operation's: API Gateway v1 tags with a PUT, and the shared tags controller's bare path tags with a POST.
|
||||
*
|
||||
* <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
|
||||
@@ -230,8 +234,9 @@ final class IamRestRoutes {
|
||||
}
|
||||
alternatives.forEach(alternative -> {
|
||||
String uri = alternative.path("requestUri").asText("");
|
||||
String alternativeMethod = alternative.has("method") ? alternative.get("method").asText("") : method;
|
||||
JsonNode members = alternative.path("located");
|
||||
if (!uri.startsWith("/") || !members.isObject()) {
|
||||
if (!uri.startsWith("/") || !members.isObject() || !METHODS.contains(alternativeMethod)) {
|
||||
throw new IllegalStateException(RESOURCE_NAME + " gives " + operation.getKey()
|
||||
+ " an invalid alternative route");
|
||||
}
|
||||
@@ -245,7 +250,8 @@ final class IamRestRoutes {
|
||||
}
|
||||
located.put(member.getKey(), source);
|
||||
});
|
||||
routes.get(scope).get(method).add(route(operation.getKey(), uri, Map.copyOf(located)));
|
||||
routes.get(scope).computeIfAbsent(alternativeMethod, ignored -> new ArrayList<>())
|
||||
.add(route(operation.getKey(), uri, Map.copyOf(located)));
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
@@ -223,7 +223,9 @@
|
||||
"BatchCreateVehicle": "iotfleetwise:CreateVehicle"
|
||||
},
|
||||
"lakeformation": {
|
||||
"GetTemporaryDataLocationCredentials": "lakeformation:GetDataAccess"
|
||||
"GetGlueFunctionSessionContext": "lakeformation:GetDataAccess",
|
||||
"GetTemporaryDataLocationCredentials": "lakeformation:GetDataAccess",
|
||||
"GetTemporaryGlueFunctionCredentials": "lakeformation:GetDataAccess"
|
||||
},
|
||||
"lambda": {
|
||||
"GetLayerVersionByArn": "lambda:GetLayerVersion",
|
||||
@@ -352,6 +354,7 @@
|
||||
"StartPolicyGeneration",
|
||||
"ValidatePolicy"
|
||||
],
|
||||
"apigateway": [],
|
||||
"cloudfront": [
|
||||
"CreateAnycastIpList",
|
||||
"CreateCachePolicy",
|
||||
@@ -1026,5 +1029,64 @@
|
||||
"UpdateIndexingRule",
|
||||
"UpdateTraceSegmentDestination"
|
||||
]
|
||||
},
|
||||
"authorizedByMethod": {
|
||||
"apigateway": [
|
||||
"CreateApi",
|
||||
"CreateApiKey",
|
||||
"CreateAuthorizer",
|
||||
"CreateDeployment",
|
||||
"CreateDomainName",
|
||||
"CreateDomainNameAccessAssociation",
|
||||
"CreateIntegration",
|
||||
"CreateModel",
|
||||
"CreateRestApi",
|
||||
"CreateStage",
|
||||
"CreateUsagePlan",
|
||||
"CreateVpcLink",
|
||||
"DeleteAuthorizer",
|
||||
"DeleteDeployment",
|
||||
"DeleteDomainName",
|
||||
"DeleteIntegration",
|
||||
"DeleteIntegrationResponse",
|
||||
"DeleteModel",
|
||||
"DeleteStage",
|
||||
"DeleteVpcLink",
|
||||
"GenerateClientCertificate",
|
||||
"GetAuthorizer",
|
||||
"GetAuthorizers",
|
||||
"GetDeployment",
|
||||
"GetDeployments",
|
||||
"GetDomainName",
|
||||
"GetDomainNames",
|
||||
"GetIntegration",
|
||||
"GetIntegrationResponse",
|
||||
"GetModel",
|
||||
"GetModelTemplate",
|
||||
"GetModels",
|
||||
"GetStage",
|
||||
"GetStages",
|
||||
"GetTags",
|
||||
"GetVpcLink",
|
||||
"GetVpcLinks",
|
||||
"ImportApi",
|
||||
"ImportRestApi",
|
||||
"PutIntegration",
|
||||
"PutRestApi",
|
||||
"ReimportApi",
|
||||
"TagResource",
|
||||
"UntagResource",
|
||||
"UpdateAccount",
|
||||
"UpdateApi",
|
||||
"UpdateAuthorizer",
|
||||
"UpdateDeployment",
|
||||
"UpdateDomainName",
|
||||
"UpdateIntegration",
|
||||
"UpdateIntegrationResponse",
|
||||
"UpdateModel",
|
||||
"UpdateRestApi",
|
||||
"UpdateStage",
|
||||
"UpdateVpcLink"
|
||||
]
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,5 @@
|
||||
{
|
||||
"_source": {"generator": "tools/aws/regen_iam_passed_roles.py", "reference": "https://servicereference.us-east-1.amazonaws.com/", "botocore": "botocore 1.43.118 (local/aws/botocore)", "retrieved": "2026-11-02", "note": "make iam-passed-roles-check re-derives every member from botocore; make iam-passed-roles-verify checks every operation against AWS."},
|
||||
"_source": {"generator": "tools/aws/regen_iam_passed_roles.py", "reference": "https://servicereference.us-east-1.amazonaws.com/", "botocore": "botocore 1.43.118 (local/aws/botocore)", "retrieved": "2026-11-12", "note": "make iam-passed-roles-check re-derives every member from botocore; make iam-passed-roles-verify checks every operation against AWS."},
|
||||
"namespaces": {"application-autoscaling": ["application-autoscaling"], "athena": ["athena"], "autoscaling": ["autoscaling"], "budgets": ["budgets"], "cloudformation": ["cloudcontrol", "cloudformation"], "cloudtrail": ["cloudtrail"], "cloudwatch": ["cloudwatch", "cloudwatchomni"], "codebuild": ["codebuild"], "codedeploy": ["codedeploy"], "codepipeline": ["codepipeline"], "cognito-identity": ["cognito-identity"], "cognito-idp": ["cognito-idp"], "comprehend": ["comprehend"], "config": ["config"], "datasync": ["datasync"], "dms": ["dms"], "dsql": ["dsql"], "ec2": ["ec2"], "ecr": ["ecr"], "ecs": ["ecs"], "eks": ["eks"], "elasticmapreduce": ["emr"], "events": ["eventbridgev2", "events"], "firehose": ["firehose"], "glue": ["glue"], "iam": ["iam"], "kinesis": ["kinesis"], "kinesisanalytics": ["kinesisanalytics", "kinesisanalyticsv2"], "lambda": ["lambda", "lambda-core", "lambda-microvms", "lambda-web"], "logs": ["logs"], "pipes": ["pipes"], "rds": ["docdb", "neptune", "rds"], "redshift": ["redshift"], "redshift-serverless": ["redshift-serverless"], "rekognition": ["rekognition"], "resource-groups": ["resource-groups"], "s3": ["s3", "s3control"], "sagemaker": ["sagemaker"], "scheduler": ["scheduler"], "secretsmanager": ["secretsmanager"], "servicecatalog": ["servicecatalog"], "ses": ["mailmanager", "pinpoint-email", "ses", "sesv2"], "sns": ["sns"], "ssm": ["ssm"], "states": ["stepfunctions"], "swf": ["swf"], "textract": ["textract"], "transcribe": ["transcribe"], "transfer": ["transfer"], "translate": ["translate"]},
|
||||
"notCovered": {"access-analyzer": "REST routes no rule maps yet", "airflow": "REST routes no rule maps yet", "apigateway": "authorized by HTTP method, so no request is checked as one of these operations", "appconfig": "REST routes no rule maps yet", "appsync": "REST routes no rule maps yet", "aps": "REST routes no rule maps yet", "aws-marketplace": "REST routes no rule maps yet", "backup": "REST routes no rule maps yet", "batch": "REST routes no rule maps yet", "bedrock": "REST routes no rule maps yet", "bedrock-agentcore": "REST routes no rule maps yet", "cloudfront": "REST routes no rule maps yet", "dlm": "REST routes no rule maps yet", "elasticfilesystem": "REST routes no rule maps yet", "emr-serverless": "REST routes no rule maps yet", "es": "REST routes no rule maps yet", "fis": "REST routes no rule maps yet", "guardduty": "REST routes no rule maps yet", "iot": "REST routes no rule maps yet", "kafka": "REST routes no rule maps yet", "macie2": "REST routes no rule maps yet", "mq": "REST routes no rule maps yet", "quicksight": "metadata-only REST subset; role passing and iam:PassRole checks are not implemented", "rum": "REST routes no rule maps yet", "s3tables": "REST routes no rule maps yet"},
|
||||
"otherNamespaces": ["agent-registry", "aidevops", "aiops", "airflow-serverless", "amplify", "aoss", "appflow", "appmesh", "apprunner", "appstream", "arc-region-switch", "backup-gateway", "backup-search", "bcm-dashboards", "braket", "chatbot", "chime", "cleanrooms", "cleanrooms-ml", "codeconnections", "codestar-connections", "cognito-sync", "comprehendmedical", "databrew", "dataexchange", "datapipeline", "datazone", "dax", "deadline", "devicefarm", "elemental-inference", "emr-containers", "entityresolution", "fms", "forecast", "frauddetector", "gamelift", "gameliftstreams", "geo", "grafana", "greengrass", "groundstation", "health-agent", "healthlake", "imagebuilder", "iotdeviceadvisor", "iotfleetwise", "iotmanagedintegrations", "iotsitewise", "iottwinmaker", "iotwireless", "kafkaconnect", "kendra", "lex", "lookoutequipment", "m2", "machinelearning", "mediaconnect", "mediaconvert", "medialive", "mediapackage", "mediapackage-vod", "mediapackagev2", "mediastore", "medical-imaging", "mobiletargeting", "neptune-graph", "observabilityadmin", "odb", "omics", "opensearch", "osis", "partnercentral", "pcs", "personalize", "profile", "proton", "qbusiness", "repostspace", "resiliencehub", "rolesanywhere", "s3files", "sagemaker-geospatial", "securityagent", "securitylake", "shield", "sms-voice", "snowball", "social-messaging", "ssm-incidents", "ssm-quicksetup", "storagegateway", "supportapp", "synthetics", "timestream", "voiceid", "wellarchitected", "wisdom", "workmail", "workspaces"],
|
||||
@@ -364,7 +364,9 @@
|
||||
{"member": "infrastructureRoleArn", "passedTo": "ecs"},
|
||||
{"member": "taskRoleArn", "passedTo": "ecs-tasks"}
|
||||
]},
|
||||
"ecs:CreateGateway": {"passedTo": ["ecs"], "notRead": "botocore's model has no such operation"},
|
||||
"ecs:CreateGateway": {"passedTo": ["ecs"], "roles": [
|
||||
{"member": "infrastructureRoleArn", "passedTo": "ecs"}
|
||||
]},
|
||||
"ecs:CreateService": {"passedTo": ["ecs", "ecs-tasks"], "byHand": "the task definition's roles and the service's infrastructure roles"},
|
||||
"ecs:CreateTaskSet": {"passedTo": ["ecs-tasks"], "byHand": "the task definition's roles"},
|
||||
"ecs:RegisterDaemonTaskDefinition": {"passedTo": ["ecs-tasks"], "roles": [
|
||||
@@ -380,7 +382,9 @@
|
||||
{"member": "executionRoleArn", "passedTo": "ecs-tasks"},
|
||||
{"member": "taskRoleArn", "passedTo": "ecs-tasks"}
|
||||
]},
|
||||
"ecs:UpdateGateway": {"passedTo": ["ecs"], "notRead": "botocore's model has no such operation"},
|
||||
"ecs:UpdateGateway": {"passedTo": ["ecs"], "roles": [
|
||||
{"member": "infrastructureRoleArn", "passedTo": "ecs"}
|
||||
]},
|
||||
"ecs:UpdateService": {"passedTo": ["ecs", "ecs-tasks"], "byHand": "the task definition's roles and the service's infrastructure roles"},
|
||||
"eks:CreateAccessEntry": {"passedTo": ["ec2"], "byHand": "the principal, for the node types alone"},
|
||||
"eks:CreateAddon": {"passedTo": ["eks"], "byHand": "the service account role and each Pod Identity association's role"},
|
||||
@@ -409,8 +413,8 @@
|
||||
{"member": "ExecutionEngine.ExecutionRoleArn"},
|
||||
{"member": "ServiceRole", "byName": true}
|
||||
]},
|
||||
"elasticmapreduce:StartSession": {"passedTo": ["elasticmapreduce", "managed-compute.elasticmapreduce"], "roles": [
|
||||
{"member": "ExecutionRoleArn", "passedTo": "elasticmapreduce"}
|
||||
"elasticmapreduce:StartSession": {"passedTo": ["managed-compute.elasticmapreduce"], "roles": [
|
||||
{"member": "ExecutionRoleArn", "passedTo": "managed-compute.elasticmapreduce"}
|
||||
]},
|
||||
"elasticmapreduce:UpdateStudio": {"passedTo": [], "notRead": "no member of the request names a role"},
|
||||
"events:CreateEndpoint": {"passedTo": ["events"], "roles": [
|
||||
@@ -605,6 +609,7 @@
|
||||
{"member": "S3Configuration.RoleARN", "passedTo": "kinesisanalytics"},
|
||||
{"member": "ServiceExecutionRole", "passedTo": "kinesisanalytics"}
|
||||
]},
|
||||
"kinesisanalytics:ImportSnapshot": {"passedTo": ["kinesisanalytics"], "notRead": "the pinned botocore does not have the operation yet, so its request cannot be read"},
|
||||
"kinesisanalytics:UpdateApplication": {"passedTo": ["kinesisanalytics"], "roles": [
|
||||
{"member": "ApplicationUpdate.CloudWatchLoggingOptionUpdates[].RoleARNUpdate", "passedTo": "kinesisanalytics"},
|
||||
{"member": "ApplicationUpdate.InputUpdates[].InputProcessingConfigurationUpdate.InputLambdaProcessorUpdate.RoleARNUpdate", "passedTo": "kinesisanalytics"},
|
||||
@@ -642,6 +647,7 @@
|
||||
"logs:PutSubscriptionFilter": {"passedTo": ["logs"], "roles": [
|
||||
{"member": "roleArn", "passedTo": "logs"}
|
||||
]},
|
||||
"logs:StartQuery": {"passedTo": ["logs"], "notRead": "no member of the request names a role"},
|
||||
"logs:UpdateScheduledQuery": {"passedTo": ["logs"], "roles": [
|
||||
{"member": "destinationConfiguration.lookupTableConfiguration.roleArn", "passedTo": "logs"},
|
||||
{"member": "destinationConfiguration.s3Configuration.roleArn", "passedTo": "logs"},
|
||||
@@ -943,6 +949,7 @@
|
||||
"ssm:CreateDocument": {"passedTo": ["justintimeaccess.ssm", "ssm"], "notRead": "no member of the request names a role"},
|
||||
"ssm:DescribeAutomationStepExecutions": {"passedTo": ["ssm"], "notRead": "no member of the request names a role"},
|
||||
"ssm:GetAutomationExecution": {"passedTo": ["ssm"], "notRead": "no member of the request names a role"},
|
||||
"ssm:RegisterDefaultHostManagementConfiguration": {"passedTo": ["ssm"], "notRead": "the pinned botocore does not have the operation yet, so its request cannot be read"},
|
||||
"ssm:RegisterTaskWithMaintenanceWindow": {"passedTo": ["ssm"], "roles": [
|
||||
{"member": "ServiceRoleArn", "passedTo": "ssm"},
|
||||
{"member": "TaskInvocationParameters.RunCommand.ServiceRoleArn", "passedTo": "ssm"}
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
{
|
||||
"_source": {"generator": "tools/aws/regen_rest_routes.py", "botocore": "botocore 1.43.118 (installed package)"},
|
||||
"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": {
|
||||
@@ -135,7 +134,7 @@
|
||||
"GetSdkTypes": {"method": "GET", "requestUri": "/sdktypes"},
|
||||
"GetStage": {"method": "GET", "requestUri": "/restapis/{restapi_id}/stages/{stage_name}"},
|
||||
"GetStages": {"method": "GET", "requestUri": "/restapis/{restapi_id}/stages"},
|
||||
"GetTags": {"method": "GET", "requestUri": "/tags/{resource_arn}"},
|
||||
"GetTags": {"method": "GET", "requestUri": "/tags/{resource_arn+}", "alternatives": [{"requestUri": "/tags", "located": {"resourceArn": "?resourceArn"}}]},
|
||||
"GetUsage": {"method": "GET", "requestUri": "/usageplans/{usageplanId}/usage"},
|
||||
"GetUsagePlan": {"method": "GET", "requestUri": "/usageplans/{usageplanId}"},
|
||||
"GetUsagePlanKey": {"method": "GET", "requestUri": "/usageplans/{usageplanId}/keys/{keyId}"},
|
||||
@@ -153,10 +152,10 @@
|
||||
"PutMethodResponse": {"method": "PUT", "requestUri": "/restapis/{restapi_id}/resources/{resource_id}/methods/{http_method}/responses/{status_code}"},
|
||||
"PutRestApi": {"method": "PUT", "requestUri": "/restapis/{restapi_id}"},
|
||||
"RejectDomainNameAccessAssociation": {"method": "POST", "requestUri": "/rejectdomainnameaccessassociations"},
|
||||
"TagResource": {"method": "PUT", "requestUri": "/tags/{resource_arn}"},
|
||||
"TagResource": {"method": "PUT", "requestUri": "/tags/{resource_arn+}", "alternatives": [{"method": "POST", "requestUri": "/tags", "located": {"resourceArn": "body"}}]},
|
||||
"TestInvokeAuthorizer": {"method": "POST", "requestUri": "/restapis/{restapi_id}/authorizers/{authorizer_id}"},
|
||||
"TestInvokeMethod": {"method": "POST", "requestUri": "/restapis/{restapi_id}/resources/{resource_id}/methods/{http_method}"},
|
||||
"UntagResource": {"method": "DELETE", "requestUri": "/tags/{resource_arn}"},
|
||||
"UntagResource": {"method": "DELETE", "requestUri": "/tags/{resource_arn+}", "alternatives": [{"requestUri": "/tags", "located": {"resourceArn": "?resourceArn"}}]},
|
||||
"UpdateAccount": {"method": "PATCH", "requestUri": "/account"},
|
||||
"UpdateApiKey": {"method": "PATCH", "requestUri": "/apikeys/{api_Key}"},
|
||||
"UpdateAuthorizer": {"method": "PATCH", "requestUri": "/restapis/{restapi_id}/authorizers/{authorizer_id}"},
|
||||
@@ -256,7 +255,7 @@
|
||||
"GetRoutingRule": {"method": "GET", "requestUri": "/v2/domainnames/{domainName}/routingrules/{routingRuleId}"},
|
||||
"GetStage": {"method": "GET", "requestUri": "/v2/apis/{apiId}/stages/{stageName}"},
|
||||
"GetStages": {"method": "GET", "requestUri": "/v2/apis/{apiId}/stages"},
|
||||
"GetTags": {"method": "GET", "requestUri": "/v2/tags/{resource-arn}"},
|
||||
"GetTags": {"method": "GET", "requestUri": "/v2/tags/{resource-arn+}"},
|
||||
"GetVpcLink": {"method": "GET", "requestUri": "/v2/vpclinks/{vpcLinkId}"},
|
||||
"GetVpcLinks": {"method": "GET", "requestUri": "/v2/vpclinks"},
|
||||
"ImportApi": {"method": "PUT", "requestUri": "/v2/apis"},
|
||||
@@ -271,8 +270,8 @@
|
||||
"PutRoutingRule": {"method": "PUT", "requestUri": "/v2/domainnames/{domainName}/routingrules/{routingRuleId}"},
|
||||
"ReimportApi": {"method": "PUT", "requestUri": "/v2/apis/{apiId}"},
|
||||
"ResetAuthorizersCache": {"method": "DELETE", "requestUri": "/v2/apis/{apiId}/stages/{stageName}/cache/authorizers"},
|
||||
"TagResource": {"method": "POST", "requestUri": "/v2/tags/{resource-arn}"},
|
||||
"UntagResource": {"method": "DELETE", "requestUri": "/v2/tags/{resource-arn}"},
|
||||
"TagResource": {"method": "POST", "requestUri": "/v2/tags/{resource-arn+}"},
|
||||
"UntagResource": {"method": "DELETE", "requestUri": "/v2/tags/{resource-arn+}"},
|
||||
"UpdateApi": {"method": "PATCH", "requestUri": "/v2/apis/{apiId}"},
|
||||
"UpdateApiMapping": {"method": "PATCH", "requestUri": "/v2/domainnames/{domainName}/apimappings/{apiMappingId}"},
|
||||
"UpdateAuthorizer": {"method": "PATCH", "requestUri": "/v2/apis/{apiId}/authorizers/{authorizerId}"},
|
||||
|
||||
+40
-1
@@ -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/\"",
|
||||
|
||||
@@ -61,16 +61,34 @@ read from `Actions`, not `Operations`, because the reference lists the operation
|
||||
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.
|
||||
|
||||
It lists too, for those scopes, the operations a request on whose route is checked as the action its HTTP
|
||||
method names, `authorizedByMethod`. API Gateway's management API is authorized by method: its developer
|
||||
guide has "The API-managing Action expression has the format apigateway:action, where action is one of the
|
||||
following API Gateway actions: GET, POST, PUT, DELETE, PATCH (to update resources)". The reference lists each
|
||||
operation the actions of the methods its routes use, in v1 and v2 alike (`TagResource` is a PUT in v1 and a
|
||||
POST in v2), beside actions AWS checks only when the request carries what they guard: the Service
|
||||
Authorization Reference has `UpdateRestApiPolicy` as "an additional authorization control for managing an
|
||||
API due to the sensitive nature of the resource policy", `AddCertificateToDomain` and
|
||||
`RemoveCertificateFromDomain` alike for mTLS, `iam:PassRole` passes a role, and the developer guide has a
|
||||
tagged resource's `PATCH` beside the tags' own method: "To update the tags for a resource, the user must have
|
||||
PATCH permissions for that resource". An operation is listed when, for every route the vendored routes give
|
||||
it, a shared controller's alternative included, the reference lists the action named after that route's
|
||||
method, and the one-action shape above does not already name its action. An operation an action of whose
|
||||
own name exists keeps it, as everywhere in this file: `CreatePortal` lists `apigateway:CreatePortal` beside
|
||||
`apigateway:POST`.
|
||||
|
||||
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; and the actions
|
||||
without resource types are listed for exactly the scopes `rest-routes.json` reads routes for.
|
||||
namespace and differing from the operation, and the anchor cases still present; the actions
|
||||
without resource types are listed for exactly the scopes `rest-routes.json` reads routes for; and
|
||||
an operation authorized by method is one a route of its scope serves, named nowhere else here.
|
||||
- `--verify` is the real gate and needs the network. Every vendored entry must still be what AWS
|
||||
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.
|
||||
publishes for that operation, every action listed without resource types must still have none,
|
||||
and every operation authorized by method must still list its routes' methods. 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
|
||||
@@ -248,7 +266,57 @@ def actions_without_resource_types(documents: list[dict], namespaces: list[str])
|
||||
return found
|
||||
|
||||
|
||||
def build(documents: list[dict], provenance: str, routed: list[str]) -> dict:
|
||||
def route_methods(routes: dict) -> dict[str, dict[str, list[str]]]:
|
||||
"""Each routed scope's operations, with the HTTP methods of every route the vendored routes give them, an
|
||||
alternative's own method included."""
|
||||
routed = set(routed_namespaces(routes))
|
||||
methods: dict[str, dict[str, set[str]]] = {}
|
||||
for model in (routes.get("models") or {}).values():
|
||||
scope = model["credentialScope"]
|
||||
if scope not in routed:
|
||||
continue
|
||||
for operation, route in (model.get("operations") or {}).items():
|
||||
found = methods.setdefault(scope, {}).setdefault(operation, set())
|
||||
found.add(route["method"])
|
||||
found.update(alternative.get("method", route["method"]) for alternative in route.get("alternatives", []))
|
||||
return {scope: {operation: sorted(found) for operation, found in sorted(operations.items())}
|
||||
for scope, operations in sorted(methods.items())}
|
||||
|
||||
|
||||
def authorized_by_method(documents: list[dict], methods: dict[str, dict[str, list[str]]],
|
||||
renamed: dict[str, dict[str, str]]) -> dict[str, list[str]]:
|
||||
"""Each routed scope's operations a request on whose route is checked as the action its method names: those
|
||||
the reference lists, every time it lists them, with the action of each of their routes' methods, which the
|
||||
one-action shape does not already name and no action of their own name settles. Scopes with none are left
|
||||
out."""
|
||||
by_name = {document.get("Name"): document for document in documents}
|
||||
found = {}
|
||||
for scope, operations in methods.items():
|
||||
document = by_name.get(scope)
|
||||
if document is None:
|
||||
raise ValueError(f"the Service Reference has no namespace {scope}, whose REST routes rest-routes.json "
|
||||
f"reads")
|
||||
own_actions = {action["Name"].lower() for action in document.get("Actions", [])
|
||||
if isinstance(action, dict) and isinstance(action.get("Name"), str)}
|
||||
listed: dict[str, list[set[str]]] = {}
|
||||
for operation in document.get("Operations", []):
|
||||
name = operation.get("Name") if isinstance(operation, dict) else None
|
||||
if not isinstance(name, str) or not NAME_RE.match(name):
|
||||
raise ValueError(f"{scope}: operation entry without a usable 'Name': {operation!r}")
|
||||
listed.setdefault(name, []).append({action for service, action in _authorized_actions(scope, operation)
|
||||
if service == scope})
|
||||
chosen = [operation for operation, route_methods_of in operations.items()
|
||||
if operation in listed and operation not in renamed.get(scope, {})
|
||||
and operation.lower() not in own_actions
|
||||
and all(set(route_methods_of) <= actions for actions in listed[operation])]
|
||||
if chosen:
|
||||
found[scope] = sorted(chosen)
|
||||
return found
|
||||
|
||||
|
||||
def build(documents: list[dict], provenance: str, routed: list[str],
|
||||
methods: dict[str, dict[str, list[str]]] | None = None) -> dict:
|
||||
renamed = authorized_actions_from(documents)
|
||||
return {
|
||||
"_source": {
|
||||
"generator": "tools/aws/regen_iam_authorized_actions.py",
|
||||
@@ -256,8 +324,9 @@ def build(documents: list[dict], provenance: str, routed: list[str]) -> dict:
|
||||
"retrieved": datetime.now(timezone.utc).strftime("%Y-%m-%d"),
|
||||
"note": "make iam-authorized-actions-verify checks every entry against AWS.",
|
||||
},
|
||||
"authorizedActions": authorized_actions_from(documents),
|
||||
"authorizedActions": renamed,
|
||||
"actionsWithoutResourceTypes": actions_without_resource_types(documents, routed),
|
||||
"authorizedByMethod": authorized_by_method(documents, methods or {}, renamed),
|
||||
}
|
||||
|
||||
|
||||
@@ -265,12 +334,14 @@ def render(document: dict) -> str:
|
||||
return json.dumps(document, indent=2) + "\n"
|
||||
|
||||
|
||||
def validate(document: dict, routed: list[str]) -> list[str]:
|
||||
"""Problems that make the vendored file unusable, rather than merely out of date."""
|
||||
def validate(document: dict, routed: list[str], methods: dict[str, dict[str, list[str]]] | None = None) -> list[str]:
|
||||
"""Problems that make the vendored file unusable, rather than merely out of date. With the routed scopes'
|
||||
route methods, an operation authorized by method must be one of their operations."""
|
||||
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"]
|
||||
problems += _by_method_problems(document.get("authorizedByMethod"), routed, methods, namespaces)
|
||||
if list(namespaces) != sorted(namespaces):
|
||||
problems.append("authorizedActions is not sorted by namespace")
|
||||
for namespace, operations in namespaces.items():
|
||||
@@ -316,6 +387,49 @@ def _unscoped_problems(unscoped: object, routed: list[str]) -> list[str]:
|
||||
return problems
|
||||
|
||||
|
||||
def _by_method_problems(by_method: object, routed: list[str], methods: dict[str, dict[str, list[str]]] | None,
|
||||
renamed: dict) -> list[str]:
|
||||
"""Problems with the operations authorized by method: for each routed scope listing any, a sorted list of
|
||||
usable names, none of them also given an action of another name, and each, when the routes are known, an
|
||||
operation a route of its scope serves."""
|
||||
if not isinstance(by_method, dict):
|
||||
return ["authorizedByMethod is missing"]
|
||||
problems = []
|
||||
if list(by_method) != sorted(by_method):
|
||||
problems.append("authorizedByMethod is not sorted by scope")
|
||||
for scope, operations in by_method.items():
|
||||
if scope not in routed:
|
||||
problems.append(f"authorizedByMethod lists {scope}, a scope rest-routes.json reads no routes for")
|
||||
if not isinstance(operations, list) or not operations or not all(
|
||||
isinstance(operation, str) and NAME_RE.match(operation) for operation in operations):
|
||||
problems.append(f"authorizedByMethod.{scope} is not a list of operation names")
|
||||
continue
|
||||
if operations != sorted(set(operations)):
|
||||
problems.append(f"authorizedByMethod.{scope} is not sorted, or repeats an operation")
|
||||
for operation in operations:
|
||||
if operation in (renamed.get(scope) or {}):
|
||||
problems.append(f"{scope}:{operation} is authorized by method and as {renamed[scope][operation]}")
|
||||
if methods is not None and operation not in methods.get(scope, {}):
|
||||
problems.append(f"authorizedByMethod lists {scope}:{operation}, which no route of {scope} serves")
|
||||
return problems
|
||||
|
||||
|
||||
def verify_by_method_against(vendored: dict[str, list[str]],
|
||||
upstream: dict[str, list[str]]) -> tuple[list[str], list[str]]:
|
||||
"""The operations the vendored file authorizes by method that AWS no longer lists with their routes' methods,
|
||||
and those it has since added.
|
||||
|
||||
A listed operation AWS no longer authorizes by its method is a failure: its request would be checked as an
|
||||
action AWS does not check for it. One AWS has added stays authorized as its own name until the next sync.
|
||||
"""
|
||||
untrue = [f"AWS no longer authorizes {scope}:{operation} by the methods of its routes"
|
||||
for scope, operations in vendored.items() for operation in operations
|
||||
if operation not in upstream.get(scope, [])]
|
||||
added = sorted(f"{scope}:{operation} by method" for scope, operations in upstream.items()
|
||||
for operation in operations if operation not in vendored.get(scope, []))
|
||||
return untrue, added
|
||||
|
||||
|
||||
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.
|
||||
@@ -361,9 +475,16 @@ def _unscoped_count(document: dict) -> str:
|
||||
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 _routes(routes: Path) -> dict:
|
||||
"""The vendored REST routes."""
|
||||
return json.loads(routes.read_text(encoding="utf-8"))
|
||||
|
||||
|
||||
def _by_method_count(document: dict) -> str:
|
||||
"""How many operations the document authorizes by method, over how many scopes."""
|
||||
by_method = document["authorizedByMethod"]
|
||||
return (f"{sum(len(operations) for operations in by_method.values())} operations authorized by method over "
|
||||
f"{len(by_method)} scopes")
|
||||
|
||||
|
||||
def _shown(path: Path) -> Path:
|
||||
@@ -392,7 +513,8 @@ 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, _routed(args.routes))
|
||||
routes = _routes(args.routes)
|
||||
problems = validate(document, routed_namespaces(routes), route_methods(routes))
|
||||
for problem in problems:
|
||||
print(f"error: {problem}", file=sys.stderr)
|
||||
if problems:
|
||||
@@ -400,7 +522,7 @@ def main(argv: list[str] | None = None) -> int:
|
||||
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"{_unscoped_count(document)})")
|
||||
f"{_unscoped_count(document)}, {_by_method_count(document)})")
|
||||
return 0
|
||||
|
||||
if args.verify:
|
||||
@@ -410,10 +532,14 @@ def main(argv: list[str] | None = None) -> int:
|
||||
vendored_document = json.loads(args.output.read_text(encoding="utf-8"))
|
||||
vendored = vendored_document["authorizedActions"]
|
||||
unscoped = vendored_document.get("actionsWithoutResourceTypes") or {}
|
||||
by_method = vendored_document.get("authorizedByMethod") or {}
|
||||
try:
|
||||
documents, provenance = fetch_references(args.source_dir)
|
||||
upstream = authorized_actions_from(documents)
|
||||
upstream_unscoped = actions_without_resource_types(documents, list(unscoped))
|
||||
methods = route_methods(_routes(args.routes)) if by_method else {}
|
||||
upstream_by_method = authorized_by_method(
|
||||
documents, {scope: methods.get(scope, {}) for scope in by_method}, upstream)
|
||||
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.
|
||||
@@ -421,8 +547,9 @@ def main(argv: list[str] | None = None) -> int:
|
||||
return 2
|
||||
untrue, added = verify_against(vendored, upstream)
|
||||
untrue_unscoped, added_unscoped = verify_unscoped_against(unscoped, upstream_unscoped)
|
||||
untrue += untrue_unscoped
|
||||
added += added_unscoped
|
||||
untrue_by_method, added_by_method = verify_by_method_against(by_method, upstream_by_method)
|
||||
untrue += untrue_unscoped + untrue_by_method
|
||||
added += added_unscoped + added_by_method
|
||||
for claim in untrue:
|
||||
print(f"error: {claim}", file=sys.stderr)
|
||||
entries = sum(len(operations) for operations in vendored.values())
|
||||
@@ -442,12 +569,14 @@ def main(argv: list[str] | None = None) -> int:
|
||||
|
||||
try:
|
||||
documents, provenance = fetch_references(args.source_dir)
|
||||
routed = _routed(args.routes)
|
||||
document = build(documents, provenance, routed)
|
||||
routes = _routes(args.routes)
|
||||
routed = routed_namespaces(routes)
|
||||
methods = route_methods(routes)
|
||||
document = build(documents, provenance, routed, methods)
|
||||
except (OSError, ValueError) as e:
|
||||
print(f"error: could not read the Service Reference ({e})", file=sys.stderr)
|
||||
return 2
|
||||
problems = validate(document, routed)
|
||||
problems = validate(document, routed, methods)
|
||||
for problem in problems:
|
||||
print(f"error: {problem}", file=sys.stderr)
|
||||
if problems:
|
||||
@@ -455,7 +584,8 @@ 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, {_unscoped_count(document)}, from {provenance})")
|
||||
f"{len(document['authorizedActions'])} namespaces, {_unscoped_count(document)}, "
|
||||
f"{_by_method_count(document)}, from {provenance})")
|
||||
return 0
|
||||
|
||||
|
||||
|
||||
@@ -245,6 +245,11 @@ BY_HAND.update({
|
||||
})
|
||||
|
||||
NO_ROLE_MEMBER = "no member of the request names a role"
|
||||
# For an operation no botocore release models, as a legacy one the SDKs dropped.
|
||||
NO_SUCH_OPERATION = "botocore's model has no such operation"
|
||||
# For an operation AWS has shipped since the botocore pin. It lasts until a bump brings the operation in,
|
||||
# when entry_for refuses it, so that the role its request names is read.
|
||||
NOT_IN_BOTOCORE = "the pinned botocore does not have the operation yet, so its request cannot be read"
|
||||
RUNBOOK_PARAMETER = "the role is a parameter of the runbook it runs, not a member of the request"
|
||||
XML_BODY = "the request body is XML, which PassedRoles does not read"
|
||||
|
||||
@@ -257,17 +262,17 @@ NOT_READ = {
|
||||
"dms:ModifyInstanceProfile": NO_ROLE_MEMBER,
|
||||
"ec2:RequestSpotFleet": "the request names its roles in EC2's own protocol, one of them as an instance profile",
|
||||
"ecs:CreateDaemon": "the roles are the daemon task definition's, which only a lookup finds",
|
||||
"ecs:CreateGateway": "botocore's model has no such operation",
|
||||
"ecs:UpdateDaemon": "the roles are the daemon task definition's, which only a lookup finds",
|
||||
"ecs:UpdateGateway": "botocore's model has no such operation",
|
||||
"eks:UpdateClusterConfig": "the reference passes the node role to ec2 or eks and nothing says which",
|
||||
"elasticmapreduce:RunJobFlow": "JobFlowRole names an instance profile, and the reference passes the roles "
|
||||
"to three services without saying which goes where",
|
||||
"elasticmapreduce:UpdateStudio": NO_ROLE_MEMBER,
|
||||
"glue:GetJob": NO_ROLE_MEMBER,
|
||||
"glue:GetJobs": NO_ROLE_MEMBER,
|
||||
"lambda:AddEventSource": "botocore's model has no such operation",
|
||||
"kinesisanalytics:ImportSnapshot": NOT_IN_BOTOCORE,
|
||||
"lambda:AddEventSource": NO_SUCH_OPERATION,
|
||||
"logs:CreateImportTask": "the reference passes the role to cloudtrail or logs and nothing says which",
|
||||
"logs:StartQuery": NO_ROLE_MEMBER,
|
||||
"rds:CreateBlueGreenDeployment": NO_ROLE_MEMBER,
|
||||
"s3:CreateAccessGrantsLocation": XML_BODY,
|
||||
"s3:PutBucketReplication": XML_BODY,
|
||||
@@ -280,6 +285,7 @@ NOT_READ = {
|
||||
"ssm:CreateDocument": NO_ROLE_MEMBER,
|
||||
"ssm:DescribeAutomationStepExecutions": NO_ROLE_MEMBER,
|
||||
"ssm:GetAutomationExecution": NO_ROLE_MEMBER,
|
||||
"ssm:RegisterDefaultHostManagementConfiguration": NOT_IN_BOTOCORE,
|
||||
"ssm:StartAutomationExecution": RUNBOOK_PARAMETER,
|
||||
"ssm:StartChangeRequestExecution": RUNBOOK_PARAMETER,
|
||||
"ssm:UpdateDocument": NO_ROLE_MEMBER,
|
||||
@@ -394,9 +400,6 @@ MEMBER_SERVICES = {
|
||||
"taskRoleArn": ECS_TASKS,
|
||||
"infrastructureRoleArn": ECS_INFRASTRUCTURE,
|
||||
},
|
||||
# "Amazon EMR uses this role" for the session. The reference also lists
|
||||
# managed-compute.elasticmapreduce, but the request cannot say which compute it runs on.
|
||||
"elasticmapreduce:StartSession": {"ExecutionRoleArn": "elasticmapreduce"},
|
||||
# rds-preview is the principal of RDS's preview environment; PassedRoles' RDS cases pass to rds.
|
||||
"rds:*": {"*": "rds"},
|
||||
}
|
||||
@@ -584,9 +587,11 @@ def entry_for(operation: str, passed_to: list[str], models: dict[str, dict]) ->
|
||||
"""What the file says for one operation, from its services and the models of its namespace."""
|
||||
if operation in BY_HAND:
|
||||
return {"passedTo": passed_to, "byHand": BY_HAND[operation]}
|
||||
if operation in NOT_READ:
|
||||
return {"passedTo": passed_to, "notRead": NOT_READ[operation]}
|
||||
name = operation.split(":", 1)[1]
|
||||
if operation in NOT_READ:
|
||||
if NOT_READ[operation] == NOT_IN_BOTOCORE and any(name in model["operations"] for model in models.values()):
|
||||
raise ValueError(f"{operation}: the pinned botocore has it now, so take it out of NOT_READ")
|
||||
return {"passedTo": passed_to, "notRead": NOT_READ[operation]}
|
||||
members: dict[str, bool] = {}
|
||||
for model in models.values():
|
||||
for path, by_name in role_members(model, name).items():
|
||||
|
||||
@@ -13,8 +13,8 @@ The credential scopes in `HAND_ROUTED` are authorized by the registry's rules al
|
||||
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. Supported shared-controller alternatives are generated beside the modeled URI, with
|
||||
member-location overrides for the bare route. These alternatives describe existing Floci compatibility
|
||||
paths, not additional botocore operations.
|
||||
member-location overrides for the bare route, and its own method where that is not the operation's. These
|
||||
alternatives describe existing Floci compatibility paths, not additional botocore operations.
|
||||
|
||||
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
|
||||
@@ -41,10 +41,7 @@ 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 "
|
||||
"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",
|
||||
}
|
||||
@@ -81,14 +78,24 @@ MODELS: dict[str, str] = {
|
||||
}
|
||||
|
||||
# Operations a model does not serve itself. The shared tags controller serves /tags/{resourceArn} for every
|
||||
# service that is a TagHandler, the ARN taking the rest of the path, and the bare /tags too. A route a service's
|
||||
# filter moves under an internal prefix is vendored at the model's own path all the same: IAM matches it on the
|
||||
# path without the prefix the filter records (SignedServiceRoute).
|
||||
# service that is a TagHandler, the ARN taking the rest of the path, and the bare /tags too. API Gateway's v1
|
||||
# tag routes are the shared controller's too. A route a service's filter moves under an internal prefix is
|
||||
# vendored at the model's own path all the same: IAM matches it on the path without the prefix the filter
|
||||
# records (SignedServiceRoute).
|
||||
SHARED_ROUTES: dict[str, frozenset[str]] = {
|
||||
"apigateway": frozenset({"TagResource", "UntagResource", "GetTags"}),
|
||||
"controltower": frozenset({"TagResource", "UntagResource", "ListTagsForResource"}),
|
||||
"signer": frozenset({"TagResource", "UntagResource", "ListTagsForResource"}),
|
||||
}
|
||||
|
||||
# Operations whose ARN label a model gives one segment, where the controller serving them lets it span
|
||||
# the slashes the ARN holds: a request may send the ARN unencoded and still reach the operation, so its
|
||||
# route has to take that request too or it would go unchecked. API Gateway v2's tag routes are
|
||||
# `/v2/tags/{resourceArn: .+}` in its controller.
|
||||
ARN_SPANNING_ROUTES: dict[str, frozenset[str]] = {
|
||||
"apigatewayv2": frozenset({"TagResource", "UntagResource", "GetTags"}),
|
||||
}
|
||||
|
||||
|
||||
def access_denied_status(model: dict) -> int | None:
|
||||
"""The HTTP status explicitly modelled for a declared AccessDenied or AccessDeniedException error."""
|
||||
@@ -116,20 +123,18 @@ def build(models: dict[str, dict], provenance: str) -> dict:
|
||||
if model["metadata"].get("protocol") not in ("rest-json", "rest-xml"):
|
||||
raise SystemExit(f"error: {name} is not a REST model")
|
||||
shared = SHARED_ROUTES.get(name, frozenset())
|
||||
spanning = ARN_SPANNING_ROUTES.get(name, frozenset())
|
||||
operations = {}
|
||||
for operation in sorted(model["operations"]):
|
||||
http = model["operations"][operation]["http"]
|
||||
request_uri = http["requestUri"]
|
||||
if operation in shared:
|
||||
# A shared tags route names its resource as an ARN, which holds slashes: the label
|
||||
# has to span them or the route matches no tag request at all.
|
||||
if operation in shared or operation in spanning:
|
||||
# A tags route names its resource as an ARN, which holds slashes: the label has to
|
||||
# span them or the route matches no tag request at all.
|
||||
request_uri = re.sub(r"\{([^}]*[Aa]rn[^}]*)}", r"{\1+}", request_uri)
|
||||
route = {"method": http["method"], "requestUri": request_uri}
|
||||
if operation in shared:
|
||||
# SharedTagsController also serves the bare path, reading POST's body and
|
||||
# GET/DELETE's query. Keep that compatibility route and its member source together.
|
||||
route["alternatives"] = [{"requestUri": "/tags", "located": {
|
||||
"resourceArn": "body" if http["method"] == "POST" else "?resourceArn"}}]
|
||||
route["alternatives"] = [bare_tags_route(http["method"])]
|
||||
operations[operation] = route
|
||||
routes[name] = {
|
||||
"credentialScope": MODELS[name],
|
||||
@@ -158,6 +163,15 @@ def build(models: dict[str, dict], provenance: str) -> dict:
|
||||
}
|
||||
|
||||
|
||||
def bare_tags_route(method: str) -> dict:
|
||||
"""The bare `/tags` route SharedTagsController also serves for a shared tags route of the method, with where it
|
||||
reads the ARN: a tagging request is a POST whose body names it, whether the service tags with POST or with
|
||||
PUT, and a GET or DELETE names it in its query. A route of another method than the operation's says so."""
|
||||
bare = "POST" if method in ("POST", "PUT") else method
|
||||
route = {"requestUri": "/tags", "located": {"resourceArn": "body" if bare == "POST" else "?resourceArn"}}
|
||||
return route if bare == method else {"method": bare, **route}
|
||||
|
||||
|
||||
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("?")
|
||||
@@ -174,7 +188,8 @@ def shared_routes(routes: dict[str, dict]) -> list[str]:
|
||||
continue
|
||||
for operation, route in model["operations"].items():
|
||||
for variant in [route, *route.get("alternatives", [])]:
|
||||
key = (model["credentialScope"],) + route_key(route["method"], variant["requestUri"])
|
||||
key = (model["credentialScope"],) + route_key(variant.get("method", route["method"]),
|
||||
variant["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]
|
||||
|
||||
@@ -422,3 +422,119 @@ def test_the_round_trip_lists_the_routed_scopes_actions(tmp_path):
|
||||
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
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# authorizedByMethod: the operations checked as the action their route's method names
|
||||
# --------------------------------------------------------------------------- #
|
||||
def by_method_service(operations: dict[str, list[str]], sdks: dict[str, list[str]] | None = None) -> dict:
|
||||
"""An API Gateway-like reference document: its methods are actions, beside actions of their own names."""
|
||||
document = service("api", operations, ["GET", "POST", "PUT", "PATCH", "DELETE", "UpdatePolicy", "CreatePortal"])
|
||||
for operation in document["Operations"]:
|
||||
operation["SDK"] = [{"Name": name} for name in (sdks or {}).get(operation["Name"], ["api"])]
|
||||
return document
|
||||
|
||||
|
||||
METHOD_ROUTES = {"handRouted": {"hand": "the rules route it alone"}, "models": {
|
||||
"api": {"credentialScope": "api", "operations": {
|
||||
"TagResource": {"method": "PUT", "requestUri": "/tags/{arn+}",
|
||||
"alternatives": [{"method": "POST", "requestUri": "/tags", "located": {"arn": "body"}}]},
|
||||
"GetStage": {"method": "GET", "requestUri": "/apis/{id}/stages/{name}"},
|
||||
"CreateApi": {"method": "POST", "requestUri": "/apis"},
|
||||
"CreatePortal": {"method": "POST", "requestUri": "/portals"}}},
|
||||
"api-v2": {"credentialScope": "api", "operations": {
|
||||
"TagResource": {"method": "POST", "requestUri": "/v2/tags/{arn+}"},
|
||||
"GetStage": {"method": "GET", "requestUri": "/v2/apis/{id}/stages/{name}"}}},
|
||||
"hand": {"credentialScope": "hand", "operations": {"GetThing": {"method": "GET", "requestUri": "/things"}}}}}
|
||||
|
||||
|
||||
def test_the_route_methods_are_each_routed_operations_alternatives_included():
|
||||
assert r.route_methods(METHOD_ROUTES) == {"api": {
|
||||
"CreateApi": ["POST"], "CreatePortal": ["POST"], "GetStage": ["GET"], "TagResource": ["POST", "PUT"]}}
|
||||
|
||||
|
||||
def test_an_operation_listing_the_action_of_each_of_its_routes_methods_is_authorized_by_method():
|
||||
# TagResource is a PUT in one model and a POST in the other, and lists both beside the resource's PATCH;
|
||||
# GetStage, listed for two SDK clients, is no single action, but each client's route is a GET.
|
||||
documents = [by_method_service({"TagResource": ["api:PATCH", "api:POST", "api:PUT"],
|
||||
"GetStage": ["api:GET"],
|
||||
"CreateApi": ["api:POST", "api:UpdatePolicy", "iam:PassRole"]},
|
||||
{"GetStage": ["api", "apiv2"]})]
|
||||
methods = r.route_methods(METHOD_ROUTES)
|
||||
assert r.authorized_by_method(documents, methods, r.authorized_actions_from(documents)) == {
|
||||
"api": ["CreateApi", "GetStage", "TagResource"]}
|
||||
|
||||
|
||||
def test_an_operation_missing_the_action_of_one_of_its_routes_methods_keeps_its_own_name():
|
||||
documents = [by_method_service({"TagResource": ["api:PATCH", "api:PUT"], "GetStage": ["api:GET"]},
|
||||
{"GetStage": ["api", "apiv2"]})]
|
||||
assert r.authorized_by_method(documents, r.route_methods(METHOD_ROUTES), {}) == {"api": ["GetStage"]}
|
||||
|
||||
|
||||
def test_an_operation_with_an_action_of_its_own_name_keeps_it():
|
||||
documents = [by_method_service({"CreatePortal": ["api:CreatePortal", "api:POST"]})]
|
||||
assert r.authorized_by_method(documents, r.route_methods(METHOD_ROUTES), {}) == {}
|
||||
|
||||
|
||||
def test_an_operation_the_one_action_shape_names_is_not_also_authorized_by_method():
|
||||
documents = [by_method_service({"CreateApi": ["api:POST"]})]
|
||||
renamed = r.authorized_actions_from(documents)
|
||||
assert renamed == {"api": {"CreateApi": "api:POST"}}
|
||||
assert r.authorized_by_method(documents, r.route_methods(METHOD_ROUTES), renamed) == {}
|
||||
|
||||
|
||||
def test_an_operation_listed_twice_must_list_its_methods_both_times():
|
||||
documents = [by_method_service({"CreateApi": ["api:POST", "iam:PassRole"]})]
|
||||
documents[0]["Operations"].append({"Name": "CreateApi", "AuthorizedActions": [{"Service": "api", "Name": "PUT"}]})
|
||||
assert r.authorized_by_method(documents, r.route_methods(METHOD_ROUTES), {}) == {}
|
||||
|
||||
|
||||
def test_a_scope_authorized_by_method_the_reference_does_not_have_is_an_error():
|
||||
with pytest.raises(ValueError, match="no namespace api"):
|
||||
r.authorized_by_method([typed("other", {})], r.route_methods(METHOD_ROUTES), {})
|
||||
|
||||
|
||||
def test_the_operations_authorized_by_method_must_be_routed_sorted_and_named_once():
|
||||
documents = ANCHOR_SERVICES + [by_method_service({"TagResource": ["api:POST", "api:PUT"]}), typed("other", {})]
|
||||
methods = r.route_methods(METHOD_ROUTES)
|
||||
document = r.build(documents, "a test", ["api"], methods)
|
||||
assert document["authorizedByMethod"] == {"api": ["TagResource"]}
|
||||
assert r.validate(document, ["api"], methods) == []
|
||||
assert "authorizedByMethod lists api, a scope rest-routes.json reads no routes for" in r.validate(document, [])
|
||||
document["authorizedByMethod"]["api"] = ["TagResource", "Missing"]
|
||||
problems = r.validate(document, ["api"], methods)
|
||||
assert "authorizedByMethod.api is not sorted, or repeats an operation" in problems
|
||||
assert "authorizedByMethod lists api:Missing, which no route of api serves" in problems
|
||||
document["authorizedByMethod"]["api"] = ["TagResource"]
|
||||
document["authorizedActions"]["api"] = {"TagResource": "api:PUT"}
|
||||
document["authorizedActions"] = dict(sorted(document["authorizedActions"].items()))
|
||||
assert "api:TagResource is authorized by method and as api:PUT" in r.validate(document, ["api"], methods)
|
||||
document["authorizedByMethod"] = {"api": []}
|
||||
assert "authorizedByMethod.api is not a list of operation names" in r.validate(document, ["api"], methods)
|
||||
del document["authorizedByMethod"]
|
||||
assert "authorizedByMethod is missing" in r.validate(document, ["api"], methods)
|
||||
|
||||
|
||||
def test_verify_fails_on_an_operation_aws_no_longer_authorizes_by_method_and_reports_one_it_added():
|
||||
untrue, added = r.verify_by_method_against({"api": ["CreateApi", "TagResource"]}, {"api": ["GetStage", "TagResource"]})
|
||||
assert untrue == ["AWS no longer authorizes api:CreateApi by the methods of its routes"]
|
||||
assert added == ["api:GetStage by method"]
|
||||
assert r.verify_by_method_against({"api": ["TagResource"]}, {"api": ["TagResource"]}) == ([], [])
|
||||
|
||||
|
||||
def test_the_round_trip_lists_the_operations_authorized_by_method(tmp_path):
|
||||
reference = by_method_service({"TagResource": ["api:PATCH", "api:POST", "api:PUT"], "GetStage": ["api:GET"]},
|
||||
{"GetStage": ["api", "apiv2"]})
|
||||
sources = saved_sources(tmp_path, ANCHOR_SERVICES + [reference])
|
||||
routes = tmp_path / "rest-routes.json"
|
||||
routes.write_text(json.dumps(METHOD_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())["authorizedByMethod"] == {"api": ["GetStage", "TagResource"]}
|
||||
assert r.main(["--check", "--output", str(output), "--routes", str(routes)]) == 0
|
||||
assert r.main(["--verify", "--source-dir", str(sources), "--output", str(output), "--routes", str(routes)]) == 0
|
||||
(tmp_path / "later").mkdir()
|
||||
later = by_method_service({"TagResource": ["api:PATCH", "api:PUT"], "GetStage": ["api:GET"]},
|
||||
{"GetStage": ["api", "apiv2"]})
|
||||
given = saved_sources(tmp_path / "later", ANCHOR_SERVICES + [later])
|
||||
assert r.main(["--verify", "--source-dir", str(given), "--output", str(output), "--routes", str(routes)]) == 1
|
||||
@@ -217,6 +217,16 @@ def test_an_operation_naming_no_role_must_say_why(corrections):
|
||||
r.entry_for("svc:CreateThing", ["svc"], empty)
|
||||
|
||||
|
||||
def test_an_operation_botocore_does_not_have_yet_is_not_read_until_a_bump_brings_it(corrections):
|
||||
corrections.setattr(r, "NOT_READ", {"svc:CreateThing": r.NOT_IN_BOTOCORE})
|
||||
before = {"svc": model({"CreateOther": "In"}, {"In": structure(Name="String")})}
|
||||
assert r.entry_for("svc:CreateThing", ["svc"], before) == {"passedTo": ["svc"],
|
||||
"notRead": r.NOT_IN_BOTOCORE}
|
||||
bumped = {"svc": model({"CreateThing": "In"}, {"In": structure(RoleArn="String")})}
|
||||
with pytest.raises(ValueError, match="take it out of NOT_READ"):
|
||||
r.entry_for("svc:CreateThing", ["svc"], bumped)
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# The whole document
|
||||
# --------------------------------------------------------------------------- #
|
||||
|
||||
@@ -83,7 +83,7 @@ def test_a_route_naming_two_operations_of_a_scope_the_rules_do_not_route_alone_i
|
||||
UploadPart=("PUT", "/{Bucket}/{Key+}")),
|
||||
}, "botocore test")
|
||||
assert doc["handRouted"] == dict(sorted(r.HAND_ROUTED.items()))
|
||||
assert set(doc["handRouted"]) == {"apigateway", "s3"}
|
||||
assert set(doc["handRouted"]) == {"s3"}
|
||||
|
||||
|
||||
def test_the_hand_routed_scopes_are_rendered_with_their_reasons():
|
||||
@@ -152,3 +152,37 @@ def test_a_model_a_route_filter_moves_under_a_prefix_keeps_its_own_paths(name):
|
||||
# IAM matches a moved request on its path without the prefix its filter records, so the routes are the model's.
|
||||
doc = r.build({name: model("rest-json", "2020-01-01", GetThing=("GET", "/things/{ThingId}"))}, "test")
|
||||
assert doc["models"][name]["operations"]["GetThing"]["requestUri"] == "/things/{ThingId}"
|
||||
|
||||
|
||||
def test_a_service_tagging_with_put_keeps_the_bare_post_the_shared_controller_serves():
|
||||
# API Gateway v1 tags with PUT on /tags/{resource_arn}, and SharedTagsController's bare /tags tags with a POST
|
||||
# naming the ARN in its body whatever the service's method, so that alternative says it is a POST.
|
||||
doc = r.build({"apigateway": model("rest-json", "2015-07-09", TagResource=("PUT", "/tags/{resource_arn}"),
|
||||
UntagResource=("DELETE", "/tags/{resource_arn}"),
|
||||
GetTags=("GET", "/tags/{resource_arn}"))}, "test")
|
||||
operations = doc["models"]["apigateway"]["operations"]
|
||||
assert operations["TagResource"] == {"method": "PUT", "requestUri": "/tags/{resource_arn+}", "alternatives": [
|
||||
{"method": "POST", "requestUri": "/tags", "located": {"resourceArn": "body"}}]}
|
||||
assert operations["UntagResource"]["alternatives"] == [
|
||||
{"requestUri": "/tags", "located": {"resourceArn": "?resourceArn"}}]
|
||||
assert operations["GetTags"]["alternatives"] == [{"requestUri": "/tags", "located": {"resourceArn": "?resourceArn"}}]
|
||||
assert json.loads(r.render(doc)) == doc
|
||||
|
||||
|
||||
def test_an_alternative_is_keyed_by_its_own_method():
|
||||
# The bare POST of a PUT tags route collides with another operation's POST /tags, never with a PUT /tags.
|
||||
with pytest.raises(SystemExit, match="one route names more than one operation"):
|
||||
r.build({"apigateway": model("rest-json", "2015-07-09", TagResource=("PUT", "/tags/{resource_arn}"),
|
||||
CreateTag=("POST", "/tags"))}, "test")
|
||||
r.build({"apigateway": model("rest-json", "2015-07-09", TagResource=("PUT", "/tags/{resource_arn}"),
|
||||
PutTags=("PUT", "/tags"))}, "test")
|
||||
|
||||
|
||||
def test_an_arn_label_the_controller_lets_span_slashes_is_greedy():
|
||||
# API Gateway v2's controller serves /v2/tags/{resourceArn: .+}, so an ARN sent unencoded reaches it; its other
|
||||
# routes and labels keep the model's one segment, and it has no bare route.
|
||||
doc = r.build({"apigatewayv2": model("rest-json", "2018-11-29", TagResource=("POST", "/v2/tags/{resource-arn}"),
|
||||
GetApi=("GET", "/v2/apis/{apiId}"))}, "test")
|
||||
operations = doc["models"]["apigatewayv2"]["operations"]
|
||||
assert operations["TagResource"] == {"method": "POST", "requestUri": "/v2/tags/{resource-arn+}"}
|
||||
assert operations["GetApi"] == {"method": "GET", "requestUri": "/v2/apis/{apiId}"}
|
||||
Reference in new issue
Block a user