mirror of
https://github.com/floci-io/floci.git
synced 2026-12-01 01:12:48 -05:00
fix(iam): check iam:PassRole on the roles an API Gateway request names (#9597)
AWS's Service Reference lists iam:PassRole for twelve API Gateway
operations, each passing its roles to apigateway.amazonaws.com. Floci
checked none: API Gateway is authorized by HTTP method, the passed-roles
table left the namespace out, and no member naming a role has a name the
table's rule knows (credentials, authorizerCredentials, credentialsArn,
authorizerCredentialsArn). An update names its role as a patch
operation's value, and an import inside its OpenAPI definition.
The roles are now checked for the operation the request's route resolves
to, which the table is keyed by, from three readings. A new vendored
source, tools/aws/sources/apigateway-roles.json, written by its own
script from the API references and developer guide, gives what they
read:
- The members that take a role, by the resource type each describes:
"To specify an IAM role for API Gateway to assume, use the role's
Amazon Resource Name (ARN)". PutIntegration, CreateIntegration,
CreateAuthorizer, CreateApi and UpdateApi read them, REST APIs' and
HTTP APIs' alike.
- A REST API update's patch operation, which names the property it
changes by its path ("the path for this property is /name"): the
value of the one whose path names a role member of the resource the
update returns, so UpdateIntegration reads
patchOperations[path=/credentials].value, UpdateAuthorizer
/authorizerCredentials and UpdateAccount /cloudwatchRoleArn. The
table gains a list step selecting the elements whose field holds a
value.
- An import's OpenAPI definition, JSON or YAML: the
x-amazon-apigateway-integration credentials of each Operation object,
the ANY method's included, and the x-amazon-apigateway-authorizer
authorizerCredentials of each security scheme, OpenAPI 2's and 3's,
where the guide says each extension sits. ImportRestApi and PutRestApi
take the whole body as the definition, ImportApi and ReimportApi a
body member. The definition is read as its service takes
and reads it, through a new PassedRoleLookup hook given the whole body:
API Gateway resolves a REST API definition's ${AWS::Region},
${AWS::AccountId} and ${AWS::Partition} before importing it, so a role
written with them is checked too, and takes an HTTP API's from its
body's body (the REST route's envelope) or Body (the JSON 1.1
handler's), or else the whole body, which the REST route also takes.
A REST JSON model's member is also read by its botocore name where its
wire name differs: Floci serves HTTP APIs over JSON 1.1 too
(AmazonApiGatewayV2.*), whose bodies name members as botocore does
(CredentialsArn, Body), and its handler takes either spelling as the
same member.
apigateway joins the passed-roles namespaces with all twelve operations
read and nothing added to the hand lists.
This commit is contained in:
1 parent
d37da2fd78
commit
a5afece703
19 files changed
+1109
-61
No files matched your search
@@ -58,6 +58,9 @@ on:
|
|||||||
- 'tools/aws/sources/emr-roles.json'
|
- 'tools/aws/sources/emr-roles.json'
|
||||||
- 'tools/aws/fetch_emr_roles.py'
|
- 'tools/aws/fetch_emr_roles.py'
|
||||||
- 'tools/aws/test_fetch_emr_roles.py'
|
- 'tools/aws/test_fetch_emr_roles.py'
|
||||||
|
- 'tools/aws/sources/apigateway-roles.json'
|
||||||
|
- 'tools/aws/fetch_apigateway_roles.py'
|
||||||
|
- 'tools/aws/test_fetch_apigateway_roles.py'
|
||||||
- 'src/main/resources/aws/iam-passed-network-connectors.json'
|
- 'src/main/resources/aws/iam-passed-network-connectors.json'
|
||||||
- 'tools/aws/regen_iam_passed_network_connectors.py'
|
- 'tools/aws/regen_iam_passed_network_connectors.py'
|
||||||
- 'tools/aws/test_regen_iam_passed_network_connectors.py'
|
- 'tools/aws/test_regen_iam_passed_network_connectors.py'
|
||||||
|
|||||||
@@ -624,7 +624,8 @@ IAM_AUTHORIZED_ACTIONS_PATHS := src/main/resources/aws/iam-authorized-actions.js
|
|||||||
IAM_PASSED_ROLES_PATHS := src/main/resources/aws/iam-passed-roles.json $(IAM_PASSED_ROLES_GENERATOR) \
|
IAM_PASSED_ROLES_PATHS := src/main/resources/aws/iam-passed-roles.json $(IAM_PASSED_ROLES_GENERATOR) \
|
||||||
tools/aws/test_regen_iam_passed_roles.py tools/aws/sources/eks-roles.json tools/aws/fetch_eks_roles.py \
|
tools/aws/test_regen_iam_passed_roles.py tools/aws/sources/eks-roles.json tools/aws/fetch_eks_roles.py \
|
||||||
tools/aws/test_fetch_eks_roles.py tools/aws/sources/emr-roles.json tools/aws/fetch_emr_roles.py \
|
tools/aws/test_fetch_eks_roles.py tools/aws/sources/emr-roles.json tools/aws/fetch_emr_roles.py \
|
||||||
tools/aws/test_fetch_emr_roles.py
|
tools/aws/test_fetch_emr_roles.py tools/aws/sources/apigateway-roles.json tools/aws/fetch_apigateway_roles.py \
|
||||||
|
tools/aws/test_fetch_apigateway_roles.py
|
||||||
IAM_PASSED_NETWORK_CONNECTORS_PATHS := src/main/resources/aws/iam-passed-network-connectors.json \
|
IAM_PASSED_NETWORK_CONNECTORS_PATHS := src/main/resources/aws/iam-passed-network-connectors.json \
|
||||||
tools/aws/regen_iam_passed_network_connectors.py $(IAM_PASSED_ROLES_GENERATOR) \
|
tools/aws/regen_iam_passed_network_connectors.py $(IAM_PASSED_ROLES_GENERATOR) \
|
||||||
tools/aws/test_regen_iam_passed_network_connectors.py
|
tools/aws/test_regen_iam_passed_network_connectors.py
|
||||||
|
|||||||
+19
-1
@@ -3103,6 +3103,24 @@ role each passes:
|
|||||||
the CLI reference's examples give the roles by name (`--service-role EMR_DefaultRole`). The steps'
|
the CLI reference's examples give the roles by name (`--service-role EMR_DefaultRole`). The steps'
|
||||||
runtime role, `StepExecutionRoleArn`, is not passed: "You can control access to the runtime role
|
runtime role, `StepExecutionRoleArn`, is not passed: "You can control access to the runtime role
|
||||||
with the condition key elasticmapreduce:ExecutionRoleArn."
|
with the condition key elasticmapreduce:ExecutionRoleArn."
|
||||||
|
- **API Gateway:** authorized by HTTP method, its roles are checked for the operation its route
|
||||||
|
resolves to, each passed to `apigateway.amazonaws.com`, all read from the table below: an
|
||||||
|
integration's `credentials` and an authorizer's `authorizerCredentials`, REST APIs' and HTTP APIs'
|
||||||
|
(`credentialsArn`, `authorizerCredentialsArn`) alike, and over the JSON 1.1 endpoint Floci also
|
||||||
|
serves HTTP APIs at by botocore's names (`CredentialsArn`, `Body`); the value of a REST API update's patch
|
||||||
|
operation whose path names one of those, or the account's `/cloudwatchRoleArn`; and, in an import's
|
||||||
|
OpenAPI definition, JSON or YAML, each Operation object's (the ANY method's included)
|
||||||
|
`x-amazon-apigateway-integration` `credentials` and each security scheme's
|
||||||
|
`x-amazon-apigateway-authorizer` `authorizerCredentials`, the definition read as API Gateway takes
|
||||||
|
and reads it: a REST API's whole body, its `${AWS::Region}`, `${AWS::AccountId}` and
|
||||||
|
`${AWS::Partition}` resolved, and an HTTP API's from its body's `body` or `Body`, or else the whole
|
||||||
|
body, as the REST route also takes one. No
|
||||||
|
member's name says it takes a role, so a vendored source, `tools/aws/sources/apigateway-roles.json`,
|
||||||
|
written by `tools/aws/fetch_apigateway_roles.py` from the API references and developer guide,
|
||||||
|
gives each: "To specify an IAM role for API Gateway to assume, use the role's Amazon Resource Name
|
||||||
|
(ARN)"; "the path for this property is /name"; "only OpenAPI definition JSON/YAML files are
|
||||||
|
supported"; and each extension, what it extends and its property "in the form of an ARN of an IAM
|
||||||
|
execution role".
|
||||||
- **CloudFormation:** `CreateStack`, `UpdateStack`, `DeleteStack`, `CreateChangeSet` and
|
- **CloudFormation:** `CreateStack`, `UpdateStack`, `DeleteStack`, `CreateChangeSet` and
|
||||||
`ContinueUpdateRollback` pass `RoleARN` to `cloudformation.amazonaws.com` when the request names
|
`ContinueUpdateRollback` pass `RoleARN` to `cloudformation.amazonaws.com` when the request names
|
||||||
one. `CreateStackSet` and `UpdateStackSet` pass `AdministrationRoleARN`, or, for a self-managed
|
one. `CreateStackSet` and `UpdateStackSet` pass `AdministrationRoleARN`, or, for a self-managed
|
||||||
@@ -3221,7 +3239,7 @@ when the caller may not pass the role.
|
|||||||
Kinesis Analytics `ImportSnapshot`, Secrets Manager `AssociateCrossAccountReplica`), whose role
|
Kinesis Analytics `ImportSnapshot`, Secrets Manager `AssociateCrossAccountReplica`), whose role
|
||||||
the generator reads as soon as a release that has it is pinned. EC2's `RequestSpotFleet` names
|
the generator reads as soon as a release that has it is pinned. EC2's `RequestSpotFleet` names
|
||||||
its roles in EC2's own protocol, one of them as an instance profile. The REST services whose
|
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.
|
routes no rule maps yet are not read either.
|
||||||
|
|
||||||
A request that names a Lambda network connector also needs `lambda:PassNetworkConnector` on it. The
|
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
|
Lambda developer guide has "The caller must have `lambda:PassNetworkConnector` on the referenced
|
||||||
|
|||||||
@@ -90,6 +90,17 @@ public class PassedRoleLookups {
|
|||||||
: iamService.findRole(accountId, roleName).map(IamRole::getArn);
|
: iamService.findRole(accountId, roleName).map(IamRole::getArn);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public List<String> openApiDefinitions(String operation, String body) {
|
||||||
|
for (PassedRoleLookup lookup : services) {
|
||||||
|
List<String> definitions = lookup.openApiDefinitions(operation, body, region);
|
||||||
|
if (!definitions.isEmpty()) {
|
||||||
|
return definitions;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return List.of();
|
||||||
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public Optional<String> serviceCatalogConstraintType(String constraintId) {
|
public Optional<String> serviceCatalogConstraintType(String constraintId) {
|
||||||
return firstFound(lookup -> lookup.serviceCatalogConstraintType(constraintId));
|
return firstFound(lookup -> lookup.serviceCatalogConstraintType(constraintId));
|
||||||
|
|||||||
@@ -34,16 +34,20 @@ final class PassedRoleMembers {
|
|||||||
|
|
||||||
private static final ObjectMapper MAPPER = new ObjectMapper();
|
private static final ObjectMapper MAPPER = new ObjectMapper();
|
||||||
|
|
||||||
/** One step of a member path: a member, then each element of a list, each value of a map, or one key's value. */
|
/**
|
||||||
|
* One step of a member path: a member, then each element of a list, each element of a list whose field holds a
|
||||||
|
* value ({@code [path=/credentials]}), each value of a map, or one key's value.
|
||||||
|
*/
|
||||||
private static final Pattern STEP = Pattern.compile(
|
private static final Pattern STEP = Pattern.compile(
|
||||||
"([A-Za-z][A-Za-z0-9_]*)(?:\\[([A-Za-z0-9_]*)]|\\{([A-Za-z0-9_]*)})?");
|
"([A-Za-z][A-Za-z0-9_]*)(?:\\[([A-Za-z0-9_]*)]|\\[([A-Za-z0-9_]+=/[A-Za-z0-9_]+)]|\\{([A-Za-z0-9_]*)})?");
|
||||||
|
|
||||||
/** How a member path goes on from a member. */
|
/** How a member path goes on from a member. */
|
||||||
enum Into { NONE, LIST, MAP, KEY }
|
enum Into { NONE, LIST, MATCH, MAP, KEY }
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* A step of a member path: the member {@code name}, then for {@link Into#LIST} each element, named
|
* A step of a member path: the member {@code name}, then for {@link Into#LIST} each element, named
|
||||||
* {@code key} in the Query protocol when its shape names it, for {@link Into#MAP} each value, and for
|
* {@code key} in the Query protocol when its shape names it, for {@link Into#MATCH} each element whose field
|
||||||
|
* holds the value {@code key} gives as {@code field=value}, for {@link Into#MAP} each value, and for
|
||||||
* {@link Into#KEY} the value under {@code key}.
|
* {@link Into#KEY} the value under {@code key}.
|
||||||
*/
|
*/
|
||||||
record Step(String name, Into into, String key) {
|
record Step(String name, Into into, String key) {
|
||||||
@@ -53,10 +57,19 @@ final class PassedRoleMembers {
|
|||||||
* A member of a request that names a role, the service it is passed to (null when the Service Reference
|
* A member of a request that names a role, the service it is passed to (null when the Service Reference
|
||||||
* names none) and whether the member takes the role by name as well as by ARN. {@code queryKeys} matches
|
* names none) and whether the member takes the role by name as well as by ARN. {@code queryKeys} matches
|
||||||
* the form parameters the Query protocol sends the member as; null for a member it cannot carry. A member
|
* the form parameters the Query protocol sends the member as; null for a member it cannot carry. A member
|
||||||
* that names an instance profile ({@code instanceProfile}), by its name or its ARN, passes the profile's roles.
|
* that names an instance profile ({@code instanceProfile}), by its name or its ARN, passes the profile's roles. A
|
||||||
|
* member holding an OpenAPI definition ({@code openApi}) passes the roles its API Gateway extensions name, and is
|
||||||
|
* the request's whole body when it is its payload ({@code payload}).
|
||||||
*/
|
*/
|
||||||
record Member(String path, List<Step> steps, Pattern queryKeys, String passedTo, boolean byName,
|
record Member(String path, List<Step> steps, Pattern queryKeys, String passedTo, boolean byName,
|
||||||
boolean instanceProfile) {
|
boolean instanceProfile, OpenApi openApi, boolean payload) {
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Where an OpenAPI definition names roles: each extension of an Operation object, each of a security scheme, with
|
||||||
|
* the property of it naming the role, and the extension standing for the ANY method's Operation object.
|
||||||
|
*/
|
||||||
|
record OpenApi(Map<String, String> operation, Map<String, String> securityScheme, String anyMethod) {
|
||||||
}
|
}
|
||||||
|
|
||||||
/** The file: the members of each operation read from it, and the operations read by hand. */
|
/** The file: the members of each operation read from it, and the operations read by hand. */
|
||||||
@@ -120,8 +133,20 @@ final class PassedRoleMembers {
|
|||||||
+ ", which is no member path");
|
+ ", which is no member path");
|
||||||
}
|
}
|
||||||
String passedTo = role.hasNonNull("passedTo") ? role.get("passedTo").asText() : null;
|
String passedTo = role.hasNonNull("passedTo") ? role.get("passedTo").asText() : null;
|
||||||
return new Member(path, steps, queryKeys(steps), passedTo, role.path("byName").asBoolean(false),
|
JsonNode openApi = role.path("openApi");
|
||||||
role.path("instanceProfile").asBoolean(false));
|
// A form carries no OpenAPI definition.
|
||||||
|
return new Member(path, steps, openApi.isObject() ? null : queryKeys(steps), passedTo,
|
||||||
|
role.path("byName").asBoolean(false),
|
||||||
|
role.path("instanceProfile").asBoolean(false), openApi.isObject() ? new OpenApi(
|
||||||
|
textMap(openApi.path("operation")), textMap(openApi.path("securityScheme")),
|
||||||
|
openApi.path("anyMethod").asText(null)) : null,
|
||||||
|
role.path("payload").asBoolean(false));
|
||||||
|
}
|
||||||
|
|
||||||
|
private static Map<String, String> textMap(JsonNode node) {
|
||||||
|
Map<String, String> map = new LinkedHashMap<>();
|
||||||
|
node.properties().forEach(entry -> map.put(entry.getKey(), entry.getValue().asText()));
|
||||||
|
return Map.copyOf(map);
|
||||||
}
|
}
|
||||||
|
|
||||||
/** The steps of a vendored member path; null when {@code path} is none. */
|
/** The steps of a vendored member path; null when {@code path} is none. */
|
||||||
@@ -132,9 +157,14 @@ final class PassedRoleMembers {
|
|||||||
if (!matcher.matches()) {
|
if (!matcher.matches()) {
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
Into into = matcher.group(2) != null ? Into.LIST : matcher.group(3) == null ? Into.NONE
|
Into into = matcher.group(2) != null ? Into.LIST : matcher.group(3) != null ? Into.MATCH
|
||||||
: matcher.group(3).isEmpty() ? Into.MAP : Into.KEY;
|
: matcher.group(4) == null ? Into.NONE : matcher.group(4).isEmpty() ? Into.MAP : Into.KEY;
|
||||||
String key = into == Into.LIST ? matcher.group(2) : into == Into.KEY ? matcher.group(3) : null;
|
String key = switch (into) {
|
||||||
|
case LIST -> matcher.group(2);
|
||||||
|
case MATCH -> matcher.group(3);
|
||||||
|
case KEY -> matcher.group(4);
|
||||||
|
case NONE, MAP -> null;
|
||||||
|
};
|
||||||
steps.add(new Step(matcher.group(1), into, key));
|
steps.add(new Step(matcher.group(1), into, key));
|
||||||
}
|
}
|
||||||
return List.copyOf(steps);
|
return List.copyOf(steps);
|
||||||
@@ -149,7 +179,7 @@ final class PassedRoleMembers {
|
|||||||
private static Pattern queryKeys(List<Step> steps) {
|
private static Pattern queryKeys(List<Step> steps) {
|
||||||
StringBuilder regex = new StringBuilder();
|
StringBuilder regex = new StringBuilder();
|
||||||
for (Step step : steps) {
|
for (Step step : steps) {
|
||||||
if (step.into() == Into.KEY) {
|
if (step.into() == Into.KEY || step.into() == Into.MATCH) {
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
if (!regex.isEmpty()) {
|
if (!regex.isEmpty()) {
|
||||||
|
|||||||
@@ -4,6 +4,7 @@ import com.fasterxml.jackson.core.JsonProcessingException;
|
|||||||
import com.fasterxml.jackson.databind.JsonNode;
|
import com.fasterxml.jackson.databind.JsonNode;
|
||||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||||
import com.fasterxml.jackson.dataformat.cbor.CBORFactory;
|
import com.fasterxml.jackson.dataformat.cbor.CBORFactory;
|
||||||
|
import com.fasterxml.jackson.dataformat.yaml.YAMLFactory;
|
||||||
import jakarta.ws.rs.container.ContainerRequestContext;
|
import jakarta.ws.rs.container.ContainerRequestContext;
|
||||||
import jakarta.ws.rs.core.HttpHeaders;
|
import jakarta.ws.rs.core.HttpHeaders;
|
||||||
import jakarta.ws.rs.core.MediaType;
|
import jakarta.ws.rs.core.MediaType;
|
||||||
@@ -81,6 +82,11 @@ import java.util.regex.Pattern;
|
|||||||
* them: {@code elasticmapreduce.amazonaws.com}, {@code application-autoscaling.amazonaws.com} and
|
* them: {@code elasticmapreduce.amazonaws.com}, {@code application-autoscaling.amazonaws.com} and
|
||||||
* {@code ec2.amazonaws.com}.
|
* {@code ec2.amazonaws.com}.
|
||||||
*
|
*
|
||||||
|
* <p>API Gateway's roles are read from the table for the operation its route resolves to: credentials members, the
|
||||||
|
* value of a REST API update's patch operation whose path names one ({@code [path=/credentials]}), and the API Gateway
|
||||||
|
* extensions of an import's OpenAPI definition, JSON or YAML, read as its service reads it
|
||||||
|
* ({@link Lookups#openApiDefinitions}).
|
||||||
|
*
|
||||||
* <p>A CloudFormation stack's service role is checked where a request names it, and not on later
|
* <p>A CloudFormation stack's service role is checked where a request names it, and not on later
|
||||||
* operations that reuse it: CloudFormation "uses this role even if the users don't have permission
|
* operations that reuse it: CloudFormation "uses this role even if the users don't have permission
|
||||||
* to pass it". A self-managed StackSet that names no administration role passes the default one:
|
* to pass it". A self-managed StackSet that names no administration role passes the default one:
|
||||||
@@ -126,6 +132,9 @@ final class PassedRoles {
|
|||||||
private static final ObjectMapper MAPPER = new ObjectMapper();
|
private static final ObjectMapper MAPPER = new ObjectMapper();
|
||||||
/** Reads the CBOR bodies the RPC v2 path carries, which name the role in the same member JSON does. */
|
/** Reads the CBOR bodies the RPC v2 path carries, which name the role in the same member JSON does. */
|
||||||
private static final ObjectMapper CBOR_MAPPER = new ObjectMapper(new CBORFactory());
|
private static final ObjectMapper CBOR_MAPPER = new ObjectMapper(new CBORFactory());
|
||||||
|
/** The fields of an OpenAPI Path Item that hold its Operation objects, one for each HTTP method. */
|
||||||
|
private static final Set<String> OPENAPI_OPERATIONS =
|
||||||
|
Set.of("get", "put", "post", "delete", "options", "head", "patch", "trace");
|
||||||
|
|
||||||
/** An IAM role ARN, the only resource {@code iam:PassRole} acts on. */
|
/** An IAM role ARN, the only resource {@code iam:PassRole} acts on. */
|
||||||
private static final Pattern ROLE_ARN = Pattern.compile("^arn:[a-z0-9-]+:iam::\\d{12}:role/.+");
|
private static final Pattern ROLE_ARN = Pattern.compile("^arn:[a-z0-9-]+:iam::\\d{12}:role/.+");
|
||||||
@@ -252,6 +261,17 @@ final class PassedRoles {
|
|||||||
|
|
||||||
/** The type of the Service Catalog constraint {@code constraintId}; empty when there is none. */
|
/** The type of the Service Catalog constraint {@code constraintId}; empty when there is none. */
|
||||||
Optional<String> serviceCatalogConstraintType(String constraintId);
|
Optional<String> serviceCatalogConstraintType(String constraintId);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The OpenAPI definitions a request for {@code operation} can import from its {@code body}, as its service takes
|
||||||
|
* them and reads them before it reads the roles they name: API Gateway resolves a REST API definition's
|
||||||
|
* {@code ${AWS::Region}}, {@code ${AWS::AccountId}} and {@code ${AWS::Partition}}, and takes an HTTP API's from
|
||||||
|
* its body's {@code body} or {@code Body}, or else from the whole body. Empty for an operation whose service
|
||||||
|
* says nothing, whose definition is then read where the table locates it.
|
||||||
|
*/
|
||||||
|
default List<String> openApiDefinitions(String operation, String body) {
|
||||||
|
return List.of();
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private PassedRoles() {
|
private PassedRoles() {
|
||||||
@@ -263,7 +283,7 @@ final class PassedRoles {
|
|||||||
*/
|
*/
|
||||||
static List<PassedRole> of(String operation, ContainerRequestContext ctx, Lookups lookups) {
|
static List<PassedRole> of(String operation, ContainerRequestContext ctx, Lookups lookups) {
|
||||||
List<PassedRole> byHand = byHand(operation, ctx, lookups);
|
List<PassedRole> byHand = byHand(operation, ctx, lookups);
|
||||||
return byHand != null ? byHand : fromTable(PassedRoleMembers.of(operation), ctx, lookups);
|
return byHand != null ? byHand : fromTable(operation, PassedRoleMembers.of(operation), ctx, lookups);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -374,8 +394,8 @@ final class PassedRoles {
|
|||||||
* when it comes in the Query protocol, from its JSON or CBOR body, and from its XML body when it comes in the
|
* when it comes in the Query protocol, from its JSON or CBOR body, and from its XML body when it comes in the
|
||||||
* REST-XML protocol (S3's {@code PutBucketReplication}, its {@code ReplicationConfiguration}'s {@code Role}).
|
* REST-XML protocol (S3's {@code PutBucketReplication}, its {@code ReplicationConfiguration}'s {@code Role}).
|
||||||
*/
|
*/
|
||||||
private static List<PassedRole> fromTable(List<PassedRoleMembers.Member> members, ContainerRequestContext ctx,
|
private static List<PassedRole> fromTable(String operation, List<PassedRoleMembers.Member> members,
|
||||||
Lookups lookups) {
|
ContainerRequestContext ctx, Lookups lookups) {
|
||||||
if (members == null) {
|
if (members == null) {
|
||||||
return List.of();
|
return List.of();
|
||||||
}
|
}
|
||||||
@@ -383,10 +403,14 @@ final class PassedRoles {
|
|||||||
Function<String, List<String>> profiles = profile -> instanceProfileRoles(lookups, profile);
|
Function<String, List<String>> profiles = profile -> instanceProfileRoles(lookups, profile);
|
||||||
Map<String, String> form = IamConditionContextResolver.formParameters(ctx);
|
Map<String, String> form = IamConditionContextResolver.formParameters(ctx);
|
||||||
JsonNode body = form.isEmpty() ? jsonBody(ctx) : null;
|
JsonNode body = form.isEmpty() ? jsonBody(ctx) : null;
|
||||||
if (form.isEmpty() && body == null) {
|
// An OpenAPI definition is read from the body's text, JSON or YAML, as the service importing it takes it.
|
||||||
|
String raw = form.isEmpty() && members.stream().anyMatch(member -> member.openApi() != null)
|
||||||
|
? IamConditionContextResolver.bodyText(ctx) : null;
|
||||||
|
if (form.isEmpty() && body == null && raw == null) {
|
||||||
return fromXml(members, IamConditionContextResolver.bodyText(ctx), named, profiles);
|
return fromXml(members, IamConditionContextResolver.bodyText(ctx), named, profiles);
|
||||||
}
|
}
|
||||||
return fromTable(members, form, body, named, profiles);
|
return fromTable(members, form, body, raw, raw == null ? List.of() : lookups.openApiDefinitions(operation, raw),
|
||||||
|
named, profiles);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -421,7 +445,8 @@ final class PassedRoles {
|
|||||||
private static Optional<String> xmlPath(List<PassedRoleMembers.Step> steps) {
|
private static Optional<String> xmlPath(List<PassedRoleMembers.Step> steps) {
|
||||||
List<String> elements = new ArrayList<>();
|
List<String> elements = new ArrayList<>();
|
||||||
for (PassedRoleMembers.Step step : steps) {
|
for (PassedRoleMembers.Step step : steps) {
|
||||||
if (step.into() == PassedRoleMembers.Into.MAP || step.into() == PassedRoleMembers.Into.KEY) {
|
if (step.into() == PassedRoleMembers.Into.MAP || step.into() == PassedRoleMembers.Into.KEY
|
||||||
|
|| step.into() == PassedRoleMembers.Into.MATCH) {
|
||||||
return Optional.empty();
|
return Optional.empty();
|
||||||
}
|
}
|
||||||
elements.add(step.name());
|
elements.add(step.name());
|
||||||
@@ -449,16 +474,40 @@ final class PassedRoles {
|
|||||||
throw new IllegalArgumentException(operation + " passes roles read by hand, from a request of its own");
|
throw new IllegalArgumentException(operation + " passes roles read by hand, from a request of its own");
|
||||||
}
|
}
|
||||||
List<PassedRoleMembers.Member> members = PassedRoleMembers.of(operation);
|
List<PassedRoleMembers.Member> members = PassedRoleMembers.of(operation);
|
||||||
return members == null ? List.of() : fromTable(members, Map.of(), body,
|
String raw = body == null ? null : body.toString();
|
||||||
|
return members == null ? List.of() : fromTable(members, Map.of(), body, raw,
|
||||||
|
raw == null ? List.of() : lookups.openApiDefinitions(operation, raw),
|
||||||
name -> lookups.heldRoleArn(name).orElseGet(() -> lookups.roleArn(name)),
|
name -> lookups.heldRoleArn(name).orElseGet(() -> lookups.roleArn(name)),
|
||||||
profile -> instanceProfileRoles(lookups, profile));
|
profile -> instanceProfileRoles(lookups, profile));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The roles the members the table gives name in a form, a JSON body or, for a member holding an OpenAPI
|
||||||
|
* definition, each definition its service says the request's body carries ({@code served}), read once for all
|
||||||
|
* such members, or else the definition the member holds, the whole body ({@code raw}) where it is the payload.
|
||||||
|
*/
|
||||||
private static List<PassedRole> fromTable(List<PassedRoleMembers.Member> members, Map<String, String> form,
|
private static List<PassedRole> fromTable(List<PassedRoleMembers.Member> members, Map<String, String> form,
|
||||||
JsonNode body, UnaryOperator<String> named,
|
JsonNode body, String raw, List<String> served,
|
||||||
Function<String, List<String>> profiles) {
|
UnaryOperator<String> named, Function<String, List<String>> profiles) {
|
||||||
List<PassedRole> passed = new ArrayList<>();
|
List<PassedRole> passed = new ArrayList<>();
|
||||||
|
boolean servedRead = false;
|
||||||
for (PassedRoleMembers.Member member : members) {
|
for (PassedRoleMembers.Member member : members) {
|
||||||
|
if (member.openApi() != null) {
|
||||||
|
List<String> texts = new ArrayList<>();
|
||||||
|
if (!served.isEmpty()) {
|
||||||
|
if (servedRead) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
servedRead = true;
|
||||||
|
texts.addAll(served);
|
||||||
|
} else if (member.payload()) {
|
||||||
|
texts.add(raw);
|
||||||
|
} else {
|
||||||
|
collect(form.isEmpty() ? body : null, member.steps(), 0, texts);
|
||||||
|
}
|
||||||
|
passed.addAll(openApiRoles(member, texts.stream().map(PassedRoles::openApiDocument).toList()));
|
||||||
|
continue;
|
||||||
|
}
|
||||||
List<String> roles = new ArrayList<>();
|
List<String> roles = new ArrayList<>();
|
||||||
if (!form.isEmpty()) {
|
if (!form.isEmpty()) {
|
||||||
if (member.queryKeys() != null) {
|
if (member.queryKeys() != null) {
|
||||||
@@ -508,6 +557,18 @@ final class PassedRoles {
|
|||||||
switch (step.into()) {
|
switch (step.into()) {
|
||||||
case NONE -> collect(value, steps, index + 1, found);
|
case NONE -> collect(value, steps, index + 1, found);
|
||||||
case KEY -> collect(value == null ? null : value.get(step.key()), steps, index + 1, found);
|
case KEY -> collect(value == null ? null : value.get(step.key()), steps, index + 1, found);
|
||||||
|
case MATCH -> {
|
||||||
|
if (value != null && value.isArray()) {
|
||||||
|
int equals = step.key().indexOf('=');
|
||||||
|
String field = step.key().substring(0, equals);
|
||||||
|
String held = step.key().substring(equals + 1);
|
||||||
|
for (JsonNode element : value) {
|
||||||
|
if (held.equals(element.path(field).asText(null))) {
|
||||||
|
collect(element, steps, index + 1, found);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
case LIST, MAP -> {
|
case LIST, MAP -> {
|
||||||
if (value != null && (step.into() == PassedRoleMembers.Into.LIST ? value.isArray() : value.isObject())) {
|
if (value != null && (step.into() == PassedRoleMembers.Into.LIST ? value.isArray() : value.isObject())) {
|
||||||
for (JsonNode element : value) {
|
for (JsonNode element : value) {
|
||||||
@@ -518,6 +579,64 @@ final class PassedRoles {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* An OpenAPI definition, JSON or YAML, as API Gateway takes one ("Currently, only OpenAPI definition JSON/YAML
|
||||||
|
* files are supported"); null for one that does not parse, which the import refuses.
|
||||||
|
*/
|
||||||
|
private static JsonNode openApiDocument(String text) {
|
||||||
|
if (text == null || text.isBlank()) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
return MAPPER.readTree(text);
|
||||||
|
} catch (IOException expected) {
|
||||||
|
// Not JSON, which YAML would also take but for JSON indented with tabs: read as YAML.
|
||||||
|
try {
|
||||||
|
return YamlHolder.MAPPER.readTree(text);
|
||||||
|
} catch (IOException e) {
|
||||||
|
LOG.debugv(e, "OpenAPI definition does not parse, so it passes no role");
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The YAML reader, made when a definition first needs it rather than when the class is. */
|
||||||
|
private static final class YamlHolder {
|
||||||
|
static final ObjectMapper MAPPER = new ObjectMapper(new YAMLFactory());
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The roles the API Gateway extensions of each OpenAPI definition name, where API Gateway reads them: an
|
||||||
|
* extension of each Operation object, a Path Item's operations and the ANY method's, and an extension of each
|
||||||
|
* security scheme, OpenAPI 2's security definitions and OpenAPI 3's {@code components.securitySchemes}.
|
||||||
|
*/
|
||||||
|
private static List<PassedRole> openApiRoles(PassedRoleMembers.Member member, List<JsonNode> documents) {
|
||||||
|
PassedRoleMembers.OpenApi openApi = member.openApi();
|
||||||
|
List<String> roles = new ArrayList<>();
|
||||||
|
for (JsonNode document : documents) {
|
||||||
|
if (document == null || !document.isObject()) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
for (JsonNode pathItem : document.path("paths")) {
|
||||||
|
pathItem.properties().forEach(operation -> {
|
||||||
|
if (OPENAPI_OPERATIONS.contains(operation.getKey())
|
||||||
|
|| operation.getKey().equals(openApi.anyMethod())) {
|
||||||
|
openApi.operation().forEach((extension, property) ->
|
||||||
|
addScalar(operation.getValue().path(extension).path(property), roles));
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
for (JsonNode schemes : List.of(document.path("securityDefinitions"),
|
||||||
|
document.path("components").path("securitySchemes"))) {
|
||||||
|
for (JsonNode scheme : schemes) {
|
||||||
|
openApi.securityScheme().forEach((extension, property) ->
|
||||||
|
addScalar(scheme.path(extension).path(property), roles));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return passed(roles, member.passedTo() == null ? null : ServicePrincipals.of(member.passedTo()));
|
||||||
|
}
|
||||||
|
|
||||||
/** Roles given by ARN or by name, a name being the role {@code named} gives for it. */
|
/** Roles given by ARN or by name, a name being the role {@code named} gives for it. */
|
||||||
private static List<String> heldOrNamedRoles(List<String> roles, UnaryOperator<String> named) {
|
private static List<String> heldOrNamedRoles(List<String> roles, UnaryOperator<String> named) {
|
||||||
List<String> arns = new ArrayList<>();
|
List<String> arns = new ArrayList<>();
|
||||||
|
|||||||
@@ -1509,15 +1509,7 @@ public class ApiGatewayController {
|
|||||||
if (payload == null || payload.isBlank()) {
|
if (payload == null || payload.isBlank()) {
|
||||||
throw new AwsException("BadRequestException", "Body is required for OpenAPI import", 400);
|
throw new AwsException("BadRequestException", "Body is required for OpenAPI import", 400);
|
||||||
}
|
}
|
||||||
try {
|
return ApiGatewayV2OpenApiImporter.restDefinition(objectMapper, payload);
|
||||||
JsonNode root = objectMapper.readTree(payload);
|
|
||||||
if (root.isObject() && root.hasNonNull("body") && root.get("body").isTextual()) {
|
|
||||||
return root.get("body").asText();
|
|
||||||
}
|
|
||||||
} catch (IOException e) {
|
|
||||||
// Not JSON at all — a raw YAML/JSON OpenAPI document.
|
|
||||||
}
|
|
||||||
return payload;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@POST
|
@POST
|
||||||
|
|||||||
@@ -55,6 +55,7 @@ import io.floci.aws.services.apigateway.model.UsagePlan;
|
|||||||
import io.floci.aws.services.apigateway.model.UsagePlanKey;
|
import io.floci.aws.services.apigateway.model.UsagePlanKey;
|
||||||
import io.floci.aws.services.apigateway.model.VpcLink;
|
import io.floci.aws.services.apigateway.model.VpcLink;
|
||||||
import io.floci.aws.services.apigatewayv2.ApiGatewayV2Service;
|
import io.floci.aws.services.apigatewayv2.ApiGatewayV2Service;
|
||||||
|
import io.floci.aws.services.iam.PassedRoleLookup;
|
||||||
import io.swagger.parser.OpenAPIParser;
|
import io.swagger.parser.OpenAPIParser;
|
||||||
import io.swagger.v3.core.util.Json;
|
import io.swagger.v3.core.util.Json;
|
||||||
import io.swagger.v3.oas.models.OpenAPI;
|
import io.swagger.v3.oas.models.OpenAPI;
|
||||||
@@ -99,7 +100,7 @@ import java.util.function.Predicate;
|
|||||||
import java.util.regex.Pattern;
|
import java.util.regex.Pattern;
|
||||||
|
|
||||||
@ApplicationScoped
|
@ApplicationScoped
|
||||||
public class ApiGatewayService implements ResourceProvider, Resettable {
|
public class ApiGatewayService implements ResourceProvider, Resettable, PassedRoleLookup {
|
||||||
|
|
||||||
/** The only partition where API Gateway offers edge-optimized APIs and custom domain names. */
|
/** The only partition where API Gateway offers edge-optimized APIs and custom domain names. */
|
||||||
private static final Set<String> EDGE_OPTIMIZED_PARTITIONS = Set.of("aws");
|
private static final Set<String> EDGE_OPTIMIZED_PARTITIONS = Set.of("aws");
|
||||||
@@ -4321,6 +4322,17 @@ public class ApiGatewayService implements ResourceProvider, Resettable {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The definition an import or an overwrite reads, its whole body, its AWS variables resolved as
|
||||||
|
* {@link #importRestApi} and {@link #putRestApi} resolve them, so the roles IAM checks are the ones the
|
||||||
|
* integrations take.
|
||||||
|
*/
|
||||||
|
@Override
|
||||||
|
public List<String> openApiDefinitions(String operation, String body, String region) {
|
||||||
|
return ("apigateway:ImportRestApi".equals(operation) || "apigateway:PutRestApi".equals(operation))
|
||||||
|
&& body != null ? List.of(resolveOpenApiAwsVariables(region, body)) : List.of();
|
||||||
|
}
|
||||||
|
|
||||||
private String resolveOpenApiAwsVariables(String region, String value) {
|
private String resolveOpenApiAwsVariables(String region, String value) {
|
||||||
if (value == null) {
|
if (value == null) {
|
||||||
return null;
|
return null;
|
||||||
|
|||||||
@@ -1,12 +1,14 @@
|
|||||||
package io.floci.aws.services.apigatewayv2;
|
package io.floci.aws.services.apigatewayv2;
|
||||||
|
|
||||||
import com.fasterxml.jackson.core.JsonProcessingException;
|
import com.fasterxml.jackson.core.JsonProcessingException;
|
||||||
|
import com.fasterxml.jackson.databind.JsonNode;
|
||||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||||
import io.floci.aws.core.common.AwsException;
|
import io.floci.aws.core.common.AwsException;
|
||||||
import io.floci.aws.services.apigatewayv2.model.Api;
|
import io.floci.aws.services.apigatewayv2.model.Api;
|
||||||
import io.floci.aws.services.apigatewayv2.model.Authorizer;
|
import io.floci.aws.services.apigatewayv2.model.Authorizer;
|
||||||
import io.floci.aws.services.apigatewayv2.model.Integration;
|
import io.floci.aws.services.apigatewayv2.model.Integration;
|
||||||
import io.floci.aws.services.apigatewayv2.model.Route;
|
import io.floci.aws.services.apigatewayv2.model.Route;
|
||||||
|
import io.floci.aws.services.iam.PassedRoleLookup;
|
||||||
import io.swagger.parser.OpenAPIParser;
|
import io.swagger.parser.OpenAPIParser;
|
||||||
import io.swagger.v3.oas.models.OpenAPI;
|
import io.swagger.v3.oas.models.OpenAPI;
|
||||||
import io.swagger.v3.oas.models.Operation;
|
import io.swagger.v3.oas.models.Operation;
|
||||||
@@ -20,6 +22,7 @@ import jakarta.enterprise.context.ApplicationScoped;
|
|||||||
import jakarta.inject.Inject;
|
import jakarta.inject.Inject;
|
||||||
import org.jboss.logging.Logger;
|
import org.jboss.logging.Logger;
|
||||||
|
|
||||||
|
import java.io.IOException;
|
||||||
import java.util.ArrayList;
|
import java.util.ArrayList;
|
||||||
import java.util.Collection;
|
import java.util.Collection;
|
||||||
import java.util.HashMap;
|
import java.util.HashMap;
|
||||||
@@ -42,7 +45,7 @@ import java.util.stream.Collectors;
|
|||||||
* {@code x-amazon-apigateway-any-method} and {@code x-amazon-apigateway-cors}.
|
* {@code x-amazon-apigateway-any-method} and {@code x-amazon-apigateway-cors}.
|
||||||
*/
|
*/
|
||||||
@ApplicationScoped
|
@ApplicationScoped
|
||||||
public class ApiGatewayV2OpenApiImporter {
|
public class ApiGatewayV2OpenApiImporter implements PassedRoleLookup {
|
||||||
|
|
||||||
private static final Logger LOG = Logger.getLogger(ApiGatewayV2OpenApiImporter.class);
|
private static final Logger LOG = Logger.getLogger(ApiGatewayV2OpenApiImporter.class);
|
||||||
private static final ObjectMapper MAP_VALUE_WRITER = new ObjectMapper();
|
private static final ObjectMapper MAP_VALUE_WRITER = new ObjectMapper();
|
||||||
@@ -54,6 +57,45 @@ public class ApiGatewayV2OpenApiImporter {
|
|||||||
|
|
||||||
private final ApiGatewayV2Service service;
|
private final ApiGatewayV2Service service;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The definition the REST import route takes from its body: the restJson1 envelope's text {@code body}, or else
|
||||||
|
* the body itself, a raw YAML or JSON definition, so a hand-rolled curl still works.
|
||||||
|
*/
|
||||||
|
public static String restDefinition(ObjectMapper mapper, String payload) {
|
||||||
|
try {
|
||||||
|
JsonNode root = mapper.readTree(payload);
|
||||||
|
if (root != null && root.isObject() && root.hasNonNull("body") && root.get("body").isTextual()) {
|
||||||
|
return root.get("body").asText();
|
||||||
|
}
|
||||||
|
} catch (IOException expected) {
|
||||||
|
// Not JSON at all: a raw YAML or JSON OpenAPI document, which the import takes as it stands.
|
||||||
|
}
|
||||||
|
return payload;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Each definition an ImportApi or ReimportApi body can carry to this service, so IAM checks the roles of whichever
|
||||||
|
* it imports: the REST route's ({@link #restDefinition}) and the JSON 1.1 handler's, its {@code Body} member.
|
||||||
|
*/
|
||||||
|
@Override
|
||||||
|
public List<String> openApiDefinitions(String operation, String body, String region) {
|
||||||
|
if (!"apigateway:ImportApi".equals(operation) && !"apigateway:ReimportApi".equals(operation)
|
||||||
|
|| body == null || body.isBlank()) {
|
||||||
|
return List.of();
|
||||||
|
}
|
||||||
|
Set<String> definitions = new LinkedHashSet<>();
|
||||||
|
definitions.add(restDefinition(MAP_VALUE_WRITER, body));
|
||||||
|
try {
|
||||||
|
JsonNode root = MAP_VALUE_WRITER.readTree(body);
|
||||||
|
if (root != null && root.path("Body").isTextual()) {
|
||||||
|
definitions.add(root.get("Body").asText());
|
||||||
|
}
|
||||||
|
} catch (IOException expected) {
|
||||||
|
// Not JSON, so no Body member: the REST route's raw definition alone, already added.
|
||||||
|
}
|
||||||
|
return List.copyOf(definitions);
|
||||||
|
}
|
||||||
|
|
||||||
@Inject
|
@Inject
|
||||||
public ApiGatewayV2OpenApiImporter(ApiGatewayV2Service service) {
|
public ApiGatewayV2OpenApiImporter(ApiGatewayV2Service service) {
|
||||||
this.service = service;
|
this.service = service;
|
||||||
|
|||||||
@@ -67,4 +67,13 @@ public interface PassedRoleLookup {
|
|||||||
default Optional<String> serviceCatalogConstraintType(String constraintId) {
|
default Optional<String> serviceCatalogConstraintType(String constraintId) {
|
||||||
return Optional.empty();
|
return Optional.empty();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The OpenAPI definitions a request for {@code operation} in {@code region} can import from its {@code body}, as
|
||||||
|
* its service takes them from it, each as the service reads it before it reads the roles it names; empty for an
|
||||||
|
* operation whose service says nothing of how, whose definition is then read where the table locates it.
|
||||||
|
*/
|
||||||
|
default List<String> openApiDefinitions(String operation, String body, String region) {
|
||||||
|
return List.of();
|
||||||
|
}
|
||||||
}
|
}
|
||||||
@@ -1,9 +1,56 @@
|
|||||||
{
|
{
|
||||||
"_source": {"generator": "tools/aws/regen_iam_passed_roles.py", "reference": "https://servicereference.us-east-1.amazonaws.com/", "botocore": "botocore 1.44.9 (installed package)", "retrieved": "2026-11-27", "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.44.9 (installed package)", "retrieved": "2026-11-27", "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"], "aps": ["amp"], "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"], "elasticfilesystem": ["efs"], "elasticloadbalancing": ["elb-proxy"], "elasticmapreduce": ["emr"], "emr-containers": ["emr-containers"], "emr-serverless": ["emr-serverless"], "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"], "s3tables": ["s3tables"], "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"], "wafv2": ["wafv2"]},
|
"namespaces": {"apigateway": ["apigateway", "apigatewayv2"], "application-autoscaling": ["application-autoscaling"], "aps": ["amp"], "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"], "elasticfilesystem": ["efs"], "elasticloadbalancing": ["elb-proxy"], "elasticmapreduce": ["emr"], "emr-containers": ["emr-containers"], "emr-serverless": ["emr-serverless"], "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"], "s3tables": ["s3tables"], "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"], "wafv2": ["wafv2"]},
|
||||||
"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": "CreateExtension and UpdateExtension pass a role in Actions{}[].RoleArn, a map of lists, which this file does not read yet", "appsync": "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", "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"},
|
"notCovered": {"access-analyzer": "REST routes no rule maps yet", "airflow": "REST routes no rule maps yet", "appconfig": "CreateExtension and UpdateExtension pass a role in Actions{}[].RoleArn, a map of lists, which this file does not read yet", "appsync": "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", "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"},
|
||||||
"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", "continuum", "databrew", "dataexchange", "datapipeline", "datazone", "dax", "deadline", "devicefarm", "elemental-inference", "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"],
|
"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", "continuum", "databrew", "dataexchange", "datapipeline", "datazone", "dax", "deadline", "devicefarm", "elemental-inference", "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"],
|
||||||
"operations": {
|
"operations": {
|
||||||
|
"apigateway:CreateApi": {"passedTo": ["apigateway"], "roles": [
|
||||||
|
{"member": "CredentialsArn", "passedTo": "apigateway"},
|
||||||
|
{"member": "credentialsArn", "passedTo": "apigateway"}
|
||||||
|
]},
|
||||||
|
"apigateway:CreateAuthorizer": {"passedTo": ["apigateway"], "roles": [
|
||||||
|
{"member": "AuthorizerCredentialsArn", "passedTo": "apigateway"},
|
||||||
|
{"member": "authorizerCredentials", "passedTo": "apigateway"},
|
||||||
|
{"member": "authorizerCredentialsArn", "passedTo": "apigateway"}
|
||||||
|
]},
|
||||||
|
"apigateway:CreateIntegration": {"passedTo": ["apigateway"], "roles": [
|
||||||
|
{"member": "CredentialsArn", "passedTo": "apigateway"},
|
||||||
|
{"member": "credentialsArn", "passedTo": "apigateway"}
|
||||||
|
]},
|
||||||
|
"apigateway:ImportApi": {"passedTo": ["apigateway"], "roles": [
|
||||||
|
{"member": "Body", "passedTo": "apigateway", "openApi": {"operation": {"x-amazon-apigateway-integration": "credentials"}, "securityScheme": {"x-amazon-apigateway-authorizer": "authorizerCredentials"}, "anyMethod": "x-amazon-apigateway-any-method"}},
|
||||||
|
{"member": "body", "passedTo": "apigateway", "openApi": {"operation": {"x-amazon-apigateway-integration": "credentials"}, "securityScheme": {"x-amazon-apigateway-authorizer": "authorizerCredentials"}, "anyMethod": "x-amazon-apigateway-any-method"}}
|
||||||
|
]},
|
||||||
|
"apigateway:ImportRestApi": {"passedTo": ["apigateway"], "roles": [
|
||||||
|
{"member": "body", "passedTo": "apigateway", "openApi": {"operation": {"x-amazon-apigateway-integration": "credentials"}, "securityScheme": {"x-amazon-apigateway-authorizer": "authorizerCredentials"}, "anyMethod": "x-amazon-apigateway-any-method"}, "payload": true}
|
||||||
|
]},
|
||||||
|
"apigateway:PutIntegration": {"passedTo": ["apigateway"], "roles": [
|
||||||
|
{"member": "credentials", "passedTo": "apigateway"}
|
||||||
|
]},
|
||||||
|
"apigateway:PutRestApi": {"passedTo": ["apigateway"], "roles": [
|
||||||
|
{"member": "body", "passedTo": "apigateway", "openApi": {"operation": {"x-amazon-apigateway-integration": "credentials"}, "securityScheme": {"x-amazon-apigateway-authorizer": "authorizerCredentials"}, "anyMethod": "x-amazon-apigateway-any-method"}, "payload": true}
|
||||||
|
]},
|
||||||
|
"apigateway:ReimportApi": {"passedTo": ["apigateway"], "roles": [
|
||||||
|
{"member": "Body", "passedTo": "apigateway", "openApi": {"operation": {"x-amazon-apigateway-integration": "credentials"}, "securityScheme": {"x-amazon-apigateway-authorizer": "authorizerCredentials"}, "anyMethod": "x-amazon-apigateway-any-method"}},
|
||||||
|
{"member": "body", "passedTo": "apigateway", "openApi": {"operation": {"x-amazon-apigateway-integration": "credentials"}, "securityScheme": {"x-amazon-apigateway-authorizer": "authorizerCredentials"}, "anyMethod": "x-amazon-apigateway-any-method"}}
|
||||||
|
]},
|
||||||
|
"apigateway:UpdateAccount": {"passedTo": ["apigateway"], "roles": [
|
||||||
|
{"member": "patchOperations[path=/cloudwatchRoleArn].value", "passedTo": "apigateway"}
|
||||||
|
]},
|
||||||
|
"apigateway:UpdateApi": {"passedTo": ["apigateway"], "roles": [
|
||||||
|
{"member": "CredentialsArn", "passedTo": "apigateway"},
|
||||||
|
{"member": "credentialsArn", "passedTo": "apigateway"}
|
||||||
|
]},
|
||||||
|
"apigateway:UpdateAuthorizer": {"passedTo": ["apigateway"], "roles": [
|
||||||
|
{"member": "AuthorizerCredentialsArn", "passedTo": "apigateway"},
|
||||||
|
{"member": "authorizerCredentialsArn", "passedTo": "apigateway"},
|
||||||
|
{"member": "patchOperations[path=/authorizerCredentials].value", "passedTo": "apigateway"}
|
||||||
|
]},
|
||||||
|
"apigateway:UpdateIntegration": {"passedTo": ["apigateway"], "roles": [
|
||||||
|
{"member": "CredentialsArn", "passedTo": "apigateway"},
|
||||||
|
{"member": "credentialsArn", "passedTo": "apigateway"},
|
||||||
|
{"member": "patchOperations[path=/credentials].value", "passedTo": "apigateway"}
|
||||||
|
]},
|
||||||
"application-autoscaling:RegisterScalableTarget": {"passedTo": ["application-autoscaling"], "byHand": "the scalable target's role"},
|
"application-autoscaling:RegisterScalableTarget": {"passedTo": ["application-autoscaling"], "byHand": "the scalable target's role"},
|
||||||
"aps:CreateScraper": {"passedTo": ["aps"], "roles": [
|
"aps:CreateScraper": {"passedTo": ["aps"], "roles": [
|
||||||
{"member": "roleConfiguration.sourceRoleArn", "passedTo": "aps"},
|
{"member": "roleConfiguration.sourceRoleArn", "passedTo": "aps"},
|
||||||
|
|||||||
@@ -20,6 +20,7 @@ import java.net.URLEncoder;
|
|||||||
import java.nio.charset.StandardCharsets;
|
import java.nio.charset.StandardCharsets;
|
||||||
import java.util.ArrayList;
|
import java.util.ArrayList;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
|
import java.util.Map;
|
||||||
import java.util.Optional;
|
import java.util.Optional;
|
||||||
import java.util.stream.Stream;
|
import java.util.stream.Stream;
|
||||||
|
|
||||||
@@ -202,6 +203,17 @@ class PassedRoleMembersTest {
|
|||||||
}
|
}
|
||||||
|
|
||||||
private static JsonNode body(Member member, String value) {
|
private static JsonNode body(Member member, String value) {
|
||||||
|
if (member.openApi() != null) {
|
||||||
|
// An OpenAPI definition whose one operation's first role-naming extension names the role.
|
||||||
|
Map.Entry<String, String> extension = member.openApi().operation().entrySet().iterator().next();
|
||||||
|
ObjectNode definition = MAPPER.createObjectNode();
|
||||||
|
definition.putObject("paths").putObject("/things").putObject("get").putObject(extension.getKey())
|
||||||
|
.put(extension.getValue(), value);
|
||||||
|
if (member.payload()) {
|
||||||
|
return definition;
|
||||||
|
}
|
||||||
|
value = definition.toString();
|
||||||
|
}
|
||||||
JsonNode node = TextNode.valueOf(value);
|
JsonNode node = TextNode.valueOf(value);
|
||||||
List<Step> steps = member.steps();
|
List<Step> steps = member.steps();
|
||||||
for (int i = steps.size() - 1; i >= 0; i--) {
|
for (int i = steps.size() - 1; i >= 0; i--) {
|
||||||
@@ -209,6 +221,10 @@ class PassedRoleMembersTest {
|
|||||||
JsonNode inner = switch (step.into()) {
|
JsonNode inner = switch (step.into()) {
|
||||||
case NONE -> node;
|
case NONE -> node;
|
||||||
case LIST -> MAPPER.createArrayNode().add(node);
|
case LIST -> MAPPER.createArrayNode().add(node);
|
||||||
|
case MATCH -> {
|
||||||
|
String[] match = step.key().split("=", 2);
|
||||||
|
yield MAPPER.createArrayNode().add(((ObjectNode) node).put(match[0], match[1]));
|
||||||
|
}
|
||||||
case MAP -> MAPPER.createObjectNode().set("any", node);
|
case MAP -> MAPPER.createObjectNode().set("any", node);
|
||||||
case KEY -> MAPPER.createObjectNode().set(step.key(), node);
|
case KEY -> MAPPER.createObjectNode().set(step.key(), node);
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -729,6 +729,58 @@ class PassedRolesTest {
|
|||||||
PassedRoles.ofBody("elasticmapreduce:RunJobFlow", new ObjectMapper().readTree(request), LOOKUPS));
|
PassedRoles.ofBody("elasticmapreduce:RunJobFlow", new ObjectMapper().readTree(request), LOOKUPS));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void apiGatewayPassesTheRolesItsCredentialsPatchOperationsAndOpenApiExtensionsName() {
|
||||||
|
String apiGateway = "apigateway.amazonaws.com";
|
||||||
|
// An integration's and an authorizer's credentials, REST API and HTTP API alike.
|
||||||
|
assertEquals(List.of(passed("integration", apiGateway)), PassedRoles.of("apigateway:PutIntegration",
|
||||||
|
json("{\"type\":\"AWS\",\"credentials\":\"" + ROLES + "integration\"}"), LOOKUPS));
|
||||||
|
assertEquals(List.of(passed("http", apiGateway)), PassedRoles.of("apigateway:CreateIntegration",
|
||||||
|
json("{\"integrationType\":\"AWS_PROXY\",\"credentialsArn\":\"" + ROLES + "http\"}"), LOOKUPS));
|
||||||
|
// Floci serves HTTP APIs over JSON 1.1 too, whose bodies name the members as botocore does.
|
||||||
|
assertEquals(List.of(passed("json", apiGateway)), PassedRoles.of("apigateway:CreateIntegration",
|
||||||
|
json("{\"IntegrationType\":\"AWS_PROXY\",\"CredentialsArn\":\"" + ROLES + "json\"}"), LOOKUPS));
|
||||||
|
// An update names the property it changes by its patch operation's path, exactly.
|
||||||
|
assertEquals(List.of(passed("patched", apiGateway)), PassedRoles.of("apigateway:UpdateIntegration",
|
||||||
|
json("{\"patchOperations\":[{\"op\":\"replace\",\"path\":\"/timeoutInMillis\",\"value\":\"1000\"},"
|
||||||
|
+ "{\"op\":\"replace\",\"path\":\"/credentials\",\"value\":\"" + ROLES + "patched\"},"
|
||||||
|
+ "{\"op\":\"replace\",\"path\":\"/Credentials\",\"value\":\"" + ROLES + "other\"}]}"), LOOKUPS));
|
||||||
|
assertEquals(List.of(passed("cloudwatch", apiGateway)), PassedRoles.of("apigateway:UpdateAccount",
|
||||||
|
json("{\"patchOperations\":[{\"op\":\"replace\",\"path\":\"/cloudwatchRoleArn\",\"value\":\""
|
||||||
|
+ ROLES + "cloudwatch\"}]}"), LOOKUPS));
|
||||||
|
// An import's OpenAPI definition, YAML here, names roles in its operations' integrations, the ANY method's
|
||||||
|
// included, and its security schemes' authorizers; an extension anywhere else is not read.
|
||||||
|
String definition = """
|
||||||
|
openapi: 3.0.1
|
||||||
|
x-amazon-apigateway-integration:
|
||||||
|
credentials: %1$sunread
|
||||||
|
paths:
|
||||||
|
/things:
|
||||||
|
x-unread:
|
||||||
|
x-amazon-apigateway-integration:
|
||||||
|
credentials: %1$snot-an-operation
|
||||||
|
get:
|
||||||
|
x-amazon-apigateway-integration:
|
||||||
|
credentials: %1$sget
|
||||||
|
x-amazon-apigateway-any-method:
|
||||||
|
x-amazon-apigateway-integration:
|
||||||
|
credentials: %1$sany
|
||||||
|
components:
|
||||||
|
securitySchemes:
|
||||||
|
custom:
|
||||||
|
x-amazon-apigateway-authorizer:
|
||||||
|
authorizerCredentials: %1$sauthorizer
|
||||||
|
""".formatted(ROLES);
|
||||||
|
assertEquals(List.of(passed("get", apiGateway), passed("any", apiGateway), passed("authorizer", apiGateway)),
|
||||||
|
PassedRoles.of("apigateway:ImportRestApi", request("application/x-yaml",
|
||||||
|
definition.getBytes(StandardCharsets.UTF_8)), LOOKUPS));
|
||||||
|
// An HTTP API import holds its definition as a string, here JSON with OpenAPI 2's security definitions.
|
||||||
|
String swagger = "{\"swagger\":\"2.0\",\"securityDefinitions\":{\"auth\":{\"x-amazon-apigateway-authorizer\":"
|
||||||
|
+ "{\"authorizerCredentials\":\"" + ROLES + "swagger\"}}}}";
|
||||||
|
assertEquals(List.of(passed("swagger", apiGateway)), PassedRoles.of("apigateway:ImportApi",
|
||||||
|
json(new ObjectMapper().createObjectNode().put("body", swagger).toString()), LOOKUPS));
|
||||||
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
void anXmlBodyPassesTheRolesItsModeledMembersName() {
|
void anXmlBodyPassesTheRolesItsModeledMembersName() {
|
||||||
// S3's PutBucketReplication, authorized as s3:PutReplicationConfiguration, passes its configuration's Role.
|
// S3's PutBucketReplication, authorized as s3:PutReplicationConfiguration, passes its configuration's Role.
|
||||||
|
|||||||
@@ -180,6 +180,87 @@ class IamPassRoleEnforcementIntegrationTest {
|
|||||||
.post("/"));
|
.post("/"));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void apiGatewayNeedsPassRoleOnTheRolesAnIntegrationAnUpdateOrAnImportNames() {
|
||||||
|
// API Gateway is authorized by HTTP method, and its roles are checked for the operation its route resolves:
|
||||||
|
// PutIntegration's credentials, the role an UpdateIntegration's patch operation sets, and an imported
|
||||||
|
// definition's integration credentials.
|
||||||
|
String role = role("apigw-integration");
|
||||||
|
String apiId = admin("apigateway").contentType("application/json").body("{\"name\":\"passrole-" + suffix() + "\"}")
|
||||||
|
.post("/restapis").then().statusCode(201).extract().path("id");
|
||||||
|
cleanup.register(() -> admin("apigateway").delete("/restapis/" + apiId));
|
||||||
|
String rootId = admin("apigateway").get("/restapis/" + apiId + "/resources").then().statusCode(200)
|
||||||
|
.extract().path("item[0].id");
|
||||||
|
String method = "/restapis/" + apiId + "/resources/" + rootId + "/methods/GET";
|
||||||
|
admin("apigateway").contentType("application/json").body("{\"authorizationType\":\"NONE\"}").put(method)
|
||||||
|
.then().statusCode(201);
|
||||||
|
String integration = """
|
||||||
|
{"type":"AWS","integrationHttpMethod":"POST","credentials":"%s",
|
||||||
|
"uri":"arn:aws:apigateway:us-east-1:sqs:path/%s/passrole-queue"}""".formatted(role, ACCOUNT);
|
||||||
|
String patch = "{\"patchOperations\":[{\"op\":\"replace\",\"path\":\"/credentials\",\"value\":\"" + role
|
||||||
|
+ "\"}]}";
|
||||||
|
String definition = """
|
||||||
|
{"openapi":"3.0.1","info":{"title":"passrole-import-%s","version":"1"},"paths":{"/things":{"get":{
|
||||||
|
"x-amazon-apigateway-integration":{"type":"aws","httpMethod":"POST","credentials":"%s",
|
||||||
|
"uri":"arn:aws:apigateway:us-east-1:sqs:path/%s/passrole-queue"}}}}}""".formatted(suffix(), role, ACCOUNT);
|
||||||
|
User user = user("passrole-apigw");
|
||||||
|
|
||||||
|
user.policy(allow("apigateway:*", "*"));
|
||||||
|
denied(user.rest("apigateway").body(integration).put(method + "/integration").then());
|
||||||
|
denied(user.rest("apigateway").body(definition).post("/restapis?mode=import").then());
|
||||||
|
// The definition is read as API Gateway reads it, its AWS variables resolved.
|
||||||
|
denied(user.rest("apigateway").body(definition.replace(role, "arn:${AWS::Partition}:iam::${AWS::AccountId}:"
|
||||||
|
+ role.substring(role.indexOf(":role/") + 1))).post("/restapis?mode=import").then());
|
||||||
|
user.policy(allow("apigateway:*", "*") + "," + passRole(role, "lambda.amazonaws.com"));
|
||||||
|
denied(user.rest("apigateway").body(integration).put(method + "/integration").then());
|
||||||
|
|
||||||
|
user.policy(allow("apigateway:*", "*") + "," + passRole(role, "apigateway.amazonaws.com"));
|
||||||
|
user.rest("apigateway").body(integration).put(method + "/integration").then().statusCode(201);
|
||||||
|
String imported = user.rest("apigateway").body(definition).post("/restapis?mode=import").then().statusCode(201)
|
||||||
|
.extract().path("id");
|
||||||
|
cleanup.register(() -> admin("apigateway").delete("/restapis/" + imported));
|
||||||
|
user.policy(allow("apigateway:*", "*"));
|
||||||
|
denied(user.rest("apigateway").body(patch).patch(method + "/integration").then());
|
||||||
|
// With the permission the update reaches API Gateway, which answers it on its own terms.
|
||||||
|
user.policy(allow("apigateway:*", "*") + "," + passRole(role, "apigateway.amazonaws.com"));
|
||||||
|
user.rest("apigateway").body(patch).patch(method + "/integration").then().statusCode(not(403));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void apiGatewayV2OverJson11NeedsPassRoleOnTheRolesItsBodyNames() {
|
||||||
|
// HTTP APIs are served over JSON 1.1 too, whose bodies name the members as botocore does.
|
||||||
|
String role = role("apigw-v2-json");
|
||||||
|
String apiId = admin("apigateway").header("X-Amz-Target", "AmazonApiGatewayV2.CreateApi")
|
||||||
|
.contentType("application/x-amz-json-1.1")
|
||||||
|
.body("{\"Name\":\"passrole-v2-" + suffix() + "\",\"ProtocolType\":\"HTTP\"}")
|
||||||
|
.post("/").then().statusCode(201).extract().path("ApiId");
|
||||||
|
cleanup.register(() -> admin("apigateway").header("X-Amz-Target", "AmazonApiGatewayV2.DeleteApi")
|
||||||
|
.contentType("application/x-amz-json-1.1").body("{\"ApiId\":\"" + apiId + "\"}").post("/"));
|
||||||
|
String integration = """
|
||||||
|
{"ApiId":"%s","IntegrationType":"AWS_PROXY","IntegrationSubtype":"SQS-SendMessage",
|
||||||
|
"PayloadFormatVersion":"1.0","CredentialsArn":"%s",
|
||||||
|
"RequestParameters":{"QueueUrl":"https://sqs.us-east-1.amazonaws.com/%s/q","MessageBody":"$request.body"}}"""
|
||||||
|
.formatted(apiId, role, ACCOUNT);
|
||||||
|
String definition = """
|
||||||
|
{"openapi":"3.0.1","info":{"title":"passrole-v2-import","version":"1"},"paths":{"/things":{"get":{
|
||||||
|
"x-amazon-apigateway-integration":{"type":"aws_proxy","httpMethod":"POST","payloadFormatVersion":"1.0",
|
||||||
|
"credentials":"%s","uri":"arn:aws:apigateway:us-east-1:lambda:path/2015-03-31/functions/x/invocations"}}}}}"""
|
||||||
|
.formatted(role);
|
||||||
|
String importApi = new ObjectMapper().createObjectNode().put("Body", definition).toString();
|
||||||
|
User user = user("passrole-apigw-v2");
|
||||||
|
|
||||||
|
user.policy(allow("apigateway:*", "*"));
|
||||||
|
deniedJson(user.json("apigateway", "AmazonApiGatewayV2.CreateIntegration").body(integration).post("/").then());
|
||||||
|
deniedJson(user.json("apigateway", "AmazonApiGatewayV2.ImportApi").body(importApi).post("/").then());
|
||||||
|
// The REST route takes the definition in its restJson1 envelope, or as the whole body.
|
||||||
|
denied(user.rest("apigateway").body(importApi.replace("\"Body\"", "\"body\"")).put("/v2/apis").then());
|
||||||
|
denied(user.rest("apigateway").body(definition).put("/v2/apis").then());
|
||||||
|
|
||||||
|
user.policy(allow("apigateway:*", "*") + "," + passRole(role, "apigateway.amazonaws.com"));
|
||||||
|
user.json("apigateway", "AmazonApiGatewayV2.CreateIntegration").body(integration).post("/").then()
|
||||||
|
.statusCode(not(400));
|
||||||
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
void aPassRoleGrantKeyedOnTheRolesTagIsNotSatisfiedByTheTag() {
|
void aPassRoleGrantKeyedOnTheRolesTagIsNotSatisfiedByTheTag() {
|
||||||
// The IAM guide warns that ResourceTag conditions with PassRole "do not have reliable results", so the
|
// The IAM guide warns that ResourceTag conditions with PassRole "do not have reliable results", so the
|
||||||
|
|||||||
@@ -0,0 +1,247 @@
|
|||||||
|
#!/usr/bin/env python3
|
||||||
|
"""Vendor where an Amazon API Gateway request names the roles it passes into tools/aws/sources/apigateway-roles.json, a
|
||||||
|
source of the passed-roles table.
|
||||||
|
|
||||||
|
AWS's Service Reference passes the roles of twelve API Gateway operations to `apigateway.amazonaws.com`, and botocore
|
||||||
|
gives their requests, but no member they name a role in matches the passed-roles rule (a name ending in `Role`,
|
||||||
|
`RoleArn` or `RoleName`): API Gateway's API references say which members take a role, and where.
|
||||||
|
|
||||||
|
- A member named for credentials takes a role, the API references say of the resource types that hold it:
|
||||||
|
|
||||||
|
credentials: To specify an IAM Role for API Gateway to assume, use the role's Amazon Resource Name (ARN).
|
||||||
|
https://docs.aws.amazon.com/apigateway/latest/api/API_Integration.html (REST APIs, also Authorizer)
|
||||||
|
https://docs.aws.amazon.com/apigatewayv2/latest/api-reference/apis-apiid-integrations-integrationid.html
|
||||||
|
|
||||||
|
- A REST API update names the property it changes by the path of a patch operation:
|
||||||
|
|
||||||
|
For example, if the target resource has an updateable property of {"name":"value"}, the path for this
|
||||||
|
property is /name.
|
||||||
|
https://docs.aws.amazon.com/apigateway/latest/api/API_PatchOperation.html
|
||||||
|
|
||||||
|
- An import's body is an OpenAPI definition ("Currently, only OpenAPI definition JSON/YAML files are supported";
|
||||||
|
"The OpenAPI definition"), whose API Gateway extensions name roles: the integration extension, "an extended
|
||||||
|
property of the OpenAPI Operation object", its `credentials` ("For AWS IAM role-based credentials, specify the ARN
|
||||||
|
of an appropriate IAM role"), and the authorizer extension, which "applies to the security definition in OpenAPI 2
|
||||||
|
and the security scheme in OpenAPI 3", its `authorizerCredentials` ("in the form of an ARN of an IAM execution
|
||||||
|
role"); the ANY method's extension "Specifies the OpenAPI Operation Object for the API Gateway catch-all ANY
|
||||||
|
method".
|
||||||
|
|
||||||
|
This script copies each of those descriptions as it stands, with the member, type, operation or extension it is
|
||||||
|
about. Nothing in the output is written by hand; regen_iam_passed_roles.py reads it to find the role members of
|
||||||
|
API Gateway's requests.
|
||||||
|
|
||||||
|
Run from anywhere in the repo:
|
||||||
|
python3 tools/aws/fetch_apigateway_roles.py # rewrite the vendored file from the pages
|
||||||
|
python3 tools/aws/fetch_apigateway_roles.py --verify # online: the file still says what the pages do
|
||||||
|
"""
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import argparse
|
||||||
|
import html
|
||||||
|
import json
|
||||||
|
import re
|
||||||
|
import sys
|
||||||
|
import urllib.request
|
||||||
|
from datetime import datetime, timezone
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
V1 = "https://docs.aws.amazon.com/apigateway/latest/api/"
|
||||||
|
V2 = "https://docs.aws.amazon.com/apigatewayv2/latest/api-reference/"
|
||||||
|
GUIDE = "https://docs.aws.amazon.com/apigateway/latest/developerguide/"
|
||||||
|
REPO_ROOT = Path(__file__).resolve().parents[2]
|
||||||
|
OUTPUT = REPO_ROOT / "tools/aws/sources/apigateway-roles.json"
|
||||||
|
|
||||||
|
# The resource types whose member takes a role, each by the API reference page describing it: a REST API type's
|
||||||
|
# page, or the HTTP API page of a resource and the schema it describes there.
|
||||||
|
ROLE_MEMBERS = (
|
||||||
|
{"model": "apigateway", "type": "Integration", "member": "credentials", "page": V1 + "API_Integration.html"},
|
||||||
|
{"model": "apigateway", "type": "Authorizer", "member": "authorizerCredentials",
|
||||||
|
"page": V1 + "API_Authorizer.html"},
|
||||||
|
{"model": "apigatewayv2", "type": "Integration", "member": "credentialsArn",
|
||||||
|
"page": V2 + "apis-apiid-integrations-integrationid.html"},
|
||||||
|
{"model": "apigatewayv2", "type": "Authorizer", "member": "authorizerCredentialsArn",
|
||||||
|
"page": V2 + "apis-apiid-authorizers-authorizerid.html"},
|
||||||
|
)
|
||||||
|
PATCH_PAGE = V1 + "API_PatchOperation.html"
|
||||||
|
# The imports whose body is an OpenAPI definition, each by the API reference page describing it, and for an HTTP
|
||||||
|
# API page the schema of its body there.
|
||||||
|
DOCUMENTS = (
|
||||||
|
{"model": "apigateway", "operation": "ImportRestApi", "member": "body", "page": V1 + "API_ImportRestApi.html"},
|
||||||
|
{"model": "apigateway", "operation": "PutRestApi", "member": "body", "page": V1 + "API_PutRestApi.html"},
|
||||||
|
{"model": "apigatewayv2", "operation": "ImportApi", "member": "body", "page": V2 + "apis.html",
|
||||||
|
"schema": "importapiinput"},
|
||||||
|
{"model": "apigatewayv2", "operation": "ReimportApi", "member": "body", "page": V2 + "apis-apiid.html",
|
||||||
|
"schema": "reimportapiinput"},
|
||||||
|
)
|
||||||
|
# The OpenAPI extensions naming a role, each by its developer guide page and the property of it that names one.
|
||||||
|
EXTENSIONS = (
|
||||||
|
{"extension": "x-amazon-apigateway-integration", "member": "credentials",
|
||||||
|
"page": GUIDE + "api-gateway-swagger-extensions-integration.html"},
|
||||||
|
{"extension": "x-amazon-apigateway-authorizer", "member": "authorizerCredentials",
|
||||||
|
"page": GUIDE + "api-gateway-swagger-extensions-authorizer.html"},
|
||||||
|
)
|
||||||
|
ANY_METHOD_PAGE = GUIDE + "api-gateway-swagger-extensions-any-method.html"
|
||||||
|
|
||||||
|
# A description saying its member takes a role's ARN.
|
||||||
|
ROLE_RE = re.compile(r"\bTo specify an IAM role for API Gateway to assume, use the role's Amazon Resource Name "
|
||||||
|
r"\(ARN\)", re.IGNORECASE)
|
||||||
|
EXTENSION_ROLE_RE = re.compile(r"\bARN of an? (?:appropriate )?IAM (?:execution )?role\b")
|
||||||
|
PATCH_RE = re.compile(r"the path for this property is /name\.")
|
||||||
|
DOCUMENT_RE = re.compile(r"\bOpenAPI definition\b")
|
||||||
|
# Where an extension sits, by what its page says it extends.
|
||||||
|
PLACEMENTS = (
|
||||||
|
("operation", re.compile(r"This extension is an extended property of the OpenAPI Operation object\.")),
|
||||||
|
("securityScheme", re.compile(r"This extension applies to the security definition in OpenAPI 2 and the "
|
||||||
|
r"security scheme in OpenAPI 3\s?\.")),
|
||||||
|
)
|
||||||
|
ANY_METHOD_RE = re.compile(r"(?P<extension>x-amazon-apigateway-any-method) object Specifies the OpenAPI Operation "
|
||||||
|
r"Object for the API Gateway catch-all ANY method in an OpenAPI Path Item Object \.")
|
||||||
|
|
||||||
|
|
||||||
|
def text(fragment: str) -> str:
|
||||||
|
"""A fragment of a page as text, spaces collapsed."""
|
||||||
|
return re.sub(r"\s+", " ", html.unescape(re.sub(r"<[^>]+>", " ", fragment))).strip()
|
||||||
|
|
||||||
|
|
||||||
|
def main_text(page: str) -> str:
|
||||||
|
"""A page's main column as text."""
|
||||||
|
start = page.find('id="main-col-body"')
|
||||||
|
return text(page[start:] if start >= 0 else page)
|
||||||
|
|
||||||
|
|
||||||
|
def definition(page: str, url: str, anchor: str) -> str:
|
||||||
|
"""The description a REST API reference page gives the entry `anchor`."""
|
||||||
|
match = re.search(r'id="' + re.escape(anchor) + r'"[^>]*>.*?<dd>(?P<body>.*?)</dd>', page, re.S)
|
||||||
|
if match is None:
|
||||||
|
raise ValueError(f"{url} has no entry {anchor}: its layout changed")
|
||||||
|
return re.sub(r"\s*Type: .*$", "", text(match.group("body")))
|
||||||
|
|
||||||
|
|
||||||
|
def property_row(page: str, url: str, anchor: str) -> str:
|
||||||
|
"""The description an HTTP API reference page's property table gives the row `anchor`."""
|
||||||
|
match = re.search(r'id="' + re.escape(anchor) + r'".*?</td>(?P<cells>.*?)</tr>', page, re.S)
|
||||||
|
if match is None:
|
||||||
|
raise ValueError(f"{url} has no property {anchor}: its layout changed")
|
||||||
|
cells = re.findall(r"<td[^>]*>(.*?)</td>", match.group("cells"), re.S)
|
||||||
|
if len(cells) < 3:
|
||||||
|
raise ValueError(f"{url} gives {anchor} no description: its layout changed")
|
||||||
|
return text(cells[2])
|
||||||
|
|
||||||
|
|
||||||
|
def slug(url: str) -> str:
|
||||||
|
return url.rsplit("/", 1)[1].removesuffix(".html")
|
||||||
|
|
||||||
|
|
||||||
|
def read_role_member(entry: dict, page: str) -> dict:
|
||||||
|
if entry["model"] == "apigateway":
|
||||||
|
description = definition(page, entry["page"], f"apigw-Type-{entry['type']}-{entry['member']}")
|
||||||
|
else:
|
||||||
|
description = property_row(page, entry["page"],
|
||||||
|
f"{slug(entry['page'])}-prop-{entry['type'].lower()}-{entry['member'].lower()}")
|
||||||
|
if not ROLE_RE.search(description):
|
||||||
|
raise ValueError(f"{entry['page']} no longer says {entry['member']} takes a role's ARN: '{description}'")
|
||||||
|
return {**entry, "description": description}
|
||||||
|
|
||||||
|
|
||||||
|
def read_document(entry: dict, page: str) -> dict:
|
||||||
|
if entry["model"] == "apigateway":
|
||||||
|
description = definition(page, entry["page"], f"apigw-{entry['operation']}-request-{entry['member']}")
|
||||||
|
else:
|
||||||
|
description = property_row(page, entry["page"], f"{slug(entry['page'])}-prop-{entry['schema']}-"
|
||||||
|
f"{entry['member']}")
|
||||||
|
if not DOCUMENT_RE.search(description):
|
||||||
|
raise ValueError(f"{entry['page']} no longer says {entry['operation']}'s {entry['member']} is an OpenAPI "
|
||||||
|
f"definition: '{description}'")
|
||||||
|
return {key: value for key, value in entry.items() if key != "schema"} | {"description": description}
|
||||||
|
|
||||||
|
|
||||||
|
def read_extension(entry: dict, page: str) -> dict:
|
||||||
|
body = main_text(page)
|
||||||
|
placement = next(((on, match.group(0)) for on, pattern in PLACEMENTS if (match := pattern.search(body))), None)
|
||||||
|
if placement is None:
|
||||||
|
raise ValueError(f"{entry['page']} no longer says what {entry['extension']} extends: its layout changed")
|
||||||
|
rows = [re.findall(r"<td[^>]*>(.*?)</td>", row, re.S) for row in re.findall(r"<tr>(.*?)</tr>", page, re.S)]
|
||||||
|
described = [text(cells[-1]) for cells in rows if cells and text(cells[0]) == entry["member"]]
|
||||||
|
if len(described) != 1 or not EXTENSION_ROLE_RE.search(described[0]):
|
||||||
|
raise ValueError(f"{entry['page']} no longer says {entry['member']} is a role's ARN: {described}")
|
||||||
|
return {**entry, "on": placement[0], "placement": placement[1], "description": described[0]}
|
||||||
|
|
||||||
|
|
||||||
|
def build(fetch) -> dict:
|
||||||
|
patch = definition(fetch(PATCH_PAGE), PATCH_PAGE, "apigw-Type-PatchOperation-path")
|
||||||
|
if not PATCH_RE.search(patch):
|
||||||
|
raise ValueError(f"{PATCH_PAGE} no longer names a property's path as /name: '{patch}'")
|
||||||
|
any_method = ANY_METHOD_RE.search(main_text(fetch(ANY_METHOD_PAGE)))
|
||||||
|
if any_method is None:
|
||||||
|
raise ValueError(f"{ANY_METHOD_PAGE} no longer names the ANY method's extension: its layout changed")
|
||||||
|
return {
|
||||||
|
"_source": {
|
||||||
|
"pages": sorted({entry["page"] for entry in ROLE_MEMBERS + DOCUMENTS + EXTENSIONS}
|
||||||
|
| {PATCH_PAGE, ANY_METHOD_PAGE}),
|
||||||
|
"fetcher": str(Path(__file__).resolve().relative_to(REPO_ROOT)),
|
||||||
|
"retrieved": datetime.now(timezone.utc).strftime("%Y-%m-%d"),
|
||||||
|
"note": "Each description copied as it stands from the API Gateway API references and developer guide: "
|
||||||
|
"the members of a resource type that take a role, how a REST API update's patch operation names "
|
||||||
|
"a property, the imports whose body is an OpenAPI definition, and the OpenAPI extensions and "
|
||||||
|
"their properties that name a role, with what each extends.",
|
||||||
|
},
|
||||||
|
"roleMembers": [read_role_member(entry, fetch(entry["page"])) for entry in ROLE_MEMBERS],
|
||||||
|
"patchPath": {"model": "apigateway", "page": PATCH_PAGE, "description": patch},
|
||||||
|
"documents": [read_document(entry, fetch(entry["page"])) for entry in DOCUMENTS],
|
||||||
|
"extensions": [read_extension(entry, fetch(entry["page"])) for entry in EXTENSIONS],
|
||||||
|
"anyMethod": {"extension": any_method.group("extension"), "page": ANY_METHOD_PAGE,
|
||||||
|
"description": any_method.group(0)},
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def fetch_url(url: str) -> str:
|
||||||
|
request = urllib.request.Request(url, headers={"User-Agent": "floci-tools"})
|
||||||
|
with urllib.request.urlopen(request, timeout=60) as response:
|
||||||
|
return response.read().decode("utf-8")
|
||||||
|
|
||||||
|
|
||||||
|
def fetch_all(fetch=fetch_url) -> tuple:
|
||||||
|
"""The pages, each fetched once."""
|
||||||
|
cache: dict[str, str] = {}
|
||||||
|
|
||||||
|
def cached(url: str) -> str:
|
||||||
|
if url not in cache:
|
||||||
|
cache[url] = fetch(url)
|
||||||
|
return cache[url]
|
||||||
|
|
||||||
|
build(cached)
|
||||||
|
return (cache,)
|
||||||
|
|
||||||
|
|
||||||
|
def stale(vendored: dict, pages: dict[str, str]) -> bool:
|
||||||
|
"""Whether the pages now give something other than the vendored file, its date aside."""
|
||||||
|
built = build(lambda url: pages[url])
|
||||||
|
return any(vendored.get(key) != built[key] for key in built if key != "_source")
|
||||||
|
|
||||||
|
|
||||||
|
def main(argv: list[str] | None = None, fetch=fetch_url) -> int:
|
||||||
|
parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
|
||||||
|
parser.add_argument("--verify", action="store_true", help="online: the vendored file matches the pages")
|
||||||
|
args = parser.parse_args(argv)
|
||||||
|
try:
|
||||||
|
(pages,) = fetch_all(fetch)
|
||||||
|
except OSError as e:
|
||||||
|
print(f"error: could not read the Amazon API Gateway documentation ({e})", file=sys.stderr)
|
||||||
|
return 2
|
||||||
|
if args.verify:
|
||||||
|
vendored = json.loads(OUTPUT.read_text(encoding="utf-8"))
|
||||||
|
if stale(vendored, pages):
|
||||||
|
print(f"error: {OUTPUT.relative_to(REPO_ROOT)} no longer says what the API Gateway documentation does: "
|
||||||
|
f"run tools/aws/fetch_apigateway_roles.py and then make iam-passed-roles-sync", file=sys.stderr)
|
||||||
|
return 1
|
||||||
|
print(f"{OUTPUT.relative_to(REPO_ROOT)} matches the API Gateway documentation")
|
||||||
|
return 0
|
||||||
|
built = build(lambda url: pages[url])
|
||||||
|
OUTPUT.write_text(json.dumps(built, indent=2) + "\n", encoding="utf-8")
|
||||||
|
print(f"wrote {OUTPUT.relative_to(REPO_ROOT)} ({len(built['roleMembers'])} role members, "
|
||||||
|
f"{len(built['documents'])} documents, {len(built['extensions'])} extensions)")
|
||||||
|
return 0
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
sys.exit(main())
|
||||||
@@ -78,6 +78,7 @@ from collections.abc import Callable, Iterable
|
|||||||
from datetime import datetime, timezone
|
from datetime import datetime, timezone
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
|
|
||||||
|
import fetch_apigateway_roles
|
||||||
import fetch_eks_roles
|
import fetch_eks_roles
|
||||||
import fetch_emr_roles
|
import fetch_emr_roles
|
||||||
from regen_iam_authorized_actions import fetch_references
|
from regen_iam_authorized_actions import fetch_references
|
||||||
@@ -93,7 +94,7 @@ SERVICE_SUFFIX = ".amazonaws.com"
|
|||||||
# The IAM namespaces whose operations this file reads: those Floci serves over the JSON and Query
|
# The IAM namespaces whose operations this file reads: those Floci serves over the JSON and Query
|
||||||
# protocols and Smithy RPC v2 CBOR, and the REST ones whose routes Floci authorizes by operation.
|
# protocols and Smithy RPC v2 CBOR, and the REST ones whose routes Floci authorizes by operation.
|
||||||
NAMESPACES = (
|
NAMESPACES = (
|
||||||
"application-autoscaling", "aps", "athena", "autoscaling", "budgets", "cloudformation", "cloudtrail",
|
"apigateway", "application-autoscaling", "aps", "athena", "autoscaling", "budgets", "cloudformation", "cloudtrail",
|
||||||
"cloudwatch", "codebuild", "codedeploy", "codepipeline", "cognito-identity", "cognito-idp",
|
"cloudwatch", "codebuild", "codedeploy", "codepipeline", "cognito-identity", "cognito-idp",
|
||||||
"comprehend", "config", "datasync", "dms", "dsql", "ec2", "ecr", "ecs", "eks",
|
"comprehend", "config", "datasync", "dms", "dsql", "ec2", "ecr", "ecs", "eks",
|
||||||
"elasticfilesystem", "elasticloadbalancing", "elasticmapreduce",
|
"elasticfilesystem", "elasticloadbalancing", "elasticmapreduce",
|
||||||
@@ -107,7 +108,6 @@ NAMESPACES = (
|
|||||||
# Namespaces Floci serves whose operations list iam:PassRole but are not read here yet, each with
|
# Namespaces Floci serves whose operations list iam:PassRole but are not read here yet, each with
|
||||||
# why. `PassedRolesCoverageTest` fails for a namespace Floci serves that is in neither list.
|
# why. `PassedRolesCoverageTest` fails for a namespace Floci serves that is in neither list.
|
||||||
NOT_COVERED = {
|
NOT_COVERED = {
|
||||||
"apigateway": "authorized by HTTP method, so no request is checked as one of these operations",
|
|
||||||
"access-analyzer": "REST routes no rule maps yet",
|
"access-analyzer": "REST routes no rule maps yet",
|
||||||
"airflow": "REST routes no rule maps yet",
|
"airflow": "REST routes no rule maps yet",
|
||||||
"appconfig": "CreateExtension and UpdateExtension pass a role in Actions{}[].RoleArn, a map of lists, which this file "
|
"appconfig": "CreateExtension and UpdateExtension pass a role in Actions{}[].RoleArn, a map of lists, which this file "
|
||||||
@@ -147,8 +147,10 @@ BY_NAME_DOC_RE = re.compile(r"\bname or (the |its )?(full )?(ARN|Amazon Resource
|
|||||||
READ_PROTOCOLS = {"json", "query", "rest-json", "rest-xml", "smithy-rpc-v2-cbor"}
|
READ_PROTOCOLS = {"json", "query", "rest-json", "rest-xml", "smithy-rpc-v2-cbor"}
|
||||||
# How a vendored member path is written: dotted segments, a list step as `[]` or `[Name]` when its
|
# How a vendored member path is written: dotted segments, a list step as `[]` or `[Name]` when its
|
||||||
# shape names its members, a map step as `{}` for every value or `{KEY}` for one key's.
|
# shape names its members, a map step as `{}` for every value or `{KEY}` for one key's.
|
||||||
MEMBER_PATH_RE = re.compile(r"^[A-Za-z][A-Za-z0-9_]*(\[[A-Za-z0-9_]*\]|\{[A-Za-z0-9_]*\})?"
|
MEMBER_PATH_RE = re.compile(r"^[A-Za-z][A-Za-z0-9_]*(\[[A-Za-z0-9_]*\]|\[[A-Za-z0-9_]+=/[A-Za-z0-9_]+\]"
|
||||||
r"(\.[A-Za-z][A-Za-z0-9_]*(\[[A-Za-z0-9_]*\]|\{[A-Za-z0-9_]*\})?)*$")
|
r"|\{[A-Za-z0-9_]*\})?"
|
||||||
|
r"(\.[A-Za-z][A-Za-z0-9_]*(\[[A-Za-z0-9_]*\]|\[[A-Za-z0-9_]+=/[A-Za-z0-9_]+\]"
|
||||||
|
r"|\{[A-Za-z0-9_]*\})?)*$")
|
||||||
NAMESPACE_RE = re.compile(r"^[a-z0-9][a-z0-9-]{0,63}$")
|
NAMESPACE_RE = re.compile(r"^[a-z0-9][a-z0-9-]{0,63}$")
|
||||||
OPERATION_RE = re.compile(r"^[a-z0-9-]+:[A-Za-z][A-Za-z0-9]{0,127}$")
|
OPERATION_RE = re.compile(r"^[a-z0-9-]+:[A-Za-z][A-Za-z0-9]{0,127}$")
|
||||||
SERVICE_RE = re.compile(r"^[a-z0-9][a-z0-9.-]*$")
|
SERVICE_RE = re.compile(r"^[a-z0-9][a-z0-9.-]*$")
|
||||||
@@ -424,14 +426,22 @@ MEMBER_SERVICES = {
|
|||||||
# and the guide's page on runtime roles that access to StepExecutionRoleArn's runtime role is controlled
|
# and the guide's page on runtime roles that access to StepExecutionRoleArn's runtime role is controlled
|
||||||
# by a condition key ("You can control access to the runtime role with the condition key
|
# by a condition key ("You can control access to the runtime role with the condition key
|
||||||
# elasticmapreduce:ExecutionRoleArn"), so it passes none; tools/aws/fetch_emr_roles.py vendors those pages and
|
# elasticmapreduce:ExecutionRoleArn"), so it passes none; tools/aws/fetch_emr_roles.py vendors those pages and
|
||||||
# `vendored_role` reads them. Each file is written by its own script from the pages, unchanged, and nothing about an
|
# `vendored_role` reads them. And granted for API Gateway: its API references say which members take a role where no
|
||||||
|
# name the rule knows does ("To specify an IAM role for API Gateway to assume, use the role's Amazon Resource Name
|
||||||
|
# (ARN)"), that a REST API update names the property it changes by its patch operation's path ("the path for this
|
||||||
|
# property is /name"), that an import's body is an OpenAPI definition, and its developer guide which of that
|
||||||
|
# definition's extensions name a role and where each sits ("an extended property of the OpenAPI Operation object");
|
||||||
|
# tools/aws/fetch_apigateway_roles.py vendors those pages and `vendored_role_names`, `patch_role_members` and
|
||||||
|
# `document_members` read them. Each file is written by its own script from the pages, unchanged, and nothing about an
|
||||||
# operation is stated here.
|
# operation is stated here.
|
||||||
ROLE_SOURCES: dict[str, Path] = {
|
ROLE_SOURCES: dict[str, Path] = {
|
||||||
|
"apigateway": REPO_ROOT / "tools/aws/sources/apigateway-roles.json",
|
||||||
"eks": REPO_ROOT / "tools/aws/sources/eks-roles.json",
|
"eks": REPO_ROOT / "tools/aws/sources/eks-roles.json",
|
||||||
"elasticmapreduce": REPO_ROOT / "tools/aws/sources/emr-roles.json",
|
"elasticmapreduce": REPO_ROOT / "tools/aws/sources/emr-roles.json",
|
||||||
}
|
}
|
||||||
# The script that writes each namespace's role source, whose pages `verify_role_sources` reads it against.
|
# The script that writes each namespace's role source, whose pages `verify_role_sources` reads it against.
|
||||||
ROLE_FETCHERS = {
|
ROLE_FETCHERS = {
|
||||||
|
"apigateway": fetch_apigateway_roles,
|
||||||
"eks": fetch_eks_roles,
|
"eks": fetch_eks_roles,
|
||||||
"elasticmapreduce": fetch_emr_roles,
|
"elasticmapreduce": fetch_emr_roles,
|
||||||
}
|
}
|
||||||
@@ -524,7 +534,7 @@ def readable(model: dict) -> bool:
|
|||||||
return bool(READ_PROTOCOLS & set(metadata.get("protocols") or [metadata.get("protocol")]))
|
return bool(READ_PROTOCOLS & set(metadata.get("protocols") or [metadata.get("protocol")]))
|
||||||
|
|
||||||
|
|
||||||
def role_members(model: dict, operation: str) -> dict[str, bool]:
|
def role_members(model: dict, operation: str, named: frozenset[str] = frozenset()) -> dict[str, bool]:
|
||||||
"""The members of the operation's request the rule reads, as vendored paths, each with whether
|
"""The members of the operation's request the rule reads, as vendored paths, each with whether
|
||||||
it takes a role by name. An XML body is read by the elements botocore names, a list's elements by
|
it takes a role by name. An XML body is read by the elements botocore names, a list's elements by
|
||||||
the name of its member or as `member`, so a role member reached through a map or a flattened list,
|
the name of its member or as `member`, so a role member reached through a map or a flattened list,
|
||||||
@@ -534,41 +544,51 @@ def role_members(model: dict, operation: str) -> dict[str, bool]:
|
|||||||
return {}
|
return {}
|
||||||
root = model["shapes"][spec["input"]["shape"]]
|
root = model["shapes"][spec["input"]["shape"]]
|
||||||
payload = root.get("payload")
|
payload = root.get("payload")
|
||||||
xml = "rest-xml" in (model["metadata"].get("protocols") or [model["metadata"].get("protocol")])
|
protocols = model["metadata"].get("protocols") or [model["metadata"].get("protocol")]
|
||||||
|
xml = "rest-xml" in protocols
|
||||||
|
# A REST JSON model's body member is also read by its botocore name where its wire name differs: Floci serves API
|
||||||
|
# Gateway v2 over JSON 1.1 too ("AmazonApiGatewayV2."), whose bodies name members as botocore does
|
||||||
|
# (CredentialsArn for credentialsArn), and its handler takes either spelling as the same member.
|
||||||
|
by_member_name = "rest-json" in protocols
|
||||||
found: dict[str, bool] = {}
|
found: dict[str, bool] = {}
|
||||||
|
|
||||||
def unnested(shape: dict) -> bool:
|
def unnested(shape: dict) -> bool:
|
||||||
return xml and (shape["type"] == "map" or (shape["type"] == "list" and bool(shape.get("flattened"))))
|
return xml and (shape["type"] == "map" or (shape["type"] == "list" and bool(shape.get("flattened"))))
|
||||||
|
|
||||||
def walk(shape_name: str, prefix: str, top: bool, seen: frozenset, through: bool) -> None:
|
def walk(shape_name: str, prefixes: tuple[str, ...], top: bool, seen: frozenset, through: bool) -> None:
|
||||||
if shape_name in seen:
|
if shape_name in seen:
|
||||||
return
|
return
|
||||||
shape = model["shapes"][shape_name]
|
shape = model["shapes"][shape_name]
|
||||||
seen = seen | {shape_name}
|
seen = seen | {shape_name}
|
||||||
if shape["type"] in ("list", "map"):
|
if shape["type"] in ("list", "map"):
|
||||||
nested = shape["member" if shape["type"] == "list" else "value"]["shape"]
|
nested = shape["member" if shape["type"] == "list" else "value"]["shape"]
|
||||||
walk(nested, prefix + _step(shape), False, seen, through or unnested(shape))
|
walk(nested, tuple(prefix + _step(shape) for prefix in prefixes), False, seen,
|
||||||
|
through or unnested(shape))
|
||||||
elif shape["type"] == "structure":
|
elif shape["type"] == "structure":
|
||||||
for name, member in shape.get("members", {}).items():
|
for name, member in shape.get("members", {}).items():
|
||||||
if top and member.get("location") not in BODY_LOCATIONS:
|
if top and member.get("location") not in BODY_LOCATIONS:
|
||||||
continue
|
continue
|
||||||
serialized = member.get("locationName", name)
|
serialized = member.get("locationName", name)
|
||||||
path = f"{prefix}.{serialized}" if prefix else serialized
|
spellings = (serialized, name) if by_member_name and name != serialized else (serialized,)
|
||||||
if _is_role_member(name, model, member["shape"]):
|
paths = tuple(dict.fromkeys(f"{prefix}.{spelling}" if prefix else spelling
|
||||||
|
for prefix in prefixes for spelling in spellings))
|
||||||
|
if _is_role_member(name, model, member["shape"]) or (
|
||||||
|
serialized in named and _leaf(model, member["shape"]) is not None):
|
||||||
if through or unnested(model["shapes"][member["shape"]]):
|
if through or unnested(model["shapes"][member["shape"]]):
|
||||||
raise ValueError(f"{operation}'s {path} reaches the elements of a map or a flattened "
|
raise ValueError(f"{operation}'s {paths[0]} reaches the elements of a map or a flattened "
|
||||||
"list, which PassedRoles does not read in an XML body")
|
"list, which PassedRoles does not read in an XML body")
|
||||||
leaf = path + _step(model["shapes"][member["shape"]])
|
|
||||||
by_name = _takes_name(name, member, model)
|
by_name = _takes_name(name, member, model)
|
||||||
found[leaf] = found.get(leaf, False) or by_name
|
for path in paths:
|
||||||
|
leaf = path + _step(model["shapes"][member["shape"]])
|
||||||
|
found[leaf] = found.get(leaf, False) or by_name
|
||||||
else:
|
else:
|
||||||
walk(member["shape"], path, False, seen, through)
|
walk(member["shape"], paths, False, seen, through)
|
||||||
|
|
||||||
if payload is not None:
|
if payload is not None:
|
||||||
member = root["members"][payload]
|
member = root["members"][payload]
|
||||||
walk(member["shape"], "", False, frozenset(), False)
|
walk(member["shape"], ("",), False, frozenset(), False)
|
||||||
else:
|
else:
|
||||||
walk(spec["input"]["shape"], "", True, frozenset(), False)
|
walk(spec["input"]["shape"], ("",), True, frozenset(), False)
|
||||||
return found
|
return found
|
||||||
|
|
||||||
|
|
||||||
@@ -620,11 +640,86 @@ def member_exists(model: dict, operation: str, path: str) -> bool:
|
|||||||
|
|
||||||
|
|
||||||
@functools.cache
|
@functools.cache
|
||||||
|
def _role_document(namespace: str) -> dict:
|
||||||
|
"""The namespace's vendored role source (`ROLE_SOURCES`); empty for a namespace it is not granted."""
|
||||||
|
path = ROLE_SOURCES.get(namespace)
|
||||||
|
return {} if path is None else json.loads(path.read_text(encoding="utf-8"))
|
||||||
|
|
||||||
|
|
||||||
def _role_source(namespace: str) -> tuple[dict, ...]:
|
def _role_source(namespace: str) -> tuple[dict, ...]:
|
||||||
"""The members the namespace's vendored role source (`ROLE_SOURCES`) gives; none for a namespace it is not
|
"""The members the namespace's vendored role source (`ROLE_SOURCES`) gives; none for a namespace it is not
|
||||||
granted."""
|
granted."""
|
||||||
path = ROLE_SOURCES.get(namespace)
|
return tuple(_role_document(namespace).get("members", ()))
|
||||||
return () if path is None else tuple(json.loads(path.read_text(encoding="utf-8"))["members"])
|
|
||||||
|
|
||||||
|
def vendored_role_names(namespace: str, client: str) -> frozenset[str]:
|
||||||
|
"""The member names the namespace's vendored role source says take a role in the SDK client's requests, where the
|
||||||
|
rule's names do not reach: API Gateway's `credentials`, "To specify an IAM Role for API Gateway to assume, use
|
||||||
|
the role's Amazon Resource Name (ARN)"."""
|
||||||
|
return frozenset(entry["member"] for entry in _role_document(namespace).get("roleMembers", ())
|
||||||
|
if entry["model"] == client)
|
||||||
|
|
||||||
|
|
||||||
|
def patch_role_members(namespace: str, client: str, model: dict, operation: str,
|
||||||
|
named: frozenset[str]) -> dict[str, bool]:
|
||||||
|
"""The patch operations of an update that change a role member of the resource it updates, where the namespace's
|
||||||
|
vendored role source says a patch operation names the property it changes by its path ("the path for this
|
||||||
|
property is /name"): `patchOperations[path=/credentials].value` for UpdateIntegration, whose Integration's
|
||||||
|
credentials name a role. A top-level member of the operation's output shape names a role by the rule's names or
|
||||||
|
the vendored ones."""
|
||||||
|
patch = _role_document(namespace).get("patchPath")
|
||||||
|
spec = model["operations"].get(operation)
|
||||||
|
if patch is None or patch["model"] != client or spec is None or "output" not in spec:
|
||||||
|
return {}
|
||||||
|
request = model["shapes"][spec["input"]["shape"]]["members"]
|
||||||
|
operations = request.get("patchOperations")
|
||||||
|
if operations is None:
|
||||||
|
return {}
|
||||||
|
element = model["shapes"][model["shapes"][operations["shape"]]["member"]["shape"]]
|
||||||
|
if not {"path", "value"} <= set(element.get("members", {})):
|
||||||
|
return {}
|
||||||
|
found = {}
|
||||||
|
for name, member in model["shapes"][spec["output"]["shape"]].get("members", {}).items():
|
||||||
|
serialized = member.get("locationName", name)
|
||||||
|
if model["shapes"][member["shape"]]["type"] == "string" and (
|
||||||
|
_is_role_member(name, model, member["shape"]) or serialized in named):
|
||||||
|
found[f"patchOperations[path=/{serialized}].value"] = False
|
||||||
|
return found
|
||||||
|
|
||||||
|
|
||||||
|
def document_members(namespace: str, client: str, model: dict, operation: str) -> dict[str, dict]:
|
||||||
|
"""The members of the operation's request the namespace's vendored role source says hold an OpenAPI definition,
|
||||||
|
each with where the definition names a role: the extensions an Operation object or a security scheme carries,
|
||||||
|
each with its property naming one, and the extension standing for the ANY method's Operation object. A member
|
||||||
|
that is the request's payload is the request's whole body (`payload`)."""
|
||||||
|
document = _role_document(namespace)
|
||||||
|
spec = model["operations"].get(operation)
|
||||||
|
if spec is None or "input" not in spec:
|
||||||
|
return {}
|
||||||
|
request = model["shapes"][spec["input"]["shape"]]
|
||||||
|
found = {}
|
||||||
|
for entry in document.get("documents", ()):
|
||||||
|
if entry["model"] != client or entry["operation"] != operation:
|
||||||
|
continue
|
||||||
|
members = [(name, member) for name, member in request.get("members", {}).items()
|
||||||
|
if member.get("locationName", name) == entry["member"] or name == entry["member"]]
|
||||||
|
if len(members) != 1:
|
||||||
|
raise ValueError(f"{namespace}:{operation}: the vendored role source names its {entry['member']}, "
|
||||||
|
f"which its request does not have")
|
||||||
|
name, member = members[0]
|
||||||
|
openapi: dict = {"operation": {}, "securityScheme": {}}
|
||||||
|
for extension in document.get("extensions", ()):
|
||||||
|
openapi[extension["on"]][extension["extension"]] = extension["member"]
|
||||||
|
openapi["anyMethod"] = document["anyMethod"]["extension"]
|
||||||
|
field = {"openApi": openapi}
|
||||||
|
if request.get("payload") == name:
|
||||||
|
field["payload"] = True
|
||||||
|
found[member.get("locationName", name)] = field
|
||||||
|
continue
|
||||||
|
# Each spelling a JSON body names it by, as role_members reads a REST JSON model's members.
|
||||||
|
for spelling in dict.fromkeys((member.get("locationName", name), name)):
|
||||||
|
found[spelling] = field
|
||||||
|
return found
|
||||||
|
|
||||||
|
|
||||||
def vendored_role(operation: str, path: str, models: dict[str, dict]) -> dict | None:
|
def vendored_role(operation: str, path: str, models: dict[str, dict]) -> dict | None:
|
||||||
@@ -721,9 +816,16 @@ def entry_for(operation: str, passed_to: list[str], models: dict[str, dict]) ->
|
|||||||
if not any(name in model["operations"] for model in models.values()):
|
if not any(name in model["operations"] for model in models.values()):
|
||||||
return {"passedTo": passed_to, "notRead": NOT_IN_BOTOCORE}
|
return {"passedTo": passed_to, "notRead": NOT_IN_BOTOCORE}
|
||||||
members: dict[str, bool] = {}
|
members: dict[str, bool] = {}
|
||||||
for model in models.values():
|
fields: dict[str, dict] = {}
|
||||||
for path, by_name in role_members(model, name).items():
|
namespace = namespace_of(operation)
|
||||||
|
for client, model in models.items():
|
||||||
|
named = vendored_role_names(namespace, client)
|
||||||
|
for path, by_name in (role_members(model, name, named)
|
||||||
|
| patch_role_members(namespace, client, model, name, named)).items():
|
||||||
members[path] = members.get(path, False) or by_name
|
members[path] = members.get(path, False) or by_name
|
||||||
|
for path, field in document_members(namespace, client, model, name).items():
|
||||||
|
members[path] = False
|
||||||
|
fields[path] = field
|
||||||
excluded = _overrides_for(EXCLUDED_MEMBERS, operation)
|
excluded = _overrides_for(EXCLUDED_MEMBERS, operation)
|
||||||
for path in excluded:
|
for path in excluded:
|
||||||
members.pop(path, None)
|
members.pop(path, None)
|
||||||
@@ -757,6 +859,7 @@ def entry_for(operation: str, passed_to: list[str], models: dict[str, dict]) ->
|
|||||||
role["byName"] = True
|
role["byName"] = True
|
||||||
if vendored.get("instanceProfile"):
|
if vendored.get("instanceProfile"):
|
||||||
role["instanceProfile"] = True
|
role["instanceProfile"] = True
|
||||||
|
role.update(fields.get(path, {}))
|
||||||
roles.append(role)
|
roles.append(role)
|
||||||
return {"passedTo": passed_to, "roles": roles}
|
return {"passedTo": passed_to, "roles": roles}
|
||||||
|
|
||||||
@@ -925,8 +1028,10 @@ def validate(document: dict) -> list[str]:
|
|||||||
if service is not None and service not in passed_to:
|
if service is not None and service not in passed_to:
|
||||||
problems.append(f"{operation}: the role at {path} goes to {service}, which the reference "
|
problems.append(f"{operation}: the role at {path} goes to {service}, which the reference "
|
||||||
f"does not name")
|
f"does not name")
|
||||||
if (set(role) - {"member", "passedTo", "byName", "instanceProfile"} or role.get("byName", True) is not True
|
if (set(role) - {"member", "passedTo", "byName", "instanceProfile", "openApi", "payload"}
|
||||||
or role.get("instanceProfile", True) is not True):
|
or role.get("byName", True) is not True or role.get("instanceProfile", True) is not True
|
||||||
|
or role.get("payload", True) is not True
|
||||||
|
or not isinstance(role.get("openApi", {}), dict)):
|
||||||
problems.append(f"{operation}: the role at {path} carries an unknown field")
|
problems.append(f"{operation}: the role at {path} carries an unknown field")
|
||||||
return problems
|
return problems
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,109 @@
|
|||||||
|
{
|
||||||
|
"_source": {
|
||||||
|
"pages": [
|
||||||
|
"https://docs.aws.amazon.com/apigateway/latest/api/API_Authorizer.html",
|
||||||
|
"https://docs.aws.amazon.com/apigateway/latest/api/API_ImportRestApi.html",
|
||||||
|
"https://docs.aws.amazon.com/apigateway/latest/api/API_Integration.html",
|
||||||
|
"https://docs.aws.amazon.com/apigateway/latest/api/API_PatchOperation.html",
|
||||||
|
"https://docs.aws.amazon.com/apigateway/latest/api/API_PutRestApi.html",
|
||||||
|
"https://docs.aws.amazon.com/apigateway/latest/developerguide/api-gateway-swagger-extensions-any-method.html",
|
||||||
|
"https://docs.aws.amazon.com/apigateway/latest/developerguide/api-gateway-swagger-extensions-authorizer.html",
|
||||||
|
"https://docs.aws.amazon.com/apigateway/latest/developerguide/api-gateway-swagger-extensions-integration.html",
|
||||||
|
"https://docs.aws.amazon.com/apigatewayv2/latest/api-reference/apis-apiid-authorizers-authorizerid.html",
|
||||||
|
"https://docs.aws.amazon.com/apigatewayv2/latest/api-reference/apis-apiid-integrations-integrationid.html",
|
||||||
|
"https://docs.aws.amazon.com/apigatewayv2/latest/api-reference/apis-apiid.html",
|
||||||
|
"https://docs.aws.amazon.com/apigatewayv2/latest/api-reference/apis.html"
|
||||||
|
],
|
||||||
|
"fetcher": "tools/aws/fetch_apigateway_roles.py",
|
||||||
|
"retrieved": "2026-11-27",
|
||||||
|
"note": "Each description copied as it stands from the API Gateway API references and developer guide: the members of a resource type that take a role, how a REST API update's patch operation names a property, the imports whose body is an OpenAPI definition, and the OpenAPI extensions and their properties that name a role, with what each extends."
|
||||||
|
},
|
||||||
|
"roleMembers": [
|
||||||
|
{
|
||||||
|
"model": "apigateway",
|
||||||
|
"type": "Integration",
|
||||||
|
"member": "credentials",
|
||||||
|
"page": "https://docs.aws.amazon.com/apigateway/latest/api/API_Integration.html",
|
||||||
|
"description": "Specifies the credentials required for the integration, if any. For AWS integrations, three options are available. To specify an IAM Role for API Gateway to assume, use the role's Amazon Resource Name (ARN). To require that the caller's identity be passed through from the request, specify the string arn:aws:iam::\\*:user/\\* . To use resource-based permissions on supported AWS services, specify null."
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"model": "apigateway",
|
||||||
|
"type": "Authorizer",
|
||||||
|
"member": "authorizerCredentials",
|
||||||
|
"page": "https://docs.aws.amazon.com/apigateway/latest/api/API_Authorizer.html",
|
||||||
|
"description": "Specifies the required credentials as an IAM role for API Gateway to invoke the authorizer. To specify an IAM role for API Gateway to assume, use the role's Amazon Resource Name (ARN). To use resource-based permissions on the Lambda function, specify null. This property is not supported for JWT authorizers."
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"model": "apigatewayv2",
|
||||||
|
"type": "Integration",
|
||||||
|
"member": "credentialsArn",
|
||||||
|
"page": "https://docs.aws.amazon.com/apigatewayv2/latest/api-reference/apis-apiid-integrations-integrationid.html",
|
||||||
|
"description": "Specifies the credentials required for the integration, if any. For AWS integrations, three options are available. To specify an IAM Role for API Gateway to assume, use the role's Amazon Resource Name (ARN). To require that the caller's identity be passed through from the request, specify the string arn:aws:iam::*:user/* . To use resource-based permissions on supported AWS services, don't specify this parameter."
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"model": "apigatewayv2",
|
||||||
|
"type": "Authorizer",
|
||||||
|
"member": "authorizerCredentialsArn",
|
||||||
|
"page": "https://docs.aws.amazon.com/apigatewayv2/latest/api-reference/apis-apiid-authorizers-authorizerid.html",
|
||||||
|
"description": "Specifies the required credentials as an IAM role for API Gateway to invoke the authorizer. To specify an IAM role for API Gateway to assume, use the role's Amazon Resource Name (ARN). To use resource-based permissions on the Lambda function, don't specify this parameter. Supported only for REQUEST authorizers."
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"patchPath": {
|
||||||
|
"model": "apigateway",
|
||||||
|
"page": "https://docs.aws.amazon.com/apigateway/latest/api/API_PatchOperation.html",
|
||||||
|
"description": "The op operation's target, as identified by a JSON Pointer value that references a location within the targeted resource. For example, if the target resource has an updateable property of { \"name\":\"value\"}, the path for this property is /name. If the name property value is a JSON object (e.g., { \"name\": { \"child/name\": \"child-value\"}}), the path for the child/name property will be /name/child~1name. Any slash (\"/\") character appearing in path names must be escaped with \"~1\", as shown in the example above. Each op operation can have only one path associated with it."
|
||||||
|
},
|
||||||
|
"documents": [
|
||||||
|
{
|
||||||
|
"model": "apigateway",
|
||||||
|
"operation": "ImportRestApi",
|
||||||
|
"member": "body",
|
||||||
|
"page": "https://docs.aws.amazon.com/apigateway/latest/api/API_ImportRestApi.html",
|
||||||
|
"description": "The POST request body containing external API definitions. Currently, only OpenAPI definition JSON/YAML files are supported. The maximum size of the API definition file is 6MB. Required: Yes"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"model": "apigateway",
|
||||||
|
"operation": "PutRestApi",
|
||||||
|
"member": "body",
|
||||||
|
"page": "https://docs.aws.amazon.com/apigateway/latest/api/API_PutRestApi.html",
|
||||||
|
"description": "The PUT request body containing external API definitions. Currently, only OpenAPI definition JSON/YAML files are supported. The maximum size of the API definition file is 6MB. Required: Yes"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"model": "apigatewayv2",
|
||||||
|
"operation": "ImportApi",
|
||||||
|
"member": "body",
|
||||||
|
"page": "https://docs.aws.amazon.com/apigatewayv2/latest/api-reference/apis.html",
|
||||||
|
"description": "The OpenAPI definition. Supported only for HTTP APIs."
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"model": "apigatewayv2",
|
||||||
|
"operation": "ReimportApi",
|
||||||
|
"member": "body",
|
||||||
|
"page": "https://docs.aws.amazon.com/apigatewayv2/latest/api-reference/apis-apiid.html",
|
||||||
|
"description": "The OpenAPI definition. Supported only for HTTP APIs."
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"extensions": [
|
||||||
|
{
|
||||||
|
"extension": "x-amazon-apigateway-integration",
|
||||||
|
"member": "credentials",
|
||||||
|
"page": "https://docs.aws.amazon.com/apigateway/latest/developerguide/api-gateway-swagger-extensions-integration.html",
|
||||||
|
"on": "operation",
|
||||||
|
"placement": "This extension is an extended property of the OpenAPI Operation object.",
|
||||||
|
"description": "For AWS IAM role-based credentials, specify the ARN of an appropriate IAM role. If unspecified, credentials default to resource-based permissions that must be added manually to allow the API to access the resource. For more information, see Granting Permissions Using a Resource Policy . Note: When using IAM credentials, make sure that AWS STS Regional endpoints are enabled for the Region where this API is deployed for best performance."
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"extension": "x-amazon-apigateway-authorizer",
|
||||||
|
"member": "authorizerCredentials",
|
||||||
|
"page": "https://docs.aws.amazon.com/apigateway/latest/developerguide/api-gateway-swagger-extensions-authorizer.html",
|
||||||
|
"on": "securityScheme",
|
||||||
|
"placement": "This extension applies to the security definition in OpenAPI 2 and the security scheme in OpenAPI 3 .",
|
||||||
|
"description": "The credentials required for invoking the authorizer, if any, in the form of an ARN of an IAM execution role. For example, \"arn:aws:iam:: account-id : IAM_role \"."
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"anyMethod": {
|
||||||
|
"extension": "x-amazon-apigateway-any-method",
|
||||||
|
"page": "https://docs.aws.amazon.com/apigateway/latest/developerguide/api-gateway-swagger-extensions-any-method.html",
|
||||||
|
"description": "x-amazon-apigateway-any-method object Specifies the OpenAPI Operation Object for the API Gateway catch-all ANY method in an OpenAPI Path Item Object ."
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,96 @@
|
|||||||
|
#!/usr/bin/env python3
|
||||||
|
"""Tests for fetch_apigateway_roles.py, on pages in the API Gateway API references' and developer guide's markup."""
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
|
||||||
|
import fetch_apigateway_roles as f
|
||||||
|
|
||||||
|
ROLE_SENTENCE = ("Specifies the credentials required for the integration, if any. To specify an IAM Role for API Gateway "
|
||||||
|
"to assume, use the role's Amazon Resource Name (ARN).")
|
||||||
|
|
||||||
|
|
||||||
|
def rest_entry(anchor: str, member: str, description: str) -> str:
|
||||||
|
return (f'<dl><dt id="{anchor}"><span class="term"><b>{member}</b></span></dt><dd><p>{description}</p>'
|
||||||
|
f'<p>Type: String</p></dd></dl>')
|
||||||
|
|
||||||
|
|
||||||
|
def http_row(anchor: str, member: str, description: str) -> str:
|
||||||
|
return (f'<table><tr><td tabindex="-1" id="{anchor}" xreflabel="{member}"><code class="code">{member}</code></td>'
|
||||||
|
f'<td tabindex="-1"><p>string</p></td><td tabindex="-1">False</td><td tabindex="-1"><p>{description}</p>'
|
||||||
|
f'</td></tr></table>')
|
||||||
|
|
||||||
|
|
||||||
|
def extension_page(extension: str, placement: str, member: str, description: str) -> str:
|
||||||
|
return (f'<div id="main-col-body"><h1>{extension} object</h1><p>Specifies things. {placement}</p>'
|
||||||
|
f'<table><tr><td>type</td><td>string</td><td>The type.</td></tr>'
|
||||||
|
f'<tr><td>{member}</td><td>string</td><td>{description}</td></tr></table></div>')
|
||||||
|
|
||||||
|
|
||||||
|
DEFINITION = "Currently, only OpenAPI definition JSON/YAML files are supported."
|
||||||
|
PAGES = {
|
||||||
|
f.V1 + "API_Integration.html": rest_entry("apigw-Type-Integration-credentials", "credentials", ROLE_SENTENCE),
|
||||||
|
f.V1 + "API_Authorizer.html": rest_entry("apigw-Type-Authorizer-authorizerCredentials", "authorizerCredentials",
|
||||||
|
ROLE_SENTENCE.replace("Role", "role")),
|
||||||
|
f.V2 + "apis-apiid-integrations-integrationid.html": http_row(
|
||||||
|
"apis-apiid-integrations-integrationid-prop-integration-credentialsarn", "credentialsArn", ROLE_SENTENCE),
|
||||||
|
f.V2 + "apis-apiid-authorizers-authorizerid.html": http_row(
|
||||||
|
"apis-apiid-authorizers-authorizerid-prop-authorizer-authorizercredentialsarn", "authorizerCredentialsArn",
|
||||||
|
ROLE_SENTENCE),
|
||||||
|
f.PATCH_PAGE: rest_entry("apigw-Type-PatchOperation-path", "path", 'The op operation\'s target. For example, if '
|
||||||
|
'the target resource has an updateable property of {"name":"value"}, the path for this '
|
||||||
|
'property is /name.'),
|
||||||
|
f.V1 + "API_ImportRestApi.html": rest_entry("apigw-ImportRestApi-request-body", "body",
|
||||||
|
"The POST request body. " + DEFINITION),
|
||||||
|
f.V1 + "API_PutRestApi.html": rest_entry("apigw-PutRestApi-request-body", "body", "The PUT request body. " + DEFINITION),
|
||||||
|
f.V2 + "apis.html": http_row("apis-prop-importapiinput-body", "body", "The OpenAPI definition."),
|
||||||
|
f.V2 + "apis-apiid.html": http_row("apis-apiid-prop-reimportapiinput-body", "body", "The OpenAPI definition."),
|
||||||
|
f.GUIDE + "api-gateway-swagger-extensions-integration.html": extension_page(
|
||||||
|
"x-amazon-apigateway-integration", "This extension is an extended property of the OpenAPI Operation object.",
|
||||||
|
"credentials", "For AWS IAM role-based credentials, specify the ARN of an appropriate IAM role."),
|
||||||
|
f.GUIDE + "api-gateway-swagger-extensions-authorizer.html": extension_page(
|
||||||
|
"x-amazon-apigateway-authorizer", "This extension applies to the security definition in OpenAPI 2 and the "
|
||||||
|
"security scheme in OpenAPI 3 .", "authorizerCredentials",
|
||||||
|
"The credentials required for invoking the authorizer, if any, in the form of an ARN of an IAM execution role."),
|
||||||
|
f.ANY_METHOD_PAGE: '<div id="main-col-body"><h1>x-amazon-apigateway-any-method object</h1><p>Specifies the OpenAPI '
|
||||||
|
'Operation Object for the API Gateway catch-all ANY method in an OpenAPI <a href="#">Path Item '
|
||||||
|
'Object</a> .</p></div>',
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def test_each_role_member_document_and_extension_is_read_with_its_description():
|
||||||
|
built = f.build(lambda url: PAGES[url])
|
||||||
|
assert [(m["model"], m["type"], m["member"]) for m in built["roleMembers"]] == [
|
||||||
|
("apigateway", "Integration", "credentials"), ("apigateway", "Authorizer", "authorizerCredentials"),
|
||||||
|
("apigatewayv2", "Integration", "credentialsArn"), ("apigatewayv2", "Authorizer", "authorizerCredentialsArn")]
|
||||||
|
assert built["roleMembers"][0]["description"] == ROLE_SENTENCE
|
||||||
|
assert [(d["operation"], d["member"]) for d in built["documents"]] == [
|
||||||
|
("ImportRestApi", "body"), ("PutRestApi", "body"), ("ImportApi", "body"), ("ReimportApi", "body")]
|
||||||
|
assert "schema" not in built["documents"][2]
|
||||||
|
assert [(e["extension"], e["on"], e["member"]) for e in built["extensions"]] == [
|
||||||
|
("x-amazon-apigateway-integration", "operation", "credentials"),
|
||||||
|
("x-amazon-apigateway-authorizer", "securityScheme", "authorizerCredentials")]
|
||||||
|
assert built["anyMethod"]["extension"] == "x-amazon-apigateway-any-method"
|
||||||
|
assert built["patchPath"]["model"] == "apigateway"
|
||||||
|
|
||||||
|
|
||||||
|
def test_a_page_whose_layout_or_wording_changed_is_refused():
|
||||||
|
for url, page, message in (
|
||||||
|
(f.V1 + "API_Integration.html", "<dl></dl>", "has no entry"),
|
||||||
|
(f.V2 + "apis.html", "<table></table>", "has no property"),
|
||||||
|
(f.V1 + "API_Authorizer.html", rest_entry("apigw-Type-Authorizer-authorizerCredentials",
|
||||||
|
"authorizerCredentials", "Some credentials."), "takes a role"),
|
||||||
|
(f.PATCH_PAGE, rest_entry("apigw-Type-PatchOperation-path", "path", "A target."), "names a property"),
|
||||||
|
(f.GUIDE + "api-gateway-swagger-extensions-integration.html", "<div id=\"main-col-body\"></div>",
|
||||||
|
"what x-amazon-apigateway-integration extends"),
|
||||||
|
(f.ANY_METHOD_PAGE, "<div id=\"main-col-body\"></div>", "ANY method")):
|
||||||
|
changed = dict(PAGES, **{url: page})
|
||||||
|
with pytest.raises(ValueError, match=message):
|
||||||
|
f.build(lambda u: changed[u])
|
||||||
|
|
||||||
|
|
||||||
|
def test_the_file_is_stale_when_a_page_says_something_else():
|
||||||
|
vendored = f.build(lambda url: PAGES[url])
|
||||||
|
assert not f.stale(vendored, PAGES)
|
||||||
|
assert f.stale(vendored, dict(PAGES, **{f.V2 + "apis.html": http_row("apis-prop-importapiinput-body", "body",
|
||||||
|
"The OpenAPI definition, YAML or JSON.")}))
|
||||||
@@ -42,7 +42,7 @@ def corrections(monkeypatch):
|
|||||||
"""No corrections at all, so a test sees the rule alone and sets what it needs."""
|
"""No corrections at all, so a test sees the rule alone and sets what it needs."""
|
||||||
for name in ("BY_HAND", "NOT_READ", "EXCLUDED_MEMBERS", "EXTRA_MEMBERS", "MEMBER_SERVICES", "ROLE_SOURCES"):
|
for name in ("BY_HAND", "NOT_READ", "EXCLUDED_MEMBERS", "EXTRA_MEMBERS", "MEMBER_SERVICES", "ROLE_SOURCES"):
|
||||||
monkeypatch.setattr(r, name, {})
|
monkeypatch.setattr(r, name, {})
|
||||||
r._role_source.cache_clear()
|
r._role_document.cache_clear()
|
||||||
monkeypatch.setattr(r, "NAMESPACES", ("svc",))
|
monkeypatch.setattr(r, "NAMESPACES", ("svc",))
|
||||||
return monkeypatch
|
return monkeypatch
|
||||||
|
|
||||||
@@ -212,7 +212,7 @@ def role_source(corrections, tmp_path, members):
|
|||||||
path = tmp_path / "svc-roles.json"
|
path = tmp_path / "svc-roles.json"
|
||||||
path.write_text(json.dumps({"members": members}), encoding="utf-8")
|
path.write_text(json.dumps({"members": members}), encoding="utf-8")
|
||||||
corrections.setattr(r, "ROLE_SOURCES", {"svc": path})
|
corrections.setattr(r, "ROLE_SOURCES", {"svc": path})
|
||||||
r._role_source.cache_clear()
|
r._role_document.cache_clear()
|
||||||
|
|
||||||
|
|
||||||
def test_a_vendored_role_source_gives_each_member_the_service_its_role_is_for(corrections, tmp_path):
|
def test_a_vendored_role_source_gives_each_member_the_service_its_role_is_for(corrections, tmp_path):
|
||||||
@@ -271,6 +271,64 @@ def test_a_vendored_role_no_operation_reads_is_reported(corrections, tmp_path):
|
|||||||
"ROLE_SOURCES gives svc's Compute.goneRoleArn, which no operation there reads a role from"]
|
"ROLE_SOURCES gives svc's Compute.goneRoleArn, which no operation there reads a role from"]
|
||||||
|
|
||||||
|
|
||||||
|
def role_document(corrections, tmp_path, document):
|
||||||
|
path = tmp_path / "svc-roles.json"
|
||||||
|
path.write_text(json.dumps(document), encoding="utf-8")
|
||||||
|
corrections.setattr(r, "ROLE_SOURCES", {"svc": path})
|
||||||
|
r._role_document.cache_clear()
|
||||||
|
|
||||||
|
|
||||||
|
def api_model() -> dict:
|
||||||
|
"""An API Gateway like model: a put taking credentials, an update by patch operations, and an import whose body is
|
||||||
|
its payload."""
|
||||||
|
m = model({"PutThing": "PutIn", "UpdateThing": "UpdateIn", "ImportThing": "ImportIn"}, {
|
||||||
|
"PutIn": structure(credentials="String", name="String"),
|
||||||
|
"UpdateIn": structure(patchOperations="Patches"),
|
||||||
|
"Patches": {"type": "list", "member": {"shape": "Patch"}},
|
||||||
|
"Patch": structure(op="String", path="String", value="String"),
|
||||||
|
"ImportIn": {"type": "structure", "payload": "body", "members": {"body": {"shape": "Blob"}}},
|
||||||
|
"Blob": {"type": "blob"},
|
||||||
|
"Thing": structure(credentials="String", cloudwatchRoleArn="String", name="String")})
|
||||||
|
m["operations"]["PutThing"]["output"] = {"shape": "Thing"}
|
||||||
|
m["operations"]["UpdateThing"]["output"] = {"shape": "Thing"}
|
||||||
|
return {"svc": m}
|
||||||
|
|
||||||
|
|
||||||
|
API_SOURCE = {"roleMembers": [{"model": "svc", "type": "Thing", "member": "credentials"}],
|
||||||
|
"patchPath": {"model": "svc"},
|
||||||
|
"documents": [{"model": "svc", "operation": "ImportThing", "member": "body"}],
|
||||||
|
"extensions": [{"extension": "x-integration", "on": "operation", "member": "credentials"},
|
||||||
|
{"extension": "x-authorizer", "on": "securityScheme", "member": "authorizerCredentials"}],
|
||||||
|
"anyMethod": {"extension": "x-any-method"}}
|
||||||
|
|
||||||
|
|
||||||
|
def test_a_vendored_role_member_name_is_read_where_the_rule_does_not_reach(corrections, tmp_path):
|
||||||
|
role_document(corrections, tmp_path, API_SOURCE)
|
||||||
|
assert r.entry_for("svc:PutThing", ["svc"], api_model())["roles"] == [{"member": "credentials", "passedTo": "svc"}]
|
||||||
|
|
||||||
|
|
||||||
|
def test_an_update_by_patch_operations_reads_the_value_of_each_role_members_path(corrections, tmp_path):
|
||||||
|
# The updated resource's role members, by the rule's names and the vendored ones, by the path naming each.
|
||||||
|
role_document(corrections, tmp_path, API_SOURCE)
|
||||||
|
assert r.entry_for("svc:UpdateThing", ["svc"], api_model())["roles"] == [
|
||||||
|
{"member": "patchOperations[path=/cloudwatchRoleArn].value", "passedTo": "svc"},
|
||||||
|
{"member": "patchOperations[path=/credentials].value", "passedTo": "svc"}]
|
||||||
|
# Without the vendored patch path, an update's patch operations name nothing.
|
||||||
|
role_document(corrections, tmp_path, {key: value for key, value in API_SOURCE.items() if key != "patchPath"})
|
||||||
|
with pytest.raises(ValueError, match="no request member names a role"):
|
||||||
|
r.entry_for("svc:UpdateThing", ["svc"], api_model())
|
||||||
|
|
||||||
|
|
||||||
|
def test_an_import_whose_body_is_an_openapi_definition_reads_its_extensions(corrections, tmp_path):
|
||||||
|
role_document(corrections, tmp_path, API_SOURCE)
|
||||||
|
entry = r.entry_for("svc:ImportThing", ["svc"], api_model())
|
||||||
|
assert entry["roles"] == [{"member": "body", "passedTo": "svc", "payload": True, "openApi": {
|
||||||
|
"operation": {"x-integration": "credentials"}, "securityScheme": {"x-authorizer": "authorizerCredentials"},
|
||||||
|
"anyMethod": "x-any-method"}}]
|
||||||
|
assert r.validate({"_source": {}, "namespaces": {"svc": ["svc"]}, "notCovered": {}, "otherNamespaces": [],
|
||||||
|
"operations": {"svc:ImportThing": entry}}) == []
|
||||||
|
|
||||||
|
|
||||||
def test_several_services_need_a_member_service(corrections):
|
def test_several_services_need_a_member_service(corrections):
|
||||||
with pytest.raises(ValueError, match="MEMBER_SERVICES"):
|
with pytest.raises(ValueError, match="MEMBER_SERVICES"):
|
||||||
r.entry_for("svc:CreateThing", ["svc", "other"], SIMPLE)
|
r.entry_for("svc:CreateThing", ["svc", "other"], SIMPLE)
|
||||||
|
|||||||
Reference in new issue
Block a user