From 96819a87fd9da480184a68c9808d6d74cd213aa5 Mon Sep 17 00:00:00 2001 From: Priamo Germosen <6233424+pgermosen@users.noreply.github.com> Date: Sun, 29 Nov 2026 13:12:46 -0400 Subject: [PATCH] fix(iam): check a Secrets Manager request for the actions its required permissions give (#9758) The Service Reference lists the actions each Secrets Manager operation is authorized by without saying when each is needed, so a request was checked as its own action alone: a BatchGetSecretValue using Filters without secretsmanager:ListSecrets, a CreateSecret adding replica Regions without secretsmanager:ReplicateSecretToRegions and a ValidateResourcePolicy without secretsmanager:PutResourcePolicy were all let through. Each operation's page in the API reference says it, in its required permissions: "If you use filters, you must also have secretsmanager:ListSecrets", "To add replica Regions, you must also have secretsmanager:ReplicateSecretToRegions", "Required permissions: secretsmanager:ValidateResourcePolicy and secretsmanager:PutResourcePolicy". tools/aws/fetch_secretsmanager_required_permissions.py copies that paragraph for each operation the Service Reference lists as authorized by another of its actions, with each clause's action and what it is needed for or on, into tools/aws/sources/secretsmanager-required-permissions.json. Two generators read it: - regen_iam_authorized_actions.py: an action needed when the request does something is a companion of the request member the clause's words name as the generators' names go (filters is Filters, add replica Regions AddReplicaRegions), where the Service Reference lists it for the operation and does not mark it as tagging, which the tag-on-create table checks. A companion a request member sets may now carry no session key. - regen_iam_request_resources.py: actions an operation always needs beside its own are each checked on what the rules read for it (ValidateResourcePolicy and PutResourcePolicy on the secret its SecretId names). A request checked by parts that names nothing is now checked on * as each action the table checks on the same resources as its own, not as its own alone, so a ValidateResourcePolicy naming no secret still needs PutResourcePolicy. The fetcher refuses a sentence naming a secretsmanager: action in a wording it does not read, so a reworded page fails rather than dropping a check, and the enforcement test runs on the AWS SDK. Not read: GetSecretValue for each secret of a batch, which AWS reports per secret in Errors rather than refusing the call; PutResourcePolicy for a cross-account replica and DeleteResourcePolicy for one stopped replicating, whose words name no member of the request; and the KMS permissions of a secret on a customer managed key. --- .github/workflows/iam-data-drift.yml | 3 + Makefile | 6 +- docs/services/iam.md | 6 +- docs/services/secrets-manager.md | 20 ++ .../aws/core/common/IamEnforcementFilter.java | 11 +- .../aws/core/common/RequestResources.java | 25 +++ .../services/iam/IamAuthorizedActions.java | 12 +- .../resources/aws/iam-authorized-actions.json | 16 ++ .../resources/aws/iam-request-resources.json | 2 +- ...PermissionsEnforcementIntegrationTest.java | 134 +++++++++++++ ...tch_secretsmanager_required_permissions.py | 187 ++++++++++++++++++ tools/aws/regen_iam_authorized_actions.py | 69 ++++++- tools/aws/regen_iam_request_resources.py | 43 +++- .../secretsmanager-required-permissions.json | 97 +++++++++ ...tch_secretsmanager_required_permissions.py | 83 ++++++++ .../aws/test_regen_iam_authorized_actions.py | 52 +++++ tools/aws/test_regen_iam_request_resources.py | 30 +++ 17 files changed, 779 insertions(+), 17 deletions(-) create mode 100644 src/test/java/io/floci/aws/services/iam/SecretsManagerRequiredPermissionsEnforcementIntegrationTest.java create mode 100644 tools/aws/fetch_secretsmanager_required_permissions.py create mode 100644 tools/aws/sources/secretsmanager-required-permissions.json create mode 100644 tools/aws/test_fetch_secretsmanager_required_permissions.py diff --git a/.github/workflows/iam-data-drift.yml b/.github/workflows/iam-data-drift.yml index bbecf8d05d..cb4a4ea678 100644 --- a/.github/workflows/iam-data-drift.yml +++ b/.github/workflows/iam-data-drift.yml @@ -115,6 +115,9 @@ on: - 'tools/aws/sources/sts-session-tags.json' - 'tools/aws/fetch_sts_session_tags.py' - 'tools/aws/test_fetch_sts_session_tags.py' + - 'tools/aws/fetch_secretsmanager_required_permissions.py' + - 'tools/aws/sources/secretsmanager-required-permissions.json' + - 'tools/aws/test_fetch_secretsmanager_required_permissions.py' - 'src/main/resources/aws/rest-routes.json' - 'tools/aws/regen_rest_routes.py' - 'tools/aws/test_regen_rest_routes.py' diff --git a/Makefile b/Makefile index 0a9972daae..d88c40b813 100644 --- a/Makefile +++ b/Makefile @@ -623,7 +623,9 @@ IAM_AUTHORIZED_ACTIONS_PATHS := src/main/resources/aws/iam-authorized-actions.js tools/aws/fetch_s3_required_actions.py tools/aws/test_fetch_s3_required_actions.py \ tools/aws/sources/sts-source-identity.json tools/aws/fetch_sts_source_identity.py \ tools/aws/test_fetch_sts_source_identity.py tools/aws/sources/sts-session-tags.json \ - tools/aws/fetch_sts_session_tags.py tools/aws/test_fetch_sts_session_tags.py + tools/aws/fetch_sts_session_tags.py tools/aws/test_fetch_sts_session_tags.py \ + tools/aws/sources/secretsmanager-required-permissions.json tools/aws/fetch_secretsmanager_required_permissions.py \ + tools/aws/test_fetch_secretsmanager_required_permissions.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 tools/aws/sources/eks-roles.json tools/aws/fetch_eks_roles.py \ tools/aws/test_fetch_eks_roles.py tools/aws/sources/emr-roles.json tools/aws/fetch_emr_roles.py \ @@ -674,6 +676,8 @@ IAM_REQUEST_RESOURCES_PATHS := src/main/resources/aws/iam-request-resources.json tools/aws/test_fetch_ssm_session_permissions.py \ tools/aws/sources/sqs-redrive-permissions.json tools/aws/fetch_sqs_redrive_permissions.py \ tools/aws/test_fetch_sqs_redrive_permissions.py \ + tools/aws/sources/secretsmanager-required-permissions.json tools/aws/fetch_secretsmanager_required_permissions.py \ + tools/aws/test_fetch_secretsmanager_required_permissions.py \ tools/aws/sources/required-resource-types.json tools/aws/fetch_required_resource_types.py \ tools/aws/test_fetch_required_resource_types.py CLOUDTRAIL_S3_DATA_EVENTS_PATHS := src/main/resources/aws/cloudtrail-s3-data-events.json \ diff --git a/docs/services/iam.md b/docs/services/iam.md index 68b40b607d..e787246c5c 100644 --- a/docs/services/iam.md +++ b/docs/services/iam.md @@ -2964,7 +2964,11 @@ destination queue", each queue the member of the request its words name (`Source CodeArtifact's destination repository is its `destinationRepository`. So `StartMessageMoveTask` is checked on its `SourceArn` as its own action and `sqs:ReceiveMessage`, `sqs:DeleteMessage` and `sqs:GetQueueAttributes`, and on its `DestinationArn` as `sqs:SendMessage`; `ListMessageMoveTasks` on its `SourceArn` as its own action and -`sqs:GetQueueAttributes`. A package a request names with no `namespace` is checked with its namespace empty, as the guide writes +`sqs:GetQueueAttributes`. A Secrets Manager operation is checked as its API reference's required permissions give, which their own +script vendors (`tools/aws/fetch_secretsmanager_required_permissions.py`) for each operation the Service Reference +lists as authorized by another of its actions: an action needed when the request does something ("If you use filters, +you must also have secretsmanager:ListSecrets") when it carries the member the words name (`Filters`), and one it +always needs ("secretsmanager:ValidateResourcePolicy and secretsmanager:PutResourcePolicy") on what it names. A package a request names with no `namespace` is checked with its namespace empty, as the guide writes such an ARN (`package/my_domain/my_repo/npm//react`), and a package group by its pattern percent-encoded as CodeArtifact writes it into the group's ARN (`/npm/team/*` is `/npm/team/%2a`): a variable the reference names `Encoded` and a botocore shape's name is filled from the member of that shape and encoded as its service encodes it. diff --git a/docs/services/secrets-manager.md b/docs/services/secrets-manager.md index d88cffaed2..5099bbb850 100644 --- a/docs/services/secrets-manager.md +++ b/docs/services/secrets-manager.md @@ -48,6 +48,26 @@ The keys are the ones the Service Reference gives the `Secret` resource type, fr the generated `resourceTagKeys` table in `iam-request-resources.json`, regenerated by `tools/aws/regen_iam_request_resources.py`. +## IAM required permissions + +With IAM enforcement enabled, a request is checked for the actions the +[API reference's](https://docs.aws.amazon.com/secretsmanager/latest/apireference/Welcome.html) required permissions +say it needs beside its own, as each operation's page gives them: + +- `BatchGetSecretValue` using `Filters` needs `secretsmanager:ListSecrets`: "If you use filters, you must also have + secretsmanager:ListSecrets". +- `CreateSecret` with `AddReplicaRegions` needs `secretsmanager:ReplicateSecretToRegions`: "To add replica Regions, + you must also have secretsmanager:ReplicateSecretToRegions". +- `ValidateResourcePolicy` needs `secretsmanager:PutResourcePolicy` on the secret it names, or on every resource where + it names none, as its own action is: "Required permissions: secretsmanager:ValidateResourcePolicy and + secretsmanager:PutResourcePolicy". + +A tagged `CreateSecret` needs `secretsmanager:TagResource`, which the tagging check gives already. Not checked yet: +`BatchGetSecretValue`'s `secretsmanager:GetSecretValue` "for each secret", which AWS reports per secret in the +response's `Errors` rather than refusing the call; `secretsmanager:PutResourcePolicy` for a cross-account replica +(`CrossAccountPrimaryARN`) and `secretsmanager:DeleteResourcePolicy` for one stopped replicating, whose sentences name +no member of the request; and the KMS permissions of a secret encrypted with a customer managed key. + ## Secret write events Successful `PutSecretValue` and `UpdateSecret` API calls emit an EventBridge event with diff --git a/src/main/java/io/floci/aws/core/common/IamEnforcementFilter.java b/src/main/java/io/floci/aws/core/common/IamEnforcementFilter.java index 4986e249a3..83614a6862 100644 --- a/src/main/java/io/floci/aws/core/common/IamEnforcementFilter.java +++ b/src/main/java/io/floci/aws/core/common/IamEnforcementFilter.java @@ -612,12 +612,14 @@ public class IamEnforcementFilter implements ContainerRequestFilter { // An operation AWS authorizes by actions its request's parts each take (KMS's ReEncrypt, kms:ReEncryptFrom on // the key it decrypts with and kms:ReEncryptTo on the one it encrypts with; each of a DynamoDB transaction's // items and each PartiQL statement, by its own) is checked as each on what the table gives it, with that - // part's condition keys, not as the operation's own; one naming nothing of any is checked as its own on *. + // part's condition keys, not as the operation's own; one naming nothing of any is checked as its own on *, + // with each action the table checks on the same resources as its own (RequestResources#checkedWith). if (RequestResources.checkedByParts(resolvedOperation.operation())) { List targets = arnBuilder.targets(credentialScope, resolvedOperation.operation(), ctx, region, accountId, requestPartition()); if (targets.isEmpty()) { - targets = List.of(new RequestResources.Target(action, List.of("*"), null)); + targets = RequestResources.checkedWith(resolvedOperation.operation(), action).stream() + .map(checked -> new RequestResources.Target(checked, List.of("*"), null)).toList(); } for (RequestResources.Target target : targets) { Map> resolved = conditionContextResolver.resolvePart(credentialScope, @@ -665,7 +667,8 @@ public class IamEnforcementFilter implements ContainerRequestFilter { continue; } boolean sets = IamConditionContextResolver.namesMember(ctx, companion.member()) - || (conditionContext != null && conditionContext.containsKey(companion.carried())); + || (conditionContext != null && companion.carried() != null + && conditionContext.containsKey(companion.carried())); if (sets && roleSession && companion.callerPolicyWhenChained() && abortIfOwnPolicyDenies(ctx, caller, companion.action(), credentialScope, resources, targetContexts, akid)) { @@ -1180,7 +1183,7 @@ public class IamEnforcementFilter implements ContainerRequestFilter { Map> context) { Map> carried = context; for (Companion companion : companions) { - List value = carried == null || companion.member() == null ? null + List value = carried == null || companion.member() == null || companion.carried() == null ? null : carried.get(companion.carried()); if (value != null && !value.isEmpty() && !IamConditionContextResolver.namesMember(ctx, companion.member())) { diff --git a/src/main/java/io/floci/aws/core/common/RequestResources.java b/src/main/java/io/floci/aws/core/common/RequestResources.java index 2d30d105f5..4291636ee9 100644 --- a/src/main/java/io/floci/aws/core/common/RequestResources.java +++ b/src/main/java/io/floci/aws/core/common/RequestResources.java @@ -89,6 +89,31 @@ public final class RequestResources { return readable(table, operation) && table.checkedAs().containsKey(operation); } + /** + * The actions an operation checked by parts is checked as on the same resources as {@code action}, the one it is + * checked as otherwise, that one first: what a request naming none of what any of its actions is checked on is + * checked as on {@code *}, as an operation checked as its own action alone is. Secrets Manager's + * ValidateResourcePolicy needs secretsmanager:PutResourcePolicy where it needs its own action, as its required + * permissions say, so on {@code *} too where it names no secret. {@code action} alone for an operation the table + * does not check by parts, or does not check as {@code action} on anything. + */ + public static List checkedWith(String operation, String action) { + RequestResourceMembers.Table table = RequestResourceMembers.table(); + Map> actions = !readable(table, operation) ? null + : table.checkedAs().get(operation); + List own = actions == null ? null : actions.get(action); + if (own == null || own.isEmpty()) { + return List.of(action); + } + List found = new ArrayList<>(List.of(action)); + actions.forEach((other, resources) -> { + if (!other.equals(action) && resources.equals(own)) { + found.add(other); + } + }); + return List.copyOf(found); + } + /** Whether {@code table} reads the operation's requests: it has an entry for it, and not an unread one. */ static boolean readable(RequestResourceMembers.Table table, String operation) { return operation != null && table.operations().containsKey(operation) && !table.unread().contains(operation); 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 5106d6609d..29d0173335 100644 --- a/src/main/java/io/floci/aws/services/iam/IamAuthorizedActions.java +++ b/src/main/java/io/floci/aws/services/iam/IamAuthorizedActions.java @@ -98,7 +98,10 @@ public final class IamAuthorizedActions { * {@code claim} carrying it instead of a member, and the {@code key} the value is present in the request as: * an AssumeRoleWithSAML whose assertion carries {@code https://aws.amazon.com/SAML/Attributes/SourceIdentity} * needs {@code sts:SetSourceIdentity} of the role's trust policy, read with it as {@code sts:SourceIdentity}. - * Each of {@code member}, {@code attribute}, {@code claim} and {@code key} is null where the file names none. + * Each of {@code member}, {@code attribute}, {@code claim} and {@code key} is null where the file names none, and + * {@code carried} where the value goes into no key of the session: a Secrets Manager batch read using + * {@code Filters} needs {@code secretsmanager:ListSecrets}, as the API reference's required permissions say ("If + * you use filters, you must also have secretsmanager:ListSecrets"). */ public record Companion(String action, String member, String attribute, String claim, String key, String carried, boolean callerPolicyWhenChained) { @@ -249,10 +252,13 @@ public final class IamAuthorizedActions { String attribute = companion.path("attribute").asText(null); String claim = companion.path("claim").asText(null); String key = companion.path("key").asText(null); - String carried = companion.path("carried").asText(""); + String carried = companion.path("carried").asText(null); boolean fromMember = member != null && attribute == null && claim == null; boolean fromProvider = member == null && key != null && (attribute == null) != (claim == null); - if (!(fromMember || fromProvider) || !carried.startsWith("aws:")) { + // A value an identity provider sets is always carried into the session; one a request member sets + // may not be (Secrets Manager's ListSecrets for a batch read using filters). + boolean carries = carried != null && carried.startsWith("aws:"); + if (!(fromMember || fromProvider) || (fromProvider || carried != null) && !carries) { throw new IllegalStateException(RESOURCE_NAME + " gives " + namespace.getKey() + ":" + operation.getKey() + " a companion naming no source of its value or no global key"); } diff --git a/src/main/resources/aws/iam-authorized-actions.json b/src/main/resources/aws/iam-authorized-actions.json index 32be860d32..48f6ea8510 100644 --- a/src/main/resources/aws/iam-authorized-actions.json +++ b/src/main/resources/aws/iam-authorized-actions.json @@ -1803,6 +1803,22 @@ } }, "companions": { + "secretsmanager": { + "BatchGetSecretValue": [ + { + "action": "secretsmanager:ListSecrets", + "member": "Filters", + "callerPolicyWhenChained": false + } + ], + "CreateSecret": [ + { + "action": "secretsmanager:ReplicateSecretToRegions", + "member": "AddReplicaRegions", + "callerPolicyWhenChained": false + } + ] + }, "sts": { "AssumeRole": [ { diff --git a/src/main/resources/aws/iam-request-resources.json b/src/main/resources/aws/iam-request-resources.json index ce3e80f7ce..261b6faf27 100644 --- a/src/main/resources/aws/iam-request-resources.json +++ b/src/main/resources/aws/iam-request-resources.json @@ -7220,7 +7220,7 @@ "secretsmanager:UntagResource": {"action": "secretsmanager:UntagResource", "types": ["Secret"], "resources": [{"type": "Secret", "fill": {"SecretId": "SecretId"}, "apis": ["json/2017-10-17"]}]}, "secretsmanager:UpdateSecret": {"action": "secretsmanager:UpdateSecret", "types": ["Secret"], "resources": [{"type": "Secret", "fill": {"SecretId": "SecretId"}, "apis": ["json/2017-10-17"]}]}, "secretsmanager:UpdateSecretVersionStage": {"action": "secretsmanager:UpdateSecretVersionStage", "types": ["Secret"], "resources": [{"type": "Secret", "fill": {"SecretId": "SecretId"}, "apis": ["json/2017-10-17"]}]}, - "secretsmanager:ValidateResourcePolicy": {"action": "secretsmanager:ValidateResourcePolicy", "types": ["Secret"], "resources": [{"type": "Secret", "fill": {"SecretId": "SecretId"}, "apis": ["json/2017-10-17"]}]}, + "secretsmanager:ValidateResourcePolicy": {"action": "secretsmanager:ValidateResourcePolicy", "types": ["Secret"], "actions": {"secretsmanager:ValidateResourcePolicy": ["Secret"], "secretsmanager:PutResourcePolicy": ["Secret"]}, "resources": [{"type": "Secret", "fill": {"SecretId": "SecretId"}, "action": "secretsmanager:ValidateResourcePolicy", "apis": ["json/2017-10-17"]}, {"type": "Secret", "fill": {"SecretId": "SecretId"}, "action": "secretsmanager:PutResourcePolicy", "apis": ["json/2017-10-17"]}]}, "securityhub:AcceptAdministratorInvitation": {"action": "securityhub:AcceptAdministratorInvitation", "types": ["hub"], "resources": [{"type": "hub", "fill": {}, "apis": ["rest-json/2018-10-26"]}]}, "securityhub:AcceptInvitation": {"action": "securityhub:AcceptInvitation", "types": ["hub"], "resources": [{"type": "hub", "fill": {}, "apis": ["rest-json/2018-10-26"]}]}, "securityhub:BatchDeleteAutomationRules": {"action": "securityhub:BatchDeleteAutomationRules", "types": ["automation-rule"], "resources": [{"types": ["automation-rule"], "arn": "AutomationRulesArns[]", "apis": ["rest-json/2018-10-26"]}]}, diff --git a/src/test/java/io/floci/aws/services/iam/SecretsManagerRequiredPermissionsEnforcementIntegrationTest.java b/src/test/java/io/floci/aws/services/iam/SecretsManagerRequiredPermissionsEnforcementIntegrationTest.java new file mode 100644 index 0000000000..b8d101ce01 --- /dev/null +++ b/src/test/java/io/floci/aws/services/iam/SecretsManagerRequiredPermissionsEnforcementIntegrationTest.java @@ -0,0 +1,134 @@ +package io.floci.aws.services.iam; + +import io.floci.aws.testing.AwsTestClients; +import io.floci.aws.testing.EnforcementFixtures; +import io.floci.aws.testing.EnforcementFixtures.UserCredentials; +import io.floci.aws.testing.IamEnforcementProfile; +import io.floci.aws.testing.PartitionCleanup; +import io.quarkus.test.common.http.TestHTTPResource; +import io.quarkus.test.junit.QuarkusTest; +import io.quarkus.test.junit.TestProfile; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.RegisterExtension; +import software.amazon.awssdk.regions.Region; +import software.amazon.awssdk.services.secretsmanager.SecretsManagerClient; +import software.amazon.awssdk.services.secretsmanager.model.FilterNameStringType; +import software.amazon.awssdk.services.secretsmanager.model.SecretsManagerException; + +import java.net.URI; +import java.util.Arrays; +import java.util.UUID; +import java.util.stream.Collectors; + +import static io.floci.aws.testing.EnforcementFixtures.auth; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +/** + * A Secrets Manager request is checked for the actions the API reference's required permissions say it needs beside + * its own: "If you use filters, you must also have secretsmanager:ListSecrets" (BatchGetSecretValue), "To add replica + * Regions, you must also have secretsmanager:ReplicateSecretToRegions" (CreateSecret), and "Required permissions: + * secretsmanager:ValidateResourcePolicy and secretsmanager:PutResourcePolicy" (ValidateResourcePolicy, with or without + * a secret named). A request that does not do what a clause says needs nothing more than its own action. + */ +@QuarkusTest +@TestProfile(IamEnforcementProfile.class) +class SecretsManagerRequiredPermissionsEnforcementIntegrationTest { + + private static final String ACCOUNT_ID = "000000000000"; + private static final String POLICY = """ + {"Version":"2012-10-17","Statement":{"Effect":"Allow","Action":"*","Resource":"*"}}"""; + + @TestHTTPResource("/") + static URI baseUri; + + @RegisterExtension + final PartitionCleanup cleanup = new PartitionCleanup(); + + @Test + void aBatchReadUsingFiltersNeedsListSecrets() { + String name = createSecret(); + try (SecretsManagerClient reading = userAllowed("secretsmanager:BatchGetSecretValue", + "secretsmanager:GetSecretValue"); + SecretsManagerClient listing = userAllowed("secretsmanager:BatchGetSecretValue", + "secretsmanager:GetSecretValue", "secretsmanager:ListSecrets")) { + refused("secretsmanager:ListSecrets", () -> reading.batchGetSecretValue(r -> r.filters( + filter -> filter.key(FilterNameStringType.NAME).values(name)))); + assertEquals(1, listing.batchGetSecretValue(r -> r.filters( + filter -> filter.key(FilterNameStringType.NAME).values(name))).secretValues().size()); + assertEquals(1, reading.batchGetSecretValue(r -> r.secretIdList(name)).secretValues().size()); + } + } + + @Test + void aCreateAddingReplicaRegionsNeedsReplicateSecretToRegions() { + String replicated = "replicated-" + UUID.randomUUID().toString().substring(0, 8); + String plain = "plain-" + UUID.randomUUID().toString().substring(0, 8); + try (SecretsManagerClient creating = userAllowed("secretsmanager:CreateSecret"); + SecretsManagerClient replicating = userAllowed("secretsmanager:CreateSecret", + "secretsmanager:ReplicateSecretToRegions")) { + refused("secretsmanager:ReplicateSecretToRegions", () -> creating.createSecret(r -> r.name(replicated) + .secretString("v").addReplicaRegions(region -> region.region("eu-west-1")))); + replicating.createSecret(r -> r.name(replicated).secretString("v") + .addReplicaRegions(region -> region.region("eu-west-1"))); + deleteLater(replicated); + creating.createSecret(r -> r.name(plain).secretString("v")); + deleteLater(plain); + } + } + + @Test + void validatingAResourcePolicyNeedsPutResourcePolicyWithOrWithoutASecret() { + String name = createSecret(); + try (SecretsManagerClient validating = userAllowed("secretsmanager:ValidateResourcePolicy"); + SecretsManagerClient putting = userAllowed("secretsmanager:ValidateResourcePolicy", + "secretsmanager:PutResourcePolicy")) { + refused("secretsmanager:PutResourcePolicy", + () -> validating.validateResourcePolicy(r -> r.secretId(name).resourcePolicy(POLICY))); + assertTrue(putting.validateResourcePolicy(r -> r.secretId(name).resourcePolicy(POLICY)) + .policyValidationPassed()); + // Naming no secret, it needs both where its own action is checked: on every resource. + refused("secretsmanager:PutResourcePolicy", + () -> validating.validateResourcePolicy(r -> r.resourcePolicy(POLICY))); + assertTrue(putting.validateResourcePolicy(r -> r.resourcePolicy(POLICY)).policyValidationPassed()); + } + } + + private static void refused(String action, Runnable call) { + SecretsManagerException denied = assertThrows(SecretsManagerException.class, call::run); + assertEquals(400, denied.statusCode()); + assertTrue(denied.awsErrorDetails().errorMessage().contains(action), denied.awsErrorDetails().errorMessage()); + } + + private String createSecret() { + String name = "required-" + UUID.randomUUID().toString().substring(0, 8); + try (SecretsManagerClient admin = AwsTestClients.create(SecretsManagerClient.builder(), ACCOUNT_ID, + Region.US_EAST_1, baseUri)) { + admin.createSecret(r -> r.name(name).secretString("v")); + } + deleteLater(name); + return name; + } + + private void deleteLater(String name) { + cleanup.register(() -> { + try (SecretsManagerClient admin = AwsTestClients.create(SecretsManagerClient.builder(), ACCOUNT_ID, + Region.US_EAST_1, baseUri)) { + admin.deleteSecret(r -> r.secretId(name).forceDeleteWithoutRecovery(true)); + } + }); + } + + private SecretsManagerClient userAllowed(String... actions) { + String userName = "secrets-" + UUID.randomUUID().toString().substring(0, 8); + UserCredentials user = EnforcementFixtures.createUser(cleanup, baseUri.getPort(), auth(ACCOUNT_ID, "iam"), + userName); + String listed = Arrays.stream(actions).map(action -> "\"" + action + "\"").collect(Collectors.joining(",")); + EnforcementFixtures.putUserPolicy(baseUri.getPort(), auth(ACCOUNT_ID, "iam"), userName, "only", + "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Allow\",\"Action\":[" + listed + + "],\"Resource\":\"*\"}]}"); + return AwsTestClients.create(SecretsManagerClient.builder(), user.accessKeyId(), user.secretAccessKey(), + Region.US_EAST_1, baseUri); + } +} diff --git a/tools/aws/fetch_secretsmanager_required_permissions.py b/tools/aws/fetch_secretsmanager_required_permissions.py new file mode 100644 index 0000000000..39ed9f6fd6 --- /dev/null +++ b/tools/aws/fetch_secretsmanager_required_permissions.py @@ -0,0 +1,187 @@ +#!/usr/bin/env python3 +"""Vendor what the AWS Secrets Manager API reference says each operation's request needs into +tools/aws/sources/secretsmanager-required-permissions.json, a source of the IAM tables. + +The Service Reference lists the actions an operation is authorized by, BatchGetSecretValue by +secretsmanager:BatchGetSecretValue, secretsmanager:GetSecretValue and secretsmanager:ListSecrets, without saying when +each is needed, and botocore does not say it either. Each operation's page in the API reference does, in a paragraph +of its own: + + Required permissions: secretsmanager:BatchGetSecretValue, and you must have secretsmanager:GetSecretValue for + each secret. If you use filters, you must also have secretsmanager:ListSecrets. + + https://docs.aws.amazon.com/secretsmanager/latest/apireference/API_BatchGetSecretValue.html + +This script reads the Service Reference for the operations it lists as authorized by an action beside their own, and +copies each one's paragraph as it stands, with each clause it gives an action in: what the operation always needs +("Required permissions: A and B"), what it needs for each thing it names ("A for each secret") or on one ("A on the +primary secret"), and what it needs when the request does something ("If you use filters, you must also have A", +"To add replica Regions, you must also have A"), with the words that say so. A sentence naming no secretsmanager: +action, as the KMS ones, is copied with the paragraph but not read, and one naming one in any other wording is +refused, so a reworded page fails rather than dropping a check. Nothing in the output is written by hand, and the +generators read it against the Service Reference's authorized actions and botocore's requests. + +Run from anywhere in the repo: + python3 tools/aws/fetch_secretsmanager_required_permissions.py # rewrite the vendored file + python3 tools/aws/fetch_secretsmanager_required_permissions.py --verify # online: the file still says it +""" +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 + +REFERENCE = "https://servicereference.us-east-1.amazonaws.com/v1/secretsmanager/secretsmanager.json" +API_PAGE = "https://docs.aws.amazon.com/secretsmanager/latest/apireference/API_{operation}.html" +REPO_ROOT = Path(__file__).resolve().parents[2] +OUTPUT = REPO_ROOT / "tools/aws/sources/secretsmanager-required-permissions.json" +NAMESPACE = "secretsmanager" + +ACTION = r"secretsmanager:[A-Za-z]+" +# The paragraph giving an operation's required permissions, and each of its sentences. +PARAGRAPH_RE = re.compile(r"^Required permissions: ") +SENTENCE_RE = re.compile(r"(?<=\.)\s+(?=[A-Z])") +# What the operation always needs, and what it needs for each thing or on one thing it names. +ALWAYS_RE = re.compile(rf"^Required permissions: (?P{ACTION}.*)\.$") +EACH_RE = re.compile(rf"^(?:and )?(?:you must have )?(?P{ACTION}) for each (?P[a-z]+(?: [a-z]+)*)$") +ON_RE = re.compile(rf"^(?:and )?(?P{ACTION}) on the (?P[a-z]+(?: [a-z]+)*)$") +BARE_RE = re.compile(rf"^(?:and )?(?P{ACTION})$") +# What the operation needs when its request does what the words say. +WHEN_RES = ( + re.compile(rf"^If you use (?P[^,]+), you must also have (?P{ACTION})(?: permissions?)?\.$"), + re.compile(rf"^If you include (?P.+?) in the secret, you also need (?P{ACTION})\.$"), + re.compile(rf"^To (?P[^,]+), you must also have (?P{ACTION})(?: permissions?)?\.$"), +) +# What the operation needs when what it acts on is what the words say. +FOR_RE = re.compile(rf"^For (?P[^,]+), you must also have (?P{ACTION})(?: permissions?)?\.$") + + +def text(fragment: str) -> str: + """A fragment of a page as text, spaces collapsed, and none left before a mark an inline tag ends ahead of.""" + collapsed = re.sub(r"\s+", " ", html.unescape(re.sub(r"<[^>]+>", " ", fragment))).strip() + return re.sub(r" (?=[.,;:)])", "", re.sub(r"\( ", "(", collapsed)) + + +def body(page: str) -> str: + """The page's own content, its navigation left out.""" + match = re.search(r'
(?P.*?)(?:
list[str]: + """The operations the Service Reference lists as authorized by an action of the namespace beside their own.""" + found = [] + for operation in reference.get("Operations", []): + actions = {f"{action['Service']}:{action['Name']}" for action in operation.get("AuthorizedActions") or []} + if any(action.startswith(NAMESPACE + ":") and action != f"{NAMESPACE}:{operation['Name']}" + for action in actions): + found.append(operation["Name"]) + return sorted(found) + + +def clauses(sentence: str) -> list[dict]: + """Each action a sentence of the paragraph gives, with what it is needed for.""" + always = ALWAYS_RE.match(sentence) + if always: + found = [] + for clause in re.split(r",? and (?=you must have|secretsmanager:)|, ", always.group("clauses")): + each, on, bare = EACH_RE.match(clause), ON_RE.match(clause), BARE_RE.match(clause) + if each: + found.append({"action": each.group("action"), "each": each.group("words")}) + elif on: + found.append({"action": on.group("action"), "on": on.group("words")}) + elif bare: + found.append({"action": bare.group("action")}) + else: + raise ValueError(f"the required permissions '{sentence}' give '{clause}', which names no action as " + f"they did: their wording changed") + return found + for when in WHEN_RES: + matched = when.match(sentence) + if matched: + return [{"action": matched.group("action"), "when": matched.group("words")}] + matched = FOR_RE.match(sentence) + if matched: + return [{"action": matched.group("action"), "for": matched.group("words")}] + # A sentence naming an action of the namespace in no wording above would drop that action from the generated + # checks on a refresh, so the page has to be read again; one naming none, as the KMS ones, says nothing here. + if re.search(ACTION, sentence): + raise ValueError(f"the required permissions say '{sentence}', which gives a {NAMESPACE}: action in no wording " + f"they used: their wording changed") + return [] + + +def read_required(operation: str, page: str) -> dict: + """The operation's paragraph of required permissions and each action it gives.""" + for paragraph in re.findall(r"

(.*?)

", body(page), re.S): + said = text(paragraph) + if PARAGRAPH_RE.match(said): + permissions = [found for sentence in SENTENCE_RE.split(said) for found in clauses(sentence)] + return {"operation": operation, "paragraph": said, "permissions": permissions} + raise ValueError(f"{API_PAGE.format(operation=operation)} gives no required permissions: its layout changed") + + +def build(reference: dict, pages: dict[str, str]) -> dict: + named = operations(reference) + return { + "_source": { + "pages": [REFERENCE, *(API_PAGE.format(operation=operation) for operation in named)], + "fetcher": str(Path(__file__).resolve().relative_to(REPO_ROOT)), + "retrieved": datetime.now(timezone.utc).strftime("%Y-%m-%d"), + "note": "The required permissions paragraph of each operation's API reference page the Service Reference " + "lists as authorized by an action beside its own, copied as it stands, with each action it gives " + "and what it is needed for.", + }, + "required": [read_required(operation, pages[operation]) for operation in named], + } + + +def fetch_url(url: str) -> str: + request = urllib.request.Request(url, headers={"User-Agent": "floci-tools"}) + with urllib.request.urlopen(request, timeout=60) as response: + return response.read().decode("utf-8") + + +def fetch_all(fetch=fetch_url) -> tuple[dict, dict[str, str]]: + """The Service Reference and the page of each operation it lists as authorized by another action.""" + reference = json.loads(fetch(REFERENCE)) + return reference, {operation: fetch(API_PAGE.format(operation=operation)) for operation in operations(reference)} + + +def stale(vendored: dict, reference: dict, pages: dict[str, str]) -> bool: + """Whether the reference and the pages now give something other than the vendored file, its date aside.""" + built = build(reference, pages) + return any(vendored.get(key) != built[key] for key in built if key != "_source") + + +def main(argv: list[str] | None = None, fetch=fetch_url) -> int: + parser = argparse.ArgumentParser(description=__doc__.splitlines()[0]) + parser.add_argument("--verify", action="store_true", help="online: the vendored file matches the pages") + args = parser.parse_args(argv) + try: + reference, pages = fetch_all(fetch) + except OSError as e: + print(f"error: could not read the AWS Secrets Manager documentation ({e})", file=sys.stderr) + return 2 + if args.verify: + vendored = json.loads(OUTPUT.read_text(encoding="utf-8")) + if stale(vendored, reference, pages): + print(f"error: {OUTPUT.relative_to(REPO_ROOT)} no longer says what the AWS Secrets Manager API reference " + f"does: run tools/aws/fetch_secretsmanager_required_permissions.py and then make " + f"iam-authorized-actions-sync and iam-request-resources-sync", file=sys.stderr) + return 1 + print(f"{OUTPUT.relative_to(REPO_ROOT)} matches the AWS Secrets Manager API reference") + return 0 + built = build(reference, pages) + OUTPUT.write_text(json.dumps(built, indent=2) + "\n", encoding="utf-8") + print(f"wrote {OUTPUT.relative_to(REPO_ROOT)} ({len(built['required'])} 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 7ee028afdf..147cd6f64c 100644 --- a/tools/aws/regen_iam_authorized_actions.py +++ b/tools/aws/regen_iam_authorized_actions.py @@ -153,6 +153,9 @@ S3_REQUIRED = REPO_ROOT / "tools/aws/sources/s3-required-actions.json" SOURCE_IDENTITY = REPO_ROOT / "tools/aws/sources/sts-source-identity.json" # The IAM user guide's page on session tags, as tools/aws/fetch_sts_session_tags.py copies it. SESSION_TAGS = REPO_ROOT / "tools/aws/sources/sts-session-tags.json" +# The AWS Secrets Manager API reference's required permissions of each operation the Service Reference lists as +# authorized by another of its actions, as tools/aws/fetch_secretsmanager_required_permissions.py copies them. +REQUIRED_PERMISSIONS = REPO_ROOT / "tools/aws/sources/secretsmanager-required-permissions.json" CARRIED_KEY_RE = re.compile(r"^aws:[A-Za-z]+(?:/\$\{TagKey\})?$") LEVEL_RE = re.compile(r"^([A-Z][A-Za-z0-9]+)(?: \((Bucket|Account)-level\))?$") SPECIFYING_RE = re.compile(r"\bspecifying (\w+) in the request") @@ -585,6 +588,11 @@ def load_session_tags(source: Path = SESSION_TAGS) -> dict | None: return json.loads(source.read_text(encoding="utf-8")) if source.exists() else None +def load_required_permissions(source: Path = REQUIRED_PERMISSIONS) -> dict | None: + """The vendored API reference's required permissions, none when the file is missing.""" + return json.loads(source.read_text(encoding="utf-8")) if source.exists() else None + + def request_members(namespace: str) -> dict[str, set[str]]: """The members of each operation's request in botocore's model of the namespace.""" data, _ = resolve_botocore_data(None) @@ -595,7 +603,7 @@ def request_members(namespace: str) -> dict[str, set[str]]: def companions(documents: list[dict], page: dict | None, requests: dict[str, dict[str, set[str]]] | None = None, - session_tags: dict | None = None) -> dict[str, dict[str, list[dict]]]: + session_tags: dict | None = None, required: dict | None = None) -> dict[str, dict[str, list[dict]]]: """The actions an operation needs beside its own only when it sets a value, from the IAM user guide's page on source identity (`page`, `load_source_identity`): for each operation the page names the request member passing the value in, the action the page says setting one needs, where the reference lists it among the operation's actions, with @@ -606,8 +614,13 @@ def companions(documents: list[dict], page: dict | None, value is present in the request as. And from the page on session tags (`session_tags`, `load_session_tags`), for each operation it names the attribute or claim an identity provider passes tags in, the action it says a role the provider is connected to needs of its trust policy, with the reference's spelling of the key the tags are present - in the request as and the key the session's requests carry them as.""" + in the request as and the key the session's requests carry them as. And from an API reference's required + permissions (`required`, `load_required_permissions`), the actions its clauses say a request needs when it does + something (`_required_permission_companions`).""" found = _session_tag_companions(documents, session_tags) + for namespace, operations in _required_permission_companions(documents, required, requests).items(): + for operation, needed in operations.items(): + found.setdefault(namespace, {}).setdefault(operation, []).extend(needed) if not page: return {namespace: dict(sorted(operations.items())) for namespace, operations in sorted(found.items())} action = page["permission"]["action"] @@ -647,6 +660,48 @@ def companions(documents: list[dict], page: dict | None, return {namespace: dict(sorted(operations.items())) for namespace, operations in sorted(found.items())} +def _required_permission_companions(documents: list[dict], source: dict | None, + requests: dict[str, dict[str, set[str]]] | None = None + ) -> dict[str, dict[str, list[dict]]]: + """The companions an API reference's required permissions give (`source`): for each clause saying an action is + needed when the request does something ("If you use filters, you must also have secretsmanager:ListSecrets", "To + add replica Regions, you must also have secretsmanager:ReplicateSecretToRegions"), the action, where the reference + lists it among the operation's actions and does not mark it as tagging, which the tag-on-create table checks, with + the member of the operation's request in botocore (`requests` by namespace, `request_members` unless given) the + clause's words name as the generators' names go (`stem`: filters is `Filters`, add replica Regions + `AddReplicaRegions`). Words naming no member, or more than one, give none ("To create a cross-account replica + secret").""" + if not source: + return {} + from regen_iam_request_resources import stem + found: dict[str, dict[str, list[dict]]] = {} + for document in documents: + namespace = document.get("Name") + operations = {operation.get("Name"): operation for operation in document.get("Operations") or []} + actions = {reference.get("Name"): reference for reference in document.get("Actions") or []} + for entry in source["required"]: + operation = operations.get(entry["operation"]) + clauses = [permission for permission in entry["permissions"] + if "when" in permission and permission["action"].split(":", 1)[0] == namespace] + if operation is None or not clauses: + continue + authorized = {f"{service}:{name}" for service, name in _authorized_actions(namespace, operation)} + members = (requests or {}).get(namespace) + if members is None: + members = request_members(namespace) + for permission in clauses: + name = permission["action"].split(":", 1)[1] + tagging = ((actions.get(name) or {}).get("Annotations") or {}).get("Properties", {}).get( + "IsTaggingOnly") is True + named = [member for member in sorted(members.get(entry["operation"], set())) + if stem(member) == stem(permission["when"])] + if permission["action"] not in authorized or tagging or len(named) != 1: + continue + found.setdefault(namespace, {}).setdefault(entry["operation"], []).append( + {"action": permission["action"], "member": named[0], "callerPolicyWhenChained": False}) + return found + + def _session_tag_companions(documents: list[dict], page: dict | None) -> dict[str, dict[str, list[dict]]]: """The session tag companions of `companions`: an operation the page names the attribute or claim of needs the page's action where the reference's action of the operation's name takes a key of the page's request key, and @@ -714,7 +769,7 @@ def build(documents: list[dict], provenance: str, routed: list[str], "actionsWithoutResourceTypes": actions_without_resource_types(documents, routed), "authorizedByMethod": authorized_by_method(documents, methods or {}, renamed), **vendored_sections(documents, page, models, query, renamed), - "companions": companions(documents, source_identity, requests, session_tags), + "companions": companions(documents, source_identity, requests, session_tags, load_required_permissions()), } @@ -784,9 +839,12 @@ def _section_problems(document: dict) -> list[str]: for namespace, operations in (document.get("companions") or {}).items(): for operation, needed in (operations.items() if isinstance(operations, dict) else []): for companion in (needed if isinstance(needed, list) else [None]): + # A companion a request member sets may carry no key into the session; one an identity provider + # sets always does. + carries = isinstance(companion, dict) and ("carried" in companion or "member" not in companion) if not isinstance(companion, dict) or not _companion_source_holds(namespace, companion) \ or not action_of(namespace, companion.get("action")) \ - or not CARRIED_KEY_RE.match(str(companion.get("carried"))) \ + or (carries and not CARRIED_KEY_RE.match(str(companion.get("carried")))) \ or not isinstance(companion.get("callerPolicyWhenChained"), bool): problems.append(f"companions {namespace}:{operation} is not an action of {namespace}, a request " f"member, a global key and whether a chained caller's policy must allow it") @@ -1014,7 +1072,8 @@ def main(argv: list[str] | None = None) -> int: return 2 untrue, added = verify_against(vendored, upstream) sections = {**vendored_sections(documents, page, models, query, upstream), - "companions": companions(documents, source_identity, None, session_tags)} + "companions": companions(documents, source_identity, None, session_tags, + load_required_permissions())} for section, value in sections.items(): if vendored_document.get(section, {}) != value: untrue.append(f"{section} differs from what AWS gives: expected {json.dumps(value)}") diff --git a/tools/aws/regen_iam_request_resources.py b/tools/aws/regen_iam_request_resources.py index 0ea624f680..25c97744bb 100644 --- a/tools/aws/regen_iam_request_resources.py +++ b/tools/aws/regen_iam_request_resources.py @@ -354,6 +354,7 @@ import fetch_ec2_id_examples import fetch_iam_identifiers import fetch_kms_api_permissions import fetch_required_resource_types +import fetch_secretsmanager_required_permissions import fetch_sqs_redrive_permissions import fetch_ssm_session_permissions from regen_iam_authorized_actions import (ROUTES as ROUTES_FILE, authorized_actions, fetch_references, @@ -587,8 +588,12 @@ PATH_SOURCES: dict[str, Path] = { # redrive's minimum permissions, the actions of each queue ("Permissions for the DLQ (source queue): # sqs:StartMessageMoveTask, ..., sqs:ReceiveMessage, sqs:DeleteMessage, sqs:GetQueueAttributes", "Permissions for # destination queue: sqs:SendMessage"), which place the actions the Service Reference lists an operation as authorized -# by; tools/aws/fetch_sqs_redrive_permissions.py vendors the page and `group_permission_resources` reads it. Each file -# is written by its own script from the pages, unchanged, and the generator only reads it: +# by; tools/aws/fetch_sqs_redrive_permissions.py vendors the page and `group_permission_resources` reads it. AWS +# Secrets Manager's API reference gives each operation's required permissions ("Required permissions: +# secretsmanager:ValidateResourcePolicy and secretsmanager:PutResourcePolicy"); +# tools/aws/fetch_secretsmanager_required_permissions.py vendors the page of each operation the Service Reference lists +# as authorized by another of its actions, and `required_permission_resources` reads what each always needs. Each +# file is written by its own script from the pages, unchanged, and the generator only reads it: # nothing about an operation is stated here. # --------------------------------------------------------------------------------------------------------------------- PERMISSION_SOURCES: dict[str, Path] = { @@ -598,6 +603,7 @@ PERMISSION_SOURCES: dict[str, Path] = { "iam": REPO_ROOT / "tools/aws/sources/iam-identifiers.json", "ssm": REPO_ROOT / "tools/aws/sources/ssm-session-permissions.json", "sqs": REPO_ROOT / "tools/aws/sources/sqs-redrive-permissions.json", + "secretsmanager": REPO_ROOT / "tools/aws/sources/secretsmanager-required-permissions.json", } # The script that writes each namespace's permission source, whose pages `verify_sources` reads it against. PERMISSION_FETCHERS = { @@ -607,6 +613,7 @@ PERMISSION_FETCHERS = { "iam": fetch_iam_identifiers, "ssm": fetch_ssm_session_permissions, "sqs": fetch_sqs_redrive_permissions, + "secretsmanager": fetch_secretsmanager_required_permissions, } # Fetched API response examples supplement the identifier prefixes in botocore. @@ -3200,6 +3207,11 @@ def entry_for(operation: str, upstream: dict, formats: dict[str, str], models: d authorized = set(upstream.get("authorized") or known) resources, actions = group_permission_resources(operation, upstream["action"], resources, source, known, authorized) + if source is not None and "required" in source: + # --check, which reads no Service Reference, takes the actions the file records for the operation. + authorized = set(upstream.get("authorized") or known) + resources, actions = required_permission_resources(operation, upstream["action"], resources, source, + known, authorized) if source is not None and "arnExamples" in source: resources = with_empty_variables(resources, source["arnExamples"], formats) if source is not None and "partiql" in source: @@ -3898,6 +3910,33 @@ def group_permission_resources(operation: str, checked_as: str, resources: list[ return rows, {action: known[action] for action in order} +def required_permission_resources(operation: str, checked_as: str, resources: list[dict], source: dict, + known: dict[str, list[str]], + authorized: set[str]) -> tuple[list[dict], dict | None]: + """The resources of an operation whose namespace's vendored API reference says it always needs actions beside the + one it is checked as (`required`: "Required permissions: secretsmanager:ValidateResourcePolicy and + secretsmanager:PutResourcePolicy"), and those actions, each with the types the Service Reference gives it + (`known`): each action on the resources the rules read for the operation, its own first, every one of them an + action the reference lists the operation as authorized by (`authorized`). A clause saying what an action is needed + for or on ("for each secret", "on the primary secret") is not one of these. The resources as they are and none for + an operation the page gives nothing beside its own action, or whose request the rules read no resource of.""" + name = operation.split(":", 1)[1] + entry = next((found for found in source["required"] if found["operation"] == name), None) + always = [] if entry is None else [found["action"] for found in entry["permissions"] if set(found) == {"action"}] + if checked_as not in always or set(always) == {checked_as} or not resources: + return resources, None + if not set(always) <= authorized: + raise ValueError(f"{operation}: the vendored required permissions give {sorted(set(always) - authorized)}, " + f"which the Service Reference does not list the operation as authorized by") + order = [checked_as] + [action for action in always if action != checked_as] + for action in order: + if action not in known or not all(set(_kinds(resource)) & set(known[action]) for resource in resources): + raise ValueError(f"{operation}: the vendored required permissions check {action}, which the Service " + f"Reference does not give the types of what the request names") + return ([{**resource, "action": action} for action in order for resource in resources], + {action: known[action] for action in order}) + + def verify_group_actions(vendored: dict, documents: list[dict]) -> list[str]: """An operation checked as the actions a namespace's vendored groups place whose actions the Service Reference no longer lists as the ones it is authorized by.""" diff --git a/tools/aws/sources/secretsmanager-required-permissions.json b/tools/aws/sources/secretsmanager-required-permissions.json new file mode 100644 index 0000000000..cdd0cc1ed3 --- /dev/null +++ b/tools/aws/sources/secretsmanager-required-permissions.json @@ -0,0 +1,97 @@ +{ + "_source": { + "pages": [ + "https://servicereference.us-east-1.amazonaws.com/v1/secretsmanager/secretsmanager.json", + "https://docs.aws.amazon.com/secretsmanager/latest/apireference/API_AssociateCrossAccountReplica.html", + "https://docs.aws.amazon.com/secretsmanager/latest/apireference/API_BatchGetSecretValue.html", + "https://docs.aws.amazon.com/secretsmanager/latest/apireference/API_CreateSecret.html", + "https://docs.aws.amazon.com/secretsmanager/latest/apireference/API_StopReplicationToReplica.html", + "https://docs.aws.amazon.com/secretsmanager/latest/apireference/API_ValidateResourcePolicy.html" + ], + "fetcher": "tools/aws/fetch_secretsmanager_required_permissions.py", + "retrieved": "2026-11-29", + "note": "The required permissions paragraph of each operation's API reference page the Service Reference lists as authorized by an action beside its own, copied as it stands, with each action it gives and what it is needed for." + }, + "required": [ + { + "operation": "AssociateCrossAccountReplica", + "paragraph": "Required permissions: secretsmanager:AssociateCrossAccountReplica, secretsmanager:GetSecretValue on the primary secret, and secretsmanager:AcceptCrossAccountReplication on the replica secret. You must also have kms:Decrypt permission for the AWS Key Management Service (AWS KMS) key that encrypts the primary secret, and kms:Encrypt permission for the AWS AWS KMS key that encrypts the replica secret. If you supply ReplicationRoleARN, you also need iam:PassRole for that role. For more information, see IAM policy actions for Secrets Manager and Authentication and access control in Secrets Manager.", + "permissions": [ + { + "action": "secretsmanager:AssociateCrossAccountReplica" + }, + { + "action": "secretsmanager:GetSecretValue", + "on": "primary secret" + }, + { + "action": "secretsmanager:AcceptCrossAccountReplication", + "on": "replica secret" + } + ] + }, + { + "operation": "BatchGetSecretValue", + "paragraph": "Required permissions: secretsmanager:BatchGetSecretValue, and you must have secretsmanager:GetSecretValue for each secret. If you use filters, you must also have secretsmanager:ListSecrets. If the secrets are encrypted using customer-managed keys instead of the AWS managed key aws/secretsmanager, then you also need kms:Decrypt permissions for the keys. For more information, see IAM policy actions for Secrets Manager and Authentication and access control in Secrets Manager.", + "permissions": [ + { + "action": "secretsmanager:BatchGetSecretValue" + }, + { + "action": "secretsmanager:GetSecretValue", + "each": "secret" + }, + { + "action": "secretsmanager:ListSecrets", + "when": "filters" + } + ] + }, + { + "operation": "CreateSecret", + "paragraph": "Required permissions: secretsmanager:CreateSecret. If you include tags in the secret, you also need secretsmanager:TagResource. To add replica Regions, you must also have secretsmanager:ReplicateSecretToRegions. To create a cross-account replica secret, you must also have secretsmanager:PutResourcePolicy permissions. For more information, see IAM policy actions for Secrets Manager and Authentication and access control in Secrets Manager.", + "permissions": [ + { + "action": "secretsmanager:CreateSecret" + }, + { + "action": "secretsmanager:TagResource", + "when": "tags" + }, + { + "action": "secretsmanager:ReplicateSecretToRegions", + "when": "add replica Regions" + }, + { + "action": "secretsmanager:PutResourcePolicy", + "when": "create a cross-account replica secret" + } + ] + }, + { + "operation": "StopReplicationToReplica", + "paragraph": "Required permissions: secretsmanager:StopReplicationToReplica. For cross-account replica secrets, you must also have secretsmanager:DeleteResourcePolicy permissions. For more information, see IAM policy actions for Secrets Manager and Authentication and access control in Secrets Manager.", + "permissions": [ + { + "action": "secretsmanager:StopReplicationToReplica" + }, + { + "action": "secretsmanager:DeleteResourcePolicy", + "for": "cross-account replica secrets" + } + ] + }, + { + "operation": "ValidateResourcePolicy", + "paragraph": "Required permissions: secretsmanager:ValidateResourcePolicy and secretsmanager:PutResourcePolicy. For more information, see IAM policy actions for Secrets Manager and Authentication and access control in Secrets Manager.", + "permissions": [ + { + "action": "secretsmanager:ValidateResourcePolicy" + }, + { + "action": "secretsmanager:PutResourcePolicy" + } + ] + } + ] +} diff --git a/tools/aws/test_fetch_secretsmanager_required_permissions.py b/tools/aws/test_fetch_secretsmanager_required_permissions.py new file mode 100644 index 0000000000..7277804d34 --- /dev/null +++ b/tools/aws/test_fetch_secretsmanager_required_permissions.py @@ -0,0 +1,83 @@ +#!/usr/bin/env python3 +"""Tests for fetch_secretsmanager_required_permissions.py, on the Service Reference and pages in the AWS Secrets +Manager API reference's markup.""" +from __future__ import annotations + +import pytest + +import fetch_secretsmanager_required_permissions as f + + +def operation(name: str, *actions: str) -> dict: + return {"Name": name, "AuthorizedActions": [{"Service": action.split(":")[0], "Name": action.split(":")[1]} + for action in (f"secretsmanager:{name}", *actions)]} + + +REFERENCE = {"Operations": [ + operation("BatchGetSecretValue", "secretsmanager:GetSecretValue", "secretsmanager:ListSecrets"), + operation("CreateSecret", "secretsmanager:ReplicateSecretToRegions"), + # An operation authorized by its own action, or by another namespace's beside it, has no page read. + operation("DescribeSecret"), + operation("RotateSecret", "iam:PassRole"), +]} +BATCH = ("

Required permissions: secretsmanager:BatchGetSecretValue, and you must have\n" + "secretsmanager:GetSecretValue for each secret. If you use filters, you must also have\n" + "secretsmanager:ListSecrets. If the secrets are encrypted using customer-managed keys, then you also " + "need kms:Decrypt permissions for the keys.

") +CREATE = ("

Required permissions: secretsmanager:CreateSecret. If you include tags in the secret, you " + "also need secretsmanager:TagResource. To add replica Regions, you must also have " + "secretsmanager:ReplicateSecretToRegions.

") + + +def page(*paragraphs: str) -> str: + return (f'

Operation

Does a thing.

{"".join(paragraphs)}' + f'

Request Syntax

') + + +def pages(batch: str = BATCH, create: str = CREATE) -> dict[str, str]: + return {"BatchGetSecretValue": page(batch), "CreateSecret": page(create)} + + +def test_each_clause_of_the_required_permissions_is_read_with_what_its_action_is_needed_for(): + built = f.build(REFERENCE, pages()) + assert [entry["operation"] for entry in built["required"]] == ["BatchGetSecretValue", "CreateSecret"] + batch, create = built["required"] + # The KMS sentence names no secretsmanager: action and is copied with the paragraph, not read. + assert batch["permissions"] == [{"action": "secretsmanager:BatchGetSecretValue"}, + {"action": "secretsmanager:GetSecretValue", "each": "secret"}, + {"action": "secretsmanager:ListSecrets", "when": "filters"}] + assert create["permissions"] == [{"action": "secretsmanager:CreateSecret"}, + {"action": "secretsmanager:TagResource", "when": "tags"}, + {"action": "secretsmanager:ReplicateSecretToRegions", + "when": "add replica Regions"}] + assert batch["paragraph"].startswith("Required permissions: secretsmanager:BatchGetSecretValue, and you must") + + +def test_both_actions_of_a_required_pair_and_one_on_a_named_resource_are_read(): + pair = f.clauses("Required permissions: secretsmanager:ValidateResourcePolicy and " + "secretsmanager:PutResourcePolicy.") + assert pair == [{"action": "secretsmanager:ValidateResourcePolicy"}, + {"action": "secretsmanager:PutResourcePolicy"}] + on = f.clauses("Required permissions: secretsmanager:AssociateCrossAccountReplica, secretsmanager:GetSecretValue " + "on the primary secret, and secretsmanager:AcceptCrossAccountReplication on the replica secret.") + assert on[1:] == [{"action": "secretsmanager:GetSecretValue", "on": "primary secret"}, + {"action": "secretsmanager:AcceptCrossAccountReplication", "on": "replica secret"}] + + +def test_a_page_whose_layout_or_wording_changed_is_refused(): + with pytest.raises(ValueError, match="gives no required permissions"): + f.build(REFERENCE, pages(batch="

Permissions: secretsmanager:BatchGetSecretValue.

")) + with pytest.raises(ValueError, match="which names no action as they did"): + f.build(REFERENCE, pages(batch="

Required permissions: secretsmanager:BatchGetSecretValue, or a key.

")) + # A conditional sentence AWS rewords is refused rather than dropping its action. + with pytest.raises(ValueError, match="gives a secretsmanager: action in no wording they used"): + f.build(REFERENCE, pages(batch=BATCH.replace("If you use filters, you must also have", + "With filters, you need"))) + + +def test_the_file_is_stale_when_the_reference_or_a_page_says_something_else(): + vendored = f.build(REFERENCE, pages()) + assert not f.stale(vendored, REFERENCE, pages()) + assert f.stale(vendored, REFERENCE, pages(create=CREATE.replace("To add replica Regions", "To add Regions"))) + fewer = {"Operations": REFERENCE["Operations"][1:]} + assert f.stale(vendored, fewer, pages()) diff --git a/tools/aws/test_regen_iam_authorized_actions.py b/tools/aws/test_regen_iam_authorized_actions.py index 44035eed7b..1754d62790 100644 --- a/tools/aws/test_regen_iam_authorized_actions.py +++ b/tools/aws/test_regen_iam_authorized_actions.py @@ -778,6 +778,58 @@ def test_a_malformed_companion_is_rejected(companion): assert any("companions sts:AssumeRole" in problem for problem in r.validate(document, [])) +REQUIRED = {"required": [ + {"operation": "BatchGetSecretValue", "permissions": [ + {"action": "secretsmanager:BatchGetSecretValue"}, + {"action": "secretsmanager:GetSecretValue", "each": "secret"}, + {"action": "secretsmanager:ListSecrets", "when": "filters"}]}, + {"operation": "CreateSecret", "permissions": [ + {"action": "secretsmanager:CreateSecret"}, + {"action": "secretsmanager:TagResource", "when": "tags"}, + {"action": "secretsmanager:ReplicateSecretToRegions", "when": "add replica Regions"}, + {"action": "secretsmanager:PutResourcePolicy", "when": "create a cross-account replica secret"}]}]} +SECRETS = service("secretsmanager", { + "BatchGetSecretValue": ["secretsmanager:BatchGetSecretValue", "secretsmanager:GetSecretValue", + "secretsmanager:ListSecrets"], + "CreateSecret": ["secretsmanager:CreateSecret", "secretsmanager:PutResourcePolicy", + "secretsmanager:ReplicateSecretToRegions", "secretsmanager:TagResource"]}, + ["BatchGetSecretValue", "CreateSecret", "GetSecretValue", "ListSecrets", "PutResourcePolicy", + "ReplicateSecretToRegions"]) +SECRETS["Actions"].append({"Name": "TagResource", "Annotations": {"Properties": {"IsTaggingOnly": True}}}) +SECRET_REQUESTS = {"secretsmanager": {"BatchGetSecretValue": {"Filters", "SecretIdList"}, + "CreateSecret": {"AddReplicaRegions", "CrossAccountPrimaryARN", "Name", "Tags"}}} + + +def test_a_required_permission_needed_when_the_request_does_something_is_a_companion_of_the_member_named(): + # The words name the member as the generators' names go: filters is Filters, add replica Regions + # AddReplicaRegions. Tagging is the tag-on-create table's, and words naming no member give none. + assert r.companions([SECRETS], None, SECRET_REQUESTS, required=REQUIRED) == {"secretsmanager": { + "BatchGetSecretValue": [{"action": "secretsmanager:ListSecrets", "member": "Filters", + "callerPolicyWhenChained": False}], + "CreateSecret": [{"action": "secretsmanager:ReplicateSecretToRegions", "member": "AddReplicaRegions", + "callerPolicyWhenChained": False}]}} + document = r.build([SECRETS, *ANCHOR_SERVICES], "a test", [], requests=SECRET_REQUESTS) + document["companions"] = r.companions([SECRETS], None, SECRET_REQUESTS, required=REQUIRED) + assert r.validate(document, []) == [] + + +def test_an_action_the_reference_does_not_list_the_operation_as_authorized_by_is_no_companion(): + unlisted = service("secretsmanager", {"BatchGetSecretValue": ["secretsmanager:BatchGetSecretValue"]}, + ["BatchGetSecretValue", "ListSecrets"]) + assert r.companions([unlisted], None, SECRET_REQUESTS, required=REQUIRED) == {} + + +def test_a_member_companion_carrying_no_key_is_valid_and_a_provider_one_is_not(): + document = anchored() + document["companions"] = {"secretsmanager": {"BatchGetSecretValue": [ + {"action": "secretsmanager:ListSecrets", "member": "Filters", "callerPolicyWhenChained": False}]}} + assert not any("companions" in problem for problem in r.validate(document, [])) + document["companions"] = {"sts": {"AssumeRoleWithSAML": [ + {"action": "sts:SetSourceIdentity", "attribute": "https://aws.amazon.com/SAML/Attributes/SourceIdentity", + "key": "sts:SourceIdentity", "callerPolicyWhenChained": False}]}} + assert any("companions sts:AssumeRoleWithSAML" in problem for problem in r.validate(document, [])) + + FEDERATED_PAGE = {**SOURCE_IDENTITY, "federated": [{"operation": "AssumeRoleWithSAML", "key": "sts:SourceIdentity", "attribute": "https://aws.amazon.com/SAML/Attributes/SourceIdentity"}, diff --git a/tools/aws/test_regen_iam_request_resources.py b/tools/aws/test_regen_iam_request_resources.py index 5c2a516ea6..b25d712443 100644 --- a/tools/aws/test_regen_iam_request_resources.py +++ b/tools/aws/test_regen_iam_request_resources.py @@ -4153,6 +4153,36 @@ def test_groups_the_reference_does_not_bear_out_are_refused(): untyped, START) +VALIDATE = {"required": [ + {"operation": "ValidateResourcePolicy", "permissions": [{"action": "svc:ValidateResourcePolicy"}, + {"action": "svc:PutResourcePolicy"}]}, + {"operation": "BatchGetSecretValue", "permissions": [{"action": "svc:BatchGetSecretValue"}, + {"action": "svc:GetSecretValue", "each": "secret"}, + {"action": "svc:ListSecrets", "when": "filters"}]}]} +SECRET_ACTIONS = {"svc:ValidateResourcePolicy": ["Secret"], "svc:PutResourcePolicy": ["Secret"], + "svc:BatchGetSecretValue": [], "svc:GetSecretValue": ["Secret"], "svc:ListSecrets": []} + + +def test_the_actions_an_operation_always_needs_are_each_checked_on_what_the_rules_read(): + read = [{"type": "Secret", "fill": {"SecretId": "SecretId"}}] + assert r.required_permission_resources("svc:ValidateResourcePolicy", "svc:ValidateResourcePolicy", read, + VALIDATE, SECRET_ACTIONS, + {"svc:ValidateResourcePolicy", "svc:PutResourcePolicy"}) == ( + [{"type": "Secret", "fill": {"SecretId": "SecretId"}, "action": "svc:ValidateResourcePolicy"}, + {"type": "Secret", "fill": {"SecretId": "SecretId"}, "action": "svc:PutResourcePolicy"}], + {"svc:ValidateResourcePolicy": ["Secret"], "svc:PutResourcePolicy": ["Secret"]}) + # What is needed for each thing named, or when the request does something, is not always needed. + assert r.required_permission_resources("svc:BatchGetSecretValue", "svc:BatchGetSecretValue", [], VALIDATE, + SECRET_ACTIONS, set(SECRET_ACTIONS)) == ([], None) + + +def test_an_always_needed_action_the_reference_does_not_list_is_refused(): + read = [{"type": "Secret", "fill": {"SecretId": "SecretId"}}] + with pytest.raises(ValueError, match="does not list the operation as authorized by"): + r.required_permission_resources("svc:ValidateResourcePolicy", "svc:ValidateResourcePolicy", read, VALIDATE, + SECRET_ACTIONS, {"svc:ValidateResourcePolicy"}) + + def test_an_example_arn_with_a_variable_empty_names_it_empty_for_a_request_leaving_its_member_out(): package = {"type": "package", "fill": {"DomainName": "domain", "PackageFormat": "format", "PackageName": "package", "PackageNamespace": "namespace", "RepositoryName": "repository"},