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 role an S3 replication configuration names (#9570)
PutBucketReplication passes the Role of its ReplicationConfiguration to S3, and AWS's Service Reference lists iam:PassRole for it with iam:PassedToService s3.amazonaws.com. Floci never checked it: the passed-roles table recorded the operation as not read, because its request body is XML, so a caller allowed s3:PutReplicationConfiguration could name any role. PassedRoles now reads a REST-XML body the way the condition keys of a REST-XML request are read (XmlParser.valuesAt): each member at the elements botocore serializes it as, below the document element, a list's elements under the name its shape gives them or as member. The text is read without surrounding whitespace, which S3 keeps in a Role it accepts. The generator reads rest-xml models too, and fails on a role member reached through a map or a flattened list, which an XML body does not nest as the table's paths do. Two operations move from notRead into the table: S3's PutBucketReplication (Role, to s3) and S3 Access Grants' CreateAccessGrantsLocation (IAMRoleArn, with no named service). Form parameters are now read only from a request the Query controller dispatches (IamActionRegistry.isQueryRequest: a form posted to the root path), as formParameters already documented. A request to another protocol's route is read as its handler reads it, whatever Content-Type it is sent with: an S3 replication configuration sent as application/x-www-form-urlencoded was parsed as one form key, so its role went unchecked while S3 stored the XML. The same held for tag-on-create and request resources reading a REST request's JSON body. S3's PutBucketReplication now refuses with MalformedXML a document that is not well-formed as a whole, or whose configuration does not hold exactly one Role with text, as it already counts each rule's Destination and Bucket. It read the first Role anywhere in the document from a parse that stopped where the configuration ended, so a second Role holding an element, or content after the configuration, left IAM reading no role while S3 stored the document. The table is keyed by operation, as the Service Reference lists it, but the enforcement filter and the Step Functions request checks looked it up by the IAM action. The two differ for PutBucketReplication, which is authorized as s3:PutReplicationConfiguration, so its entry would never have been found. Both now look roles up by the request's operation, as tag-on-create already does. DMS's ModifyDataProvider and ModifyMigrationProject, authorized as UpdateDataProvider and UpdateMigrationProject, are found the same way once Floci serves them.
This commit is contained in:
1 parent
e55988e705
commit
6ba4970877
23 files changed
+332
-75
No files matched your search
+10
-3
@@ -3147,8 +3147,15 @@ authorized as operations, is checked from a table generated from the Service Ref
|
||||
botocore's models, `src/main/resources/aws/iam-passed-roles.json`. A request member names a role
|
||||
when its name ends in `Role`, `RoleArn` or `RoleName` (or a plural, or one of those followed by
|
||||
`Update` or `Override`) and it holds a string, or a list or map of them; it is read from a JSON or
|
||||
CBOR body or from Query form parameters, in either list form, and its role is passed to the service
|
||||
the Service Reference names. That covers Athena, CloudTrail, CloudWatch metric streams (to
|
||||
CBOR body, from Query form parameters, in either list form, or from a REST-XML body by the elements
|
||||
botocore names, and its role is passed to the service the Service Reference names. Form parameters
|
||||
are read only from a request the Query protocol dispatches, a form posted to the root path, so a
|
||||
request to another protocol's route is read as its handler reads it whatever `Content-Type` it is
|
||||
sent with: an S3 replication configuration sent as a form is still read as its XML. The table is keyed
|
||||
by operation, as the Service Reference lists it, so S3's `PutBucketReplication`, which is authorized as
|
||||
`s3:PutReplicationConfiguration`, needs `iam:PassRole` for `s3.amazonaws.com` on the `Role` its
|
||||
`ReplicationConfiguration` names, and S3 Access Grants' `CreateAccessGrantsLocation` on its
|
||||
`IAMRoleArn`, with no `iam:PassedToService`. That covers Athena, CloudTrail, CloudWatch metric streams (to
|
||||
`streams.metrics.cloudwatch.amazonaws.com`), CodeBuild, CodeDeploy, CodePipeline, Cognito, Config,
|
||||
DataSync, ECR, Firehose, Glue, Kinesis Analytics, CloudWatch Logs, SageMaker, Secrets Manager,
|
||||
Budgets actions, SES, SSM, Service Catalog, SWF, Textract, Transcribe and Transfer Family, among
|
||||
@@ -3186,7 +3193,7 @@ when the caller may not pass the role.
|
||||
`StartAutomationExecution`, Config `PutRemediationConfigurations`); one the Service Reference
|
||||
passes roles from to several services without saying which member goes where (EMR `RunJobFlow`,
|
||||
whose `JobFlowRole` also names an instance profile, EKS `UpdateClusterConfig`, CloudWatch Logs
|
||||
`CreateImportTask`); one whose body is XML (S3 `PutBucketReplication`); and one the botocore
|
||||
`CreateImportTask`); and one the botocore
|
||||
models Floci is pinned to do not have yet (SSM `RegisterDefaultHostManagementConfiguration`,
|
||||
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
|
||||
|
||||
+1
-1
@@ -33,7 +33,7 @@
|
||||
|
||||
**RestoreObject** tracks temporary restore state for GLACIER and DEEP_ARCHIVE objects per version. HeadObject reports `x-amz-restore`, and GetObject reports it after restoration completes; ListObjects, ListObjectsV2, and ListObjectVersions report `RestoreStatus` when requested with `x-amz-optional-object-attributes: RestoreStatus`. New restores return 202, while extending a completed restore returns 200. Restores complete immediately by default; `FLOCI_SERVICES_S3_RESTORE_COMPLETION_DELAY_SECONDS` sets a delay for polling workflows. The temporary copy expires at the next UTC midnight after its requested days elapse from completion. GetObject returns `InvalidObjectState` (HTTP 403) before restoration, while it is in progress, and after the temporary copy expires.
|
||||
|
||||
**Replication** is configuration-only: the replication configuration is stored on the bucket and round-trips through `GetBucketReplication`, but no objects are actually replicated.
|
||||
**Replication** is configuration-only: the replication configuration is stored on the bucket and round-trips through `GetBucketReplication`, but no objects are actually replicated. `PutBucketReplication` refuses with `MalformedXML` a document that is not well-formed as a whole, or that does not have exactly one `Role` holding text directly in the configuration, as it refuses a rule without its own `Status` and `Destination/Bucket`.
|
||||
|
||||
`ListBuckets` includes each bucket's `BucketRegion` when `bucket-region`, `continuation-token`,
|
||||
`max-buckets`, or `prefix` is present. It uses the stored bucket region, falling back to the
|
||||
|
||||
@@ -784,7 +784,8 @@ public class IamConditionContextResolver {
|
||||
&& s3UploadEncryptionConditionContext(ctx) == null && s3Service.isResolvable();
|
||||
}
|
||||
|
||||
private static String bodyText(ContainerRequestContext ctx) {
|
||||
/** The request's body as UTF-8 text, buffered once and restored for its handler; null when it has none. */
|
||||
static String bodyText(ContainerRequestContext ctx) {
|
||||
byte[] body = bufferEntity(ctx);
|
||||
return body == null ? null : new String(body, StandardCharsets.UTF_8);
|
||||
}
|
||||
@@ -1236,8 +1237,9 @@ public class IamConditionContextResolver {
|
||||
}
|
||||
|
||||
/**
|
||||
* The decoded form parameters of a Query-protocol request, buffered once per request and
|
||||
* restored for the controller that reads the form next. A repeated key keeps its first
|
||||
* The decoded form parameters of a Query-protocol request, one the Query controller dispatches
|
||||
* ({@link IamActionRegistry#isQueryRequest}), buffered once per request and restored for the
|
||||
* controller that reads the form next; none for any other request. A repeated key keeps its first
|
||||
* value, which is the value the Query handlers read through {@code getFirst}, so the
|
||||
* resource this context describes is the resource the handler acts on.
|
||||
*/
|
||||
@@ -1255,16 +1257,17 @@ public class IamConditionContextResolver {
|
||||
});
|
||||
return parameters;
|
||||
}
|
||||
// Only a request the Query controller dispatches carries its members as a form. Another protocol's handler
|
||||
// reads its own body (S3's XML, a REST service's JSON) whatever Content-Type it is sent with, so a form type on
|
||||
// it names no members here.
|
||||
if (!IamActionRegistry.isQueryRequest(ctx)) {
|
||||
return Map.of();
|
||||
}
|
||||
Object cached = ctx.getProperty(BUFFERED_FORM_BODY);
|
||||
if (cached instanceof Map<?, ?> map) {
|
||||
return (Map<String, String>) map;
|
||||
}
|
||||
MediaType mediaType = ctx.getMediaType();
|
||||
if (mediaType == null
|
||||
|| !"application".equalsIgnoreCase(mediaType.getType())
|
||||
|| !"x-www-form-urlencoded".equalsIgnoreCase(mediaType.getSubtype())) {
|
||||
return Map.of();
|
||||
}
|
||||
byte[] body = bufferEntity(ctx);
|
||||
if (body == null || body.length == 0) {
|
||||
return Map.of();
|
||||
|
||||
@@ -629,8 +629,8 @@ public class IamEnforcementFilter implements ContainerRequestFilter {
|
||||
region, accountId, akid)) {
|
||||
return;
|
||||
}
|
||||
if (abortIfRolePassDenied(ctx, caller, principal, callerArns.orElse(null), action, credentialScope,
|
||||
region, accountId, akid)) {
|
||||
if (abortIfRolePassDenied(ctx, caller, principal, callerArns.orElse(null), action,
|
||||
resolvedOperation.operation(), credentialScope, region, accountId, akid)) {
|
||||
return;
|
||||
}
|
||||
if (abortIfConnectorPassDenied(ctx, caller, callerArns.orElse(null), resolvedOperation.operation(),
|
||||
@@ -967,13 +967,15 @@ public class IamEnforcementFilter implements ContainerRequestFilter {
|
||||
* service, when AWS's Service Reference names one, and the keys that say who is calling, which
|
||||
* {@code callerArns} writes when it is known. What a request names that holds roles, an instance
|
||||
* profile, a launch template or a task definition, is looked up in the request's account, as the
|
||||
* service resolves it; one that does not exist passes nothing, and the operation reports it. Returns
|
||||
* true when the request was aborted.
|
||||
* service resolves it; one that does not exist passes nothing, and the operation reports it. The roles are
|
||||
* read for the request's {@code operation}, which the table of passed roles is keyed by, as AWS's Service
|
||||
* Reference lists it: S3's {@code PutBucketReplication} is authorized as {@code s3:PutReplicationConfiguration}.
|
||||
* Returns true when the request was aborted.
|
||||
*/
|
||||
private boolean abortIfRolePassDenied(ContainerRequestContext ctx, CallerContext caller, RequestPrincipal principal,
|
||||
CallerArns callerArns, String action, String credentialScope,
|
||||
String region, String accountId, String akid) {
|
||||
for (PassedRoles.PassedRole passed : PassedRoles.of(action, ctx, lookupsFor(accountId, region))) {
|
||||
CallerArns callerArns, String action, String operation,
|
||||
String credentialScope, String region, String accountId, String akid) {
|
||||
for (PassedRoles.PassedRole passed : PassedRoles.of(operation, ctx, lookupsFor(accountId, region))) {
|
||||
Map<String, List<String>> context = new HashMap<>();
|
||||
if (callerArns != null) {
|
||||
callerArns.putPrincipalKeys(context);
|
||||
|
||||
@@ -252,10 +252,13 @@ final class PassedRoles {
|
||||
private PassedRoles() {
|
||||
}
|
||||
|
||||
/** The roles a request for {@code action} passes; empty when the operation passes none or the request names none. */
|
||||
static List<PassedRole> of(String action, ContainerRequestContext ctx, Lookups lookups) {
|
||||
List<PassedRole> byHand = byHand(action, ctx, lookups);
|
||||
return byHand != null ? byHand : fromTable(PassedRoleMembers.of(action), ctx, lookups);
|
||||
/**
|
||||
* The roles a request for {@code operation}, as {@code <namespace>:<Operation>}, passes; empty when the operation
|
||||
* passes none or the request names none.
|
||||
*/
|
||||
static List<PassedRole> of(String operation, ContainerRequestContext ctx, Lookups lookups) {
|
||||
List<PassedRole> byHand = byHand(operation, ctx, lookups);
|
||||
return byHand != null ? byHand : fromTable(PassedRoleMembers.of(operation), ctx, lookups);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -342,29 +345,78 @@ final class PassedRoles {
|
||||
|
||||
/**
|
||||
* The roles a request names in the members the table gives for its operation: from its form parameters
|
||||
* when it comes in the Query protocol, and from its JSON or CBOR body otherwise.
|
||||
* 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}).
|
||||
*/
|
||||
private static List<PassedRole> fromTable(List<PassedRoleMembers.Member> members, ContainerRequestContext ctx,
|
||||
Lookups lookups) {
|
||||
if (members == null) {
|
||||
return List.of();
|
||||
}
|
||||
UnaryOperator<String> named = name -> lookups.heldRoleArn(name).orElseGet(() -> lookups.roleArn(name));
|
||||
Map<String, String> form = IamConditionContextResolver.formParameters(ctx);
|
||||
return fromTable(members, form, form.isEmpty() ? jsonBody(ctx) : null,
|
||||
name -> lookups.heldRoleArn(name).orElseGet(() -> lookups.roleArn(name)));
|
||||
JsonNode body = form.isEmpty() ? jsonBody(ctx) : null;
|
||||
if (form.isEmpty() && body == null) {
|
||||
return fromXml(members, IamConditionContextResolver.bodyText(ctx), named);
|
||||
}
|
||||
return fromTable(members, form, body, named);
|
||||
}
|
||||
|
||||
/**
|
||||
* The roles a JSON request for {@code action} passes, for a call that is not an HTTP request of its own (a state
|
||||
* machine's task to its integrated service), read from the members the table gives its operation as a direct
|
||||
* request's are, a role given by name being the one {@code named} gives. An operation whose roles are read by
|
||||
* hand here, from a request of its own, is not read so, and fails.
|
||||
* The roles an XML body names in the members the table gives, read as a REST-XML request's condition keys are
|
||||
* ({@link XmlParser#valuesAt}): each member at the elements its path names below the document element, by the
|
||||
* names they are serialized under, a list's elements under the name its shape gives them or as {@code member}.
|
||||
* An element's text is read without the whitespace around it, which S3 keeps in a {@code Role} it accepts. None
|
||||
* when the body does not parse, which its operation refuses.
|
||||
*/
|
||||
static List<PassedRole> ofBody(String action, JsonNode body, UnaryOperator<String> named) {
|
||||
if (PassedRoleMembers.table().byHand().contains(action)) {
|
||||
throw new IllegalArgumentException(action + " passes roles read by hand, from a request of its own");
|
||||
private static List<PassedRole> fromXml(List<PassedRoleMembers.Member> members, String xml,
|
||||
UnaryOperator<String> named) {
|
||||
Map<PassedRoleMembers.Member, String> paths = new LinkedHashMap<>();
|
||||
for (PassedRoleMembers.Member member : members) {
|
||||
xmlPath(member.steps()).ifPresent(path -> paths.put(member, path));
|
||||
}
|
||||
List<PassedRoleMembers.Member> members = PassedRoleMembers.of(action);
|
||||
Map<String, List<String>> read = paths.isEmpty() ? null : XmlParser.valuesAt(xml, paths.values());
|
||||
if (read == null) {
|
||||
return List.of();
|
||||
}
|
||||
List<PassedRole> passed = new ArrayList<>();
|
||||
paths.forEach((member, path) -> {
|
||||
List<String> roles = read.getOrDefault(path, List.of()).stream().map(String::strip).toList();
|
||||
passed.addAll(passed(member.byName() ? heldOrNamedRoles(roles, named) : roles,
|
||||
member.passedTo() == null ? null : ServicePrincipals.of(member.passedTo())));
|
||||
});
|
||||
return passed;
|
||||
}
|
||||
|
||||
/**
|
||||
* The elements a member path names in an XML body, joined by dots; empty for one stepping into a map, which
|
||||
* {@code regen_iam_passed_roles.py} gives no REST-XML operation, as it gives none a flattened list.
|
||||
*/
|
||||
private static Optional<String> xmlPath(List<PassedRoleMembers.Step> steps) {
|
||||
List<String> elements = new ArrayList<>();
|
||||
for (PassedRoleMembers.Step step : steps) {
|
||||
if (step.into() == PassedRoleMembers.Into.MAP || step.into() == PassedRoleMembers.Into.KEY) {
|
||||
return Optional.empty();
|
||||
}
|
||||
elements.add(step.name());
|
||||
if (step.into() == PassedRoleMembers.Into.LIST) {
|
||||
elements.add(step.key().isEmpty() ? "member" : step.key());
|
||||
}
|
||||
}
|
||||
return Optional.of(String.join(".", elements));
|
||||
}
|
||||
|
||||
/**
|
||||
* The roles a JSON request for {@code operation} passes, for a call that is not an HTTP request of its own (a
|
||||
* state machine's task to its integrated service), read from the members the table gives the operation as a
|
||||
* direct request's are, a role given by name being the one {@code named} gives. An operation whose roles are
|
||||
* read by hand here, from a request of its own, is not read so, and fails.
|
||||
*/
|
||||
static List<PassedRole> ofBody(String operation, JsonNode body, UnaryOperator<String> named) {
|
||||
if (PassedRoleMembers.table().byHand().contains(operation)) {
|
||||
throw new IllegalArgumentException(operation + " passes roles read by hand, from a request of its own");
|
||||
}
|
||||
List<PassedRoleMembers.Member> members = PassedRoleMembers.of(operation);
|
||||
return members == null ? List.of() : fromTable(members, Map.of(), body, named);
|
||||
}
|
||||
|
||||
|
||||
@@ -51,7 +51,7 @@ public final class RequestChecks {
|
||||
for (String resource : resources) {
|
||||
contexts.forEach(context -> checks.add(new Check(action, resource, Map.copyOf(context))));
|
||||
}
|
||||
for (PassedRoles.PassedRole passed : PassedRoles.ofBody(action, body,
|
||||
for (PassedRoles.PassedRole passed : PassedRoles.ofBody(operation, body,
|
||||
name -> new AwsArnUtils.Arn(partition, "iam", "", accountId, "role/" + name).toString())) {
|
||||
checks.add(new Check("iam:PassRole", passed.roleArn(), passed.passedToService() == null ? Map.of()
|
||||
: Map.of("iam:PassedToService", List.of(passed.passedToService()))));
|
||||
|
||||
@@ -6794,28 +6794,36 @@ public class S3Service implements Resettable, ResourceProvider {
|
||||
|
||||
/**
|
||||
* Stores the bucket replication configuration for round-trip fidelity. The document is
|
||||
* validated minimally (a {@code Role} and at least one {@code Rule} with a
|
||||
* {@code Destination/Bucket}) and stored verbatim; Floci performs no actual replication.
|
||||
* validated minimally (well-formed as a whole, one {@code Role} and at least one {@code Rule}
|
||||
* with a {@code Destination/Bucket}) and stored verbatim; Floci performs no actual replication.
|
||||
*/
|
||||
public void putBucketReplication(String bucketName, String replicationXml) {
|
||||
mutateBucket(bucketName, bucket -> {
|
||||
if (!"ReplicationConfiguration".equals(XmlParser.rootElementName(replicationXml))) {
|
||||
// The whole document is parsed, as S3 parses it: one that is not well-formed after its
|
||||
// configuration ends is refused, not stored for the part that parsed.
|
||||
XmlParser.XmlElement root = XmlParser.parseDocumentElementTree(replicationXml);
|
||||
if (root == null || !"ReplicationConfiguration".equals(root.name())) {
|
||||
throw new AwsException("MalformedXML",
|
||||
"The XML you provided was not well-formed or did not validate against our published schema.",
|
||||
400);
|
||||
}
|
||||
String role = XmlParser.extractFirst(replicationXml, "Role", null);
|
||||
List<Map<String, List<String>>> rules = XmlParser.extractGroupsMulti(replicationXml, "Rule");
|
||||
// Role is a required scalar member of ReplicationConfiguration (botocore
|
||||
// s3/2006-03-01/service-2.json: "Role":{"shape":"Role"}, a string), read from the
|
||||
// configuration's own children and counted as Destination's Bucket is below: a second
|
||||
// Role, or one holding elements, does not validate, and the one Role there is is the
|
||||
// role IAM checks iam:PassRole on.
|
||||
List<XmlParser.XmlElement> roles = root.children().stream()
|
||||
.filter(c -> "Role".equals(c.name())).toList();
|
||||
XmlParser.XmlElement role = roles.size() == 1 && roles.get(0).children().isEmpty() ? roles.get(0) : null;
|
||||
// A document-wide count of Rule vs Destination elements can't tell a well-formed
|
||||
// document from one where a rule has two Destinations and another has none (the
|
||||
// totals still balance). Destination is a direct child of Rule, so walking the parsed
|
||||
// element tree and inspecting each Rule's own children is the only way to require
|
||||
// that every rule carries exactly its own destination.
|
||||
XmlParser.XmlElement root = XmlParser.extractElementTree(replicationXml, "ReplicationConfiguration");
|
||||
List<XmlParser.XmlElement> ruleElements = root == null
|
||||
? List.of()
|
||||
: root.children().stream().filter(c -> "Rule".equals(c.name())).toList();
|
||||
if (role == null || role.isBlank() || ruleElements.isEmpty()) {
|
||||
List<XmlParser.XmlElement> ruleElements = root.children().stream()
|
||||
.filter(c -> "Rule".equals(c.name())).toList();
|
||||
if (role == null || role.text().isBlank() || ruleElements.isEmpty()) {
|
||||
throw new AwsException("MalformedXML",
|
||||
"The XML you provided was not well-formed or did not validate against our published schema.",
|
||||
400);
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
{
|
||||
"_source": {"generator": "tools/aws/regen_iam_passed_roles.py", "reference": "https://servicereference.us-east-1.amazonaws.com/", "botocore": "botocore 1.44.9 (local/aws/botocore)", "retrieved": "2026-11-26", "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"]},
|
||||
"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"},
|
||||
"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"],
|
||||
@@ -774,8 +774,12 @@
|
||||
"resource-groups:StartTagSyncTask": {"passedTo": ["resource-groups"], "roles": [
|
||||
{"member": "RoleArn", "passedTo": "resource-groups"}
|
||||
]},
|
||||
"s3:CreateAccessGrantsLocation": {"passedTo": [], "notRead": "the request body is XML, which PassedRoles does not read"},
|
||||
"s3:PutBucketReplication": {"passedTo": ["s3"], "notRead": "the request body is XML, which PassedRoles does not read"},
|
||||
"s3:CreateAccessGrantsLocation": {"passedTo": [], "roles": [
|
||||
{"member": "IAMRoleArn"}
|
||||
]},
|
||||
"s3:PutBucketReplication": {"passedTo": ["s3"], "roles": [
|
||||
{"member": "Role", "passedTo": "s3"}
|
||||
]},
|
||||
"s3tables:PutTableBucketReplication": {"passedTo": ["replication.s3tables"], "roles": [
|
||||
{"member": "configuration.role", "passedTo": "replication.s3tables"}
|
||||
]},
|
||||
|
||||
@@ -27,6 +27,7 @@ import io.floci.aws.services.iam.model.IamUser;
|
||||
import io.floci.aws.services.lambdaweb.LambdaWebService;
|
||||
import io.floci.aws.services.lambdaweb.model.WebFunctionEndpoint;
|
||||
import io.floci.aws.services.s3.S3Service;
|
||||
import io.floci.aws.testing.MockQueryRequests;
|
||||
import io.floci.aws.testing.ParallelLocks;
|
||||
import jakarta.enterprise.inject.Instance;
|
||||
import jakarta.ws.rs.WebApplicationException;
|
||||
@@ -273,7 +274,7 @@ class IamConditionContextResolverTest {
|
||||
.thenReturn(MediaType.valueOf("application/x-www-form-urlencoded"));
|
||||
when(containerRequest.getEntityStream())
|
||||
.thenAnswer(invocation -> new ByteArrayInputStream(body.getBytes(StandardCharsets.UTF_8)));
|
||||
return containerRequest;
|
||||
return MockQueryRequests.postedToRoot(containerRequest);
|
||||
}
|
||||
|
||||
/** An XML request whose body can be read again, as a real request's restored stream can. */
|
||||
|
||||
@@ -8,6 +8,7 @@ import io.floci.aws.core.common.PassedRoleMembers.Into;
|
||||
import io.floci.aws.core.common.PassedRoleMembers.Member;
|
||||
import io.floci.aws.core.common.PassedRoleMembers.Step;
|
||||
import io.floci.aws.core.common.PassedRoles.PassedRole;
|
||||
import io.floci.aws.testing.MockQueryRequests;
|
||||
import jakarta.ws.rs.container.ContainerRequestContext;
|
||||
import jakarta.ws.rs.core.MediaType;
|
||||
import org.junit.jupiter.api.DynamicTest;
|
||||
@@ -242,7 +243,7 @@ class PassedRoleMembersTest {
|
||||
}
|
||||
|
||||
private static ContainerRequestContext form(String body) {
|
||||
return request("application/x-www-form-urlencoded", body);
|
||||
return MockQueryRequests.postedToRoot(request("application/x-www-form-urlencoded", body));
|
||||
}
|
||||
|
||||
private static ContainerRequestContext request(String mediaType, String body) {
|
||||
|
||||
@@ -3,6 +3,7 @@ package io.floci.aws.core.common;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.dataformat.cbor.CBORFactory;
|
||||
import io.floci.aws.core.common.PassedRoles.PassedRole;
|
||||
import io.floci.aws.testing.MockQueryRequests;
|
||||
import jakarta.ws.rs.container.ContainerRequestContext;
|
||||
import jakarta.ws.rs.core.MediaType;
|
||||
import org.junit.jupiter.api.Test;
|
||||
@@ -692,6 +693,36 @@ class PassedRolesTest {
|
||||
json("{\"name\":\"p\",\"serviceRole\":\"app-role\"}"), LOOKUPS));
|
||||
}
|
||||
|
||||
@Test
|
||||
void anXmlBodyPassesTheRolesItsModeledMembersName() {
|
||||
// S3's PutBucketReplication, authorized as s3:PutReplicationConfiguration, passes its configuration's Role.
|
||||
assertEquals(List.of(passed("replication", "s3.amazonaws.com")), PassedRoles.of("s3:PutBucketReplication",
|
||||
xml("<?xml version=\"1.0\" encoding=\"UTF-8\"?>"
|
||||
+ "<ReplicationConfiguration xmlns=\"http://s3.amazonaws.com/doc/2006-03-01/\"><Role>" + ROLES
|
||||
+ "replication</Role><Rule><Status>Enabled</Status><Destination><Bucket>arn:aws:s3:::dest"
|
||||
+ "</Bucket></Destination></Rule></ReplicationConfiguration>"), LOOKUPS));
|
||||
// S3 Access Grants' location role, which the Service Reference passes to no named service.
|
||||
assertEquals(List.of(new PassedRole(ROLES + "grants", null)), PassedRoles.of("s3:CreateAccessGrantsLocation",
|
||||
xml("<CreateAccessGrantsLocationRequest xmlns=\"http://awss3control.amazonaws.com/doc/2018-08-20/\">"
|
||||
+ "<LocationScope>s3://</LocationScope><IAMRoleArn>" + ROLES + "grants</IAMRoleArn>"
|
||||
+ "</CreateAccessGrantsLocationRequest>"), LOOKUPS));
|
||||
// A form type on a request another protocol's route takes, which is no Query request, leaves its XML read.
|
||||
ContainerRequestContext asForm = request("application/x-www-form-urlencoded", ("<ReplicationConfiguration>"
|
||||
+ "<Role>" + ROLES + "replication</Role></ReplicationConfiguration>").getBytes(StandardCharsets.UTF_8));
|
||||
when(asForm.getMethod()).thenReturn("PUT");
|
||||
assertEquals(List.of(passed("replication", "s3.amazonaws.com")),
|
||||
PassedRoles.of("s3:PutBucketReplication", asForm, LOOKUPS));
|
||||
// A role set off by whitespace is the role, as S3 takes it.
|
||||
assertEquals(List.of(passed("replication", "s3.amazonaws.com")), PassedRoles.of("s3:PutBucketReplication",
|
||||
xml("<ReplicationConfiguration>\n <Role>\n " + ROLES + "replication\n </Role>\n"
|
||||
+ "</ReplicationConfiguration>"), LOOKUPS));
|
||||
// A Role inside a rule is no member of the configuration, and a body that does not parse names none.
|
||||
assertEquals(List.of(), PassedRoles.of("s3:PutBucketReplication", xml("<ReplicationConfiguration><Rule><Role>"
|
||||
+ ROLES + "nested</Role></Rule></ReplicationConfiguration>"), LOOKUPS));
|
||||
assertEquals(List.of(), PassedRoles.of("s3:PutBucketReplication",
|
||||
xml("<ReplicationConfiguration><Role>" + ROLES + "replication"), LOOKUPS));
|
||||
}
|
||||
|
||||
private static String constraint(String type, String parameters) {
|
||||
return "{\"PortfolioId\":\"port\",\"ProductId\":\"prod\",\"Type\":\"" + type + "\",\"Parameters\":\""
|
||||
+ parameters + "\"}";
|
||||
@@ -705,6 +736,10 @@ class PassedRolesTest {
|
||||
return request("application/x-amz-json-1.1", body.getBytes(StandardCharsets.UTF_8));
|
||||
}
|
||||
|
||||
private static ContainerRequestContext xml(String body) {
|
||||
return request("application/xml", body.getBytes(StandardCharsets.UTF_8));
|
||||
}
|
||||
|
||||
private static ContainerRequestContext cbor(String body) throws IOException {
|
||||
return request("application/cbor",
|
||||
new ObjectMapper(new CBORFactory()).writeValueAsBytes(new ObjectMapper().readTree(body)));
|
||||
@@ -721,7 +756,8 @@ class PassedRolesTest {
|
||||
}
|
||||
|
||||
private static ContainerRequestContext form(String body) {
|
||||
return request("application/x-www-form-urlencoded", body.getBytes(StandardCharsets.UTF_8));
|
||||
return MockQueryRequests.postedToRoot(request("application/x-www-form-urlencoded",
|
||||
body.getBytes(StandardCharsets.UTF_8)));
|
||||
}
|
||||
|
||||
private static ContainerRequestContext request(String mediaType, byte[] body) {
|
||||
|
||||
@@ -5,6 +5,7 @@ import com.fasterxml.jackson.databind.node.ObjectNode;
|
||||
import io.floci.aws.core.common.RequestResourceMembers.ArnFormat;
|
||||
import io.floci.aws.core.common.RequestResourceMembers.Member;
|
||||
import io.floci.aws.core.common.RequestResourceMembers.Resource;
|
||||
import io.floci.aws.testing.MockQueryRequests;
|
||||
import jakarta.ws.rs.container.ContainerRequestContext;
|
||||
import jakarta.ws.rs.core.MediaType;
|
||||
import jakarta.ws.rs.core.MultivaluedHashMap;
|
||||
@@ -1044,7 +1045,7 @@ class RequestResourceMembersTest {
|
||||
}
|
||||
|
||||
private static ContainerRequestContext form(String body) {
|
||||
return request("application/x-www-form-urlencoded", body);
|
||||
return MockQueryRequests.postedToRoot(request("application/x-www-form-urlencoded", body));
|
||||
}
|
||||
|
||||
private static ContainerRequestContext request(String mediaType, String body) {
|
||||
|
||||
@@ -2,6 +2,7 @@ package io.floci.aws.core.common;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.dataformat.cbor.CBORFactory;
|
||||
import io.floci.aws.testing.MockQueryRequests;
|
||||
import jakarta.ws.rs.container.ContainerRequestContext;
|
||||
import jakarta.ws.rs.core.MediaType;
|
||||
import jakarta.ws.rs.core.MultivaluedHashMap;
|
||||
@@ -1748,7 +1749,7 @@ class RequestResourcesTest {
|
||||
}
|
||||
|
||||
private static ContainerRequestContext form(String body) {
|
||||
return request("application/x-www-form-urlencoded", body);
|
||||
return MockQueryRequests.postedToRoot(request("application/x-www-form-urlencoded", body));
|
||||
}
|
||||
|
||||
/** The JSON body as EventBridge's JSON 1.1 handler serves it. */
|
||||
|
||||
@@ -7,6 +7,7 @@ import io.floci.aws.core.common.PassedRoleMembers.Into;
|
||||
import io.floci.aws.core.common.PassedRoleMembers.Step;
|
||||
import io.floci.aws.core.common.TagOnCreateMembers.Entry;
|
||||
import io.floci.aws.core.common.TagOnCreateMembers.Member;
|
||||
import io.floci.aws.testing.MockQueryRequests;
|
||||
import jakarta.ws.rs.container.ContainerRequestContext;
|
||||
import jakarta.ws.rs.core.MediaType;
|
||||
import org.junit.jupiter.api.DynamicTest;
|
||||
@@ -220,7 +221,7 @@ class TagOnCreateMembersTest {
|
||||
}
|
||||
|
||||
private static ContainerRequestContext form(String body) {
|
||||
return request("application/x-www-form-urlencoded", body);
|
||||
return MockQueryRequests.postedToRoot(request("application/x-www-form-urlencoded", body));
|
||||
}
|
||||
|
||||
private static ContainerRequestContext request(String mediaType, String body) {
|
||||
|
||||
@@ -4,6 +4,7 @@ import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.dataformat.cbor.CBORFactory;
|
||||
import io.floci.aws.core.common.TagOnCreate.TagSet;
|
||||
import io.floci.aws.core.common.TagOnCreate.Tagging;
|
||||
import io.floci.aws.testing.MockQueryRequests;
|
||||
import jakarta.ws.rs.container.ContainerRequestContext;
|
||||
import jakarta.ws.rs.core.MediaType;
|
||||
import org.junit.jupiter.api.Test;
|
||||
@@ -289,7 +290,8 @@ class TagOnCreateTest {
|
||||
}
|
||||
|
||||
private static ContainerRequestContext form(String body) {
|
||||
return request("application/x-www-form-urlencoded", body.getBytes(StandardCharsets.UTF_8));
|
||||
return MockQueryRequests.postedToRoot(request("application/x-www-form-urlencoded",
|
||||
body.getBytes(StandardCharsets.UTF_8)));
|
||||
}
|
||||
|
||||
private static ContainerRequestContext request(String mediaType, byte[] bytes) {
|
||||
|
||||
@@ -163,6 +163,7 @@ class Ec2NetworkInterfaceResourceArnTest {
|
||||
when(context.getUriInfo()).thenReturn(uri);
|
||||
when(uri.getPath()).thenReturn("/");
|
||||
when(uri.getQueryParameters()).thenReturn(new MultivaluedHashMap<>());
|
||||
when(context.getMethod()).thenReturn("POST");
|
||||
when(context.getMediaType()).thenReturn(MediaType.APPLICATION_FORM_URLENCODED_TYPE);
|
||||
when(context.getEntityStream()).thenReturn(
|
||||
new ByteArrayInputStream(body.getBytes(StandardCharsets.UTF_8)));
|
||||
|
||||
@@ -7,6 +7,7 @@ import io.floci.aws.services.ec2.model.Tag;
|
||||
import io.floci.aws.services.ec2.model.Vpc;
|
||||
import io.floci.aws.services.iam.IamPolicyEvaluator.Decision;
|
||||
import io.floci.aws.services.s3.S3Service;
|
||||
import io.floci.aws.testing.MockQueryRequests;
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import jakarta.inject.Inject;
|
||||
import jakarta.ws.rs.container.ContainerRequestContext;
|
||||
@@ -359,7 +360,7 @@ class IamEnforcementIntegrationTest {
|
||||
when(request.getMediaType()).thenReturn(MediaType.valueOf("application/x-www-form-urlencoded"));
|
||||
when(request.getEntityStream())
|
||||
.thenReturn(new ByteArrayInputStream(form.getBytes(StandardCharsets.UTF_8)));
|
||||
return request;
|
||||
return MockQueryRequests.postedToRoot(request);
|
||||
}
|
||||
|
||||
private static ContainerRequestContext s3Request(String path) {
|
||||
|
||||
@@ -98,6 +98,40 @@ class IamPassRoleEnforcementIntegrationTest {
|
||||
.delete("/2015-03-31/functions/{name}", name));
|
||||
}
|
||||
|
||||
@Test
|
||||
void replicatingABucketNeedsPassRoleOnTheRoleItsConfigurationNamesForS3() {
|
||||
// S3 authorizes PutBucketReplication as s3:PutReplicationConfiguration, and its role is the Role of the
|
||||
// ReplicationConfiguration its XML body is.
|
||||
String role = role("replication");
|
||||
String bucket = "passrole-replication-" + suffix();
|
||||
admin("s3").put("/" + bucket).then().statusCode(200);
|
||||
cleanup.register(() -> EnforcementFixtures.removeBucket(baseUri.getPort(), auth(ADMIN, "s3"), bucket));
|
||||
User user = user("passrole-replication");
|
||||
String configuration = """
|
||||
<ReplicationConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/"><Role>%s</Role>\
|
||||
<Rule><ID>r</ID><Status>Enabled</Status><Destination><Bucket>arn:aws:s3:::%s-target</Bucket>\
|
||||
</Destination></Rule></ReplicationConfiguration>""".formatted(role, bucket);
|
||||
|
||||
user.policy(allow("s3:PutReplicationConfiguration", "*"));
|
||||
denied(user.s3().body(configuration).put("/" + bucket + "?replication").then());
|
||||
// Addressed by its virtual host, with the role set off by whitespace, which S3 accepts, and sent as a form,
|
||||
// which S3 still reads as its XML.
|
||||
denied(user.s3().header("Host", bucket + ".localhost").body(configuration).put("/?replication").then());
|
||||
denied(user.s3().body(configuration.replace(role, "\n " + role + "\n"))
|
||||
.put("/" + bucket + "?replication").then());
|
||||
denied(user.s3().contentType("application/x-www-form-urlencoded").body(configuration)
|
||||
.put("/" + bucket + "?replication").then());
|
||||
// A second Role that is not one text element leaves the first unread, and S3 refuses the document.
|
||||
user.s3().body(configuration.replace("</Role>", "</Role><Role><x/></Role>"))
|
||||
.put("/" + bucket + "?replication").then().statusCode(400).body(containsString("MalformedXML"));
|
||||
|
||||
user.policy(allow("s3:PutReplicationConfiguration", "*") + "," + passRole(role, "ec2.amazonaws.com"));
|
||||
denied(user.s3().body(configuration).put("/" + bucket + "?replication").then());
|
||||
|
||||
user.policy(allow("s3:PutReplicationConfiguration", "*") + "," + passRole(role, "s3.amazonaws.com"));
|
||||
user.s3().body(configuration).put("/" + bucket + "?replication").then().statusCode(200);
|
||||
}
|
||||
|
||||
@Test
|
||||
void aPassRoleGrantKeyedOnTheRolesTagIsNotSatisfiedByTheTag() {
|
||||
// The IAM guide warns that ResourceTag conditions with PassRole "do not have reliable results", so the
|
||||
@@ -1602,6 +1636,10 @@ class IamPassRoleEnforcementIntegrationTest {
|
||||
return given().header("Authorization", auth(accessKeyId, "lambda")).contentType("application/json");
|
||||
}
|
||||
|
||||
RequestSpecification s3() {
|
||||
return given().header("Authorization", auth(accessKeyId, "s3")).contentType("application/xml");
|
||||
}
|
||||
|
||||
RequestSpecification ec2(String action) {
|
||||
return given().header("Authorization", auth(accessKeyId, "ec2")).formParam("Action", action);
|
||||
}
|
||||
|
||||
@@ -130,12 +130,13 @@ class ResourceArnBuilderTest {
|
||||
}).when(ctx).setProperty(any(), any());
|
||||
}
|
||||
|
||||
/** Query-protocol services carry their parameters in a form body, as IAM does. */
|
||||
/** Query-protocol services carry their parameters in a form body, as IAM does, posted to the root path. */
|
||||
private void setFormBody(String form) {
|
||||
sentForm = form;
|
||||
contextProperties.clear();
|
||||
byte[] bytes = form.getBytes(StandardCharsets.UTF_8);
|
||||
ByteArrayInputStream in = new ByteArrayInputStream(bytes);
|
||||
when(ctx.getMethod()).thenReturn("POST");
|
||||
when(ctx.getMediaType()).thenReturn(MediaType.APPLICATION_FORM_URLENCODED_TYPE);
|
||||
when(ctx.getEntityStream()).thenReturn(in);
|
||||
doAnswer(inv -> {
|
||||
|
||||
@@ -498,4 +498,39 @@ class S3ReplicationConfigurationIntegrationTest {
|
||||
.statusCode(404)
|
||||
.body(containsString("ReplicationConfigurationNotFoundError"));
|
||||
}
|
||||
|
||||
/**
|
||||
* {@code Role} is a required <em>scalar</em> member of the configuration itself (botocore
|
||||
* s3/2006-03-01/service-2.json: {@code "Role":{"shape":"Role"}}, a string), and the document
|
||||
* must be well-formed as a whole. A second Role, one holding elements, one only inside a rule,
|
||||
* or content after the configuration ends does not validate, so none is stored.
|
||||
*/
|
||||
@Test
|
||||
@Order(19)
|
||||
void putReplicationRejectsARoleThatIsNotTheConfigurationsOneTextElement() {
|
||||
String role = "<Role>arn:aws:iam::000000000000:role/replication-role</Role>";
|
||||
String rule = "<Rule><ID>r</ID><Status>Enabled</Status><Destination>"
|
||||
+ "<Bucket>arn:aws:s3:::replication-config-int-test-target</Bucket></Destination></Rule>";
|
||||
String open = "<ReplicationConfiguration xmlns=\"http://s3.amazonaws.com/doc/2006-03-01/\">";
|
||||
String close = "</ReplicationConfiguration>";
|
||||
for (String document : new String[] {
|
||||
open + role + "<Role>arn:aws:iam::000000000000:role/other</Role>" + rule + close,
|
||||
open + role + "<Role><Arn>arn:aws:iam::000000000000:role/other</Arn></Role>" + rule + close,
|
||||
open + rule.replace("<ID>r</ID>", "<ID>r</ID>" + role) + close,
|
||||
open + role + rule + close + "<Role>arn:aws:iam::000000000000:role/other</Role>"}) {
|
||||
given()
|
||||
.body(document)
|
||||
.when()
|
||||
.put("/" + BUCKET + "?replication")
|
||||
.then()
|
||||
.statusCode(400)
|
||||
.body(containsString("MalformedXML"));
|
||||
}
|
||||
given()
|
||||
.when()
|
||||
.get("/" + BUCKET + "?replication")
|
||||
.then()
|
||||
.statusCode(404)
|
||||
.body(containsString("ReplicationConfigurationNotFoundError"));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
package io.floci.aws.testing;
|
||||
|
||||
import jakarta.ws.rs.container.ContainerRequestContext;
|
||||
import jakarta.ws.rs.core.MultivaluedHashMap;
|
||||
import jakarta.ws.rs.core.UriInfo;
|
||||
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
/**
|
||||
* Mocked requests sent as the Query controller dispatches them. IAM reads a request's form parameters only for a
|
||||
* Query request, a form posted to the root path, so a mocked form request that names no method or path is read as
|
||||
* carrying none, as a form sent to another protocol's route is.
|
||||
*/
|
||||
public final class MockQueryRequests {
|
||||
|
||||
private MockQueryRequests() {
|
||||
}
|
||||
|
||||
/**
|
||||
* {@code request}, a mock carrying a form body, posted to the root path with no query or path parameters. A test
|
||||
* that stubs its own {@link UriInfo} afterwards replaces this one.
|
||||
*/
|
||||
public static ContainerRequestContext postedToRoot(ContainerRequestContext request) {
|
||||
when(request.getMethod()).thenReturn("POST");
|
||||
UriInfo root = mock(UriInfo.class);
|
||||
when(root.getPath()).thenReturn("/");
|
||||
when(root.getQueryParameters()).thenReturn(new MultivaluedHashMap<>());
|
||||
when(root.getPathParameters()).thenReturn(new MultivaluedHashMap<>());
|
||||
when(request.getUriInfo()).thenReturn(root);
|
||||
return request;
|
||||
}
|
||||
}
|
||||
@@ -23,7 +23,10 @@ A member of the operation's request is read as a role it passes when its name en
|
||||
(`RoleARNUpdate`, `serviceRoleOverride`), and it is a string or a list of strings without an enum.
|
||||
That leaves out `RoleSessionName` and `AmbiguousRoleResolution`, which name no role. A member whose
|
||||
own documentation says it takes a role by name as well as by ARN is marked `byName`, and Floci
|
||||
resolves the name in the request's account, as the services do. What the rule gets wrong for an
|
||||
resolves the name in the request's account, as the services do. A REST-XML request's members are
|
||||
read from its XML body by the elements botocore serializes them as (S3's `PutBucketReplication`, the
|
||||
`Role` of its `ReplicationConfiguration`), and one reached through a map or a flattened list, which
|
||||
`PassedRoles` does not read there, fails generation. What the rule gets wrong for an
|
||||
operation is corrected here, each with its reason: a role member it does not see (`EXTRA_MEMBERS`),
|
||||
a member it sees that passes no role (`EXCLUDED_MEMBERS`), and which service a member's role goes to
|
||||
when the reference names several (`MEMBER_SERVICES`).
|
||||
@@ -131,8 +134,8 @@ BY_NAME_DOC_RE = re.compile(r"\bname or (the |its )?(full )?(ARN|Amazon Resource
|
||||
r"|\brole or (the )?(ARN|Amazon Resource Name)\b"
|
||||
r"|(?<!Resource )\bname of (the |a |an )?(\S+ ){0,5}role\b",
|
||||
re.IGNORECASE)
|
||||
# The protocols whose requests PassedRoles reads: form parameters, or a JSON or CBOR body.
|
||||
READ_PROTOCOLS = {"json", "query", "rest-json", "smithy-rpc-v2-cbor"}
|
||||
# The protocols whose requests PassedRoles reads: form parameters, or a JSON, CBOR or XML body.
|
||||
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
|
||||
# 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_]*\})?"
|
||||
@@ -257,7 +260,6 @@ NOT_IN_BOTOCORE = "the pinned botocore does not have the operation yet, so its r
|
||||
# member in, and entry_for reads it.
|
||||
MEMBER_NOT_IN_BOTOCORE = "the pinned botocore does not have the member naming the role yet, so it cannot be read"
|
||||
RUNBOOK_PARAMETER = "the role is a parameter of the runbook it runs, not a member of the request"
|
||||
XML_BODY = "the request body is XML, which PassedRoles does not read"
|
||||
|
||||
# Operations whose request names no role this file can read.
|
||||
NOT_READ = {
|
||||
@@ -281,8 +283,6 @@ NOT_READ = {
|
||||
"logs:CreateImportTask": "the reference passes the role to cloudtrail or logs and nothing says which",
|
||||
"logs:StartQuery": NO_ROLE_MEMBER,
|
||||
"rds:CreateBlueGreenDeployment": NO_ROLE_MEMBER,
|
||||
"s3:CreateAccessGrantsLocation": XML_BODY,
|
||||
"s3:PutBucketReplication": XML_BODY,
|
||||
"redshift:ModifyLakehouseConfiguration": NO_ROLE_MEMBER,
|
||||
"redshift-serverless:UpdateLakehouseConfiguration": NO_ROLE_MEMBER,
|
||||
"sagemaker:CreateTransformJob": NO_ROLE_MEMBER,
|
||||
@@ -491,30 +491,35 @@ def _takes_name(name: str, member: dict, model: dict) -> bool:
|
||||
|
||||
|
||||
def readable(model: dict) -> bool:
|
||||
"""Whether the model's requests come as form parameters or a JSON or CBOR body."""
|
||||
"""Whether the model's requests come as form parameters or a JSON, CBOR or XML body."""
|
||||
metadata = model["metadata"]
|
||||
return bool(READ_PROTOCOLS & set(metadata.get("protocols") or [metadata.get("protocol")]))
|
||||
|
||||
|
||||
def role_members(model: dict, operation: str) -> dict[str, bool]:
|
||||
"""The members of the operation's request the rule reads, as vendored paths, each with whether
|
||||
it takes a role by name."""
|
||||
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,
|
||||
which do not nest as these paths do, fails rather than being read wrong."""
|
||||
spec = model["operations"].get(operation)
|
||||
if spec is None or "input" not in spec or not readable(model):
|
||||
return {}
|
||||
root = model["shapes"][spec["input"]["shape"]]
|
||||
payload = root.get("payload")
|
||||
xml = "rest-xml" in (model["metadata"].get("protocols") or [model["metadata"].get("protocol")])
|
||||
found: dict[str, bool] = {}
|
||||
|
||||
def walk(shape_name: str, prefix: str, top: bool, seen: frozenset) -> None:
|
||||
def unnested(shape: dict) -> bool:
|
||||
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:
|
||||
if shape_name in seen:
|
||||
return
|
||||
shape = model["shapes"][shape_name]
|
||||
seen = seen | {shape_name}
|
||||
if shape["type"] == "list":
|
||||
walk(shape["member"]["shape"], prefix + _step(shape), False, seen)
|
||||
elif shape["type"] == "map":
|
||||
walk(shape["value"]["shape"], prefix + _step(shape), False, seen)
|
||||
if shape["type"] in ("list", "map"):
|
||||
nested = shape["member" if shape["type"] == "list" else "value"]["shape"]
|
||||
walk(nested, prefix + _step(shape), False, seen, through or unnested(shape))
|
||||
elif shape["type"] == "structure":
|
||||
for name, member in shape.get("members", {}).items():
|
||||
if top and member.get("location") not in BODY_LOCATIONS:
|
||||
@@ -522,17 +527,20 @@ def role_members(model: dict, operation: str) -> dict[str, bool]:
|
||||
serialized = member.get("locationName", name)
|
||||
path = f"{prefix}.{serialized}" if prefix else serialized
|
||||
if _is_role_member(name, model, 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 "
|
||||
"list, which PassedRoles does not read in an XML body")
|
||||
leaf = path + _step(model["shapes"][member["shape"]])
|
||||
by_name = _takes_name(name, member, model)
|
||||
found[leaf] = found.get(leaf, False) or by_name
|
||||
else:
|
||||
walk(member["shape"], path, False, seen)
|
||||
walk(member["shape"], path, False, seen, through)
|
||||
|
||||
if payload is not None:
|
||||
member = root["members"][payload]
|
||||
walk(member["shape"], "", False, frozenset())
|
||||
walk(member["shape"], "", False, frozenset(), False)
|
||||
else:
|
||||
walk(spec["input"]["shape"], "", True, frozenset())
|
||||
walk(spec["input"]["shape"], "", True, frozenset(), False)
|
||||
return found
|
||||
|
||||
|
||||
|
||||
@@ -149,12 +149,33 @@ def test_a_pattern_that_only_admits_an_arn_takes_no_name():
|
||||
assert r.role_members(m, "Op") == {"ExecutionRoleArn": False}
|
||||
|
||||
|
||||
@pytest.mark.parametrize("protocol", ["ec2", "rest-xml"])
|
||||
def test_a_model_whose_requests_are_not_read_has_no_members(protocol):
|
||||
m = model({"Op": "In"}, {"In": structure(RoleArn="String")}, protocol=protocol)
|
||||
def test_a_model_whose_requests_are_not_read_has_no_members():
|
||||
m = model({"Op": "In"}, {"In": structure(RoleArn="String")}, protocol="ec2")
|
||||
assert r.role_members(m, "Op") == {}
|
||||
|
||||
|
||||
def test_an_xml_body_is_read_below_its_payload_by_the_names_its_members_are_serialized_under():
|
||||
# S3's PutBucketReplication: the Role of the ReplicationConfiguration its body is, not the URI's bucket.
|
||||
m = model({"Op": "In"}, {"In": {"type": "structure", "payload": "Configuration", "members": {
|
||||
"Bucket": {"shape": "String", "location": "uri", "locationName": "Bucket"},
|
||||
"Configuration": {"shape": "Configuration", "locationName": "Configuration"}}},
|
||||
"Configuration": structure(Role="String", Targets={"shape": "Targets",
|
||||
"locationName": "Target"}),
|
||||
"Targets": {"type": "list", "member": {"shape": "Target"}},
|
||||
"Target": structure(RoleArn="String")}, protocol="rest-xml")
|
||||
assert r.role_members(m, "Op") == {"Role": False, "Target[].RoleArn": False}
|
||||
|
||||
|
||||
@pytest.mark.parametrize("nesting", [{"type": "list", "member": {"shape": "Target"}, "flattened": True},
|
||||
{"type": "map", "key": {"shape": "String"}, "value": {"shape": "Target"}}])
|
||||
def test_an_xml_role_member_reached_through_a_map_or_a_flattened_list_fails(nesting):
|
||||
shapes = {"In": structure(Targets="Targets"), "Targets": nesting, "Target": structure(RoleArn="String")}
|
||||
with pytest.raises(ValueError, match="map or a flattened list"):
|
||||
r.role_members(model({"Op": "In"}, shapes, protocol="rest-xml"), "Op")
|
||||
# A JSON body nests them as the paths do.
|
||||
assert len(r.role_members(model({"Op": "In"}, shapes), "Op")) == 1
|
||||
|
||||
|
||||
def test_a_member_path_with_a_map_key_exists_only_for_a_key_the_enum_lists():
|
||||
m = model({"Op": "In"}, {"In": structure(Definition="Definition"),
|
||||
"Definition": {"type": "map", "key": {"shape": "Key"}, "value": {"shape": "String"}},
|
||||
|
||||
Reference in new issue
Block a user