From 84cea7714a7cd6343538f8fed2cacabf074a1104 Mon Sep 17 00:00:00 2001 From: Priamo Germosen <6233424+pgermosen@users.noreply.github.com> Date: Sat, 21 Nov 2026 14:13:43 -0400 Subject: [PATCH] feat(iam): read S3's actions from its user guide, by model and by version (#9147) Where the Service Reference gives an S3 operation no one answer, S3's user guide does. tools/aws/fetch_s3_required_actions.py copies its "Required permissions for Amazon S3 API operations" rows unchanged into tools/aws/sources/s3-required-actions.json, and the authorized-actions generator reads them: an operation's one required action (ListObjectsV2 is s3:ListBucket, CopyObject s3:PutObject), the action for one model's requests of an operation S3 and S3 Control both have (authorizedByModel: S3 Control's account-level GetPublicAccessBlock is s3:GetAccountPublicAccessBlock), and an Either row's choice by versionId where botocore gives it in the query (versioned). Measured entries quote the Service Authorization Reference for the account-level GetPublicAccessBlock the page mislabels and the version annotation actions it omits. The one answer the reference gives an operation several clients list goes to the namesake client (S3's GetBucketLifecycleConfiguration is s3:GetLifecycleConfiguration), and the file records the reference's spelling of an action named as its operation in another case (MemoryDB's CreateACL is memorydb:CreateAcl). IamAuthorizedActions reads the new sections and gives an action for a route's model and query, which IamActionRegistry uses wherever it reads a route's action. S3 stays hand-routed, so its rules still decide its requests; only the spellings show, in the action an AccessDenied message names. A hand-routed scope's routes list what their requests must carry, for the coverage test, which now also checks each model-specific action against that model's routes. --- Makefile | 6 +- docs/services/iam.md | 8 +- .../aws/services/iam/IamActionRegistry.java | 25 +- .../services/iam/IamAuthorizedActions.java | 93 +- .../resources/aws/iam-authorized-actions.json | 170 ++- src/main/resources/aws/rest-routes.json | 238 ++-- .../iam/IamAuthorizedActionsTest.java | 64 + .../iam/IamRestRouteCoverageTest.java | 55 +- tools/aws/fetch_s3_required_actions.py | 164 +++ tools/aws/regen_iam_authorized_actions.py | 297 ++++- tools/aws/regen_iam_request_resources.py | 26 +- tools/aws/regen_rest_routes.py | 44 +- tools/aws/sources/s3-required-actions.json | 1172 +++++++++++++++++ tools/aws/test_fetch_s3_required_actions.py | 124 ++ .../aws/test_regen_iam_authorized_actions.py | 172 +++ tools/aws/test_regen_rest_routes.py | 13 + 16 files changed, 2509 insertions(+), 162 deletions(-) create mode 100644 tools/aws/fetch_s3_required_actions.py create mode 100644 tools/aws/sources/s3-required-actions.json create mode 100644 tools/aws/test_fetch_s3_required_actions.py diff --git a/Makefile b/Makefile index dbc366b423..e9a493f52b 100644 --- a/Makefile +++ b/Makefile @@ -598,7 +598,8 @@ IAM_ACTION_RESOURCES_PATHS := src/main/resources/aws/iam-action-resources.json \ tools/aws/regen_iam_action_resources.py tools/aws/test_regen_iam_action_resources.py IAM_AUTHORIZED_ACTIONS_PATHS := src/main/resources/aws/iam-authorized-actions.json \ tools/aws/regen_iam_authorized_actions.py tools/aws/test_regen_iam_authorized_actions.py \ - src/main/resources/aws/rest-routes.json + src/main/resources/aws/rest-routes.json tools/aws/sources/s3-required-actions.json \ + tools/aws/fetch_s3_required_actions.py tools/aws/test_fetch_s3_required_actions.py IAM_PASSED_ROLES_PATHS := src/main/resources/aws/iam-passed-roles.json $(IAM_PASSED_ROLES_GENERATOR) \ tools/aws/test_regen_iam_passed_roles.py IAM_PASSED_NETWORK_CONNECTORS_PATHS := src/main/resources/aws/iam-passed-network-connectors.json \ @@ -623,7 +624,8 @@ DOCUMENTED_ROUTES_PATHS := src/main/resources/aws/rest-routes.json tools/aws/reg IAM_REQUEST_RESOURCES_PATHS := src/main/resources/aws/iam-request-resources.json \ tools/aws/regen_iam_request_resources.py $(IAM_PASSED_ROLES_GENERATOR) \ tools/aws/test_regen_iam_request_resources.py tools/aws/sources/athena-glue-ddl-permissions.json \ - tools/aws/fetch_athena_glue_ddl_permissions.py tools/aws/test_fetch_athena_glue_ddl_permissions.py + tools/aws/fetch_athena_glue_ddl_permissions.py tools/aws/test_fetch_athena_glue_ddl_permissions.py \ + tools/aws/regen_iam_authorized_actions.py tools/aws/sources/s3-required-actions.json iam-data-verify: ## CI gate (online): every vendored IAM file must still match AWS; CHANGED="" checks only the ones they cover @# Every check runs even when an earlier one fails, so one file's drift cannot hide another's diff --git a/docs/services/iam.md b/docs/services/iam.md index b88e6ad648..452c7e7e59 100644 --- a/docs/services/iam.md +++ b/docs/services/iam.md @@ -3012,8 +3012,12 @@ IAM action, grants nothing. Budgets operations other than its budget actions are `budgets:ModifyBudget` or `budgets:ViewBudget`, which the Service Reference lists for them beside the `aws-portal` Billing console permissions. Those are not checked: the Billing and Cost Management user guide, on moving off them, says "Programmatic requests to AWS Cost Explorer, AWS Cost and Usage -Reports, and AWS Budgets remains unaffected". The mapping is taken from AWS's Service Reference and -vendored in `src/main/resources/aws/iam-authorized-actions.json`. DynamoDB `TransactGetItems`, which +Reports, and AWS Budgets remains unaffected". An action the Service Reference spells otherwise than +its operation's name, in case alone, is checked under its spelling: MemoryDB's `CreateACL` is +`memorydb:CreateAcl` and Amplify's `CreateWebhook` `amplify:CreateWebHook`, the names an AccessDenied +message gives. IAM matches action names without regard to case, so a policy naming either spelling +covers the call. The mapping is taken from AWS's Service Reference and vendored in +`src/main/resources/aws/iam-authorized-actions.json`. DynamoDB `TransactGetItems`, which AWS checks as `dynamodb:GetItem`, is checked item by item, as described under [Condition keys floci populates](#condition-keys-floci-populates): each `Get` as `dynamodb:GetItem` on its own table, with its own `dynamodb:LeadingKeys`. diff --git a/src/main/java/io/floci/aws/services/iam/IamActionRegistry.java b/src/main/java/io/floci/aws/services/iam/IamActionRegistry.java index 777c09da96..0403d84f85 100644 --- a/src/main/java/io/floci/aws/services/iam/IamActionRegistry.java +++ b/src/main/java/io/floci/aws/services/iam/IamActionRegistry.java @@ -710,12 +710,13 @@ public class IamActionRegistry { return rule.action(); } } - Optional operation = restRoutes.match(credentialScope, method, withoutInternalPrefix(ctx, path), - ctx.getUriInfo() == null ? null : ctx.getUriInfo().getQueryParameters(), movedUnderPrefix(ctx), - ctx.getHeaders()).map(IamRestRoutes.Match::operation); - if (operation.isPresent()) { - String action = IamAuthorizedActions.actionFor(credentialScope, operation.get(), method); - if (checkedAsAws(credentialScope, operation.get(), action)) { + MultivaluedMap query = ctx.getUriInfo() == null ? null : ctx.getUriInfo().getQueryParameters(); + Optional match = restRoutes.match(credentialScope, method, withoutInternalPrefix(ctx, path), + query, movedUnderPrefix(ctx), ctx.getHeaders()); + if (match.isPresent()) { + String action = IamAuthorizedActions.actionFor(credentialScope, match.get().operation(), method, + match.get().model(), query); + if (checkedAsAws(credentialScope, match.get().operation(), action)) { return action; } } @@ -782,12 +783,12 @@ public class IamActionRegistry { return action; } String method = ctx.getMethod().toUpperCase(); - return restRoutes.match(credentialScope, method, withoutInternalPrefix(ctx, routedPath(ctx)), - ctx.getUriInfo() == null ? null : ctx.getUriInfo().getQueryParameters(), movedUnderPrefix(ctx), - ctx.getHeaders()) - .map(IamRestRoutes.Match::operation) - .filter(operation -> action.equals(IamAuthorizedActions.actionFor(credentialScope, operation, method))) - .map(operation -> credentialScope + ":" + operation) + MultivaluedMap query = ctx.getUriInfo() == null ? null : ctx.getUriInfo().getQueryParameters(); + return restRoutes.match(credentialScope, method, withoutInternalPrefix(ctx, routedPath(ctx)), query, + movedUnderPrefix(ctx), ctx.getHeaders()) + .filter(match -> action.equals(IamAuthorizedActions.actionFor(credentialScope, match.operation(), + method, match.model(), query))) + .map(match -> credentialScope + ":" + match.operation()) .orElse(action); } diff --git a/src/main/java/io/floci/aws/services/iam/IamAuthorizedActions.java b/src/main/java/io/floci/aws/services/iam/IamAuthorizedActions.java index 659e8a397f..d72d5483a4 100644 --- a/src/main/java/io/floci/aws/services/iam/IamAuthorizedActions.java +++ b/src/main/java/io/floci/aws/services/iam/IamAuthorizedActions.java @@ -3,6 +3,7 @@ package io.floci.aws.services.iam; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import io.floci.aws.core.common.VendoredResources; +import jakarta.ws.rs.core.MultivaluedMap; import java.io.IOException; import java.io.InputStream; @@ -67,10 +68,20 @@ public final class IamAuthorizedActions { /** * The file: the action of each operation it names, keyed by {@code :}, the actions of - * no resource type, as {@code :} in lower case, and the operations authorized by method, as - * {@code :}. + * no resource type, as {@code :} in lower case, the operations authorized by method, as + * {@code :}, the action of an operation for a request of one model's route, keyed by + * {@code :@}, the operations whose action a request parameter chooses, and the + * reference's spelling of an action named as its operation in another case. */ - record Table(Map actions, Set withoutResourceTypes, Set byMethod) { + record Table(Map actions, Set withoutResourceTypes, Set byMethod, + Map byModel, Map versioned, Map spellings) { + } + + /** + * An operation whose action is one or another by whether its request names {@code parameter}: S3's GetObject is + * {@code s3:GetObject}, and {@code s3:GetObjectVersion} for a request naming a {@code versionId}. + */ + record Versioned(String parameter, String without, String with) { } private static final class Holder { @@ -90,7 +101,28 @@ public final class IamAuthorizedActions { if (KEPT_FOR_ITEM_CHECKS.contains(own)) { return own; } - return Holder.TABLE.actions().getOrDefault(own, own); + String renamed = Holder.TABLE.actions().get(own); + return renamed != null ? renamed : Holder.TABLE.spellings().getOrDefault(own, own); + } + + /** + * As {@link #actionFor(String, String, String)}, for a request of the route of {@code model}'s operation carrying + * {@code query}: the action the file gives the operation for that model's requests (S3 Control's account-level + * GetPublicAccessBlock is {@code s3:GetAccountPublicAccessBlock}, S3's {@code s3:GetBucketPublicAccessBlock}), or + * the one its request's parameter chooses (a GetObject naming a {@code versionId} is {@code s3:GetObjectVersion}). + */ + public static String actionFor(String namespace, String operation, String method, String model, + MultivaluedMap query) { + String own = namespace + ":" + operation; + String byModel = model == null ? null : Holder.TABLE.byModel().get(own + "@" + model); + if (byModel != null) { + return byModel; + } + Versioned versioned = Holder.TABLE.versioned().get(own); + if (versioned != null) { + return query != null && query.containsKey(versioned.parameter()) ? versioned.with() : versioned.without(); + } + return actionFor(namespace, operation, method); } /** @@ -138,7 +170,58 @@ public final class IamAuthorizedActions { }); }); return new Table(Map.copyOf(actions), withoutResourceTypes(document.path("actionsWithoutResourceTypes")), - byMethod(document.path("authorizedByMethod"))); + byMethod(document.path("authorizedByMethod")), byModel(document.path("authorizedByModel")), + versioned(document.path("versioned")), spellings(document.path("spellings"))); + } + + /** Each namespace's operations' actions for one model's requests, keyed {@code :@}. */ + private static Map byModel(JsonNode namespaces) { + Map found = new LinkedHashMap<>(); + namespaces.properties().forEach(namespace -> namespace.getValue().properties().forEach(model -> + model.getValue().properties().forEach(operation -> found.put( + namespace.getKey() + ":" + operation.getKey() + "@" + model.getKey(), + actionOf(namespace.getKey(), operation.getKey(), operation.getValue()))))); + return Map.copyOf(found); + } + + /** Each namespace's operations whose action a request parameter chooses. */ + private static Map versioned(JsonNode namespaces) { + Map found = new LinkedHashMap<>(); + namespaces.properties().forEach(namespace -> namespace.getValue().properties().forEach(operation -> { + JsonNode choice = operation.getValue(); + if (!choice.path("parameter").isTextual() || choice.path("parameter").asText().isEmpty()) { + throw new IllegalStateException(RESOURCE_NAME + " gives " + namespace.getKey() + ":" + + operation.getKey() + " a version choice naming no parameter"); + } + found.put(namespace.getKey() + ":" + operation.getKey(), new Versioned(choice.path("parameter").asText(), + actionOf(namespace.getKey(), operation.getKey(), choice.path("without")), + actionOf(namespace.getKey(), operation.getKey(), choice.path("with")))); + })); + return Map.copyOf(found); + } + + /** Each namespace's actions spelled otherwise than their operations, keyed {@code :}. */ + private static Map spellings(JsonNode namespaces) { + Map found = new LinkedHashMap<>(); + namespaces.properties().forEach(namespace -> namespace.getValue().properties().forEach(operation -> { + String action = actionOf(namespace.getKey(), operation.getKey(), operation.getValue()); + if (!action.substring(namespace.getKey().length() + 1).equalsIgnoreCase(operation.getKey())) { + throw new IllegalStateException(RESOURCE_NAME + " spells " + namespace.getKey() + ":" + + operation.getKey() + " as " + action + ", another name"); + } + found.put(namespace.getKey() + ":" + operation.getKey(), action); + })); + return Map.copyOf(found); + } + + /** The action a value names, refused unless it is one of the namespace's. */ + private static String actionOf(String namespace, String operation, JsonNode value) { + String action = value.asText(""); + if (!action.startsWith(namespace + ":") || action.length() == namespace.length() + 1) { + throw new IllegalStateException(RESOURCE_NAME + " maps " + namespace + ":" + operation + " to " + value + + ", which is not an action of " + namespace); + } + return action; } /** The operations authorized by method, each scope's a list of operation names. */ diff --git a/src/main/resources/aws/iam-authorized-actions.json b/src/main/resources/aws/iam-authorized-actions.json index 435c382487..b0ad5961cc 100644 --- a/src/main/resources/aws/iam-authorized-actions.json +++ b/src/main/resources/aws/iam-authorized-actions.json @@ -271,6 +271,10 @@ "BatchUpdateFirewallRule": "route53resolver:UpdateFirewallRule" }, "s3": { + "CompleteMultipartUpload": "s3:PutObject", + "CopyObject": "s3:PutObject", + "CreateBucketMetadataConfiguration": "s3:CreateBucketMetadataTableConfiguration", + "CreateMultipartUpload": "s3:PutObject", "DeleteBucketAnalyticsConfiguration": "s3:PutAnalyticsConfiguration", "DeleteBucketCors": "s3:PutBucketCORS", "DeleteBucketEncryption": "s3:PutEncryptionConfiguration", @@ -290,13 +294,19 @@ "GetBucketMetricsConfiguration": "s3:GetMetricsConfiguration", "GetBucketNotificationConfiguration": "s3:GetBucketNotification", "GetObjectLockConfiguration": "s3:GetBucketObjectLockConfiguration", + "GetObjectTorrent": "s3:GetObject", "HeadBucket": "s3:ListBucket", + "HeadObject": "s3:GetObject", "ListBucketAnalyticsConfigurations": "s3:GetAnalyticsConfiguration", "ListBucketIntelligentTieringConfigurations": "s3:GetIntelligentTieringConfiguration", "ListBucketInventoryConfigurations": "s3:GetInventoryConfiguration", "ListBucketMetricsConfigurations": "s3:GetMetricsConfiguration", "ListBuckets": "s3:ListAllMyBuckets", + "ListMultipartUploads": "s3:ListBucketMultipartUploads", "ListObjectVersions": "s3:ListBucketVersions", + "ListObjects": "s3:ListBucket", + "ListObjectsV2": "s3:ListBucket", + "ListParts": "s3:ListMultipartUploadParts", "PutBucketAccelerateConfiguration": "s3:PutAccelerateConfiguration", "PutBucketAnalyticsConfiguration": "s3:PutAnalyticsConfiguration", "PutBucketEncryption": "s3:PutEncryptionConfiguration", @@ -306,7 +316,9 @@ "PutBucketMetricsConfiguration": "s3:PutMetricsConfiguration", "PutBucketNotificationConfiguration": "s3:PutBucketNotification", "PutObjectLockConfiguration": "s3:PutBucketObjectLockConfiguration", - "SelectObjectContent": "s3:GetObject" + "SelectObjectContent": "s3:GetObject", + "UploadPart": "s3:PutObject", + "UploadPartCopy": "s3:PutObject" }, "sagemaker": { "UpdateRecord": "sagemaker:PutRecord" @@ -1287,5 +1299,161 @@ "UpdateStage", "UpdateVpcLink" ] + }, + "authorizedByModel": { + "apigateway": { + "apigateway": { + "CreateAuthorizer": "apigateway:POST", + "CreateDeployment": "apigateway:POST", + "CreateModel": "apigateway:POST", + "DeleteAuthorizer": "apigateway:DELETE", + "DeleteDeployment": "apigateway:DELETE", + "DeleteIntegration": "apigateway:DELETE", + "DeleteIntegrationResponse": "apigateway:DELETE", + "DeleteModel": "apigateway:DELETE", + "DeleteStage": "apigateway:DELETE", + "DeleteVpcLink": "apigateway:DELETE", + "GetAuthorizer": "apigateway:GET", + "GetAuthorizers": "apigateway:GET", + "GetDeployment": "apigateway:GET", + "GetDeployments": "apigateway:GET", + "GetDomainName": "apigateway:GET", + "GetDomainNames": "apigateway:GET", + "GetIntegration": "apigateway:GET", + "GetIntegrationResponse": "apigateway:GET", + "GetModel": "apigateway:GET", + "GetModelTemplate": "apigateway:GET", + "GetModels": "apigateway:GET", + "GetStage": "apigateway:GET", + "GetStages": "apigateway:GET", + "GetTags": "apigateway:GET", + "GetVpcLink": "apigateway:GET", + "GetVpcLinks": "apigateway:GET", + "UpdateAuthorizer": "apigateway:PATCH", + "UpdateDeployment": "apigateway:PATCH", + "UpdateIntegration": "apigateway:PATCH", + "UpdateIntegrationResponse": "apigateway:PATCH", + "UpdateModel": "apigateway:PATCH", + "UpdateStage": "apigateway:PATCH", + "UpdateVpcLink": "apigateway:PATCH" + } + }, + "s3": { + "s3": { + "DeleteBucketReplication": "s3:PutReplicationConfiguration", + "DeleteBucketTagging": "s3:PutBucketTagging", + "DeletePublicAccessBlock": "s3:PutBucketPublicAccessBlock", + "GetBucketLifecycleConfiguration": "s3:GetLifecycleConfiguration", + "GetBucketReplication": "s3:GetReplicationConfiguration", + "GetPublicAccessBlock": "s3:GetBucketPublicAccessBlock", + "PutBucketLifecycleConfiguration": "s3:PutLifecycleConfiguration", + "PutBucketReplication": "s3:PutReplicationConfiguration", + "PutPublicAccessBlock": "s3:PutBucketPublicAccessBlock" + }, + "s3control": { + "DeletePublicAccessBlock": "s3:PutAccountPublicAccessBlock", + "GetPublicAccessBlock": "s3:GetAccountPublicAccessBlock", + "PutPublicAccessBlock": "s3:PutAccountPublicAccessBlock" + } + } + }, + "versioned": { + "s3": { + "DeleteObject": { + "parameter": "versionId", + "without": "s3:DeleteObject", + "with": "s3:DeleteObjectVersion" + }, + "DeleteObjectAnnotation": { + "parameter": "versionId", + "without": "s3:DeleteObjectAnnotation", + "with": "s3:DeleteObjectVersionAnnotation" + }, + "DeleteObjectTagging": { + "parameter": "versionId", + "without": "s3:DeleteObjectTagging", + "with": "s3:DeleteObjectVersionTagging" + }, + "GetObject": { + "parameter": "versionId", + "without": "s3:GetObject", + "with": "s3:GetObjectVersion" + }, + "GetObjectAcl": { + "parameter": "versionId", + "without": "s3:GetObjectAcl", + "with": "s3:GetObjectVersionAcl" + }, + "GetObjectAnnotation": { + "parameter": "versionId", + "without": "s3:GetObjectAnnotation", + "with": "s3:GetObjectVersionAnnotation" + }, + "GetObjectAttributes": { + "parameter": "versionId", + "without": "s3:GetObject", + "with": "s3:GetObjectVersion" + }, + "GetObjectTagging": { + "parameter": "versionId", + "without": "s3:GetObjectTagging", + "with": "s3:GetObjectVersionTagging" + }, + "ListObjectAnnotations": { + "parameter": "versionId", + "without": "s3:ListObjectAnnotations", + "with": "s3:ListObjectVersionAnnotations" + }, + "PutObjectAcl": { + "parameter": "versionId", + "without": "s3:PutObjectAcl", + "with": "s3:PutObjectVersionAcl" + }, + "PutObjectAnnotation": { + "parameter": "versionId", + "without": "s3:PutObjectAnnotation", + "with": "s3:PutObjectVersionAnnotation" + }, + "PutObjectTagging": { + "parameter": "versionId", + "without": "s3:PutObjectTagging", + "with": "s3:PutObjectVersionTagging" + } + } + }, + "spellings": { + "amplify": { + "CreateWebhook": "amplify:CreateWebHook", + "DeleteWebhook": "amplify:DeleteWebHook", + "GetWebhook": "amplify:GetWebHook", + "ListWebhooks": "amplify:ListWebHooks", + "UpdateWebhook": "amplify:UpdateWebHook" + }, + "appflow": { + "UnregisterConnector": "appflow:UnRegisterConnector" + }, + "cleanrooms-ml": { + "UntagResource": "cleanrooms-ml:UnTagResource" + }, + "cloudsearch": { + "Search": "cloudsearch:search", + "Suggest": "cloudsearch:suggest" + }, + "codeguru-reviewer": { + "UntagResource": "codeguru-reviewer:UnTagResource" + }, + "lookoutequipment": { + "DescribeLabel": "lookoutequipment:Describelabel" + }, + "memorydb": { + "CreateACL": "memorydb:CreateAcl", + "DeleteACL": "memorydb:DeleteAcl", + "DescribeACLs": "memorydb:DescribeAcls", + "UpdateACL": "memorydb:UpdateAcl" + }, + "s3": { + "GetBucketCors": "s3:GetBucketCORS", + "PutBucketCors": "s3:PutBucketCORS" + } } } diff --git a/src/main/resources/aws/rest-routes.json b/src/main/resources/aws/rest-routes.json index af47424255..c8d5283446 100644 --- a/src/main/resources/aws/rest-routes.json +++ b/src/main/resources/aws/rest-routes.json @@ -1972,49 +1972,49 @@ "accessDeniedStatus": 403, "signedElsewhere": {"ListDirectoryBuckets": "s3express", "WriteGetObjectResponse": "s3-object-lambda"}, "operations": { - "AbortMultipartUpload": {"method": "DELETE", "requestUri": "/{Bucket}/{Key+}", "requires": {"query": ["uploadId"]}}, - "CompleteMultipartUpload": {"method": "POST", "requestUri": "/{Bucket}/{Key+}"}, - "CopyObject": {"method": "PUT", "requestUri": "/{Bucket}/{Key+}", "requires": {"headers": ["x-amz-copy-source"]}}, + "AbortMultipartUpload": {"method": "DELETE", "requestUri": "/{Bucket}/{Key+}", "required": {"query": ["uploadId"]}, "requires": {"query": ["uploadId"]}}, + "CompleteMultipartUpload": {"method": "POST", "requestUri": "/{Bucket}/{Key+}", "required": {"query": ["uploadId"]}}, + "CopyObject": {"method": "PUT", "requestUri": "/{Bucket}/{Key+}", "required": {"headers": ["x-amz-copy-source"]}, "requires": {"headers": ["x-amz-copy-source"]}}, "CreateBucket": {"method": "PUT", "requestUri": "/{Bucket}"}, "CreateBucketMetadataConfiguration": {"method": "POST", "requestUri": "/{Bucket}?metadataConfiguration"}, "CreateBucketMetadataTableConfiguration": {"method": "POST", "requestUri": "/{Bucket}?metadataTable"}, "CreateMultipartUpload": {"method": "POST", "requestUri": "/{Bucket}/{Key+}?uploads"}, "CreateSession": {"method": "GET", "requestUri": "/{Bucket}?session"}, "DeleteBucket": {"method": "DELETE", "requestUri": "/{Bucket}"}, - "DeleteBucketAnalyticsConfiguration": {"method": "DELETE", "requestUri": "/{Bucket}?analytics"}, + "DeleteBucketAnalyticsConfiguration": {"method": "DELETE", "requestUri": "/{Bucket}?analytics", "required": {"query": ["id"]}}, "DeleteBucketCors": {"method": "DELETE", "requestUri": "/{Bucket}?cors"}, "DeleteBucketEncryption": {"method": "DELETE", "requestUri": "/{Bucket}?encryption"}, - "DeleteBucketIntelligentTieringConfiguration": {"method": "DELETE", "requestUri": "/{Bucket}?intelligent-tiering"}, - "DeleteBucketInventoryConfiguration": {"method": "DELETE", "requestUri": "/{Bucket}?inventory"}, + "DeleteBucketIntelligentTieringConfiguration": {"method": "DELETE", "requestUri": "/{Bucket}?intelligent-tiering", "required": {"query": ["id"]}}, + "DeleteBucketInventoryConfiguration": {"method": "DELETE", "requestUri": "/{Bucket}?inventory", "required": {"query": ["id"]}}, "DeleteBucketLifecycle": {"method": "DELETE", "requestUri": "/{Bucket}?lifecycle"}, "DeleteBucketMetadataConfiguration": {"method": "DELETE", "requestUri": "/{Bucket}?metadataConfiguration"}, "DeleteBucketMetadataTableConfiguration": {"method": "DELETE", "requestUri": "/{Bucket}?metadataTable"}, - "DeleteBucketMetricsConfiguration": {"method": "DELETE", "requestUri": "/{Bucket}?metrics"}, + "DeleteBucketMetricsConfiguration": {"method": "DELETE", "requestUri": "/{Bucket}?metrics", "required": {"query": ["id"]}}, "DeleteBucketOwnershipControls": {"method": "DELETE", "requestUri": "/{Bucket}?ownershipControls"}, "DeleteBucketPolicy": {"method": "DELETE", "requestUri": "/{Bucket}?policy"}, "DeleteBucketReplication": {"method": "DELETE", "requestUri": "/{Bucket}?replication"}, "DeleteBucketTagging": {"method": "DELETE", "requestUri": "/{Bucket}?tagging"}, "DeleteBucketWebsite": {"method": "DELETE", "requestUri": "/{Bucket}?website"}, "DeleteObject": {"method": "DELETE", "requestUri": "/{Bucket}/{Key+}"}, - "DeleteObjectAnnotation": {"method": "DELETE", "requestUri": "/{Bucket}/{Key+}?annotation"}, + "DeleteObjectAnnotation": {"method": "DELETE", "requestUri": "/{Bucket}/{Key+}?annotation", "required": {"query": ["annotationName"]}}, "DeleteObjectTagging": {"method": "DELETE", "requestUri": "/{Bucket}/{Key+}?tagging"}, "DeleteObjects": {"method": "POST", "requestUri": "/{Bucket}?delete"}, "DeletePublicAccessBlock": {"method": "DELETE", "requestUri": "/{Bucket}?publicAccessBlock"}, "GetBucketAbac": {"method": "GET", "requestUri": "/{Bucket}?abac"}, "GetBucketAccelerateConfiguration": {"method": "GET", "requestUri": "/{Bucket}?accelerate"}, "GetBucketAcl": {"method": "GET", "requestUri": "/{Bucket}?acl"}, - "GetBucketAnalyticsConfiguration": {"method": "GET", "requestUri": "/{Bucket}?analytics", "requires": {"query": ["id"]}}, + "GetBucketAnalyticsConfiguration": {"method": "GET", "requestUri": "/{Bucket}?analytics", "required": {"query": ["id"]}, "requires": {"query": ["id"]}}, "GetBucketCors": {"method": "GET", "requestUri": "/{Bucket}?cors"}, "GetBucketEncryption": {"method": "GET", "requestUri": "/{Bucket}?encryption"}, - "GetBucketIntelligentTieringConfiguration": {"method": "GET", "requestUri": "/{Bucket}?intelligent-tiering", "requires": {"query": ["id"]}}, - "GetBucketInventoryConfiguration": {"method": "GET", "requestUri": "/{Bucket}?inventory", "requires": {"query": ["id"]}}, + "GetBucketIntelligentTieringConfiguration": {"method": "GET", "requestUri": "/{Bucket}?intelligent-tiering", "required": {"query": ["id"]}, "requires": {"query": ["id"]}}, + "GetBucketInventoryConfiguration": {"method": "GET", "requestUri": "/{Bucket}?inventory", "required": {"query": ["id"]}, "requires": {"query": ["id"]}}, "GetBucketLifecycle": {"method": "GET", "requestUri": "/{Bucket}?lifecycle", "deprecated": true}, "GetBucketLifecycleConfiguration": {"method": "GET", "requestUri": "/{Bucket}?lifecycle"}, "GetBucketLocation": {"method": "GET", "requestUri": "/{Bucket}?location"}, "GetBucketLogging": {"method": "GET", "requestUri": "/{Bucket}?logging"}, "GetBucketMetadataConfiguration": {"method": "GET", "requestUri": "/{Bucket}?metadataConfiguration"}, "GetBucketMetadataTableConfiguration": {"method": "GET", "requestUri": "/{Bucket}?metadataTable"}, - "GetBucketMetricsConfiguration": {"method": "GET", "requestUri": "/{Bucket}?metrics", "requires": {"query": ["id"]}}, + "GetBucketMetricsConfiguration": {"method": "GET", "requestUri": "/{Bucket}?metrics", "required": {"query": ["id"]}, "requires": {"query": ["id"]}}, "GetBucketNotification": {"method": "GET", "requestUri": "/{Bucket}?notification", "deprecated": true}, "GetBucketNotificationConfiguration": {"method": "GET", "requestUri": "/{Bucket}?notification"}, "GetBucketOwnershipControls": {"method": "GET", "requestUri": "/{Bucket}?ownershipControls"}, @@ -2027,8 +2027,8 @@ "GetBucketWebsite": {"method": "GET", "requestUri": "/{Bucket}?website"}, "GetObject": {"method": "GET", "requestUri": "/{Bucket}/{Key+}"}, "GetObjectAcl": {"method": "GET", "requestUri": "/{Bucket}/{Key+}?acl"}, - "GetObjectAnnotation": {"method": "GET", "requestUri": "/{Bucket}/{Key+}?annotation", "requires": {"query": ["annotationName"]}}, - "GetObjectAttributes": {"method": "GET", "requestUri": "/{Bucket}/{Key+}?attributes"}, + "GetObjectAnnotation": {"method": "GET", "requestUri": "/{Bucket}/{Key+}?annotation", "required": {"query": ["annotationName"]}, "requires": {"query": ["annotationName"]}}, + "GetObjectAttributes": {"method": "GET", "requestUri": "/{Bucket}/{Key+}?attributes", "required": {"headers": ["x-amz-object-attributes"]}}, "GetObjectLegalHold": {"method": "GET", "requestUri": "/{Bucket}/{Key+}?legal-hold"}, "GetObjectLockConfiguration": {"method": "GET", "requestUri": "/{Bucket}?object-lock"}, "GetObjectRetention": {"method": "GET", "requestUri": "/{Bucket}/{Key+}?retention"}, @@ -2047,19 +2047,19 @@ "ListObjectVersions": {"method": "GET", "requestUri": "/{Bucket}?versions"}, "ListObjects": {"method": "GET", "requestUri": "/{Bucket}"}, "ListObjectsV2": {"method": "GET", "requestUri": "/{Bucket}?list-type=2"}, - "ListParts": {"method": "GET", "requestUri": "/{Bucket}/{Key+}", "requires": {"query": ["uploadId"]}}, + "ListParts": {"method": "GET", "requestUri": "/{Bucket}/{Key+}", "required": {"query": ["uploadId"]}, "requires": {"query": ["uploadId"]}}, "PutBucketAbac": {"method": "PUT", "requestUri": "/{Bucket}?abac"}, "PutBucketAccelerateConfiguration": {"method": "PUT", "requestUri": "/{Bucket}?accelerate"}, "PutBucketAcl": {"method": "PUT", "requestUri": "/{Bucket}?acl"}, - "PutBucketAnalyticsConfiguration": {"method": "PUT", "requestUri": "/{Bucket}?analytics"}, + "PutBucketAnalyticsConfiguration": {"method": "PUT", "requestUri": "/{Bucket}?analytics", "required": {"query": ["id"]}}, "PutBucketCors": {"method": "PUT", "requestUri": "/{Bucket}?cors"}, "PutBucketEncryption": {"method": "PUT", "requestUri": "/{Bucket}?encryption"}, - "PutBucketIntelligentTieringConfiguration": {"method": "PUT", "requestUri": "/{Bucket}?intelligent-tiering"}, - "PutBucketInventoryConfiguration": {"method": "PUT", "requestUri": "/{Bucket}?inventory"}, + "PutBucketIntelligentTieringConfiguration": {"method": "PUT", "requestUri": "/{Bucket}?intelligent-tiering", "required": {"query": ["id"]}}, + "PutBucketInventoryConfiguration": {"method": "PUT", "requestUri": "/{Bucket}?inventory", "required": {"query": ["id"]}}, "PutBucketLifecycle": {"method": "PUT", "requestUri": "/{Bucket}?lifecycle", "deprecated": true}, "PutBucketLifecycleConfiguration": {"method": "PUT", "requestUri": "/{Bucket}?lifecycle"}, "PutBucketLogging": {"method": "PUT", "requestUri": "/{Bucket}?logging"}, - "PutBucketMetricsConfiguration": {"method": "PUT", "requestUri": "/{Bucket}?metrics"}, + "PutBucketMetricsConfiguration": {"method": "PUT", "requestUri": "/{Bucket}?metrics", "required": {"query": ["id"]}}, "PutBucketNotification": {"method": "PUT", "requestUri": "/{Bucket}?notification", "deprecated": true}, "PutBucketNotificationConfiguration": {"method": "PUT", "requestUri": "/{Bucket}?notification"}, "PutBucketOwnershipControls": {"method": "PUT", "requestUri": "/{Bucket}?ownershipControls"}, @@ -2071,124 +2071,124 @@ "PutBucketWebsite": {"method": "PUT", "requestUri": "/{Bucket}?website"}, "PutObject": {"method": "PUT", "requestUri": "/{Bucket}/{Key+}"}, "PutObjectAcl": {"method": "PUT", "requestUri": "/{Bucket}/{Key+}?acl"}, - "PutObjectAnnotation": {"method": "PUT", "requestUri": "/{Bucket}/{Key+}?annotation"}, + "PutObjectAnnotation": {"method": "PUT", "requestUri": "/{Bucket}/{Key+}?annotation", "required": {"query": ["annotationName"]}}, "PutObjectLegalHold": {"method": "PUT", "requestUri": "/{Bucket}/{Key+}?legal-hold"}, "PutObjectLockConfiguration": {"method": "PUT", "requestUri": "/{Bucket}?object-lock"}, "PutObjectRetention": {"method": "PUT", "requestUri": "/{Bucket}/{Key+}?retention"}, "PutObjectTagging": {"method": "PUT", "requestUri": "/{Bucket}/{Key+}?tagging"}, "PutPublicAccessBlock": {"method": "PUT", "requestUri": "/{Bucket}?publicAccessBlock"}, - "RenameObject": {"method": "PUT", "requestUri": "/{Bucket}/{Key+}?renameObject"}, + "RenameObject": {"method": "PUT", "requestUri": "/{Bucket}/{Key+}?renameObject", "required": {"headers": ["x-amz-rename-source"]}}, "RestoreObject": {"method": "POST", "requestUri": "/{Bucket}/{Key+}?restore"}, "SelectObjectContent": {"method": "POST", "requestUri": "/{Bucket}/{Key+}?select&select-type=2"}, "UpdateBucketMetadataAnnotationTableConfiguration": {"method": "PUT", "requestUri": "/{Bucket}?metadataAnnotationTable"}, "UpdateBucketMetadataInventoryTableConfiguration": {"method": "PUT", "requestUri": "/{Bucket}?metadataInventoryTable"}, "UpdateBucketMetadataJournalTableConfiguration": {"method": "PUT", "requestUri": "/{Bucket}?metadataJournalTable"}, "UpdateObjectEncryption": {"method": "PUT", "requestUri": "/{Bucket}/{Key+}?encryption"}, - "UploadPart": {"method": "PUT", "requestUri": "/{Bucket}/{Key+}", "requires": {"query": ["partNumber", "uploadId"]}}, - "UploadPartCopy": {"method": "PUT", "requestUri": "/{Bucket}/{Key+}", "requires": {"query": ["partNumber", "uploadId"], "headers": ["x-amz-copy-source"]}} + "UploadPart": {"method": "PUT", "requestUri": "/{Bucket}/{Key+}", "required": {"query": ["partNumber", "uploadId"]}, "requires": {"query": ["partNumber", "uploadId"]}}, + "UploadPartCopy": {"method": "PUT", "requestUri": "/{Bucket}/{Key+}", "required": {"query": ["partNumber", "uploadId"], "headers": ["x-amz-copy-source"]}, "requires": {"query": ["partNumber", "uploadId"], "headers": ["x-amz-copy-source"]}} } }, "s3control": { "credentialScope": "s3", "apiVersion": "2018-08-20", "operations": { - "AssociateAccessGrantsIdentityCenter": {"method": "POST", "requestUri": "/v20180820/accessgrantsinstance/identitycenter"}, - "CreateAccessGrant": {"method": "POST", "requestUri": "/v20180820/accessgrantsinstance/grant"}, - "CreateAccessGrantsInstance": {"method": "POST", "requestUri": "/v20180820/accessgrantsinstance"}, - "CreateAccessGrantsLocation": {"method": "POST", "requestUri": "/v20180820/accessgrantsinstance/location"}, - "CreateAccessPoint": {"method": "PUT", "requestUri": "/v20180820/accesspoint/{name}"}, - "CreateAccessPointForObjectLambda": {"method": "PUT", "requestUri": "/v20180820/accesspointforobjectlambda/{name}"}, + "AssociateAccessGrantsIdentityCenter": {"method": "POST", "requestUri": "/v20180820/accessgrantsinstance/identitycenter", "required": {"headers": ["x-amz-account-id"]}}, + "CreateAccessGrant": {"method": "POST", "requestUri": "/v20180820/accessgrantsinstance/grant", "required": {"headers": ["x-amz-account-id"]}}, + "CreateAccessGrantsInstance": {"method": "POST", "requestUri": "/v20180820/accessgrantsinstance", "required": {"headers": ["x-amz-account-id"]}}, + "CreateAccessGrantsLocation": {"method": "POST", "requestUri": "/v20180820/accessgrantsinstance/location", "required": {"headers": ["x-amz-account-id"]}}, + "CreateAccessPoint": {"method": "PUT", "requestUri": "/v20180820/accesspoint/{name}", "required": {"headers": ["x-amz-account-id"]}}, + "CreateAccessPointForObjectLambda": {"method": "PUT", "requestUri": "/v20180820/accesspointforobjectlambda/{name}", "required": {"headers": ["x-amz-account-id"]}}, "CreateBucket": {"method": "PUT", "requestUri": "/v20180820/bucket/{name}"}, - "CreateJob": {"method": "POST", "requestUri": "/v20180820/jobs"}, - "CreateMultiRegionAccessPoint": {"method": "POST", "requestUri": "/v20180820/async-requests/mrap/create"}, - "CreateStorageLensGroup": {"method": "POST", "requestUri": "/v20180820/storagelensgroup"}, - "DeleteAccessGrant": {"method": "DELETE", "requestUri": "/v20180820/accessgrantsinstance/grant/{id}"}, - "DeleteAccessGrantsInstance": {"method": "DELETE", "requestUri": "/v20180820/accessgrantsinstance"}, - "DeleteAccessGrantsInstanceResourcePolicy": {"method": "DELETE", "requestUri": "/v20180820/accessgrantsinstance/resourcepolicy"}, - "DeleteAccessGrantsLocation": {"method": "DELETE", "requestUri": "/v20180820/accessgrantsinstance/location/{id}"}, - "DeleteAccessPoint": {"method": "DELETE", "requestUri": "/v20180820/accesspoint/{name}"}, - "DeleteAccessPointForObjectLambda": {"method": "DELETE", "requestUri": "/v20180820/accesspointforobjectlambda/{name}"}, - "DeleteAccessPointPolicy": {"method": "DELETE", "requestUri": "/v20180820/accesspoint/{name}/policy"}, - "DeleteAccessPointPolicyForObjectLambda": {"method": "DELETE", "requestUri": "/v20180820/accesspointforobjectlambda/{name}/policy"}, - "DeleteAccessPointScope": {"method": "DELETE", "requestUri": "/v20180820/accesspoint/{name}/scope"}, - "DeleteBucket": {"method": "DELETE", "requestUri": "/v20180820/bucket/{name}"}, - "DeleteBucketLifecycleConfiguration": {"method": "DELETE", "requestUri": "/v20180820/bucket/{name}/lifecycleconfiguration"}, - "DeleteBucketPolicy": {"method": "DELETE", "requestUri": "/v20180820/bucket/{name}/policy"}, - "DeleteBucketReplication": {"method": "DELETE", "requestUri": "/v20180820/bucket/{name}/replication"}, - "DeleteBucketTagging": {"method": "DELETE", "requestUri": "/v20180820/bucket/{name}/tagging"}, - "DeleteJobTagging": {"method": "DELETE", "requestUri": "/v20180820/jobs/{id}/tagging"}, - "DeleteMultiRegionAccessPoint": {"method": "POST", "requestUri": "/v20180820/async-requests/mrap/delete"}, - "DeletePublicAccessBlock": {"method": "DELETE", "requestUri": "/v20180820/configuration/publicAccessBlock"}, - "DeleteStorageLensConfiguration": {"method": "DELETE", "requestUri": "/v20180820/storagelens/{storagelensid}"}, - "DeleteStorageLensConfigurationTagging": {"method": "DELETE", "requestUri": "/v20180820/storagelens/{storagelensid}/tagging"}, - "DeleteStorageLensGroup": {"method": "DELETE", "requestUri": "/v20180820/storagelensgroup/{name}"}, - "DescribeJob": {"method": "GET", "requestUri": "/v20180820/jobs/{id}"}, - "DescribeMultiRegionAccessPointOperation": {"method": "GET", "requestUri": "/v20180820/async-requests/mrap/{request_token+}"}, - "DissociateAccessGrantsIdentityCenter": {"method": "DELETE", "requestUri": "/v20180820/accessgrantsinstance/identitycenter"}, - "GetAccessGrant": {"method": "GET", "requestUri": "/v20180820/accessgrantsinstance/grant/{id}"}, - "GetAccessGrantsInstance": {"method": "GET", "requestUri": "/v20180820/accessgrantsinstance"}, - "GetAccessGrantsInstanceForPrefix": {"method": "GET", "requestUri": "/v20180820/accessgrantsinstance/prefix"}, - "GetAccessGrantsInstanceResourcePolicy": {"method": "GET", "requestUri": "/v20180820/accessgrantsinstance/resourcepolicy"}, - "GetAccessGrantsLocation": {"method": "GET", "requestUri": "/v20180820/accessgrantsinstance/location/{id}"}, - "GetAccessPoint": {"method": "GET", "requestUri": "/v20180820/accesspoint/{name}"}, - "GetAccessPointConfigurationForObjectLambda": {"method": "GET", "requestUri": "/v20180820/accesspointforobjectlambda/{name}/configuration"}, - "GetAccessPointForObjectLambda": {"method": "GET", "requestUri": "/v20180820/accesspointforobjectlambda/{name}"}, - "GetAccessPointPolicy": {"method": "GET", "requestUri": "/v20180820/accesspoint/{name}/policy"}, - "GetAccessPointPolicyForObjectLambda": {"method": "GET", "requestUri": "/v20180820/accesspointforobjectlambda/{name}/policy"}, - "GetAccessPointPolicyStatus": {"method": "GET", "requestUri": "/v20180820/accesspoint/{name}/policyStatus"}, - "GetAccessPointPolicyStatusForObjectLambda": {"method": "GET", "requestUri": "/v20180820/accesspointforobjectlambda/{name}/policyStatus"}, - "GetAccessPointScope": {"method": "GET", "requestUri": "/v20180820/accesspoint/{name}/scope"}, - "GetBucket": {"method": "GET", "requestUri": "/v20180820/bucket/{name}"}, - "GetBucketLifecycleConfiguration": {"method": "GET", "requestUri": "/v20180820/bucket/{name}/lifecycleconfiguration"}, - "GetBucketPolicy": {"method": "GET", "requestUri": "/v20180820/bucket/{name}/policy"}, - "GetBucketReplication": {"method": "GET", "requestUri": "/v20180820/bucket/{name}/replication"}, - "GetBucketTagging": {"method": "GET", "requestUri": "/v20180820/bucket/{name}/tagging"}, - "GetBucketVersioning": {"method": "GET", "requestUri": "/v20180820/bucket/{name}/versioning"}, - "GetDataAccess": {"method": "GET", "requestUri": "/v20180820/accessgrantsinstance/dataaccess"}, - "GetJobTagging": {"method": "GET", "requestUri": "/v20180820/jobs/{id}/tagging"}, - "GetMultiRegionAccessPoint": {"method": "GET", "requestUri": "/v20180820/mrap/instances/{name+}"}, - "GetMultiRegionAccessPointPolicy": {"method": "GET", "requestUri": "/v20180820/mrap/instances/{name+}/policy"}, - "GetMultiRegionAccessPointPolicyStatus": {"method": "GET", "requestUri": "/v20180820/mrap/instances/{name+}/policystatus"}, - "GetMultiRegionAccessPointRoutes": {"method": "GET", "requestUri": "/v20180820/mrap/instances/{mrap+}/routes"}, - "GetPublicAccessBlock": {"method": "GET", "requestUri": "/v20180820/configuration/publicAccessBlock"}, - "GetStorageLensConfiguration": {"method": "GET", "requestUri": "/v20180820/storagelens/{storagelensid}"}, - "GetStorageLensConfigurationTagging": {"method": "GET", "requestUri": "/v20180820/storagelens/{storagelensid}/tagging"}, - "GetStorageLensGroup": {"method": "GET", "requestUri": "/v20180820/storagelensgroup/{name}"}, - "ListAccessGrants": {"method": "GET", "requestUri": "/v20180820/accessgrantsinstance/grants"}, - "ListAccessGrantsInstances": {"method": "GET", "requestUri": "/v20180820/accessgrantsinstances"}, - "ListAccessGrantsLocations": {"method": "GET", "requestUri": "/v20180820/accessgrantsinstance/locations"}, - "ListAccessPoints": {"method": "GET", "requestUri": "/v20180820/accesspoint"}, - "ListAccessPointsForDirectoryBuckets": {"method": "GET", "requestUri": "/v20180820/accesspointfordirectory"}, - "ListAccessPointsForObjectLambda": {"method": "GET", "requestUri": "/v20180820/accesspointforobjectlambda"}, - "ListCallerAccessGrants": {"method": "GET", "requestUri": "/v20180820/accessgrantsinstance/caller/grants"}, - "ListJobs": {"method": "GET", "requestUri": "/v20180820/jobs"}, - "ListMultiRegionAccessPoints": {"method": "GET", "requestUri": "/v20180820/mrap/instances"}, - "ListRegionalBuckets": {"method": "GET", "requestUri": "/v20180820/bucket"}, - "ListStorageLensConfigurations": {"method": "GET", "requestUri": "/v20180820/storagelens"}, - "ListStorageLensGroups": {"method": "GET", "requestUri": "/v20180820/storagelensgroup"}, - "ListTagsForResource": {"method": "GET", "requestUri": "/v20180820/tags/{resourceArn+}"}, - "PutAccessGrantsInstanceResourcePolicy": {"method": "PUT", "requestUri": "/v20180820/accessgrantsinstance/resourcepolicy"}, - "PutAccessPointConfigurationForObjectLambda": {"method": "PUT", "requestUri": "/v20180820/accesspointforobjectlambda/{name}/configuration"}, - "PutAccessPointPolicy": {"method": "PUT", "requestUri": "/v20180820/accesspoint/{name}/policy"}, - "PutAccessPointPolicyForObjectLambda": {"method": "PUT", "requestUri": "/v20180820/accesspointforobjectlambda/{name}/policy"}, - "PutAccessPointScope": {"method": "PUT", "requestUri": "/v20180820/accesspoint/{name}/scope"}, - "PutBucketLifecycleConfiguration": {"method": "PUT", "requestUri": "/v20180820/bucket/{name}/lifecycleconfiguration"}, - "PutBucketPolicy": {"method": "PUT", "requestUri": "/v20180820/bucket/{name}/policy"}, - "PutBucketReplication": {"method": "PUT", "requestUri": "/v20180820/bucket/{name}/replication"}, - "PutBucketTagging": {"method": "PUT", "requestUri": "/v20180820/bucket/{name}/tagging"}, - "PutBucketVersioning": {"method": "PUT", "requestUri": "/v20180820/bucket/{name}/versioning"}, - "PutJobTagging": {"method": "PUT", "requestUri": "/v20180820/jobs/{id}/tagging"}, - "PutMultiRegionAccessPointPolicy": {"method": "POST", "requestUri": "/v20180820/async-requests/mrap/put-policy"}, - "PutPublicAccessBlock": {"method": "PUT", "requestUri": "/v20180820/configuration/publicAccessBlock"}, - "PutStorageLensConfiguration": {"method": "PUT", "requestUri": "/v20180820/storagelens/{storagelensid}"}, - "PutStorageLensConfigurationTagging": {"method": "PUT", "requestUri": "/v20180820/storagelens/{storagelensid}/tagging"}, - "SubmitMultiRegionAccessPointRoutes": {"method": "PATCH", "requestUri": "/v20180820/mrap/instances/{mrap+}/routes"}, - "TagResource": {"method": "POST", "requestUri": "/v20180820/tags/{resourceArn+}"}, - "UntagResource": {"method": "DELETE", "requestUri": "/v20180820/tags/{resourceArn+}"}, - "UpdateAccessGrantsLocation": {"method": "PUT", "requestUri": "/v20180820/accessgrantsinstance/location/{id}"}, - "UpdateJobPriority": {"method": "POST", "requestUri": "/v20180820/jobs/{id}/priority"}, - "UpdateJobStatus": {"method": "POST", "requestUri": "/v20180820/jobs/{id}/status"}, - "UpdateStorageLensGroup": {"method": "PUT", "requestUri": "/v20180820/storagelensgroup/{name}"} + "CreateJob": {"method": "POST", "requestUri": "/v20180820/jobs", "required": {"headers": ["x-amz-account-id"]}}, + "CreateMultiRegionAccessPoint": {"method": "POST", "requestUri": "/v20180820/async-requests/mrap/create", "required": {"headers": ["x-amz-account-id"]}}, + "CreateStorageLensGroup": {"method": "POST", "requestUri": "/v20180820/storagelensgroup", "required": {"headers": ["x-amz-account-id"]}}, + "DeleteAccessGrant": {"method": "DELETE", "requestUri": "/v20180820/accessgrantsinstance/grant/{id}", "required": {"headers": ["x-amz-account-id"]}}, + "DeleteAccessGrantsInstance": {"method": "DELETE", "requestUri": "/v20180820/accessgrantsinstance", "required": {"headers": ["x-amz-account-id"]}}, + "DeleteAccessGrantsInstanceResourcePolicy": {"method": "DELETE", "requestUri": "/v20180820/accessgrantsinstance/resourcepolicy", "required": {"headers": ["x-amz-account-id"]}}, + "DeleteAccessGrantsLocation": {"method": "DELETE", "requestUri": "/v20180820/accessgrantsinstance/location/{id}", "required": {"headers": ["x-amz-account-id"]}}, + "DeleteAccessPoint": {"method": "DELETE", "requestUri": "/v20180820/accesspoint/{name}", "required": {"headers": ["x-amz-account-id"]}}, + "DeleteAccessPointForObjectLambda": {"method": "DELETE", "requestUri": "/v20180820/accesspointforobjectlambda/{name}", "required": {"headers": ["x-amz-account-id"]}}, + "DeleteAccessPointPolicy": {"method": "DELETE", "requestUri": "/v20180820/accesspoint/{name}/policy", "required": {"headers": ["x-amz-account-id"]}}, + "DeleteAccessPointPolicyForObjectLambda": {"method": "DELETE", "requestUri": "/v20180820/accesspointforobjectlambda/{name}/policy", "required": {"headers": ["x-amz-account-id"]}}, + "DeleteAccessPointScope": {"method": "DELETE", "requestUri": "/v20180820/accesspoint/{name}/scope", "required": {"headers": ["x-amz-account-id"]}}, + "DeleteBucket": {"method": "DELETE", "requestUri": "/v20180820/bucket/{name}", "required": {"headers": ["x-amz-account-id"]}}, + "DeleteBucketLifecycleConfiguration": {"method": "DELETE", "requestUri": "/v20180820/bucket/{name}/lifecycleconfiguration", "required": {"headers": ["x-amz-account-id"]}}, + "DeleteBucketPolicy": {"method": "DELETE", "requestUri": "/v20180820/bucket/{name}/policy", "required": {"headers": ["x-amz-account-id"]}}, + "DeleteBucketReplication": {"method": "DELETE", "requestUri": "/v20180820/bucket/{name}/replication", "required": {"headers": ["x-amz-account-id"]}}, + "DeleteBucketTagging": {"method": "DELETE", "requestUri": "/v20180820/bucket/{name}/tagging", "required": {"headers": ["x-amz-account-id"]}}, + "DeleteJobTagging": {"method": "DELETE", "requestUri": "/v20180820/jobs/{id}/tagging", "required": {"headers": ["x-amz-account-id"]}}, + "DeleteMultiRegionAccessPoint": {"method": "POST", "requestUri": "/v20180820/async-requests/mrap/delete", "required": {"headers": ["x-amz-account-id"]}}, + "DeletePublicAccessBlock": {"method": "DELETE", "requestUri": "/v20180820/configuration/publicAccessBlock", "required": {"headers": ["x-amz-account-id"]}}, + "DeleteStorageLensConfiguration": {"method": "DELETE", "requestUri": "/v20180820/storagelens/{storagelensid}", "required": {"headers": ["x-amz-account-id"]}}, + "DeleteStorageLensConfigurationTagging": {"method": "DELETE", "requestUri": "/v20180820/storagelens/{storagelensid}/tagging", "required": {"headers": ["x-amz-account-id"]}}, + "DeleteStorageLensGroup": {"method": "DELETE", "requestUri": "/v20180820/storagelensgroup/{name}", "required": {"headers": ["x-amz-account-id"]}}, + "DescribeJob": {"method": "GET", "requestUri": "/v20180820/jobs/{id}", "required": {"headers": ["x-amz-account-id"]}}, + "DescribeMultiRegionAccessPointOperation": {"method": "GET", "requestUri": "/v20180820/async-requests/mrap/{request_token+}", "required": {"headers": ["x-amz-account-id"]}}, + "DissociateAccessGrantsIdentityCenter": {"method": "DELETE", "requestUri": "/v20180820/accessgrantsinstance/identitycenter", "required": {"headers": ["x-amz-account-id"]}}, + "GetAccessGrant": {"method": "GET", "requestUri": "/v20180820/accessgrantsinstance/grant/{id}", "required": {"headers": ["x-amz-account-id"]}}, + "GetAccessGrantsInstance": {"method": "GET", "requestUri": "/v20180820/accessgrantsinstance", "required": {"headers": ["x-amz-account-id"]}}, + "GetAccessGrantsInstanceForPrefix": {"method": "GET", "requestUri": "/v20180820/accessgrantsinstance/prefix", "required": {"query": ["s3prefix"], "headers": ["x-amz-account-id"]}}, + "GetAccessGrantsInstanceResourcePolicy": {"method": "GET", "requestUri": "/v20180820/accessgrantsinstance/resourcepolicy", "required": {"headers": ["x-amz-account-id"]}}, + "GetAccessGrantsLocation": {"method": "GET", "requestUri": "/v20180820/accessgrantsinstance/location/{id}", "required": {"headers": ["x-amz-account-id"]}}, + "GetAccessPoint": {"method": "GET", "requestUri": "/v20180820/accesspoint/{name}", "required": {"headers": ["x-amz-account-id"]}}, + "GetAccessPointConfigurationForObjectLambda": {"method": "GET", "requestUri": "/v20180820/accesspointforobjectlambda/{name}/configuration", "required": {"headers": ["x-amz-account-id"]}}, + "GetAccessPointForObjectLambda": {"method": "GET", "requestUri": "/v20180820/accesspointforobjectlambda/{name}", "required": {"headers": ["x-amz-account-id"]}}, + "GetAccessPointPolicy": {"method": "GET", "requestUri": "/v20180820/accesspoint/{name}/policy", "required": {"headers": ["x-amz-account-id"]}}, + "GetAccessPointPolicyForObjectLambda": {"method": "GET", "requestUri": "/v20180820/accesspointforobjectlambda/{name}/policy", "required": {"headers": ["x-amz-account-id"]}}, + "GetAccessPointPolicyStatus": {"method": "GET", "requestUri": "/v20180820/accesspoint/{name}/policyStatus", "required": {"headers": ["x-amz-account-id"]}}, + "GetAccessPointPolicyStatusForObjectLambda": {"method": "GET", "requestUri": "/v20180820/accesspointforobjectlambda/{name}/policyStatus", "required": {"headers": ["x-amz-account-id"]}}, + "GetAccessPointScope": {"method": "GET", "requestUri": "/v20180820/accesspoint/{name}/scope", "required": {"headers": ["x-amz-account-id"]}}, + "GetBucket": {"method": "GET", "requestUri": "/v20180820/bucket/{name}", "required": {"headers": ["x-amz-account-id"]}}, + "GetBucketLifecycleConfiguration": {"method": "GET", "requestUri": "/v20180820/bucket/{name}/lifecycleconfiguration", "required": {"headers": ["x-amz-account-id"]}}, + "GetBucketPolicy": {"method": "GET", "requestUri": "/v20180820/bucket/{name}/policy", "required": {"headers": ["x-amz-account-id"]}}, + "GetBucketReplication": {"method": "GET", "requestUri": "/v20180820/bucket/{name}/replication", "required": {"headers": ["x-amz-account-id"]}}, + "GetBucketTagging": {"method": "GET", "requestUri": "/v20180820/bucket/{name}/tagging", "required": {"headers": ["x-amz-account-id"]}}, + "GetBucketVersioning": {"method": "GET", "requestUri": "/v20180820/bucket/{name}/versioning", "required": {"headers": ["x-amz-account-id"]}}, + "GetDataAccess": {"method": "GET", "requestUri": "/v20180820/accessgrantsinstance/dataaccess", "required": {"query": ["permission", "target"], "headers": ["x-amz-account-id"]}}, + "GetJobTagging": {"method": "GET", "requestUri": "/v20180820/jobs/{id}/tagging", "required": {"headers": ["x-amz-account-id"]}}, + "GetMultiRegionAccessPoint": {"method": "GET", "requestUri": "/v20180820/mrap/instances/{name+}", "required": {"headers": ["x-amz-account-id"]}}, + "GetMultiRegionAccessPointPolicy": {"method": "GET", "requestUri": "/v20180820/mrap/instances/{name+}/policy", "required": {"headers": ["x-amz-account-id"]}}, + "GetMultiRegionAccessPointPolicyStatus": {"method": "GET", "requestUri": "/v20180820/mrap/instances/{name+}/policystatus", "required": {"headers": ["x-amz-account-id"]}}, + "GetMultiRegionAccessPointRoutes": {"method": "GET", "requestUri": "/v20180820/mrap/instances/{mrap+}/routes", "required": {"headers": ["x-amz-account-id"]}}, + "GetPublicAccessBlock": {"method": "GET", "requestUri": "/v20180820/configuration/publicAccessBlock", "required": {"headers": ["x-amz-account-id"]}}, + "GetStorageLensConfiguration": {"method": "GET", "requestUri": "/v20180820/storagelens/{storagelensid}", "required": {"headers": ["x-amz-account-id"]}}, + "GetStorageLensConfigurationTagging": {"method": "GET", "requestUri": "/v20180820/storagelens/{storagelensid}/tagging", "required": {"headers": ["x-amz-account-id"]}}, + "GetStorageLensGroup": {"method": "GET", "requestUri": "/v20180820/storagelensgroup/{name}", "required": {"headers": ["x-amz-account-id"]}}, + "ListAccessGrants": {"method": "GET", "requestUri": "/v20180820/accessgrantsinstance/grants", "required": {"headers": ["x-amz-account-id"]}}, + "ListAccessGrantsInstances": {"method": "GET", "requestUri": "/v20180820/accessgrantsinstances", "required": {"headers": ["x-amz-account-id"]}}, + "ListAccessGrantsLocations": {"method": "GET", "requestUri": "/v20180820/accessgrantsinstance/locations", "required": {"headers": ["x-amz-account-id"]}}, + "ListAccessPoints": {"method": "GET", "requestUri": "/v20180820/accesspoint", "required": {"headers": ["x-amz-account-id"]}}, + "ListAccessPointsForDirectoryBuckets": {"method": "GET", "requestUri": "/v20180820/accesspointfordirectory", "required": {"headers": ["x-amz-account-id"]}}, + "ListAccessPointsForObjectLambda": {"method": "GET", "requestUri": "/v20180820/accesspointforobjectlambda", "required": {"headers": ["x-amz-account-id"]}}, + "ListCallerAccessGrants": {"method": "GET", "requestUri": "/v20180820/accessgrantsinstance/caller/grants", "required": {"headers": ["x-amz-account-id"]}}, + "ListJobs": {"method": "GET", "requestUri": "/v20180820/jobs", "required": {"headers": ["x-amz-account-id"]}}, + "ListMultiRegionAccessPoints": {"method": "GET", "requestUri": "/v20180820/mrap/instances", "required": {"headers": ["x-amz-account-id"]}}, + "ListRegionalBuckets": {"method": "GET", "requestUri": "/v20180820/bucket", "required": {"headers": ["x-amz-account-id"]}}, + "ListStorageLensConfigurations": {"method": "GET", "requestUri": "/v20180820/storagelens", "required": {"headers": ["x-amz-account-id"]}}, + "ListStorageLensGroups": {"method": "GET", "requestUri": "/v20180820/storagelensgroup", "required": {"headers": ["x-amz-account-id"]}}, + "ListTagsForResource": {"method": "GET", "requestUri": "/v20180820/tags/{resourceArn+}", "required": {"headers": ["x-amz-account-id"]}}, + "PutAccessGrantsInstanceResourcePolicy": {"method": "PUT", "requestUri": "/v20180820/accessgrantsinstance/resourcepolicy", "required": {"headers": ["x-amz-account-id"]}}, + "PutAccessPointConfigurationForObjectLambda": {"method": "PUT", "requestUri": "/v20180820/accesspointforobjectlambda/{name}/configuration", "required": {"headers": ["x-amz-account-id"]}}, + "PutAccessPointPolicy": {"method": "PUT", "requestUri": "/v20180820/accesspoint/{name}/policy", "required": {"headers": ["x-amz-account-id"]}}, + "PutAccessPointPolicyForObjectLambda": {"method": "PUT", "requestUri": "/v20180820/accesspointforobjectlambda/{name}/policy", "required": {"headers": ["x-amz-account-id"]}}, + "PutAccessPointScope": {"method": "PUT", "requestUri": "/v20180820/accesspoint/{name}/scope", "required": {"headers": ["x-amz-account-id"]}}, + "PutBucketLifecycleConfiguration": {"method": "PUT", "requestUri": "/v20180820/bucket/{name}/lifecycleconfiguration", "required": {"headers": ["x-amz-account-id"]}}, + "PutBucketPolicy": {"method": "PUT", "requestUri": "/v20180820/bucket/{name}/policy", "required": {"headers": ["x-amz-account-id"]}}, + "PutBucketReplication": {"method": "PUT", "requestUri": "/v20180820/bucket/{name}/replication", "required": {"headers": ["x-amz-account-id"]}}, + "PutBucketTagging": {"method": "PUT", "requestUri": "/v20180820/bucket/{name}/tagging", "required": {"headers": ["x-amz-account-id"]}}, + "PutBucketVersioning": {"method": "PUT", "requestUri": "/v20180820/bucket/{name}/versioning", "required": {"headers": ["x-amz-account-id"]}}, + "PutJobTagging": {"method": "PUT", "requestUri": "/v20180820/jobs/{id}/tagging", "required": {"headers": ["x-amz-account-id"]}}, + "PutMultiRegionAccessPointPolicy": {"method": "POST", "requestUri": "/v20180820/async-requests/mrap/put-policy", "required": {"headers": ["x-amz-account-id"]}}, + "PutPublicAccessBlock": {"method": "PUT", "requestUri": "/v20180820/configuration/publicAccessBlock", "required": {"headers": ["x-amz-account-id"]}}, + "PutStorageLensConfiguration": {"method": "PUT", "requestUri": "/v20180820/storagelens/{storagelensid}", "required": {"headers": ["x-amz-account-id"]}}, + "PutStorageLensConfigurationTagging": {"method": "PUT", "requestUri": "/v20180820/storagelens/{storagelensid}/tagging", "required": {"headers": ["x-amz-account-id"]}}, + "SubmitMultiRegionAccessPointRoutes": {"method": "PATCH", "requestUri": "/v20180820/mrap/instances/{mrap+}/routes", "required": {"headers": ["x-amz-account-id"]}}, + "TagResource": {"method": "POST", "requestUri": "/v20180820/tags/{resourceArn+}", "required": {"headers": ["x-amz-account-id"]}}, + "UntagResource": {"method": "DELETE", "requestUri": "/v20180820/tags/{resourceArn+}", "required": {"query": ["tagKeys"], "headers": ["x-amz-account-id"]}}, + "UpdateAccessGrantsLocation": {"method": "PUT", "requestUri": "/v20180820/accessgrantsinstance/location/{id}", "required": {"headers": ["x-amz-account-id"]}}, + "UpdateJobPriority": {"method": "POST", "requestUri": "/v20180820/jobs/{id}/priority", "required": {"query": ["priority"], "headers": ["x-amz-account-id"]}}, + "UpdateJobStatus": {"method": "POST", "requestUri": "/v20180820/jobs/{id}/status", "required": {"query": ["requestedJobStatus"], "headers": ["x-amz-account-id"]}}, + "UpdateStorageLensGroup": {"method": "PUT", "requestUri": "/v20180820/storagelensgroup/{name}", "required": {"headers": ["x-amz-account-id"]}} } }, "s3tables": { diff --git a/src/test/java/io/floci/aws/services/iam/IamAuthorizedActionsTest.java b/src/test/java/io/floci/aws/services/iam/IamAuthorizedActionsTest.java index 2c8ccef63a..82311a447c 100644 --- a/src/test/java/io/floci/aws/services/iam/IamAuthorizedActionsTest.java +++ b/src/test/java/io/floci/aws/services/iam/IamAuthorizedActionsTest.java @@ -1,5 +1,7 @@ package io.floci.aws.services.iam; +import jakarta.ws.rs.core.MultivaluedHashMap; +import jakarta.ws.rs.core.MultivaluedMap; import org.junit.jupiter.api.Test; import java.io.ByteArrayInputStream; @@ -56,6 +58,68 @@ class IamAuthorizedActionsTest { assertEquals(Set.of("apigateway:GetStage", "apigateway:TagResource"), parsed.byMethod()); } + @Test + void theActionsOfAModelsRequestsAVersionChoiceAndSpellingsAreKeyedByOperation() throws IOException { + IamAuthorizedActions.Table parsed = IamAuthorizedActions.parse(json(""" + {"authorizedActions": {"sqs": {"SendMessageBatch": "sqs:SendMessage"}}, + "actionsWithoutResourceTypes": {}, "authorizedByMethod": {}, + "authorizedByModel": {"s3": {"s3control": {"GetPublicAccessBlock": "s3:GetAccountPublicAccessBlock"}}}, + "versioned": {"s3": {"GetObject": {"parameter": "versionId", "without": "s3:GetObject", + "with": "s3:GetObjectVersion"}}}, + "spellings": {"memorydb": {"CreateACL": "memorydb:CreateAcl"}}} + """)); + assertEquals(Map.of("s3:GetPublicAccessBlock@s3control", "s3:GetAccountPublicAccessBlock"), parsed.byModel()); + assertEquals(Map.of("s3:GetObject", new IamAuthorizedActions.Versioned("versionId", "s3:GetObject", + "s3:GetObjectVersion")), parsed.versioned()); + assertEquals(Map.of("memorydb:CreateACL", "memorydb:CreateAcl"), parsed.spellings()); + } + + @Test + void aMalformedModelVersionOrSpellingEntryIsRefused() { + String base = "\"authorizedActions\": {\"sqs\": {\"A\": \"sqs:B\"}}, \"actionsWithoutResourceTypes\": {}, " + + "\"authorizedByMethod\": {}, "; + assertThrows(IllegalStateException.class, () -> IamAuthorizedActions.parse(json("{" + base + + "\"authorizedByModel\": {\"s3\": {\"s3control\": {\"GetPublicAccessBlock\": \"sqs:SendMessage\"}}}}"))); + assertThrows(IllegalStateException.class, () -> IamAuthorizedActions.parse(json("{" + base + + "\"versioned\": {\"s3\": {\"GetObject\": {\"without\": \"s3:GetObject\", \"with\": \"s3:X\"}}}}"))); + assertThrows(IllegalStateException.class, () -> IamAuthorizedActions.parse(json("{" + base + + "\"spellings\": {\"memorydb\": {\"CreateACL\": \"memorydb:CreateCluster\"}}}"))); + } + + /** + * A request of a route's model and query is checked as the action the file gives that model's requests, or the + * one its query chooses: S3 Control's account-level GetPublicAccessBlock and S3's bucket-level one, a GetObject + * naming a version, and S3's GetBucketLifecycleConfiguration, the action the reference gives its namesake client. + */ + @Test + void aRouteOfAModelOrARequestNamingAVersionIsCheckedAsTheActionTheFileGivesIt() { + MultivaluedMap none = new MultivaluedHashMap<>(); + MultivaluedMap version = new MultivaluedHashMap<>(); + version.add("versionId", "null"); + assertEquals("s3:GetAccountPublicAccessBlock", + IamAuthorizedActions.actionFor("s3", "GetPublicAccessBlock", "GET", "s3control", none)); + assertEquals("s3:GetBucketPublicAccessBlock", + IamAuthorizedActions.actionFor("s3", "GetPublicAccessBlock", "GET", "s3", none)); + assertEquals("s3:GetObject", IamAuthorizedActions.actionFor("s3", "GetObject", "GET", "s3", none)); + assertEquals("s3:GetObjectVersion", IamAuthorizedActions.actionFor("s3", "GetObject", "GET", "s3", version)); + assertEquals("s3:GetObjectVersionAnnotation", + IamAuthorizedActions.actionFor("s3", "GetObjectAnnotation", "GET", "s3", version)); + assertEquals("s3:GetLifecycleConfiguration", + IamAuthorizedActions.actionFor("s3", "GetBucketLifecycleConfiguration", "GET", "s3", none)); + assertEquals("s3:ListBucket", IamAuthorizedActions.actionFor("s3", "ListObjectsV2", "GET", "s3", none)); + assertEquals("s3:PutObject", IamAuthorizedActions.actionFor("s3", "CopyObject", "PUT", "s3", none)); + // A model the file gives nothing for keeps the answer the operation gets otherwise. + assertEquals("apigateway:PUT", IamAuthorizedActions.actionFor("apigateway", "TagResource", "PUT", null, none)); + } + + /** An action the reference spells otherwise than its operation, in case alone, is named with its spelling. */ + @Test + void anActionIsNamedAsTheReferenceSpellsIt() { + assertEquals("memorydb:CreateAcl", IamAuthorizedActions.actionFor("memorydb", "CreateACL")); + assertEquals("s3:PutBucketCORS", IamAuthorizedActions.actionFor("s3", "PutBucketCors", "PUT")); + assertEquals("sqs:SendMessage", IamAuthorizedActions.actionFor("sqs", "SendMessageBatch")); + } + /** * A request on the route of an operation the file authorizes by method is checked as the action its method * names: API Gateway's {@code TagResource} is a PUT in v1 and a POST in v2. An operation the file renames keeps diff --git a/src/test/java/io/floci/aws/services/iam/IamRestRouteCoverageTest.java b/src/test/java/io/floci/aws/services/iam/IamRestRouteCoverageTest.java index 43248a73c9..01267fa73c 100644 --- a/src/test/java/io/floci/aws/services/iam/IamRestRouteCoverageTest.java +++ b/src/test/java/io/floci/aws/services/iam/IamRestRouteCoverageTest.java @@ -113,6 +113,38 @@ class IamRestRouteCoverageTest { return tests.stream(); } + /** + * Each action the vendored file gives an operation for one model's requests is what a request on that model's route + * resolves to: S3's GetPublicAccessBlock is s3:GetBucketPublicAccessBlock, S3 Control's account-level one + * s3:GetAccountPublicAccessBlock, and S3's GetBucketLifecycleConfiguration s3:GetLifecycleConfiguration. + */ + @TestFactory + Stream eachVendoredActionOfAModelsRequestsIsWhatItsRouteResolvesTo() throws IOException { + JsonNode models = load("/aws/rest-routes.json").path("models"); + JsonNode byModel = load("/aws/iam-authorized-actions.json").path("authorizedByModel"); + List tests = new ArrayList<>(); + for (String namespace : ROUTED_NAMESPACES) { + Iterator> clients = byModel.path(namespace).fields(); + while (clients.hasNext()) { + Map.Entry client = clients.next(); + Iterator> entries = client.getValue().fields(); + while (entries.hasNext()) { + Map.Entry entry = entries.next(); + List routes = routesOf(models, namespace, entry.getKey()).stream() + .filter(route -> route.model().equals(client.getKey())).toList(); + String expected = entry.getValue().asText(); + tests.add(DynamicTest.dynamicTest(client.getKey() + " " + entry.getKey(), () -> { + assertFalse(routes.isEmpty(), "no " + client.getKey() + " route for " + entry.getKey()); + for (Route route : routes) { + assertEquals(expected, resolve(route), route.toString()); + } + })); + } + } + } + return tests.stream(); + } + /** * Every operation of a scope the vendored routes do not leave to the rules alone resolves to its action when * Floci can check it as AWS does: its resources built by hand for its namespace or read by the vendored request @@ -245,8 +277,10 @@ class IamRestRouteCoverageTest { Map.Entry model = all.next(); JsonNode route = model.getValue().path("operations").path(operation); if (scope.equals(model.getValue().path("credentialScope").asText()) && !route.isMissingNode()) { + // A hand-routed scope's route lists all its request must carry; another's what tells it apart. + JsonNode carries = route.has("required") ? route.path("required") : route.path("requires"); routes.add(new Route(scope, model.getKey(), operation, route.path("method").asText(), - route.path("requestUri").asText())); + route.path("requestUri").asText(), carries)); } } return routes; @@ -263,7 +297,17 @@ class IamRestRouteCoverageTest { } /** An operation's route: its method, and its request URI with each label filled in. */ - private record Route(String scope, String model, String operation, String method, String requestUri) { + /** + * A route of a model's operation, and what botocore requires its request to carry ({@code required} for a + * hand-routed scope's, {@code requires} where several operations share it), which the request built on it carries + * as an SDK sends it. + */ + private record Route(String scope, String model, String operation, String method, String requestUri, + JsonNode requires) { + + Route(String scope, String model, String operation, String method, String requestUri) { + this(scope, model, operation, method, requestUri, MAPPER.createObjectNode()); + } ContainerRequestContext request() { int question = requestUri.indexOf('?'); @@ -276,7 +320,14 @@ class IamRestRouteCoverageTest { equals < 0 ? "" : parameter.substring(equals + 1)); } } + requires.path("query").forEach(parameter -> query.add(parameter.asText(), "required-value")); ContainerRequestContext ctx = mock(ContainerRequestContext.class); + MultivaluedMap headers = new MultivaluedHashMap<>(); + requires.path("headers").forEach(header -> { + headers.add(header.asText(), "required-value"); + when(ctx.getHeaderString(header.asText())).thenReturn("required-value"); + }); + when(ctx.getHeaders()).thenReturn(headers); UriInfo uriInfo = mock(UriInfo.class); when(uriInfo.getQueryParameters()).thenReturn(query); when(uriInfo.getPath()).thenReturn(path); diff --git a/tools/aws/fetch_s3_required_actions.py b/tools/aws/fetch_s3_required_actions.py new file mode 100644 index 0000000000..2537e13368 --- /dev/null +++ b/tools/aws/fetch_s3_required_actions.py @@ -0,0 +1,164 @@ +#!/usr/bin/env python3 +"""Vendor the actions the S3 user guide requires for each S3 API operation into +tools/aws/sources/s3-required-actions.json, a source of the IAM tables. + +The Service Reference lists the actions that authorize each operation with no word on which one a request needs: it +gives ListObjectsV2 s3:ListBucket and s3:GetObjectAcl, and GetObject s3:GetObject and s3:GetObjectVersion alike, and +one entry for S3's and S3 Control's GetPublicAccessBlock. The S3 user guide's "Required permissions for Amazon S3 API +operations" does: each operation's "(Required)" action, its "(Conditionally required)" ones apart, the two operations +of one name told apart as "(Bucket-level)" and "(Account-level)", and the choice of a version action in one form: + + (Required) Either s3:GetObject or s3:GetObjectVersion + s3:GetObject - Required if you want to get an object without specifying versionId in the request. + s3:GetObjectVersion - Required if you want to get a specific version of an object by specifying versionId in the + request. + + https://docs.aws.amazon.com/AmazonS3/latest/userguide/using-with-s3-policy-actions.html + +This script copies every operation's "(Required)" rows as they stand: the operation as the page heads it, its section, +each single required action, and an Either row's two actions with each one's sentence. Nothing in the output is +written by hand; the generators read them against botocore's operations and members. + +Run from anywhere in the repo: + python3 tools/aws/fetch_s3_required_actions.py # rewrite the vendored file from the page + python3 tools/aws/fetch_s3_required_actions.py --verify # online: the file still says what the page does +""" +from __future__ import annotations + +import argparse +import html +import json +import re +import sys +import urllib.request +from datetime import datetime, timezone +from pathlib import Path + +PAGE = "https://docs.aws.amazon.com/AmazonS3/latest/userguide/using-with-s3-policy-actions.html" +REPO_ROOT = Path(__file__).resolve().parents[2] +OUTPUT = REPO_ROOT / "tools/aws/sources/s3-required-actions.json" +# A heading: the operation, or operations a row covers together ("CreateStorageLensGroup, TagResource"), with a note in +# brackets the page may add, which can run onto the next line; of the notes only a level tells two operations of one +# name apart ("GetPublicAccessBlock (Bucket-level)"). +OPERATION_RE = re.compile(r"([A-Z][A-Za-z0-9]+(?:, [A-Z][A-Za-z0-9]+)*)(?: \((.*))?") +LEVEL_RE = re.compile(r"(Bucket|Account)-level\)") +SECTION_RE = re.compile(r".+ operations and permissions") +# A "(Required)" row's actions, other services' among them ("s3tables:CreateTable", "kms:ReEncrypt*"); one ending in a +# comma runs onto the next line ("(Required) s3:CreateStorageLensGroup," then "s3:TagResource"). +ACTIONS = r"([a-z0-9-]+:[A-Za-z0-9*]+(?:, [a-z0-9-]+:[A-Za-z0-9*]+)*)(,?)" +REQUIRED_RE = re.compile(r"\(Required\) " + ACTIONS) +CONTINUED_RE = re.compile(ACTIONS) +EITHER_RE = re.compile(r"\(Required\) Either (s3:\w+) or (s3:\w+)") +SENTENCE_RE = re.compile(r"(s3:\w+) [–-] (Required if .*)") + + +def lines(page: str) -> list[str]: + """The page's main column as text lines, spaces (non-breaking ones too) collapsed.""" + match = re.search(r'
(.*?)
", "", body, flags=re.S) + body = re.sub(r"|

||||||", "\n", body) + text = html.unescape(re.sub(r"<[^>]+>", "", body)).replace(" ", " ") + return [re.sub(r"\s+", " ", line).strip() for line in text.splitlines() if line.strip()] + + +def required_actions(text: list[str], index: int, row: re.Match) -> list[str]: + """The actions of the "(Required)" row at `index`, the lines it runs onto included.""" + actions = row.group(1).split(", ") + more = row.group(2) + for following in text[index + 1:]: + if not more: + break + continued = CONTINUED_RE.fullmatch(following) + if continued is None: + raise ValueError(f"a required row ends in a comma and no action follows it: {text[index]}") + actions += continued.group(1).split(", ") + more = continued.group(2) + return actions + + +def read_page(page: str) -> dict: + """Each heading's "(Required)" rows, as the page gives them: its section, its single required actions, and an + Either row's two actions with each one's sentence. A heading naming several operations keeps its rows as one + entry under that heading ("CreateStorageLensGroup, TagResource").""" + found: dict[str, dict] = {} + operation = None + section = None + text = lines(page) + for index, line in enumerate(text): + if SECTION_RE.fullmatch(line): + section = line + continue + heading = OPERATION_RE.fullmatch(line) + if heading: + level = LEVEL_RE.match(heading.group(2) or "") + operation = heading.group(1) + (f" ({level.group(1)}-level)" if level else "") + continue + single = REQUIRED_RE.fullmatch(line) + if single and operation is not None: + entry = found.setdefault(operation, {"section": section}) + for action in required_actions(text, index, single): + if action not in entry.setdefault("required", []): + entry["required"].append(action) + continue + either = EITHER_RE.fullmatch(line) + if not either or operation is None: + continue + sentences = {} + for following in text[index + 1:index + 4]: + sentence = SENTENCE_RE.fullmatch(following) + if sentence and sentence.group(1) in either.groups(): + sentences[sentence.group(1)] = sentence.group(2) + if set(sentences) != set(either.groups()): + raise ValueError(f"{operation}'s Either row does not give both actions a sentence: {line}") + found.setdefault(operation, {"section": section})["either"] = {"actions": list(either.groups()), + "sentences": sentences} + return dict(sorted(found.items())) + + +# The page lists some 170 operations and eleven Either rows; far fewer means its layout changed under the parser. +MINIMUM_OPERATIONS = 100 + + +def build(page: str) -> dict: + operations = read_page(page) + if len(operations) < MINIMUM_OPERATIONS or not any("either" in entry for entry in operations.values()): + raise ValueError(f"{PAGE} gives {len(operations)} operations and no Either row: its layout changed") + return { + "_source": { + "page": PAGE, + "fetcher": str(Path(__file__).resolve().relative_to(REPO_ROOT)), + "retrieved": datetime.now(timezone.utc).strftime("%Y-%m-%d"), + "note": "Each heading's '(Required)' rows of the page, under the heading as it stands (one naming several " + "operations kept whole): its single required actions, and an Either row's two actions with the " + "sentence it gives each, copied as they stand.", + }, + "operations": operations, + } + + +def fetch_url(url: str) -> str: + request = urllib.request.Request(url, headers={"User-Agent": "floci-tools"}) + with urllib.request.urlopen(request, timeout=60) as response: + return response.read().decode("utf-8") + + +def main(argv: list[str] | None = None, fetch=fetch_url) -> int: + parser = argparse.ArgumentParser(description=__doc__.splitlines()[0]) + parser.add_argument("--verify", action="store_true", help="online: the vendored file matches the page") + args = parser.parse_args(argv) + built = build(fetch(PAGE)) + if args.verify: + vendored = json.loads(OUTPUT.read_text(encoding="utf-8")) + if vendored["operations"] != built["operations"]: + print(f"error: {OUTPUT.relative_to(REPO_ROOT)} no longer says what {PAGE} does", file=sys.stderr) + return 1 + print(f"{OUTPUT.relative_to(REPO_ROOT)} matches {PAGE}") + return 0 + OUTPUT.write_text(json.dumps(built, indent=2) + "\n", encoding="utf-8") + print(f"wrote {OUTPUT.relative_to(REPO_ROOT)} ({len(built['operations'])} operations)") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tools/aws/regen_iam_authorized_actions.py b/tools/aws/regen_iam_authorized_actions.py index dc2735ca3a..b0451db631 100644 --- a/tools/aws/regen_iam_authorized_actions.py +++ b/tools/aws/regen_iam_authorized_actions.py @@ -29,7 +29,9 @@ each exclusion is deliberate: - **An action of the operation's own name exists.** Glue lists `CreatePartitionIndex` as authorized by `glue:UpdateTable` while also publishing `glue:CreatePartitionIndex`, and no source says which one AWS checks. A name differing only in case falls here too: IAM matches action - names without regard to case, so it is not a different action. + names without regard to case, so it is not a different action. The file still records the + reference's spelling (`spellings`: MemoryDB's CreateACL is `memorydb:CreateAcl`), which a denial + names the action by. - **A tagging action alone.** EC2 lists `CreateCapacityReservationDateChangeQuote` as authorized by `ec2:CreateTags` only, the tag-on-create permission with the operation's own action missing. @@ -50,6 +52,20 @@ Two kinds of listed action do not count towards "exactly one": and modify budgets", adding "Creating a budget with tags also requires the 'budgets:TagResource' permission". +Where the reference gives an S3 operation no one answer, the S3 user guide's "Required permissions for +Amazon S3 API operations" does, copied unchanged into tools/aws/sources/s3-required-actions.json by +tools/aws/fetch_s3_required_actions.py (`s3_required`): an operation's one required action +(ListObjectsV2 is `s3:ListBucket`, CopyObject `s3:PutObject`), an "Account-level" row's for S3 Control's +operation of a name S3 shares (`authorizedByModel`: its GetPublicAccessBlock is +`s3:GetAccountPublicAccessBlock`), and an Either row's choice by whether the request names the +parameter its sentences name (`versioned`: GetObject is `s3:GetObjectVersion` with a `versionId`). +The one answer the reference gives an operation several SDK clients list, all their routes vendored, +is the namesake client's (`namesake_by_model`: S3's GetBucketLifecycleConfiguration is +`s3:GetLifecycleConfiguration`, botocore's S3 Control client documenting its own call as +`s3-outposts:GetLifecycleConfiguration`). Where neither says it, `MEASURED_BY_MODEL` and +`MEASURED_VERSIONED` give what the Service Authorization Reference's actions table does, quoted +with its link. + The file also lists, for each credential scope whose REST routes `rest-routes.json` reads (the scopes it leaves to the registry's rules, `handRouted`, aside), the actions of that namespace the reference gives no resource type, from its `Actions`. A REST request no rule of `IamActionRegistry` @@ -107,9 +123,17 @@ from concurrent.futures import ThreadPoolExecutor from datetime import datetime, timezone from pathlib import Path +from regen_partitions import resolve_botocore_data +from regen_query_services import latest_model_dir, load_model + REPO_ROOT = Path(__file__).resolve().parents[2] OUTPUT = REPO_ROOT / "src/main/resources/aws/iam-authorized-actions.json" ROUTES = REPO_ROOT / "src/main/resources/aws/rest-routes.json" +# The S3 user guide's required actions of each S3 operation, as tools/aws/fetch_s3_required_actions.py copies them. +S3_REQUIRED = REPO_ROOT / "tools/aws/sources/s3-required-actions.json" +LEVEL_RE = re.compile(r"^([A-Z][A-Za-z0-9]+)(?: \((Bucket|Account)-level\))?$") +SPECIFYING_RE = re.compile(r"\bspecifying (\w+) in the request") +_S3_ACTIONS_TABLE = "https://docs.aws.amazon.com/service-authorization/latest/reference/list_amazons3.html" INDEX_URL = "https://servicereference.us-east-1.amazonaws.com/" FETCH_TIMEOUT_SECONDS = 30 FETCH_WORKERS = 8 @@ -140,6 +164,37 @@ ANCHORS = { } +# --------------------------------------------------------------------------------------------------------------------- +# What AWS documents where neither the Service Reference nor the S3 user guide's page says it: the page heads S3 Control's +# account-level GetPublicAccessBlock "GetAccessPointPolicy (Account-level)", and gives the version annotation actions +# nowhere. Each entry quotes the Service Authorization Reference's actions table, which links the action to its +# operation's API page. An entry is refused without a link, or when the page gives it (`s3_required`). +# --------------------------------------------------------------------------------------------------------------------- +MEASURED_BY_MODEL: dict[tuple[str, str, str], tuple[str, str]] = { + ("s3", "s3control", "GetPublicAccessBlock"): ( + "s3:GetAccountPublicAccessBlock", + f"the Service Authorization Reference's Amazon S3 actions table ({_S3_ACTIONS_TABLE}) gives " + "s3:GetAccountPublicAccessBlock 'Grants permission to retrieve the PublicAccessBlock configuration for an AWS " + "account' and links it to https://docs.aws.amazon.com/AmazonS3/latest/API/API_control_GetPublicAccessBlock.html"), +} +MEASURED_VERSIONED: dict[tuple[str, str], tuple[str, str, str, str]] = { + ("s3", operation): ("versionId", f"s3:{operation}", f"s3:{version}", + f"the Service Authorization Reference's Amazon S3 actions table ({_S3_ACTIONS_TABLE}) gives " + f"s3:{version} '{sentence}' and links it to " + f"https://docs.aws.amazon.com/AmazonS3/latest/API/API_{operation}.html, whose request names " + f"the version by versionId") + for operation, version, sentence in ( + ("GetObjectAnnotation", "GetObjectVersionAnnotation", + "Grants permission to retrieve an annotation from a specific version of an object"), + ("PutObjectAnnotation", "PutObjectVersionAnnotation", + "Grants permission to add or replace an annotation on a specific version of an object"), + ("DeleteObjectAnnotation", "DeleteObjectVersionAnnotation", + "Grants permission to delete an annotation from a specific version of an object"), + ("ListObjectAnnotations", "ListObjectVersionAnnotations", + "Grants permission to list annotations on a specific version of an object")) +} + + def _get_json(url: str): request = urllib.request.Request(url, headers={"Accept": "application/json"}) with urllib.request.urlopen(request, timeout=FETCH_TIMEOUT_SECONDS) as response: @@ -210,6 +265,175 @@ def authorized_actions_from(documents: list[dict]) -> dict[str, dict[str, str]]: return {namespace: operations for namespace, operations in found.items() if operations} +def authorized_actions(documents: list[dict], page: dict | None = None, models: dict | None = None, + query: dict[str, list[str]] | None = None) -> dict[str, dict[str, str]]: + """`authorized_actions_from`, an S3 operation the reference gives no one answer taking the one the S3 user guide + requires (`s3_required`). Where both answer and disagree, the generation fails: which AWS checks is not known.""" + found = {namespace: dict(operations) for namespace, operations in authorized_actions_from(documents).items()} + actions = {action["Name"].lower(): action["Name"] for document in documents if document.get("Name") == "s3" + for action in document.get("Actions", [])} + conflicts = [] + for operation, action in s3_sections(documents, page, models, query)[0].items(): + listed = found.get("s3", {}).get(operation) + if listed is not None: + if listed != action: + conflicts.append(f"s3:{operation}: the reference gives {listed}, the S3 user guide {action}") + elif action.lower() != f"s3:{operation}".lower() and action.split(":", 1)[1].lower() in actions: + found.setdefault("s3", {})[operation] = action + if conflicts: + raise ValueError("; ".join(conflicts)) + return {namespace: dict(sorted(operations.items())) for namespace, operations in sorted(found.items()) + if operations} + + +def s3_query_parameters(data: Path | None = None) -> dict[str, list[str]]: + """The query parameters botocore's S3 model gives each operation's request, from the botocore `regen_rest_routes` + reads unless `data` names one.""" + model = load_model(latest_model_dir(data or resolve_botocore_data(None)[0], "s3")) + shapes = model.get("shapes", {}) + found = {} + for operation, spec in model["operations"].items(): + members = shapes.get(spec.get("input", {}).get("shape", ""), {}).get("members", {}) + found[operation] = sorted(member.get("locationName", name) for name, member in members.items() + if member.get("location") == "querystring") + return found + + +def s3_sections(documents: list[dict], page: dict | None, models: dict | None, + query: dict[str, list[str]] | None = None) -> tuple[dict[str, str], dict, dict]: + """`s3_required` for references that include S3's, nothing for any others (a test's, or a partial set); `query` is + `s3_query_parameters()` unless given.""" + if not any(document.get("Name") == "s3" for document in documents): + return {}, {}, {} + return s3_required(page or {}, models or {}, s3_query_parameters() if query is None else query) + + +def s3_required(page: dict, models: dict, query: dict[str, list[str]]) -> tuple[dict[str, str], dict, dict]: + """What the S3 user guide's required-permissions page gives S3's operations (`page`, its vendored `operations`), + read against the vendored routes' `models` and botocore's S3 `query` parameters (`s3_query_parameters`): each one's + single required s3 action, and an Either row's choice by the request parameter its sentences name (`versioned`), + when botocore gives that parameter in the operation's query and the operation has no single required action of its + own (CopyObject's Either is about its copy source; DeleteObjects names its versions in its body). An operation both + S3 and S3 Control have takes the page's action for one model's requests alone (`authorizedByModel`): an + Account-level row's for S3 Control's, any other row's for S3's, the page being S3's guide (S3 Control's + GetBucketReplication is an S3 on Outposts call). An Account-level row whose S3 Control route names a resource in + its path is refused. A level on an operation one model has tells nothing apart, so the page's + "GetAccessPointPolicy (Account-level)" is not read; nor is a heading naming several operations + ("CreateStorageLensGroup, TagResource"). `MEASURED_BY_MODEL` and `MEASURED_VERSIONED` add what the page does not + say.""" + s3_ops = models.get("s3", {}).get("operations", {}) + control_ops = models.get("s3control", {}).get("operations", {}) + actions: dict[str, str] = {} + by_model: dict[str, str] = {} + s3_model: dict[str, str] = {} + versioned: dict[str, dict] = {} + for heading, entry in page.items(): + head = LEVEL_RE.match(heading) + if head is None: + continue + operation, level = head.groups() + singles = [action for action in entry.get("required", []) if action.startswith("s3:")] + if level and not (operation in s3_ops and operation in control_ops): + continue + if level == "Account": + if "{" in control_ops[operation]["requestUri"]: + raise ValueError(f"the S3 user guide heads {operation} Account-level, but S3 Control's route " + f"{control_ops[operation]['requestUri']} names a resource") + if len(singles) == 1: + by_model[operation] = singles[0] + continue + if len(singles) == 1 and operation in s3_ops and operation in control_ops: + if singles[0].lower() != f"s3:{operation}".lower(): + s3_model[operation] = singles[0] + elif len(singles) == 1: + actions[operation] = singles[0] + elif not singles and "either" in entry: + sentences = entry["either"]["sentences"] + named = {match.group(1) for match in map(SPECIFYING_RE.search, sentences.values()) if match} + without = [action for action, sentence in sentences.items() if "without specifying" in sentence] + with_ = [action for action, sentence in sentences.items() if "without specifying" not in sentence] + if (len(named) == 1 and len(without) == 1 and len(with_) == 1 + and next(iter(named)) in query.get(operation, [])): + versioned[operation] = {"parameter": next(iter(named)), "without": without[0], "with": with_[0]} + for (namespace, model, operation), (action, evidence) in MEASURED_BY_MODEL.items(): + if "https://" not in evidence: + raise ValueError(f"MEASURED_BY_MODEL gives {model}:{operation} with no link to its evidence") + if operation in by_model: + raise ValueError(f"MEASURED_BY_MODEL gives {model}:{operation}, which the S3 user guide gives: take it out") + by_model[operation] = action + for (namespace, operation), (parameter, without, with_, evidence) in MEASURED_VERSIONED.items(): + if "https://" not in evidence: + raise ValueError(f"MEASURED_VERSIONED gives {operation} with no link to its evidence") + if operation in versioned: + raise ValueError(f"MEASURED_VERSIONED gives {operation}, which the S3 user guide gives: take it out") + if parameter not in query.get(operation, []): + raise ValueError(f"MEASURED_VERSIONED gives {operation} a choice by {parameter}, which botocore does not " + f"give in its query") + versioned[operation] = {"parameter": parameter, "without": without, "with": with_} + models_actions = {model: dict(sorted(operations.items())) + for model, operations in (("s3", s3_model), ("s3control", by_model)) if operations} + return (dict(sorted(actions.items())), + {"s3": models_actions} if models_actions else {}, + {"s3": dict(sorted(versioned.items()))} if versioned else {}) + + +def namesake_by_model(documents: list[dict], routed: set[str]) -> dict[str, dict[str, dict[str, str]]]: + """The one answer the reference gives an operation it lists for several SDK clients, for the client named as the + namespace, when every such client's routes are vendored (`routed`, the models of `rest-routes.json`) so a request's + route tells which client's it is: S3's GetBucketLifecycleConfiguration is s3:GetLifecycleConfiguration, botocore's + S3 Control client documenting its own call as s3-outposts:GetLifecycleConfiguration. `authorized_actions_from` + gives such an operation no answer, AWS authorizing each client's call its own way.""" + found: dict[str, dict[str, dict[str, str]]] = {} + for document in documents: + namespace = document.get("Name") + own_actions = {action["Name"].lower() for action in document.get("Actions", []) if isinstance(action, dict)} + for operation in document.get("Operations", []): + name = operation.get("Name") + clients = _sdk_clients(namespace, operation) + if len(clients) < 2 or namespace not in clients or not clients <= routed or name.lower() in own_actions: + continue + authorized = [(service, action) for service, action + in _counted_actions(namespace, _authorized_actions(namespace, operation)) + if service == namespace] + if len({action for _, action in authorized}) == 1: + action = authorized[0][1] + if NAME_RE.match(action) and action != name and not TAGGING_ACTION_RE.match(action): + found.setdefault(namespace, {}).setdefault(namespace, {})[name] = f"{namespace}:{action}" + return {namespace: {client: dict(sorted(operations.items())) for client, operations in sorted(clients.items())} + for namespace, clients in sorted(found.items())} + + +def spellings(documents: list[dict]) -> dict[str, dict[str, str]]: + """The reference's spelling of each operation's action that differs from the operation's name only in case: + MemoryDB's CreateACL is memorydb:CreateAcl, S3's PutBucketCors s3:PutBucketCORS.""" + found: dict[str, dict[str, str]] = {} + for document in documents: + namespace = document.get("Name") + actions = {action["Name"].lower(): action["Name"] for action in document.get("Actions", []) + if isinstance(action, dict) and isinstance(action.get("Name"), str)} + for operation in document.get("Operations", []): + name = operation.get("Name") + spelled = actions.get(name.lower()) if isinstance(name, str) else None + if spelled is not None and spelled != name: + found.setdefault(namespace, {})[name] = f"{namespace}:{spelled}" + return {namespace: dict(sorted(operations.items())) for namespace, operations in sorted(found.items())} + + +def _merged_by_model(*sources: dict) -> dict: + merged: dict = {} + for source in sources: + for namespace, clients in source.items(): + for client, operations in clients.items(): + merged.setdefault(namespace, {}).setdefault(client, {}).update(operations) + return {namespace: {client: dict(sorted(operations.items())) for client, operations in sorted(clients.items())} + for namespace, clients in sorted(merged.items())} + + +def load_s3_required(source: Path = S3_REQUIRED) -> dict: + """The vendored S3 user guide page's operations, none when the file is missing.""" + return json.loads(source.read_text(encoding="utf-8"))["operations"] if source.exists() else {} + + def _authorized_actions(namespace: str, operation: dict) -> list[tuple[str, str]]: """The operation's authorized actions as (service, name) pairs. A record of the wrong shape is a malformed response, not an operation to leave out: skipping it would vendor a map that @@ -314,9 +538,28 @@ def authorized_by_method(documents: list[dict], methods: dict[str, dict[str, lis return found +def vendored_sections(documents: list[dict], page: dict | None, models: dict | None, + query: dict[str, list[str]] | None, renamed: dict[str, dict[str, str]]) -> dict[str, dict]: + """The `authorizedByModel`, `versioned` and `spellings` sections, given the operations `authorized_actions` renames + (`renamed`), whose spellings the renames already give.""" + _, by_model, versioned = s3_sections(documents, page, models, query) + return { + "authorizedByModel": _merged_by_model(by_model, namesake_by_model(documents, set(models or {}))), + "versioned": versioned, + "spellings": {namespace: {operation: action for operation, action in operations.items() + if operation not in renamed.get(namespace, {})} + for namespace, operations in spellings(documents).items()}, + } + + def build(documents: list[dict], provenance: str, routed: list[str], - methods: dict[str, dict[str, list[str]]] | None = None) -> dict: - renamed = authorized_actions_from(documents) + methods: dict[str, dict[str, list[str]]] | None = None, page: dict | None = None, + models: dict | None = None, query: dict[str, list[str]] | None = None) -> dict: + """The vendored document; `page` is the S3 user guide's operations (`load_s3_required`), `models` the vendored + routes' models, `query` botocore's S3 query parameters (`s3_query_parameters`, unless given).""" + if query is None and any(document.get("Name") == "s3" for document in documents): + query = s3_query_parameters() + renamed = authorized_actions(documents, page, models, query) return { "_source": { "generator": "tools/aws/regen_iam_authorized_actions.py", @@ -327,6 +570,7 @@ def build(documents: list[dict], provenance: str, routed: list[str], "authorizedActions": renamed, "actionsWithoutResourceTypes": actions_without_resource_types(documents, routed), "authorizedByMethod": authorized_by_method(documents, methods or {}, renamed), + **vendored_sections(documents, page, models, query, renamed), } @@ -361,6 +605,7 @@ def validate(document: dict, routed: list[str], methods: dict[str, dict[str, lis f"which is not an action of {namespace}") elif name.lower() == operation.lower(): problems.append(f"{namespace}:{operation} maps to its own name") + problems += _section_problems(document) for (namespace, operation), expected in ANCHORS.items(): actual = namespaces.get(namespace, {}).get(operation) if actual != expected: @@ -369,6 +614,32 @@ def validate(document: dict, routed: list[str], methods: dict[str, dict[str, lis return problems +def _section_problems(document: dict) -> list[str]: + """Problems with the shape of `authorizedByModel`, `versioned` and `spellings`.""" + problems = [] + def action_of(namespace: str, action: object) -> bool: + prefix, _, name = action.partition(":") if isinstance(action, str) else ("", "", "") + return prefix == namespace and bool(NAME_RE.match(name)) + for namespace, models in (document.get("authorizedByModel") or {}).items(): + for model, operations in (models.items() if isinstance(models, dict) else []): + for operation, action in (operations.items() if isinstance(operations, dict) else []): + if not NAME_RE.match(operation) or not action_of(namespace, action): + problems.append(f"authorizedByModel {namespace} {model}:{operation} maps to {action!r}, " + f"which is not an action of {namespace}") + for namespace, operations in (document.get("versioned") or {}).items(): + for operation, choice in (operations.items() if isinstance(operations, dict) else []): + if not isinstance(choice, dict) or set(choice) != {"parameter", "without", "with"} \ + or not NAME_RE.match(str(choice.get("parameter"))) \ + or not action_of(namespace, choice.get("without")) or not action_of(namespace, choice.get("with")): + problems.append(f"versioned {namespace}:{operation} is not a parameter and two actions of {namespace}") + for namespace, operations in (document.get("spellings") or {}).items(): + for operation, action in (operations.items() if isinstance(operations, dict) else []): + if not action_of(namespace, action) or action.split(":", 1)[1].lower() != operation.lower() \ + or action.split(":", 1)[1] == operation: + problems.append(f"spellings {namespace}:{operation} gives {action!r}, not its name spelled otherwise") + return problems + + def _unscoped_problems(unscoped: object, routed: list[str]) -> list[str]: """Problems with the actions without resource types: one sorted list of usable names for each scope whose routes are read, and for no other.""" @@ -535,7 +806,20 @@ def main(argv: list[str] | None = None) -> int: by_method = vendored_document.get("authorizedByMethod") or {} try: documents, provenance = fetch_references(args.source_dir) - upstream = authorized_actions_from(documents) + page = load_s3_required() + if args.source_dir is None: + # The page the vendored copy was taken from must still say what the copy does. + import fetch_s3_required_actions + live = fetch_s3_required_actions.read_page(fetch_s3_required_actions.fetch_url( + fetch_s3_required_actions.PAGE)) + if live != page: + print(f"error: {S3_REQUIRED.relative_to(REPO_ROOT)} no longer says what " + f"{fetch_s3_required_actions.PAGE} does (run tools/aws/fetch_s3_required_actions.py)", + file=sys.stderr) + return 1 + models = _routes(args.routes)["models"] + query = s3_query_parameters() + upstream = authorized_actions(documents, page, models, query) upstream_unscoped = actions_without_resource_types(documents, list(unscoped)) methods = route_methods(_routes(args.routes)) if by_method else {} upstream_by_method = authorized_by_method( @@ -546,6 +830,9 @@ def main(argv: list[str] | None = None) -> int: print(f"error: could not read the Service Reference ({e})", file=sys.stderr) return 2 untrue, added = verify_against(vendored, upstream) + for section, value in vendored_sections(documents, page, models, query, upstream).items(): + if vendored_document.get(section, {}) != value: + untrue.append(f"{section} differs from what AWS gives: expected {json.dumps(value)}") untrue_unscoped, added_unscoped = verify_unscoped_against(unscoped, upstream_unscoped) untrue_by_method, added_by_method = verify_by_method_against(by_method, upstream_by_method) untrue += untrue_unscoped + untrue_by_method @@ -572,7 +859,7 @@ def main(argv: list[str] | None = None) -> int: routes = _routes(args.routes) routed = routed_namespaces(routes) methods = route_methods(routes) - document = build(documents, provenance, routed, methods) + document = build(documents, provenance, routed, methods, load_s3_required(), routes["models"]) except (OSError, ValueError) as e: print(f"error: could not read the Service Reference ({e})", file=sys.stderr) return 2 diff --git a/tools/aws/regen_iam_request_resources.py b/tools/aws/regen_iam_request_resources.py index cb7e2f05ae..670fc5e5c0 100644 --- a/tools/aws/regen_iam_request_resources.py +++ b/tools/aws/regen_iam_request_resources.py @@ -268,7 +268,8 @@ from datetime import datetime, timezone from pathlib import Path import fetch_athena_glue_ddl_permissions -from regen_iam_authorized_actions import authorized_actions_from, fetch_references +from regen_iam_authorized_actions import (ROUTES as ROUTES_FILE, authorized_actions, fetch_references, + load_s3_required, s3_query_parameters, vendored_sections) from regen_iam_passed_roles import ( NAMESPACE_RE, OPERATION_RE, @@ -562,11 +563,30 @@ def related(a: str, b: str) -> bool: # --------------------------------------------------------------------------- # # The Service Reference # --------------------------------------------------------------------------- # +def action_mapping(documents: list[dict]) -> dict[str, dict[str, str]]: + """The action each operation is checked as where it is not its own name, as the authorized-actions file gives it + (`regen_iam_authorized_actions.authorized_actions`), an operation the S3 user guide gives a version choice taking + its action without a version, whose types are the same, and one several clients share its namesake client's + (`namesake_by_model`, and the S3 user guide's for S3's requests).""" + page = load_s3_required() + models = json.loads(ROUTES_FILE.read_text(encoding="utf-8"))["models"] if ROUTES_FILE.exists() else {} + query = s3_query_parameters() if any(document.get("Name") == "s3" for document in documents) else None + mapped = authorized_actions(documents, page, models, query) + sections = vendored_sections(documents, page, models, query, mapped) + for namespace, operations in sections["versioned"].items(): + for operation, choice in operations.items(): + mapped.setdefault(namespace, {}).setdefault(operation, choice["without"]) + for namespace, clients in sections["authorizedByModel"].items(): + for operation, action in clients.get(namespace, {}).items(): + mapped.setdefault(namespace, {}).setdefault(operation, action) + return mapped + + def checked_actions(documents: list[dict]) -> dict[str, dict]: """Each operation of each namespace, as `:`, with the action Floci checks it as, that action's resource types (null when the namespace has no action of that name) and the operation's SDK clients.""" - mapped = authorized_actions_from(documents) + mapped = action_mapping(documents) found = {} for document in documents: namespace = document["Name"] @@ -3246,7 +3266,7 @@ def with_rest_operations(upstream: dict[str, dict], documents: list[dict], reports a vendored one as no longer listed. The reference lists the operations of one client of a namespace: OpenSearch Service's are the `es` client's alone, while the `opensearch` client's are named after `es` actions all the same.""" - mapped = authorized_actions_from(documents) + mapped = action_mapping(documents) actions = {document["Name"]: {action["Name"].lower(): action for action in document.get("Actions", [])} for document in documents} found = dict(upstream) diff --git a/tools/aws/regen_rest_routes.py b/tools/aws/regen_rest_routes.py index 8e71e8d37e..284d381a7a 100644 --- a/tools/aws/regen_rest_routes.py +++ b/tools/aws/regen_rest_routes.py @@ -10,7 +10,9 @@ A request no rule maps is the operation whose route it matches, checked as the a request on each route and compares the action the registry gives with that one. The credential scopes in `HAND_ROUTED` are authorized by the registry's rules alone, each for its -reason, and their routes are vendored for the coverage test only. Operations sharing a route are told +reason, and their routes are vendored for the coverage test only, each with the query parameters and +headers botocore requires its request to carry (`required`), which the registry's rules read: S3's +CompleteMultipartUpload, on `POST /{Bucket}/{Key+}`, is told by its `uploadId`. Operations sharing a route are told apart by what botocore models their requests as carrying: the query parameters and headers of the members their input requires (`requires`: S3's UploadPart, on `PUT /{Bucket}/{Key+}` with PutObject, requires `partNumber` and `uploadId`, CopyObject the `x-amz-copy-source` header), and a deprecated @@ -388,6 +390,7 @@ def build(models: dict[str, dict], provenance: str, documented: dict[str, dict] raise SystemExit(f"error: {name} is both a botocore model and a documented endpoint") routes[name] = model routes = dict(sorted(routes.items())) + with_required(routes, models) with_conditions(routes, models) shared = shared_routes(routes) if shared: @@ -403,6 +406,31 @@ def build(models: dict[str, dict], provenance: str, documented: dict[str, dict] } +def required_members(model: dict, operation: str) -> dict[str, list[str]]: + """The query parameters and headers of the members the operation's input requires, as botocore models it.""" + spec = model["operations"][operation] + shape = model.get("shapes", {}).get(spec.get("input", {}).get("shape", ""), {}) + required = set(shape.get("required", [])) + located = [(member.get("location"), member.get("locationName", member_name)) + for member_name, member in shape.get("members", {}).items() if member_name in required] + query = sorted(where for location, where in located if location == "querystring") + headers = sorted(where.lower() for location, where in located if location == "header") + return {**({"query": query} if query else {}), **({"headers": headers} if headers else {})} + + +def with_required(routes: dict[str, dict], models: dict[str, dict]) -> None: + """Each operation of a hand-routed scope given what its request must carry (`required`), for the coverage test to + build the request the registry's rules read; the routes of other scopes, which requests are matched on, need it only + where operations share them (`with_conditions`).""" + for name, model in routes.items(): + if model["credentialScope"] not in HAND_ROUTED or name not in models: + continue + for operation, route in model["operations"].items(): + required = required_members(models[name], operation) + if required: + route["required"] = required + + def with_conditions(routes: dict[str, dict], models: dict[str, dict]) -> None: """Each operation of a route that names several within its scope given what botocore models its request as carrying: the query parameters and headers of the members its input requires (`requires`), and whether botocore @@ -418,17 +446,11 @@ def with_conditions(routes: dict[str, dict], models: dict[str, dict]) -> None: for name, operation in operations: if name not in models: continue - spec = models[name]["operations"][operation] - shape = models[name].get("shapes", {}).get(spec.get("input", {}).get("shape", ""), {}) - required = set(shape.get("required", [])) - located = [(member.get("location"), member.get("locationName", member_name)) - for member_name, member in shape.get("members", {}).items() if member_name in required] - query = sorted(where for location, where in located if location == "querystring") - headers = sorted(where.lower() for location, where in located if location == "header") route = routes[name]["operations"][operation] - if query or headers: - route["requires"] = {**({"query": query} if query else {}), **({"headers": headers} if headers else {})} - if spec.get("deprecated"): + requires = required_members(models[name], operation) + if requires: + route["requires"] = requires + if models[name]["operations"][operation].get("deprecated"): route["deprecated"] = True diff --git a/tools/aws/sources/s3-required-actions.json b/tools/aws/sources/s3-required-actions.json new file mode 100644 index 0000000000..5bc7fc68a4 --- /dev/null +++ b/tools/aws/sources/s3-required-actions.json @@ -0,0 +1,1172 @@ +{ + "_source": { + "page": "https://docs.aws.amazon.com/AmazonS3/latest/userguide/using-with-s3-policy-actions.html", + "fetcher": "tools/aws/fetch_s3_required_actions.py", + "retrieved": "2026-11-21", + "note": "Each heading's '(Required)' rows of the page, under the heading as it stands (one naming several operations kept whole): its single required actions, and an Either row's two actions with the sentence it gives each, copied as they stand." + }, + "operations": { + "AbortMultipartUpload": { + "section": "Object operations and permissions", + "required": [ + "s3:AbortMultipartUpload" + ] + }, + "AssociateAccessGrantsIdentityCenter": { + "section": "S3 Access Grants instance operations and permissions", + "required": [ + "s3:AssociateAccessGrantsIdentityCenter" + ] + }, + "CompleteMultipartUpload": { + "section": "Object operations and permissions", + "required": [ + "s3:PutObject" + ] + }, + "CopyObject": { + "section": "Object operations and permissions", + "either": { + "actions": [ + "s3:GetObject", + "s3:GetObjectVersion" + ], + "sentences": { + "s3:GetObject": "Required if you want to copy an object from the source bucket without specifying versionId in the request.", + "s3:GetObjectVersion": "Required if you want to copy a specific version of an object from the source bucket by specifying versionId in the request." + } + }, + "required": [ + "s3:PutObject" + ] + }, + "CreateAccessGrant": { + "section": "S3 Access Grants grant operations and permissions", + "required": [ + "s3:CreateAccessGrant" + ] + }, + "CreateAccessGrantsInstance": { + "section": "S3 Access Grants instance operations and permissions", + "required": [ + "s3:CreateAccessGrantsInstance" + ] + }, + "CreateAccessGrantsLocation": { + "section": "S3 Access Grants location operations and permissions", + "required": [ + "s3:CreateAccessGrantsLocation" + ] + }, + "CreateAccessPoint": { + "section": "Access point for general purpose buckets operations and permissions", + "required": [ + "s3:CreateAccessPoint" + ] + }, + "CreateAccessPointForObjectLambda": { + "section": "Object Lambda Access Point operations and permissions", + "required": [ + "s3:CreateAccessPointForObjectLambda" + ] + }, + "CreateBucket": { + "section": "Bucket operations and permissions", + "required": [ + "s3:CreateBucket" + ] + }, + "CreateBucketMetadataConfiguration": { + "section": "Bucket operations and permissions", + "required": [ + "s3:CreateBucketMetadataTableConfiguration", + "s3tables:CreateTableBucket", + "s3tables:CreateNamespace", + "s3tables:CreateTable", + "s3tables:GetTable", + "s3tables:PutTablePolicy", + "s3tables:PutTableEncryption", + "kms:DescribeKey" + ] + }, + "CreateBucketMetadataTableConfiguration": { + "section": "Bucket operations and permissions", + "required": [ + "s3:CreateBucketMetadataTableConfiguration", + "s3tables:CreateNamespace", + "s3tables:CreateTable", + "s3tables:GetTable", + "s3tables:PutTablePolicy" + ] + }, + "CreateJob": { + "section": "Account operations and permissions", + "required": [ + "s3:CreateJob" + ] + }, + "CreateMultiRegionAccessPoint": { + "section": "Multi-Region Access Point operations and permissions", + "required": [ + "s3:CreateMultiRegionAccessPoint" + ] + }, + "CreateMultipartUpload": { + "section": "Object operations and permissions", + "required": [ + "s3:PutObject" + ] + }, + "CreateStorageLensGroup": { + "section": "S3 Storage Lens groups operations and permissions", + "required": [ + "s3:CreateStorageLensGroup" + ] + }, + "CreateStorageLensGroup, TagResource": { + "section": "S3 Storage Lens groups operations and permissions", + "required": [ + "s3:CreateStorageLensGroup", + "s3:TagResource" + ] + }, + "DeleteAccessGrant": { + "section": "S3 Access Grants grant operations and permissions", + "required": [ + "s3:DeleteAccessGrant" + ] + }, + "DeleteAccessGrantsInstance": { + "section": "S3 Access Grants instance operations and permissions", + "required": [ + "s3:DeleteAccessGrantsInstance" + ] + }, + "DeleteAccessGrantsInstanceResourcePolicy": { + "section": "S3 Access Grants instance operations and permissions", + "required": [ + "s3:DeleteAccessGrantsInstanceResourcePolicy" + ] + }, + "DeleteAccessGrantsLocation": { + "section": "S3 Access Grants location operations and permissions", + "required": [ + "s3:DeleteAccessGrantsLocation" + ] + }, + "DeleteAccessPoint": { + "section": "Access point for general purpose buckets operations and permissions", + "required": [ + "s3:DeleteAccessPoint" + ] + }, + "DeleteAccessPointForObjectLambda": { + "section": "Object Lambda Access Point operations and permissions", + "required": [ + "s3:DeleteAccessPointForObjectLambda" + ] + }, + "DeleteAccessPointPolicy": { + "section": "Access point for general purpose buckets operations and permissions", + "required": [ + "s3:DeleteAccessPointPolicy" + ] + }, + "DeleteAccessPointPolicyForObjectLambda": { + "section": "Object Lambda Access Point operations and permissions", + "required": [ + "s3:DeleteAccessPointPolicyForObjectLambda" + ] + }, + "DeleteBucket": { + "section": "Bucket operations and permissions", + "required": [ + "s3:DeleteBucket" + ] + }, + "DeleteBucketAnalyticsConfiguration": { + "section": "Bucket operations and permissions", + "required": [ + "s3:PutAnalyticsConfiguration" + ] + }, + "DeleteBucketCors": { + "section": "Bucket operations and permissions", + "required": [ + "s3:PutBucketCORS" + ] + }, + "DeleteBucketEncryption": { + "section": "Bucket operations and permissions", + "required": [ + "s3:PutEncryptionConfiguration" + ] + }, + "DeleteBucketIntelligentTieringConfiguration": { + "section": "Bucket operations and permissions", + "required": [ + "s3:PutIntelligentTieringConfiguration" + ] + }, + "DeleteBucketInventoryConfiguration": { + "section": "Bucket operations and permissions", + "required": [ + "s3:PutInventoryConfiguration" + ] + }, + "DeleteBucketLifecycle": { + "section": "Bucket operations and permissions", + "required": [ + "s3:PutLifecycleConfiguration" + ] + }, + "DeleteBucketMetadataConfiguration": { + "section": "Bucket operations and permissions", + "required": [ + "s3:DeleteBucketMetadataTableConfiguration" + ] + }, + "DeleteBucketMetadataTableConfiguration": { + "section": "Bucket operations and permissions", + "required": [ + "s3:DeleteBucketMetadataTableConfiguration" + ] + }, + "DeleteBucketMetricsConfiguration": { + "section": "Bucket operations and permissions", + "required": [ + "s3:PutMetricsConfiguration" + ] + }, + "DeleteBucketOwnershipControls": { + "section": "Bucket operations and permissions", + "required": [ + "s3:PutBucketOwnershipControls" + ] + }, + "DeleteBucketPolicy": { + "section": "Bucket operations and permissions", + "required": [ + "s3:DeleteBucketPolicy" + ] + }, + "DeleteBucketReplication": { + "section": "Bucket operations and permissions", + "required": [ + "s3:PutReplicationConfiguration" + ] + }, + "DeleteBucketTagging": { + "section": "Bucket operations and permissions", + "required": [ + "s3:PutBucketTagging" + ] + }, + "DeleteBucketWebsite": { + "section": "Bucket operations and permissions", + "required": [ + "s3:DeleteBucketWebsite" + ] + }, + "DeleteJobTagging": { + "section": "Batch job operations and permissions", + "required": [ + "s3:DeleteJobTagging" + ] + }, + "DeleteMultiRegionAccessPoint": { + "section": "Multi-Region Access Point operations and permissions", + "required": [ + "s3:DeleteMultiRegionAccessPoint" + ] + }, + "DeleteObject": { + "section": "Object operations and permissions", + "either": { + "actions": [ + "s3:DeleteObject", + "s3:DeleteObjectVersion" + ], + "sentences": { + "s3:DeleteObject": "Required if you want to remove an object without specifying versionId in the request.", + "s3:DeleteObjectVersion": "Required if you want to remove a specific version of an object by specifying versionId in the request." + } + } + }, + "DeleteObjectTagging": { + "section": "Object operations and permissions", + "either": { + "actions": [ + "s3:DeleteObjectTagging", + "s3:DeleteObjectVersionTagging" + ], + "sentences": { + "s3:DeleteObjectTagging": "Required if you want to remove the entire tag set of an object without specifying versionId in the request.", + "s3:DeleteObjectVersionTagging": "Required if you want to delete tags of a specific object version by specifying versionId in the request." + } + } + }, + "DeleteObjects": { + "section": "Object operations and permissions", + "either": { + "actions": [ + "s3:DeleteObject", + "s3:DeleteObjectVersion" + ], + "sentences": { + "s3:DeleteObject": "Required if you want to remove an object without specifying versionId in the request.", + "s3:DeleteObjectVersion": "Required if you want to remove a specific version of an object by specifying versionId in the request." + } + } + }, + "DeletePublicAccessBlock (Account-level)": { + "section": "Account operations and permissions", + "required": [ + "s3:PutAccountPublicAccessBlock" + ] + }, + "DeletePublicAccessBlock (Bucket-level)": { + "section": "Bucket operations and permissions", + "required": [ + "s3:PutBucketPublicAccessBlock" + ] + }, + "DeleteStorageLensConfiguration": { + "section": "S3 Storage Lens configuration operations and permissions", + "required": [ + "s3:DeleteStorageLensConfiguration" + ] + }, + "DeleteStorageLensConfigurationTagging": { + "section": "S3 Storage Lens configuration operations and permissions", + "required": [ + "s3:DeleteStorageLensConfigurationTagging" + ] + }, + "DeleteStorageLensGroup": { + "section": "S3 Storage Lens groups operations and permissions", + "required": [ + "s3:DeleteStorageLensGroup" + ] + }, + "DescribeJob": { + "section": "Batch job operations and permissions", + "required": [ + "s3:DescribeJob" + ] + }, + "DescribeMultiRegionAccessPointOperation": { + "section": "Multi-Region Access Point operations and permissions", + "required": [ + "s3:DescribeMultiRegionAccessPointOperation" + ] + }, + "DissociateAccessGrantsIdentityCenter": { + "section": "S3 Access Grants instance operations and permissions", + "required": [ + "s3:DissociateAccessGrantsIdentityCenter" + ] + }, + "GetAccessGrant": { + "section": "S3 Access Grants grant operations and permissions", + "required": [ + "s3:GetAccessGrant" + ] + }, + "GetAccessGrantsInstance": { + "section": "S3 Access Grants instance operations and permissions", + "required": [ + "s3:GetAccessGrantsInstance" + ] + }, + "GetAccessGrantsInstanceForPrefix": { + "section": "S3 Access Grants instance operations and permissions", + "required": [ + "s3:GetAccessGrantsInstanceForPrefix" + ] + }, + "GetAccessGrantsInstanceResourcePolicy": { + "section": "S3 Access Grants instance operations and permissions", + "required": [ + "s3:GetAccessGrantsInstanceResourcePolicy" + ] + }, + "GetAccessGrantsLocation": { + "section": "S3 Access Grants location operations and permissions", + "required": [ + "s3:GetAccessGrantsLocation" + ] + }, + "GetAccessPoint": { + "section": "Account operations and permissions", + "required": [ + "s3:GetAccessPoint" + ] + }, + "GetAccessPointConfigurationForObjectLambda": { + "section": "Object Lambda Access Point operations and permissions", + "required": [ + "s3:GetAccessPointConfigurationForObjectLambda" + ] + }, + "GetAccessPointForObjectLambda": { + "section": "Object Lambda Access Point operations and permissions", + "required": [ + "s3:GetAccessPointForObjectLambda" + ] + }, + "GetAccessPointPolicy": { + "section": "Access point for general purpose buckets operations and permissions", + "required": [ + "s3:GetAccessPointPolicy" + ] + }, + "GetAccessPointPolicy (Account-level)": { + "section": "Account operations and permissions", + "required": [ + "s3:GetAccountPublicAccessBlock" + ] + }, + "GetAccessPointPolicyForObjectLambda": { + "section": "Object Lambda Access Point operations and permissions", + "required": [ + "s3:GetAccessPointPolicyForObjectLambda" + ] + }, + "GetAccessPointPolicyStatus": { + "section": "Access point for general purpose buckets operations and permissions", + "required": [ + "s3:GetAccessPointPolicyStatus" + ] + }, + "GetAccessPointPolicyStatusForObjectLambda": { + "section": "Object Lambda Access Point operations and permissions", + "required": [ + "s3:GetAccessPointPolicyStatusForObjectLambda" + ] + }, + "GetBucketAccelerateConfiguration": { + "section": "Bucket operations and permissions", + "required": [ + "s3:GetAccelerateConfiguration" + ] + }, + "GetBucketAcl": { + "section": "Bucket operations and permissions", + "required": [ + "s3:GetBucketAcl" + ] + }, + "GetBucketAnalyticsConfiguration": { + "section": "Bucket operations and permissions", + "required": [ + "s3:GetAnalyticsConfiguration" + ] + }, + "GetBucketCors": { + "section": "Bucket operations and permissions", + "required": [ + "s3:GetBucketCORS" + ] + }, + "GetBucketEncryption": { + "section": "Bucket operations and permissions", + "required": [ + "s3:GetEncryptionConfiguration" + ] + }, + "GetBucketIntelligentTieringConfiguration": { + "section": "Bucket operations and permissions", + "required": [ + "s3:GetIntelligentTieringConfiguration" + ] + }, + "GetBucketInventoryConfiguration": { + "section": "Bucket operations and permissions", + "required": [ + "s3:GetInventoryConfiguration" + ] + }, + "GetBucketLifecycle": { + "section": "Bucket operations and permissions", + "required": [ + "s3:GetLifecycleConfiguration" + ] + }, + "GetBucketLocation": { + "section": "Bucket operations and permissions", + "required": [ + "s3:GetBucketLocation" + ] + }, + "GetBucketLogging": { + "section": "Bucket operations and permissions", + "required": [ + "s3:GetBucketLogging" + ] + }, + "GetBucketMetadataConfiguration": { + "section": "Bucket operations and permissions", + "required": [ + "s3:GetBucketMetadataTableConfiguration" + ] + }, + "GetBucketMetadataTableConfiguration": { + "section": "Bucket operations and permissions", + "required": [ + "s3:GetBucketMetadataTableConfiguration" + ] + }, + "GetBucketMetricsConfiguration": { + "section": "Bucket operations and permissions", + "required": [ + "s3:GetMetricsConfiguration" + ] + }, + "GetBucketNotificationConfiguration": { + "section": "Bucket operations and permissions", + "required": [ + "s3:GetBucketNotification" + ] + }, + "GetBucketOwnershipControls": { + "section": "Bucket operations and permissions", + "required": [ + "s3:GetBucketOwnershipControls" + ] + }, + "GetBucketPolicy": { + "section": "Bucket operations and permissions", + "required": [ + "s3:GetBucketPolicy" + ] + }, + "GetBucketPolicyStatus": { + "section": "Bucket operations and permissions", + "required": [ + "s3:GetBucketPolicyStatus" + ] + }, + "GetBucketReplication": { + "section": "Bucket operations and permissions", + "required": [ + "s3:GetReplicationConfiguration" + ] + }, + "GetBucketRequestPayment": { + "section": "Bucket operations and permissions", + "required": [ + "s3:GetBucketRequestPayment" + ] + }, + "GetBucketTagging": { + "section": "Bucket operations and permissions", + "required": [ + "s3:GetBucketTagging" + ] + }, + "GetBucketVersioning": { + "section": "Bucket operations and permissions", + "required": [ + "s3:GetBucketVersioning" + ] + }, + "GetBucketWebsite": { + "section": "Bucket operations and permissions", + "required": [ + "s3:GetBucketWebsite" + ] + }, + "GetJobTagging": { + "section": "Batch job operations and permissions", + "required": [ + "s3:GetJobTagging" + ] + }, + "GetMultiRegionAccessPoint": { + "section": "Multi-Region Access Point operations and permissions", + "required": [ + "s3:GetMultiRegionAccessPoint" + ] + }, + "GetMultiRegionAccessPointPolicy": { + "section": "Multi-Region Access Point operations and permissions", + "required": [ + "s3:GetMultiRegionAccessPointPolicy" + ] + }, + "GetMultiRegionAccessPointPolicyStatus": { + "section": "Multi-Region Access Point operations and permissions", + "required": [ + "s3:GetMultiRegionAccessPointPolicyStatus" + ] + }, + "GetMultiRegionAccessPointRoutes": { + "section": "Multi-Region Access Point operations and permissions", + "required": [ + "s3:GetMultiRegionAccessPointRoutes" + ] + }, + "GetObject": { + "section": "Object operations and permissions", + "either": { + "actions": [ + "s3:GetObject", + "s3:GetObjectVersion" + ], + "sentences": { + "s3:GetObject": "Required if you want to get an object without specifying versionId in the request.", + "s3:GetObjectVersion": "Required if you want to get a specific version of an object by specifying versionId in the request." + } + } + }, + "GetObjectAcl": { + "section": "Object operations and permissions", + "either": { + "actions": [ + "s3:GetObjectAcl", + "s3:GetObjectVersionAcl" + ], + "sentences": { + "s3:GetObjectAcl": "Required if you want to get the access control list (ACL) of an object without specifying versionId in the request.", + "s3:GetObjectVersionAcl": "Required if you want to get the access control list (ACL) of an object by specifying versionId in the request." + } + } + }, + "GetObjectAttributes": { + "section": "Object operations and permissions", + "either": { + "actions": [ + "s3:GetObject", + "s3:GetObjectVersion" + ], + "sentences": { + "s3:GetObject": "Required if you want to retrieve attributes related to an object without specifying versionId in the request.", + "s3:GetObjectVersion": "Required if you want to retrieve attributes related to a specific object version by specifying versionId in the request." + } + } + }, + "GetObjectLegalHold": { + "section": "Object operations and permissions", + "required": [ + "s3:GetObjectLegalHold" + ] + }, + "GetObjectLockConfiguration": { + "section": "Bucket operations and permissions", + "required": [ + "s3:GetBucketObjectLockConfiguration" + ] + }, + "GetObjectRetention": { + "section": "Object operations and permissions", + "required": [ + "s3:GetObjectRetention" + ] + }, + "GetObjectTagging": { + "section": "Object operations and permissions", + "either": { + "actions": [ + "s3:GetObjectTagging", + "s3:GetObjectVersionTagging" + ], + "sentences": { + "s3:GetObjectTagging": "Required if you want to get the tag set of an object without specifying versionId in the request.", + "s3:GetObjectVersionTagging": "Required if you want to get the tags of a specific object version by specifying versionId in the request." + } + } + }, + "GetObjectTorrent": { + "section": "Object operations and permissions", + "required": [ + "s3:GetObject" + ] + }, + "GetPublicAccessBlock (Bucket-level)": { + "section": "Bucket operations and permissions", + "required": [ + "s3:GetBucketPublicAccessBlock" + ] + }, + "GetStorageLensConfiguration": { + "section": "S3 Storage Lens configuration operations and permissions", + "required": [ + "s3:GetStorageLensConfiguration" + ] + }, + "GetStorageLensConfigurationTagging": { + "section": "S3 Storage Lens configuration operations and permissions", + "required": [ + "s3:GetStorageLensConfigurationTagging" + ] + }, + "GetStorageLensGroup": { + "section": "S3 Storage Lens groups operations and permissions", + "required": [ + "s3:GetStorageLensGroup" + ] + }, + "HeadBucket": { + "section": "Bucket operations and permissions", + "required": [ + "s3:ListBucket" + ] + }, + "HeadObject": { + "section": "Object operations and permissions", + "required": [ + "s3:GetObject" + ] + }, + "ListAccessGrants": { + "section": "S3 Access Grants grant operations and permissions", + "required": [ + "s3:ListAccessGrants" + ] + }, + "ListAccessGrantsInstances": { + "section": "S3 Access Grants instance operations and permissions", + "required": [ + "s3:ListAccessGrantsInstances" + ] + }, + "ListAccessGrantsLocations": { + "section": "S3 Access Grants location operations and permissions", + "required": [ + "s3:ListAccessGrantsLocations" + ] + }, + "ListAccessPoints": { + "section": "Account operations and permissions", + "required": [ + "s3:ListAccessPoints" + ] + }, + "ListAccessPointsForObjectLambda": { + "section": "Account operations and permissions", + "required": [ + "s3:ListAccessPointsForObjectLambda" + ] + }, + "ListBucketAnalyticsConfigurations": { + "section": "Bucket operations and permissions", + "required": [ + "s3:GetAnalyticsConfiguration" + ] + }, + "ListBucketIntelligentTieringConfigurations": { + "section": "Bucket operations and permissions", + "required": [ + "s3:GetIntelligentTieringConfiguration" + ] + }, + "ListBucketInventoryConfigurations": { + "section": "Bucket operations and permissions", + "required": [ + "s3:GetInventoryConfiguration" + ] + }, + "ListBucketMetricsConfigurations": { + "section": "Bucket operations and permissions", + "required": [ + "s3:GetMetricsConfiguration" + ] + }, + "ListBuckets": { + "section": "Account operations and permissions", + "required": [ + "s3:ListAllMyBuckets" + ] + }, + "ListCallerAccessGrants": { + "section": "S3 Access Grants grant operations and permissions", + "required": [ + "s3:ListCallerAccessGrants" + ] + }, + "ListJobs": { + "section": "Account operations and permissions", + "required": [ + "s3:ListJobs" + ] + }, + "ListMultiRegionAccessPoints": { + "section": "Account operations and permissions", + "required": [ + "s3:ListMultiRegionAccessPoints" + ] + }, + "ListMultipartUploads": { + "section": "Object operations and permissions", + "required": [ + "s3:ListBucketMultipartUploads" + ] + }, + "ListObjectVersions": { + "section": "Bucket operations and permissions", + "required": [ + "s3:ListBucketVersions" + ] + }, + "ListObjects": { + "section": "Bucket operations and permissions", + "required": [ + "s3:ListBucket" + ] + }, + "ListObjectsV2": { + "section": "Bucket operations and permissions", + "required": [ + "s3:ListBucket" + ] + }, + "ListParts": { + "section": "Object operations and permissions", + "required": [ + "s3:ListMultipartUploadParts" + ] + }, + "ListStorageLensConfigurations": { + "section": "Account operations and permissions", + "required": [ + "s3:ListStorageLensConfigurations" + ] + }, + "ListStorageLensGroups": { + "section": "S3 Storage Lens groups operations and permissions", + "required": [ + "s3:ListStorageLensGroups" + ] + }, + "ListTagsForResource": { + "section": "S3 Storage Lens groups operations and permissions", + "required": [ + "s3:ListTagsForResource" + ] + }, + "PutAccessGrantsInstanceResourcePolicy": { + "section": "S3 Access Grants instance operations and permissions", + "required": [ + "s3:PutAccessGrantsInstanceResourcePolicy" + ] + }, + "PutAccessPointConfigurationForObjectLambda": { + "section": "Object Lambda Access Point operations and permissions", + "required": [ + "s3:PutAccessPointConfigurationForObjectLambda" + ] + }, + "PutAccessPointPolicy": { + "section": "Access point for general purpose buckets operations and permissions", + "required": [ + "s3:PutAccessPointPolicy" + ] + }, + "PutAccessPointPolicyForObjectLambda": { + "section": "Object Lambda Access Point operations and permissions", + "required": [ + "s3:PutAccessPointPolicyForObjectLambda" + ] + }, + "PutBucketAccelerateConfiguration": { + "section": "Bucket operations and permissions", + "required": [ + "s3:PutAccelerateConfiguration" + ] + }, + "PutBucketAcl": { + "section": "Bucket operations and permissions", + "required": [ + "s3:PutBucketAcl" + ] + }, + "PutBucketAnalyticsConfiguration": { + "section": "Bucket operations and permissions", + "required": [ + "s3:PutAnalyticsConfiguration" + ] + }, + "PutBucketCors": { + "section": "Bucket operations and permissions", + "required": [ + "s3:PutBucketCORS" + ] + }, + "PutBucketEncryption": { + "section": "Bucket operations and permissions", + "required": [ + "s3:PutEncryptionConfiguration" + ] + }, + "PutBucketIntelligentTieringConfiguration": { + "section": "Bucket operations and permissions", + "required": [ + "s3:PutIntelligentTieringConfiguration" + ] + }, + "PutBucketInventoryConfiguration": { + "section": "Bucket operations and permissions", + "required": [ + "s3:PutInventoryConfiguration" + ] + }, + "PutBucketLifecycle": { + "section": "Bucket operations and permissions", + "required": [ + "s3:PutLifecycleConfiguration" + ] + }, + "PutBucketLogging": { + "section": "Bucket operations and permissions", + "required": [ + "s3:PutBucketLogging" + ] + }, + "PutBucketMetricsConfiguration": { + "section": "Bucket operations and permissions", + "required": [ + "s3:PutMetricsConfiguration" + ] + }, + "PutBucketNotificationConfiguration": { + "section": "Bucket operations and permissions", + "required": [ + "s3:PutBucketNotification" + ] + }, + "PutBucketOwnershipControls": { + "section": "Bucket operations and permissions", + "required": [ + "s3:PutBucketOwnershipControls" + ] + }, + "PutBucketPolicy": { + "section": "Bucket operations and permissions", + "required": [ + "s3:PutBucketPolicy" + ] + }, + "PutBucketReplication": { + "section": "Bucket operations and permissions", + "required": [ + "s3:PutReplicationConfiguration" + ] + }, + "PutBucketRequestPayment": { + "section": "Bucket operations and permissions", + "required": [ + "s3:PutBucketRequestPayment" + ] + }, + "PutBucketTagging": { + "section": "Bucket operations and permissions", + "required": [ + "s3:PutBucketTagging" + ] + }, + "PutBucketVersioning": { + "section": "Bucket operations and permissions", + "required": [ + "s3:PutBucketVersioning" + ] + }, + "PutBucketWebsite": { + "section": "Bucket operations and permissions", + "required": [ + "s3:PutBucketWebsite" + ] + }, + "PutJobTagging": { + "section": "Batch job operations and permissions", + "required": [ + "s3:PutJobTagging" + ] + }, + "PutMultiRegionAccessPointPolicy": { + "section": "Multi-Region Access Point operations and permissions", + "required": [ + "s3:PutMultiRegionAccessPointPolicy" + ] + }, + "PutObject": { + "section": "Object operations and permissions", + "required": [ + "s3:PutObject" + ] + }, + "PutObjectAcl": { + "section": "Object operations and permissions", + "either": { + "actions": [ + "s3:PutObjectAcl", + "s3:PutObjectVersionAcl" + ], + "sentences": { + "s3:PutObjectAcl": "Required if you want to set the access control list (ACL) permissions for a new or existing object without specifying versionId in the request.", + "s3:PutObjectVersionAcl": "Required if you want to set the access control list (ACL) permissions for a new or existing object by specifying versionId in the request." + } + } + }, + "PutObjectLegalHold": { + "section": "Object operations and permissions", + "required": [ + "s3:PutObjectLegalHold" + ] + }, + "PutObjectLockConfiguration": { + "section": "Bucket operations and permissions", + "required": [ + "s3:PutBucketObjectLockConfiguration" + ] + }, + "PutObjectRetention": { + "section": "Object operations and permissions", + "required": [ + "s3:PutObjectRetention" + ] + }, + "PutObjectTagging": { + "section": "Object operations and permissions", + "either": { + "actions": [ + "s3:PutObjectTagging", + "s3:PutObjectVersionTagging" + ], + "sentences": { + "s3:PutObjectTagging": "Required if you want to set the supplied tag set to an object that already exists in a bucket without specifying versionId in the request.", + "s3:PutObjectVersionTagging": "Required if you want to set the supplied tag set to an object that already exists in a bucket by specifying versionId in the request." + } + } + }, + "PutPublicAccessBlock (Account-level)": { + "section": "Account operations and permissions", + "required": [ + "s3:PutAccountPublicAccessBlock" + ] + }, + "PutPublicAccessBlock (Bucket-level)": { + "section": "Bucket operations and permissions", + "required": [ + "s3:PutBucketPublicAccessBlock" + ] + }, + "PutStorageLensConfiguration": { + "section": "Account operations and permissions", + "required": [ + "s3:PutStorageLensConfiguration" + ] + }, + "PutStorageLensConfigurationTagging": { + "section": "S3 Storage Lens configuration operations and permissions", + "required": [ + "s3:PutStorageLensConfigurationTagging" + ] + }, + "RestoreObject": { + "section": "Object operations and permissions", + "required": [ + "s3:RestoreObject" + ] + }, + "SelectObjectContent": { + "section": "Object operations and permissions", + "required": [ + "s3:GetObject" + ] + }, + "SubmitMultiRegionAccessPointRoutes": { + "section": "Multi-Region Access Point operations and permissions", + "required": [ + "s3:SubmitMultiRegionAccessPointRoutes" + ] + }, + "TagResource": { + "section": "S3 Storage Lens groups operations and permissions", + "required": [ + "s3:TagResource" + ] + }, + "UntagResource": { + "section": "S3 Storage Lens groups operations and permissions", + "required": [ + "s3:UntagResource" + ] + }, + "UpdateAccessGrantsLocation": { + "section": "S3 Access Grants location operations and permissions", + "required": [ + "s3:UpdateAccessGrantsLocation" + ] + }, + "UpdateBucketMetadataInventoryTableConfiguration": { + "section": "Bucket operations and permissions", + "required": [ + "s3:UpdateBucketMetadataInventoryTableConfiguration", + "s3tables:CreateTableBucket", + "s3tables:CreateNamespace", + "s3tables:CreateTable", + "s3tables:GetTable", + "s3tables:PutTablePolicy", + "s3tables:PutTableEncryption", + "kms:DescribeKey" + ] + }, + "UpdateBucketMetadataJournalTableConfiguration": { + "section": "Bucket operations and permissions", + "required": [ + "s3:UpdateBucketMetadataJournalTableConfiguration" + ] + }, + "UpdateJobPriority": { + "section": "Batch job operations and permissions", + "required": [ + "s3:UpdateJobPriority" + ] + }, + "UpdateJobStatus": { + "section": "Batch job operations and permissions", + "required": [ + "s3:UpdateJobStatus" + ] + }, + "UpdateObjectEncryption": { + "section": "Object operations and permissions", + "required": [ + "s3:UpdateObjectEncryption", + "kms:Encrypt", + "kms:Decrypt", + "kms:GenerateDataKey", + "kms:ReEncrypt*" + ] + }, + "UpdateStorageLensGroup": { + "section": "S3 Storage Lens groups operations and permissions", + "required": [ + "s3:UpdateStorageLensGroup" + ] + }, + "UploadPart": { + "section": "Object operations and permissions", + "required": [ + "s3:PutObject" + ] + }, + "UploadPartCopy": { + "section": "Object operations and permissions", + "either": { + "actions": [ + "s3:GetObject", + "s3:GetObjectVersion" + ], + "sentences": { + "s3:GetObject": "Required if you want to copy an object from the source bucket without specifying versionId in the request.", + "s3:GetObjectVersion": "Required if you want to copy a specific version of an object from the source bucket by specifying versionId in the request." + } + }, + "required": [ + "s3:PutObject" + ] + } + } +} diff --git a/tools/aws/test_fetch_s3_required_actions.py b/tools/aws/test_fetch_s3_required_actions.py new file mode 100644 index 0000000000..0f3d7460e8 --- /dev/null +++ b/tools/aws/test_fetch_s3_required_actions.py @@ -0,0 +1,124 @@ +#!/usr/bin/env python3 +"""Tests for fetch_s3_required_actions.py, on pages in the S3 user guide's markup.""" +from __future__ import annotations + +import pytest + +import fetch_s3_required_actions as f + + +def page(*rows: str) -> str: + """A page whose main column holds the rows, each a line of the definition list the guide renders.""" + body = "".join(f"

{row}

" for row in rows) + return f'
{body}
' + + +def test_each_operation_keeps_its_required_actions_and_its_section(): + operations = f.read_page(page( + "Bucket operations and permissions", + "ListObjectsV2", + "(Required) s3:ListBucket", + "Required to list some or all (up to 1,000) of the objects in an S3 bucket.", + "(Conditionally required) s3:GetObjectAcl", + "Required if you want to display object owner information.", + "Object operations and permissions", + "CopyObject", + "(Required) s3:PutObject", + "Required to write the object to the destination bucket.", + )) + assert operations == { + "CopyObject": {"section": "Object operations and permissions", "required": ["s3:PutObject"]}, + "ListObjectsV2": {"section": "Bucket operations and permissions", "required": ["s3:ListBucket"]}, + } + + +def test_an_either_row_keeps_both_actions_and_the_sentence_each_gives(): + operations = f.read_page(page( + "Object operations and permissions", + "GetObject", + "(Required) Either s3:GetObject or s3:GetObjectVersion", + "s3:GetObject – Required if you want to get an object without specifying versionId in the request.", + "s3:GetObjectVersion – Required if you want to get a specific version of an object by specifying " + "versionId in the request.", + )) + assert operations["GetObject"]["either"] == { + "actions": ["s3:GetObject", "s3:GetObjectVersion"], + "sentences": { + "s3:GetObject": "Required if you want to get an object without specifying versionId in the request.", + "s3:GetObjectVersion": "Required if you want to get a specific version of an object by specifying " + "versionId in the request.", + }, + } + + +def test_an_either_row_missing_a_sentence_is_refused(): + with pytest.raises(ValueError): + f.read_page(page("GetObject", "(Required) Either s3:GetObject or s3:GetObjectVersion", + "s3:GetObject - Required if you want to get an object without specifying versionId.")) + + +def test_a_level_tells_two_operations_of_one_name_apart_and_other_notes_are_dropped(): + operations = f.read_page(page( + "GetPublicAccessBlock (Bucket-level)", + "(Required) s3:GetBucketPublicAccessBlock", + "PutPublicAccessBlock (Account-level)", + "(Required) s3:PutAccountPublicAccessBlock", + # A note may run onto the next line; the rows under it are its operation's, not the one before. + "DeleteBucketLifecycle", + "(Required) s3:PutLifecycleConfiguration", + "DeleteBucketMetadataConfiguration (V2 API operation. The IAM", + "policy action name is the same for the V1 and V2 API operations.)", + "(Required) s3:DeleteBucketMetadataTableConfiguration", + )) + assert operations["GetPublicAccessBlock (Bucket-level)"]["required"] == ["s3:GetBucketPublicAccessBlock"] + assert operations["PutPublicAccessBlock (Account-level)"]["required"] == ["s3:PutAccountPublicAccessBlock"] + assert operations["DeleteBucketLifecycle"]["required"] == ["s3:PutLifecycleConfiguration"] + assert operations["DeleteBucketMetadataConfiguration"]["required"] == ["s3:DeleteBucketMetadataTableConfiguration"] + + +def test_a_row_several_operations_share_is_kept_whole_under_its_heading(): + operations = f.read_page(page( + "CreateStorageLensGroup", + "(Required) s3:CreateStorageLensGroup", + "CreateStorageLensGroup, TagResource", + "(Required) s3:CreateStorageLensGroup,", + "s3:TagResource", + "ListStorageLensGroups", + "(Required) s3:ListStorageLensGroups", + "(Required) s3:ListStorageLensGroups", + )) + assert operations["CreateStorageLensGroup"]["required"] == ["s3:CreateStorageLensGroup"] + assert operations["CreateStorageLensGroup, TagResource"]["required"] == ["s3:CreateStorageLensGroup", + "s3:TagResource"] + assert operations["ListStorageLensGroups"]["required"] == ["s3:ListStorageLensGroups"] + + +def test_a_required_row_running_over_lines_keeps_every_action_other_services_included(): + operations = f.read_page(page( + "UpdateObjectEncryption", + "(Required) s3:UpdateObjectEncryption,", + "kms:Encrypt, kms:Decrypt, kms:GenerateDataKey,", + "kms:ReEncrypt*", + "Required if you want to change encrypted objects between server-side encryption types.", + )) + assert operations["UpdateObjectEncryption"]["required"] == [ + "s3:UpdateObjectEncryption", "kms:Encrypt", "kms:Decrypt", "kms:GenerateDataKey", "kms:ReEncrypt*"] + + +def test_a_required_row_ending_in_a_comma_with_no_action_after_it_is_refused(): + with pytest.raises(ValueError): + f.read_page(page("CreateStorageLensGroup, TagResource", "(Required) s3:CreateStorageLensGroup,", + "Required to create a Storage Lens group with tags.")) + + +def test_the_source_names_its_fetcher(): + assert f.build(page(*[row for index in range(f.MINIMUM_OPERATIONS) for row in ( + f"GetThing{index}", "(Required) Either s3:GetObject or s3:GetObjectVersion", + "s3:GetObject - Required if you want to get an object without specifying versionId in the request.", + "s3:GetObjectVersion - Required if you want to get a specific version of an object by specifying versionId " + "in the request.")]))["_source"]["fetcher"] == "tools/aws/fetch_s3_required_actions.py" + + +def test_a_page_giving_too_few_operations_has_changed_its_layout(): + with pytest.raises(ValueError): + f.build(page("ListObjectsV2", "(Required) s3:ListBucket")) diff --git a/tools/aws/test_regen_iam_authorized_actions.py b/tools/aws/test_regen_iam_authorized_actions.py index 058919bc6b..fc13f21d9e 100644 --- a/tools/aws/test_regen_iam_authorized_actions.py +++ b/tools/aws/test_regen_iam_authorized_actions.py @@ -538,3 +538,175 @@ def test_the_round_trip_lists_the_operations_authorized_by_method(tmp_path): {"GetStage": ["api", "apiv2"]}) given = saved_sources(tmp_path / "later", ANCHOR_SERVICES + [later]) assert r.main(["--verify", "--source-dir", str(given), "--output", str(output), "--routes", str(routes)]) == 1 + + +# --------------------------------------------------------------------------- # +# The S3 user guide's required actions, the namesake client and spellings +# --------------------------------------------------------------------------- # +S3_MODELS = { + "s3": {"credentialScope": "s3", "operations": { + "GetPublicAccessBlock": {"method": "GET", "requestUri": "/{Bucket}?publicAccessBlock"}, + "PutPublicAccessBlock": {"method": "PUT", "requestUri": "/{Bucket}?publicAccessBlock"}}}, + "s3control": {"credentialScope": "s3", "operations": { + "GetPublicAccessBlock": {"method": "GET", "requestUri": "/v20180820/configuration/publicAccessBlock"}, + "PutPublicAccessBlock": {"method": "PUT", "requestUri": "/v20180820/configuration/publicAccessBlock"}, + "GetAccessPointPolicy": {"method": "GET", "requestUri": "/v20180820/accesspoint/{name}/policy"}}}, +} +VERSION_SENTENCES = { + "s3:GetObject": "Required if you want to get an object without specifying versionId in the request.", + "s3:GetObjectVersion": "Required if you want to get a specific version of an object by specifying versionId " + "in the request.", +} +S3_PAGE = { + "ListObjectsV2": {"section": "Bucket operations and permissions", "required": ["s3:ListBucket"]}, + "CopyObject": {"section": "Object operations and permissions", "required": ["s3:PutObject"], + "either": {"actions": ["s3:GetObject", "s3:GetObjectVersion"], "sentences": VERSION_SENTENCES}}, + "GetObject": {"section": "Object operations and permissions", + "either": {"actions": ["s3:GetObject", "s3:GetObjectVersion"], "sentences": VERSION_SENTENCES}}, + "GetPublicAccessBlock (Bucket-level)": {"section": "Bucket operations and permissions", + "required": ["s3:GetBucketPublicAccessBlock"]}, + "PutPublicAccessBlock (Account-level)": {"section": "Account operations and permissions", + "required": ["s3:PutAccountPublicAccessBlock"]}, + # The page's own error: S3 Control's account-level GetPublicAccessBlock, headed as another operation. + "GetAccessPointPolicy (Account-level)": {"section": "Account operations and permissions", + "required": ["s3:GetAccountPublicAccessBlock"]}, + # A row several operations share is not one operation's. + "CreateStorageLensGroup, TagResource": {"section": "Account operations and permissions", + "required": ["s3:CreateStorageLensGroup", "s3:TagResource"]}, +} +# The query parameters botocore gives each operation's request (`s3_query_parameters`). +S3_QUERY = {"GetObject": ["partNumber", "versionId"], "CopyObject": [], "DeleteObjects": [], + **{operation: ["versionId"] for operation in ( + "GetObjectAnnotation", "PutObjectAnnotation", "DeleteObjectAnnotation", "ListObjectAnnotations")}} + + +def test_the_s3_user_guide_gives_an_operation_its_one_required_action(): + actions, _, _ = r.s3_required(S3_PAGE, S3_MODELS, S3_QUERY) + assert actions == {"CopyObject": "s3:PutObject", "ListObjectsV2": "s3:ListBucket"} + + +def test_an_operation_both_models_have_takes_the_pages_action_for_one_models_requests(): + _, by_model, _ = r.s3_required(S3_PAGE, S3_MODELS, S3_QUERY) + # The Account-level row is S3 Control's, any other S3's. GetAccessPointPolicy is S3 Control's alone, so its level + # tells nothing apart; the measured entry gives the account-level GetPublicAccessBlock the page mislabels. + assert by_model == {"s3": { + "s3": {"GetPublicAccessBlock": "s3:GetBucketPublicAccessBlock"}, + "s3control": {"GetPublicAccessBlock": "s3:GetAccountPublicAccessBlock", + "PutPublicAccessBlock": "s3:PutAccountPublicAccessBlock"}}} + + +def test_an_either_row_is_a_choice_by_the_parameter_its_sentences_name_unless_the_operation_requires_its_own(): + _, _, versioned = r.s3_required(S3_PAGE, S3_MODELS, S3_QUERY) + assert versioned["s3"]["GetObject"] == {"parameter": "versionId", "without": "s3:GetObject", + "with": "s3:GetObjectVersion"} + # CopyObject's own action is s3:PutObject; its Either is about the source it copies. + assert "CopyObject" not in versioned["s3"] + assert versioned["s3"]["GetObjectAnnotation"]["with"] == "s3:GetObjectVersionAnnotation" + + +def test_a_version_choice_is_read_only_where_botocore_gives_its_parameter_in_the_query(): + deletes = {"section": "Object operations and permissions", + "either": {"actions": ["s3:DeleteObject", "s3:DeleteObjectVersion"], "sentences": { + "s3:DeleteObject": "Required if you want to remove an object without specifying versionId in the " + "request.", + "s3:DeleteObjectVersion": "Required if you want to remove a specific version of an object by " + "specifying versionId in the request."}}} + # DeleteObjects names each version in its body, so a request's query never says which it deletes. + _, _, versioned = r.s3_required({**S3_PAGE, "DeleteObjects": deletes}, S3_MODELS, S3_QUERY) + assert "DeleteObjects" not in versioned["s3"] + assert "GetObject" in versioned["s3"] + + +def test_a_measured_version_choice_by_a_parameter_botocore_gives_no_query_is_refused(): + with pytest.raises(ValueError): + r.s3_required(S3_PAGE, S3_MODELS, {**S3_QUERY, "GetObjectAnnotation": []}) + + +def test_an_account_level_row_whose_s3_control_route_names_a_resource_is_refused(): + named = {**S3_MODELS, "s3control": {"credentialScope": "s3", "operations": { + **S3_MODELS["s3control"]["operations"], + "PutPublicAccessBlock": {"method": "PUT", "requestUri": "/v20180820/bucket/{name}/publicAccessBlock"}}}} + with pytest.raises(ValueError): + r.s3_required(S3_PAGE, named, S3_QUERY) + + +def test_the_query_parameters_are_read_from_botocores_s3_model(tmp_path): + directory = tmp_path / "s3" / "2006-03-01" + directory.mkdir(parents=True) + (directory / "service-2.json").write_text(json.dumps({ + "operations": {"GetObject": {"input": {"shape": "GetObjectRequest"}}, + "DeleteObjects": {"input": {"shape": "DeleteObjectsRequest"}}}, + "shapes": {"GetObjectRequest": {"members": { + "Bucket": {"location": "uri", "locationName": "Bucket"}, + "VersionId": {"location": "querystring", "locationName": "versionId"}}}, + "DeleteObjectsRequest": {"members": {"Delete": {"locationName": "Delete"}}}}}), encoding="utf-8") + assert r.s3_query_parameters(tmp_path) == {"GetObject": ["versionId"], "DeleteObjects": []} + + +def test_the_vendored_sections_are_assembled_in_one_place(): + s3 = with_sdk_clients(service("s3", {"GetObject": ["s3:GetObject", "s3:GetObjectVersion"]}, + ["GetObject", "GetObjectVersion"]), "s3", "s3control") + memorydb = service("memorydb", {"CreateACL": ["memorydb:CreateAcl"]}, ["CreateAcl"]) + sections = r.vendored_sections([s3, memorydb], S3_PAGE, S3_MODELS, S3_QUERY, {}) + assert set(sections) == {"authorizedByModel", "versioned", "spellings"} + assert sections["versioned"]["s3"]["GetObject"]["with"] == "s3:GetObjectVersion" + assert sections["authorizedByModel"]["s3"]["s3control"]["PutPublicAccessBlock"] == "s3:PutAccountPublicAccessBlock" + assert sections["spellings"] == {"memorydb": {"CreateACL": "memorydb:CreateAcl"}} + # A rename already gives the spelling, so the section does not repeat it. + assert r.vendored_sections([memorydb], S3_PAGE, S3_MODELS, S3_QUERY, + {"memorydb": {"CreateACL": "memorydb:CreateAcl"}})["spellings"] == {"memorydb": {}} + + +def test_a_measured_entry_with_no_link_or_one_the_page_gives_is_refused(monkeypatch): + with pytest.raises(ValueError): + r.s3_required({**S3_PAGE, "GetPublicAccessBlock (Account-level)": { + "section": "Account operations and permissions", "required": ["s3:GetAccountPublicAccessBlock"]}}, + S3_MODELS, S3_QUERY) + monkeypatch.setattr(r, "MEASURED_BY_MODEL", {("s3", "s3control", "GetPublicAccessBlock"): ( + "s3:GetAccountPublicAccessBlock", "the actions table says so")}) + with pytest.raises(ValueError): + r.s3_required(S3_PAGE, S3_MODELS, S3_QUERY) + + +def test_the_page_answers_an_s3_operation_the_reference_does_not_and_a_disagreement_fails(): + s3 = service("s3", {"ListObjectsV2": ["s3:ListBucket", "s3:GetObjectAcl"], "CopyObject": ["s3:PutObject"]}, + ["ListBucket", "GetObjectAcl", "PutObject"]) + assert r.authorized_actions([s3], S3_PAGE, S3_MODELS, S3_QUERY) == { + "s3": {"CopyObject": "s3:PutObject", "ListObjectsV2": "s3:ListBucket"}} + disagreeing = service("s3", {"ListObjectsV2": ["s3:GetObjectAcl"]}, ["ListBucket", "GetObjectAcl"]) + # An operation both models have is answered for S3's requests alone, not in the map every model's request reads. + shared = service("s3", {"GetPublicAccessBlock": ["s3:GetBucketPublicAccessBlock"]}, ["GetBucketPublicAccessBlock"]) + assert r.authorized_actions([with_sdk_clients(shared, "s3", "s3control")], S3_PAGE, S3_MODELS, S3_QUERY) == {} + with pytest.raises(ValueError): + r.authorized_actions([disagreeing], S3_PAGE, S3_MODELS, S3_QUERY) + # References without S3's read nothing of the page. + assert r.authorized_actions(ANCHOR_SERVICES, S3_PAGE, S3_MODELS, S3_QUERY) == r.authorized_actions_from(ANCHOR_SERVICES) + + +def test_the_namesake_client_takes_the_one_answer_of_an_operation_several_clients_list(): + lifecycle = with_sdk_clients(service("s3", {"GetBucketLifecycleConfiguration": [ + "s3:GetLifecycleConfiguration", "s3express:GetLifecycleConfiguration"]}, ["GetLifecycleConfiguration"]), + "s3", "s3control") + assert r.namesake_by_model([lifecycle], {"s3", "s3control"}) == { + "s3": {"s3": {"GetBucketLifecycleConfiguration": "s3:GetLifecycleConfiguration"}}} + # A client whose routes are not vendored cannot be told from its request's route. + assert r.namesake_by_model([lifecycle], {"s3"}) == {} + + +def test_an_action_spelled_otherwise_than_its_operation_keeps_the_references_spelling(): + memorydb = service("memorydb", {"CreateACL": ["memorydb:CreateAcl"], "CreateCluster": ["memorydb:CreateCluster"]}, + ["CreateAcl", "CreateCluster"]) + assert r.spellings([memorydb]) == {"memorydb": {"CreateACL": "memorydb:CreateAcl"}} + + +def test_the_new_sections_are_built_only_for_references_with_s3_and_validated(): + document = r.build(ANCHOR_SERVICES, "a test", [], page=S3_PAGE, models=S3_MODELS) + assert document["authorizedByModel"] == {} and document["versioned"] == {} + assert r.validate(document, []) == [] + broken = dict(document, authorizedByModel={"s3": {"s3control": {"GetPublicAccessBlock": "sqs:SendMessage"}}}, + versioned={"s3": {"GetObject": {"parameter": "versionId", "without": "s3:GetObject"}}}, + spellings={"memorydb": {"CreateACL": "memorydb:CreateCluster"}}) + problems = r.validate(broken, []) + assert any("authorizedByModel" in problem for problem in problems) + assert any("versioned" in problem for problem in problems) + assert any("spellings" in problem for problem in problems) diff --git a/tools/aws/test_regen_rest_routes.py b/tools/aws/test_regen_rest_routes.py index 62929223a1..0c17d19f1c 100644 --- a/tools/aws/test_regen_rest_routes.py +++ b/tools/aws/test_regen_rest_routes.py @@ -454,3 +454,16 @@ def test_vendored_documented_routes_read_from_another_page_or_malformed_are_refu malformed["operations"]["GetCatalog"] = {"method": "FETCH", "requestUri": "/iceberg/v1/config"} with pytest.raises(SystemExit, match="malformed"): r.carried_documented(r.render(r.build({}, "test", {"glue-iceberg-rest": malformed}))) + + +def test_a_hand_routed_scopes_routes_list_all_their_requests_must_carry_for_the_coverage_test(): + s3 = shaped(model("rest-xml", "2006-03-01", CompleteMultipartUpload=("POST", "/{Bucket}/{Key+}"), + PutObject=("PUT", "/{Bucket}/{Key+}")), + "CompleteMultipartUpload", {"UploadId": ("querystring", "uploadId")}) + lam = shaped(model("rest-json", "2015-03-31", GetThing=("GET", "/things/{Name}")), + "GetThing", {"Qualifier": ("querystring", "Qualifier")}) + doc = r.build({"s3": s3, "lambda": lam}, "botocore test") + assert doc["models"]["s3"]["operations"]["CompleteMultipartUpload"]["required"] == {"query": ["uploadId"]} + assert "required" not in doc["models"]["s3"]["operations"]["PutObject"] + # A routed scope's requests are matched on its routes, which carry only what tells shared ones apart. + assert "required" not in doc["models"]["lambda"]["operations"]["GetThing"]