diff --git a/docs/services/iam.md b/docs/services/iam.md index 8e68c734de..57d79f18db 100644 --- a/docs/services/iam.md +++ b/docs/services/iam.md @@ -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 diff --git a/docs/services/s3.md b/docs/services/s3.md index 2b0cbf2514..3ec55b4a7f 100644 --- a/docs/services/s3.md +++ b/docs/services/s3.md @@ -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 diff --git a/src/main/java/io/floci/aws/core/common/IamConditionContextResolver.java b/src/main/java/io/floci/aws/core/common/IamConditionContextResolver.java index 4c0e78afd7..a2bb8a84b2 100644 --- a/src/main/java/io/floci/aws/core/common/IamConditionContextResolver.java +++ b/src/main/java/io/floci/aws/core/common/IamConditionContextResolver.java @@ -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) 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(); diff --git a/src/main/java/io/floci/aws/core/common/IamEnforcementFilter.java b/src/main/java/io/floci/aws/core/common/IamEnforcementFilter.java index 1aefe72cbe..ff70343cbd 100644 --- a/src/main/java/io/floci/aws/core/common/IamEnforcementFilter.java +++ b/src/main/java/io/floci/aws/core/common/IamEnforcementFilter.java @@ -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> context = new HashMap<>(); if (callerArns != null) { callerArns.putPrincipalKeys(context); diff --git a/src/main/java/io/floci/aws/core/common/PassedRoles.java b/src/main/java/io/floci/aws/core/common/PassedRoles.java index 74fc84bca9..ad6868ea49 100644 --- a/src/main/java/io/floci/aws/core/common/PassedRoles.java +++ b/src/main/java/io/floci/aws/core/common/PassedRoles.java @@ -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 of(String action, ContainerRequestContext ctx, Lookups lookups) { - List byHand = byHand(action, ctx, lookups); - return byHand != null ? byHand : fromTable(PassedRoleMembers.of(action), ctx, lookups); + /** + * The roles a request for {@code operation}, as {@code :}, passes; empty when the operation + * passes none or the request names none. + */ + static List of(String operation, ContainerRequestContext ctx, Lookups lookups) { + List 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 fromTable(List members, ContainerRequestContext ctx, Lookups lookups) { if (members == null) { return List.of(); } + UnaryOperator named = name -> lookups.heldRoleArn(name).orElseGet(() -> lookups.roleArn(name)); Map 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 ofBody(String action, JsonNode body, UnaryOperator 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 fromXml(List members, String xml, + UnaryOperator named) { + Map paths = new LinkedHashMap<>(); + for (PassedRoleMembers.Member member : members) { + xmlPath(member.steps()).ifPresent(path -> paths.put(member, path)); } - List members = PassedRoleMembers.of(action); + Map> read = paths.isEmpty() ? null : XmlParser.valuesAt(xml, paths.values()); + if (read == null) { + return List.of(); + } + List passed = new ArrayList<>(); + paths.forEach((member, path) -> { + List 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 xmlPath(List steps) { + List 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 ofBody(String operation, JsonNode body, UnaryOperator named) { + if (PassedRoleMembers.table().byHand().contains(operation)) { + throw new IllegalArgumentException(operation + " passes roles read by hand, from a request of its own"); + } + List members = PassedRoleMembers.of(operation); return members == null ? List.of() : fromTable(members, Map.of(), body, named); } diff --git a/src/main/java/io/floci/aws/core/common/RequestChecks.java b/src/main/java/io/floci/aws/core/common/RequestChecks.java index 015a82a6f1..a0f595d37d 100644 --- a/src/main/java/io/floci/aws/core/common/RequestChecks.java +++ b/src/main/java/io/floci/aws/core/common/RequestChecks.java @@ -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())))); diff --git a/src/main/java/io/floci/aws/services/s3/S3Service.java b/src/main/java/io/floci/aws/services/s3/S3Service.java index 3259b1bef2..eb606641f0 100644 --- a/src/main/java/io/floci/aws/services/s3/S3Service.java +++ b/src/main/java/io/floci/aws/services/s3/S3Service.java @@ -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>> 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 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 ruleElements = root == null - ? List.of() - : root.children().stream().filter(c -> "Rule".equals(c.name())).toList(); - if (role == null || role.isBlank() || ruleElements.isEmpty()) { + List 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); diff --git a/src/main/resources/aws/iam-passed-roles.json b/src/main/resources/aws/iam-passed-roles.json index b691b761ee..41aa9de4fb 100644 --- a/src/main/resources/aws/iam-passed-roles.json +++ b/src/main/resources/aws/iam-passed-roles.json @@ -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"} ]}, diff --git a/src/test/java/io/floci/aws/core/common/IamConditionContextResolverTest.java b/src/test/java/io/floci/aws/core/common/IamConditionContextResolverTest.java index d2104968f3..f3de010baf 100644 --- a/src/test/java/io/floci/aws/core/common/IamConditionContextResolverTest.java +++ b/src/test/java/io/floci/aws/core/common/IamConditionContextResolverTest.java @@ -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. */ diff --git a/src/test/java/io/floci/aws/core/common/PassedRoleMembersTest.java b/src/test/java/io/floci/aws/core/common/PassedRoleMembersTest.java index 0fddfd61c1..53e62f3b82 100644 --- a/src/test/java/io/floci/aws/core/common/PassedRoleMembersTest.java +++ b/src/test/java/io/floci/aws/core/common/PassedRoleMembersTest.java @@ -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) { diff --git a/src/test/java/io/floci/aws/core/common/PassedRolesTest.java b/src/test/java/io/floci/aws/core/common/PassedRolesTest.java index c988acad16..2ea0648799 100644 --- a/src/test/java/io/floci/aws/core/common/PassedRolesTest.java +++ b/src/test/java/io/floci/aws/core/common/PassedRolesTest.java @@ -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("" + + "" + ROLES + + "replicationEnabledarn:aws:s3:::dest" + + ""), 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("" + + "s3://" + ROLES + "grants" + + ""), 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", ("" + + "" + ROLES + "replication").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("\n \n " + ROLES + "replication\n \n" + + ""), 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("" + + ROLES + "nested"), LOOKUPS)); + assertEquals(List.of(), PassedRoles.of("s3:PutBucketReplication", + xml("" + 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) { diff --git a/src/test/java/io/floci/aws/core/common/RequestResourceMembersTest.java b/src/test/java/io/floci/aws/core/common/RequestResourceMembersTest.java index 682102feef..6b37004612 100644 --- a/src/test/java/io/floci/aws/core/common/RequestResourceMembersTest.java +++ b/src/test/java/io/floci/aws/core/common/RequestResourceMembersTest.java @@ -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) { diff --git a/src/test/java/io/floci/aws/core/common/RequestResourcesTest.java b/src/test/java/io/floci/aws/core/common/RequestResourcesTest.java index 5439d79917..f545c08dcd 100644 --- a/src/test/java/io/floci/aws/core/common/RequestResourcesTest.java +++ b/src/test/java/io/floci/aws/core/common/RequestResourcesTest.java @@ -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. */ diff --git a/src/test/java/io/floci/aws/core/common/TagOnCreateMembersTest.java b/src/test/java/io/floci/aws/core/common/TagOnCreateMembersTest.java index bc8e5cb5cb..d3cd2c1c2b 100644 --- a/src/test/java/io/floci/aws/core/common/TagOnCreateMembersTest.java +++ b/src/test/java/io/floci/aws/core/common/TagOnCreateMembersTest.java @@ -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) { diff --git a/src/test/java/io/floci/aws/core/common/TagOnCreateTest.java b/src/test/java/io/floci/aws/core/common/TagOnCreateTest.java index 6a1b523d19..9ef381015f 100644 --- a/src/test/java/io/floci/aws/core/common/TagOnCreateTest.java +++ b/src/test/java/io/floci/aws/core/common/TagOnCreateTest.java @@ -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) { diff --git a/src/test/java/io/floci/aws/services/iam/Ec2NetworkInterfaceResourceArnTest.java b/src/test/java/io/floci/aws/services/iam/Ec2NetworkInterfaceResourceArnTest.java index 5e583a1664..54ec1d74be 100644 --- a/src/test/java/io/floci/aws/services/iam/Ec2NetworkInterfaceResourceArnTest.java +++ b/src/test/java/io/floci/aws/services/iam/Ec2NetworkInterfaceResourceArnTest.java @@ -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))); diff --git a/src/test/java/io/floci/aws/services/iam/IamEnforcementIntegrationTest.java b/src/test/java/io/floci/aws/services/iam/IamEnforcementIntegrationTest.java index 656cb7eda8..6060bef18e 100644 --- a/src/test/java/io/floci/aws/services/iam/IamEnforcementIntegrationTest.java +++ b/src/test/java/io/floci/aws/services/iam/IamEnforcementIntegrationTest.java @@ -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) { diff --git a/src/test/java/io/floci/aws/services/iam/IamPassRoleEnforcementIntegrationTest.java b/src/test/java/io/floci/aws/services/iam/IamPassRoleEnforcementIntegrationTest.java index e8d516820d..65eb379a4b 100644 --- a/src/test/java/io/floci/aws/services/iam/IamPassRoleEnforcementIntegrationTest.java +++ b/src/test/java/io/floci/aws/services/iam/IamPassRoleEnforcementIntegrationTest.java @@ -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 = """ + %s\ + rEnabledarn:aws:s3:::%s-target\ + """.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("", "")) + .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); } diff --git a/src/test/java/io/floci/aws/services/iam/ResourceArnBuilderTest.java b/src/test/java/io/floci/aws/services/iam/ResourceArnBuilderTest.java index 1d7e1347c3..5bdc9c0f90 100644 --- a/src/test/java/io/floci/aws/services/iam/ResourceArnBuilderTest.java +++ b/src/test/java/io/floci/aws/services/iam/ResourceArnBuilderTest.java @@ -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 -> { diff --git a/src/test/java/io/floci/aws/services/s3/S3ReplicationConfigurationIntegrationTest.java b/src/test/java/io/floci/aws/services/s3/S3ReplicationConfigurationIntegrationTest.java index b510b554db..91219478b2 100644 --- a/src/test/java/io/floci/aws/services/s3/S3ReplicationConfigurationIntegrationTest.java +++ b/src/test/java/io/floci/aws/services/s3/S3ReplicationConfigurationIntegrationTest.java @@ -498,4 +498,39 @@ class S3ReplicationConfigurationIntegrationTest { .statusCode(404) .body(containsString("ReplicationConfigurationNotFoundError")); } + + /** + * {@code Role} is a required scalar 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 = "arn:aws:iam::000000000000:role/replication-role"; + String rule = "rEnabled" + + "arn:aws:s3:::replication-config-int-test-target"; + String open = ""; + String close = ""; + for (String document : new String[] { + open + role + "arn:aws:iam::000000000000:role/other" + rule + close, + open + role + "arn:aws:iam::000000000000:role/other" + rule + close, + open + rule.replace("r", "r" + role) + close, + open + role + rule + close + "arn:aws:iam::000000000000:role/other"}) { + given() + .body(document) + .when() + .put("/" + BUCKET + "?replication") + .then() + .statusCode(400) + .body(containsString("MalformedXML")); + } + given() + .when() + .get("/" + BUCKET + "?replication") + .then() + .statusCode(404) + .body(containsString("ReplicationConfigurationNotFoundError")); + } } diff --git a/src/test/java/io/floci/aws/testing/MockQueryRequests.java b/src/test/java/io/floci/aws/testing/MockQueryRequests.java new file mode 100644 index 0000000000..5829ef1c38 --- /dev/null +++ b/src/test/java/io/floci/aws/testing/MockQueryRequests.java @@ -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; + } +} diff --git a/tools/aws/regen_iam_passed_roles.py b/tools/aws/regen_iam_passed_roles.py index 389ec8c9cc..4ee68bd094 100644 --- a/tools/aws/regen_iam_passed_roles.py +++ b/tools/aws/regen_iam_passed_roles.py @@ -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"|(? 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 diff --git a/tools/aws/test_regen_iam_passed_roles.py b/tools/aws/test_regen_iam_passed_roles.py index 3316690678..4eb6af9744 100644 --- a/tools/aws/test_regen_iam_passed_roles.py +++ b/tools/aws/test_regen_iam_passed_roles.py @@ -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"}},