diff --git a/.github/workflows/iam-data-drift.yml b/.github/workflows/iam-data-drift.yml index 6dbef83ec8..d6b096552f 100644 --- a/.github/workflows/iam-data-drift.yml +++ b/.github/workflows/iam-data-drift.yml @@ -105,9 +105,10 @@ jobs: with: python-version: "3.x" - # No dependency install: the generators are deliberately stdlib-only, and this job runs no - # tests. The pinned botocore the sibling workflow needs is for the partition generator. - # + # IAM role-tag coverage also depends on which operations name a role in pinned botocore. + - name: Install the pinned botocore + run: pip install -r tools/aws/requirements.txt + # A pull request checks the files it changes; the weekly and manual runs check every file. A # diff that cannot be read leaves CHANGED empty, which checks every file too. - name: Check the vendored IAM files still match upstream diff --git a/docs/services/iam.md b/docs/services/iam.md index 8f101767ea..da7ff74a58 100644 --- a/docs/services/iam.md +++ b/docs/services/iam.md @@ -2617,11 +2617,31 @@ floci populates: `DeleteRolePermissionsBoundary`. A role or user without a boundary, or one that does not exist, carries no value for the key. + Resource tags use the same `fromTarget` route: `aws:ResourceTag/` and + `iam:ResourceTag/` come from the stored role or user named by the generated target, + where the Service Reference lists those keys for that resource type. The lookup uses + the request account and the tags before any mutation. The table retains the source + resource types so a secondary `RoleName`, such as on `AddRoleToInstanceProfile`, cannot + supply the instance profile's tags. Missing targets carry no resource-tag values. + Creation of the target, unsupported target types, and ARN/task-ID-based lookups are + recorded in `notRead`. `PassRole` is a reasoned generator exception: the + [IAM guide](https://docs.aws.amazon.com/IAM/latest/UserGuide/access_tags.html) warns that + ResourceTag conditions with this action do not have reliable results. Caller principal + tags are not read here. + + The `requestTags` entries cover all 16 IAM tagging actions: the Tag/Untag pairs for + instance profiles, MFA devices, OIDC providers, policies, roles, SAML providers, + server certificates and users. Their action/key pairs come from `ActionConditionKeys` + on actions marked `IsTaggingOnly` in the Service Reference. Botocore supplies the + list member and, for tag structures, the key/value member names. The resolver reads + those generated fields; creation continues through the existing tag-on-create path. + A request without the parameter carries no value for the key, and the target remains the authorized resource. Every other pair the reference lists is in the table's `notRead` with its reason. Regenerate with `make iam-condition-keys-sync`. - `s3:prefix`, `s3:delimiter`, `s3:max-keys`: from the S3 request parameters. - `aws:RequestTag/`: the tags named in the request itself, before they are applied, for + IAM tagging actions listed in the generated `requestTags` table (the modeled tag list), `ec2:RunInstances` (`TagSpecification.N`), `ec2:CreateTags` (`Tag.N`) and `s3:PutBucketTagging` (the `` body), for S3 Control's `s3:TagResource` (its `Tags` body), and for every create in the tag-on-create table whose action takes it, as described under the @@ -2709,7 +2729,8 @@ floci populates: session, a federated user or the account root it is absent, and a statement that matches on it cannot match: an absent key has no equal or like value. That absence is the enforcement rather than a gap in it. -- `aws:TagKeys`: the case-sensitive requested tag keys for EC2 `RunInstances` and +- `aws:TagKeys`: the case-sensitive requested tag keys for all 16 IAM tagging actions + in the generated table (tag structures or a list of keys), EC2 `RunInstances` and `CreateTags`, S3 `PutBucketTagging`, S3 Control `TagResource` (its `Tags` body) and `UntagResource` (its `tagKeys` query parameters), and every create in the tag-on-create table whose action takes it. S3 Control's come from `s3control-tag-condition-keys.json`, which diff --git a/src/main/java/io/github/hectorvent/floci/core/common/IamConditionContextResolver.java b/src/main/java/io/github/hectorvent/floci/core/common/IamConditionContextResolver.java index e7caca27d0..e57ad8c422 100644 --- a/src/main/java/io/github/hectorvent/floci/core/common/IamConditionContextResolver.java +++ b/src/main/java/io/github/hectorvent/floci/core/common/IamConditionContextResolver.java @@ -29,6 +29,7 @@ import jakarta.enterprise.inject.Instance; import jakarta.inject.Inject; import jakarta.ws.rs.container.ContainerRequestContext; import jakarta.ws.rs.core.MediaType; +import jakarta.ws.rs.core.MultivaluedHashMap; import jakarta.ws.rs.core.MultivaluedMap; import org.jboss.logging.Logger; @@ -48,6 +49,7 @@ import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.Set; +import java.util.function.Function; /** * Builds the IAM request context: the condition keys a policy's Condition block can match, @@ -235,7 +237,8 @@ public class IamConditionContextResolver { private Map> iamConditionContext(String action, ContainerRequestContext ctx) { Map members = IamConditionKeys.members(action); Map targets = IamConditionKeys.targets(action); - if (members.isEmpty() && targets.isEmpty()) { + Map requestTags = IamConditionKeys.requestTags(action); + if (members.isEmpty() && targets.isEmpty() && requestTags.isEmpty()) { return null; } Map form = formParameters(ctx); @@ -246,24 +249,61 @@ public class IamConditionContextResolver { conditions.put(key, List.of(value)); } }); - // iam:PermissionsBoundary on an existing role or user is the boundary stored on it, left off when it has none. targets.forEach((key, target) -> { - String value = storedPermissionsBoundary(target, form.get(target)); - if (value != null) { - conditions.put(key, List.of(value)); + if (key.contains("${TagKey}")) { + Map tags = storedTargetValue(target, form.get(target), IamRole::getTags, IamUser::getTags); + if (tags != null) { + tags.forEach((tag, value) -> conditions.put(key.replace("${TagKey}", tag), List.of(value))); + } + } else { + String value = storedTargetValue(target, form.get(target), + IamRole::getPermissionsBoundaryArn, IamUser::getPermissionsBoundaryArn); + if (value != null) { + conditions.put(key, List.of(value)); + } } }); + if (!requestTags.isEmpty()) { + addIamRequestTags(conditions, form, requestTags); + } return conditions.isEmpty() ? null : conditions; } - private String storedPermissionsBoundary(String target, String name) { + private static void addIamRequestTags(Map> conditions, Map form, + Map requestTags) { + MultivaluedMap parameters = new MultivaluedHashMap<>(); + form.forEach(parameters::putSingle); + requestTags.forEach((key, fields) -> { + List keys = new ArrayList<>(); + for (AwsQueryLists.IndexedMember member : AwsQueryLists.members(parameters, fields.member(), null)) { + String tag = form.get(member.prefix() + (fields.keyMember() == null ? "" : "." + fields.keyMember())); + if (tag == null) { + continue; + } + if ("aws:TagKeys".equals(key)) { + if (!keys.contains(tag)) { + keys.add(tag); + } + } else { + conditions.put(key.replace("${TagKey}", tag), + List.of(form.getOrDefault(member.prefix() + "." + fields.valueMember(), ""))); + } + } + if (!keys.isEmpty()) { + conditions.put(key, keys); + } + }); + } + + private T storedTargetValue(String target, String name, + Function roleValue, Function userValue) { if (name == null || !iamService.isResolvable()) { return null; } String account = requestContext.getAccountId(); return switch (target) { - case "RoleName" -> iamService.get().findRole(account, name).map(IamRole::getPermissionsBoundaryArn).orElse(null); - case "UserName" -> iamService.get().findUser(account, name).map(IamUser::getPermissionsBoundaryArn).orElse(null); + case "RoleName" -> iamService.get().findRole(account, name).map(roleValue).orElse(null); + case "UserName" -> iamService.get().findUser(account, name).map(userValue).orElse(null); default -> throw new IllegalStateException("Unknown IAM condition key target: " + target); }; } diff --git a/src/main/java/io/github/hectorvent/floci/core/common/IamConditionKeys.java b/src/main/java/io/github/hectorvent/floci/core/common/IamConditionKeys.java index b9b8caf82c..42058b0ca1 100644 --- a/src/main/java/io/github/hectorvent/floci/core/common/IamConditionKeys.java +++ b/src/main/java/io/github/hectorvent/floci/core/common/IamConditionKeys.java @@ -5,6 +5,7 @@ import com.fasterxml.jackson.databind.ObjectMapper; import java.util.LinkedHashMap; import java.util.Map; +import java.util.function.Function; /** * The {@code iam:} condition keys an IAM request carries in its own members, and those read from the @@ -13,34 +14,43 @@ import java.util.Map; */ final class IamConditionKeys { - private record Table(Map> members, Map> targets) {} + record RequestTags(String member, String keyMember, String valueMember) {} + + private record Table(Map> members, Map> targets, + Map> requestTags) {} private static final Table TABLE = VendoredResources.read( "aws/iam-condition-keys.json", "IAM condition keys", input -> { JsonNode document = new ObjectMapper().readTree(input); - return new Table(section(document.path("read"), "member"), - section(document.path("fromTarget"), "target")); + return new Table(section(document.path("read"), entry -> text(entry, "member")), + section(document.path("fromTarget"), entry -> text(entry, "target")), + section(document.path("requestTags"), entry -> new RequestTags(text(entry, "member"), + entry.has("keyMember") ? text(entry, "keyMember") : null, + entry.has("keyMember") ? text(entry, "valueMember") : null))); }); private IamConditionKeys() {} - private static Map> section(JsonNode entries, String field) { + private static Map> section(JsonNode entries, Function value) { if (!entries.isArray() || entries.isEmpty()) { throw new IllegalStateException("Malformed IAM condition key table"); } - Map> byAction = new LinkedHashMap<>(); + Map> byAction = new LinkedHashMap<>(); for (JsonNode entry : entries) { - if (!entry.path("action").isTextual() || !entry.path("key").isTextual() - || !entry.path(field).isTextual()) { - throw new IllegalStateException("Malformed IAM condition key entry: " + entry); - } - byAction.computeIfAbsent(entry.get("action").asText(), action -> new LinkedHashMap<>()) - .put(entry.get("key").asText(), entry.get(field).asText()); + byAction.computeIfAbsent(text(entry, "action"), action -> new LinkedHashMap<>()) + .put(text(entry, "key"), value.apply(entry)); } byAction.replaceAll((action, keys) -> Map.copyOf(keys)); return Map.copyOf(byAction); } + private static String text(JsonNode entry, String field) { + if (!entry.path(field).isTextual()) { + throw new IllegalStateException("Malformed IAM condition key entry: " + entry); + } + return entry.get(field).asText(); + } + /** Each condition key a request for {@code action} carries, to the member that holds it; empty when none. */ static Map members(String action) { return TABLE.members().getOrDefault(action, Map.of()); @@ -53,4 +63,8 @@ final class IamConditionKeys { static Map targets(String action) { return TABLE.targets().getOrDefault(action, Map.of()); } + + static Map requestTags(String action) { + return TABLE.requestTags().getOrDefault(action, Map.of()); + } } diff --git a/src/main/resources/aws/iam-condition-keys.json b/src/main/resources/aws/iam-condition-keys.json index 94342d97f8..a8aa48ae46 100644 --- a/src/main/resources/aws/iam-condition-keys.json +++ b/src/main/resources/aws/iam-condition-keys.json @@ -1,7 +1,7 @@ { "source": "https://servicereference.us-east-1.amazonaws.com/v1/iam/iam.json", "botocore": "botocore 1.43.118 (installed package)", - "types": {"iam:AWSServiceName": ["String"], "iam:AccountPropertyNamespaces": ["ArrayOfString"], "iam:AssociatedResourceArn": ["ARN"], "iam:DelegationDuration": ["String"], "iam:DelegationRequestOwner": ["ARN"], "iam:FIDO-FIPS-140-2-certification": ["String"], "iam:FIDO-FIPS-140-3-certification": ["String"], "iam:FIDO-certification": ["String"], "iam:NotificationChannel": ["String"], "iam:OrganizationsPolicyId": ["String"], "iam:PassedToService": ["String"], "iam:PermissionsBoundary": ["ARN"], "iam:PolicyARN": ["ARN"], "iam:RegisterSecurityKey": ["String"], "iam:RoleTemplateARN": ["ARN"], "iam:ServiceSpecificCredentialAgeDays": ["Numeric"], "iam:ServiceSpecificCredentialServiceName": ["String"], "iam:TemplateArn": ["ARN"]}, + "types": {"aws:ResourceTag/${TagKey}": ["String"], "iam:AWSServiceName": ["String"], "iam:AccountPropertyNamespaces": ["ArrayOfString"], "iam:AssociatedResourceArn": ["ARN"], "iam:DelegationDuration": ["String"], "iam:DelegationRequestOwner": ["ARN"], "iam:FIDO-FIPS-140-2-certification": ["String"], "iam:FIDO-FIPS-140-3-certification": ["String"], "iam:FIDO-certification": ["String"], "iam:NotificationChannel": ["String"], "iam:OrganizationsPolicyId": ["String"], "iam:PassedToService": ["String"], "iam:PermissionsBoundary": ["ARN"], "iam:PolicyARN": ["ARN"], "iam:RegisterSecurityKey": ["String"], "iam:ResourceTag/${TagKey}": ["String"], "iam:RoleTemplateARN": ["ARN"], "iam:ServiceSpecificCredentialAgeDays": ["Numeric"], "iam:ServiceSpecificCredentialServiceName": ["String"], "iam:TemplateArn": ["ARN"]}, "read": [ {"action": "iam:AttachGroupPolicy", "key": "iam:PolicyARN", "member": "PolicyArn"}, {"action": "iam:AttachRolePolicy", "key": "iam:PolicyARN", "member": "PolicyArn"}, @@ -22,47 +22,267 @@ {"action": "iam:PutUserPermissionsBoundary", "key": "iam:PermissionsBoundary", "member": "PermissionsBoundary"} ], "fromTarget": [ + {"action": "iam:AttachRolePolicy", "key": "aws:ResourceTag/${TagKey}", "target": "RoleName", "resources": ["role"]}, {"action": "iam:AttachRolePolicy", "key": "iam:PermissionsBoundary", "target": "RoleName"}, + {"action": "iam:AttachRolePolicy", "key": "iam:ResourceTag/${TagKey}", "target": "RoleName", "resources": ["role"]}, + {"action": "iam:AttachUserPolicy", "key": "aws:ResourceTag/${TagKey}", "target": "UserName", "resources": ["user"]}, {"action": "iam:AttachUserPolicy", "key": "iam:PermissionsBoundary", "target": "UserName"}, + {"action": "iam:AttachUserPolicy", "key": "iam:ResourceTag/${TagKey}", "target": "UserName", "resources": ["user"]}, + {"action": "iam:CreateAccessKey", "key": "aws:ResourceTag/${TagKey}", "target": "UserName", "resources": ["user"]}, + {"action": "iam:CreateAccessKey", "key": "iam:ResourceTag/${TagKey}", "target": "UserName", "resources": ["user"]}, + {"action": "iam:CreateLoginProfile", "key": "aws:ResourceTag/${TagKey}", "target": "UserName", "resources": ["user"]}, + {"action": "iam:CreateLoginProfile", "key": "iam:ResourceTag/${TagKey}", "target": "UserName", "resources": ["user"]}, + {"action": "iam:CreateServiceSpecificCredential", "key": "aws:ResourceTag/${TagKey}", "target": "UserName", "resources": ["user"]}, + {"action": "iam:CreateServiceSpecificCredential", "key": "iam:ResourceTag/${TagKey}", "target": "UserName", "resources": ["user"]}, + {"action": "iam:DeactivateMFADevice", "key": "aws:ResourceTag/${TagKey}", "target": "UserName", "resources": ["user"]}, + {"action": "iam:DeactivateMFADevice", "key": "iam:ResourceTag/${TagKey}", "target": "UserName", "resources": ["user"]}, + {"action": "iam:DeleteAccessKey", "key": "aws:ResourceTag/${TagKey}", "target": "UserName", "resources": ["user"]}, + {"action": "iam:DeleteAccessKey", "key": "iam:ResourceTag/${TagKey}", "target": "UserName", "resources": ["user"]}, + {"action": "iam:DeleteLoginProfile", "key": "aws:ResourceTag/${TagKey}", "target": "UserName", "resources": ["user"]}, + {"action": "iam:DeleteLoginProfile", "key": "iam:ResourceTag/${TagKey}", "target": "UserName", "resources": ["user"]}, + {"action": "iam:DeleteRole", "key": "aws:ResourceTag/${TagKey}", "target": "RoleName", "resources": ["role"]}, {"action": "iam:DeleteRole", "key": "iam:PermissionsBoundary", "target": "RoleName"}, + {"action": "iam:DeleteRole", "key": "iam:ResourceTag/${TagKey}", "target": "RoleName", "resources": ["role"]}, + {"action": "iam:DeleteRolePermissionsBoundary", "key": "aws:ResourceTag/${TagKey}", "target": "RoleName", "resources": ["role"]}, {"action": "iam:DeleteRolePermissionsBoundary", "key": "iam:PermissionsBoundary", "target": "RoleName"}, + {"action": "iam:DeleteRolePermissionsBoundary", "key": "iam:ResourceTag/${TagKey}", "target": "RoleName", "resources": ["role"]}, + {"action": "iam:DeleteRolePolicy", "key": "aws:ResourceTag/${TagKey}", "target": "RoleName", "resources": ["role"]}, {"action": "iam:DeleteRolePolicy", "key": "iam:PermissionsBoundary", "target": "RoleName"}, + {"action": "iam:DeleteRolePolicy", "key": "iam:ResourceTag/${TagKey}", "target": "RoleName", "resources": ["role"]}, + {"action": "iam:DeleteSSHPublicKey", "key": "aws:ResourceTag/${TagKey}", "target": "UserName", "resources": ["user"]}, + {"action": "iam:DeleteSSHPublicKey", "key": "iam:ResourceTag/${TagKey}", "target": "UserName", "resources": ["user"]}, + {"action": "iam:DeleteServiceLinkedRole", "key": "aws:ResourceTag/${TagKey}", "target": "RoleName", "resources": ["role"]}, + {"action": "iam:DeleteServiceLinkedRole", "key": "iam:ResourceTag/${TagKey}", "target": "RoleName", "resources": ["role"]}, + {"action": "iam:DeleteServiceSpecificCredential", "key": "aws:ResourceTag/${TagKey}", "target": "UserName", "resources": ["user"]}, + {"action": "iam:DeleteServiceSpecificCredential", "key": "iam:ResourceTag/${TagKey}", "target": "UserName", "resources": ["user"]}, + {"action": "iam:DeleteSigningCertificate", "key": "aws:ResourceTag/${TagKey}", "target": "UserName", "resources": ["user"]}, + {"action": "iam:DeleteSigningCertificate", "key": "iam:ResourceTag/${TagKey}", "target": "UserName", "resources": ["user"]}, + {"action": "iam:DeleteUser", "key": "aws:ResourceTag/${TagKey}", "target": "UserName", "resources": ["user"]}, + {"action": "iam:DeleteUser", "key": "iam:ResourceTag/${TagKey}", "target": "UserName", "resources": ["user"]}, + {"action": "iam:DeleteUserPermissionsBoundary", "key": "aws:ResourceTag/${TagKey}", "target": "UserName", "resources": ["user"]}, {"action": "iam:DeleteUserPermissionsBoundary", "key": "iam:PermissionsBoundary", "target": "UserName"}, + {"action": "iam:DeleteUserPermissionsBoundary", "key": "iam:ResourceTag/${TagKey}", "target": "UserName", "resources": ["user"]}, + {"action": "iam:DeleteUserPolicy", "key": "aws:ResourceTag/${TagKey}", "target": "UserName", "resources": ["user"]}, {"action": "iam:DeleteUserPolicy", "key": "iam:PermissionsBoundary", "target": "UserName"}, + {"action": "iam:DeleteUserPolicy", "key": "iam:ResourceTag/${TagKey}", "target": "UserName", "resources": ["user"]}, + {"action": "iam:DetachRolePolicy", "key": "aws:ResourceTag/${TagKey}", "target": "RoleName", "resources": ["role"]}, {"action": "iam:DetachRolePolicy", "key": "iam:PermissionsBoundary", "target": "RoleName"}, + {"action": "iam:DetachRolePolicy", "key": "iam:ResourceTag/${TagKey}", "target": "RoleName", "resources": ["role"]}, + {"action": "iam:DetachUserPolicy", "key": "aws:ResourceTag/${TagKey}", "target": "UserName", "resources": ["user"]}, {"action": "iam:DetachUserPolicy", "key": "iam:PermissionsBoundary", "target": "UserName"}, + {"action": "iam:DetachUserPolicy", "key": "iam:ResourceTag/${TagKey}", "target": "UserName", "resources": ["user"]}, + {"action": "iam:EnableMFADevice", "key": "aws:ResourceTag/${TagKey}", "target": "UserName", "resources": ["user"]}, + {"action": "iam:EnableMFADevice", "key": "iam:ResourceTag/${TagKey}", "target": "UserName", "resources": ["user"]}, + {"action": "iam:GetLoginProfile", "key": "aws:ResourceTag/${TagKey}", "target": "UserName", "resources": ["user"]}, + {"action": "iam:GetLoginProfile", "key": "iam:ResourceTag/${TagKey}", "target": "UserName", "resources": ["user"]}, + {"action": "iam:GetMFADevice", "key": "aws:ResourceTag/${TagKey}", "target": "UserName", "resources": ["user"]}, + {"action": "iam:GetMFADevice", "key": "iam:ResourceTag/${TagKey}", "target": "UserName", "resources": ["user"]}, + {"action": "iam:GetRole", "key": "aws:ResourceTag/${TagKey}", "target": "RoleName", "resources": ["role"]}, {"action": "iam:GetRole", "key": "iam:PermissionsBoundary", "target": "RoleName"}, + {"action": "iam:GetRole", "key": "iam:ResourceTag/${TagKey}", "target": "RoleName", "resources": ["role"]}, + {"action": "iam:GetRolePolicy", "key": "aws:ResourceTag/${TagKey}", "target": "RoleName", "resources": ["role"]}, + {"action": "iam:GetRolePolicy", "key": "iam:ResourceTag/${TagKey}", "target": "RoleName", "resources": ["role"]}, + {"action": "iam:GetSSHPublicKey", "key": "aws:ResourceTag/${TagKey}", "target": "UserName", "resources": ["user"]}, + {"action": "iam:GetSSHPublicKey", "key": "iam:ResourceTag/${TagKey}", "target": "UserName", "resources": ["user"]}, + {"action": "iam:GetUser", "key": "aws:ResourceTag/${TagKey}", "target": "UserName", "resources": ["user"]}, + {"action": "iam:GetUser", "key": "iam:ResourceTag/${TagKey}", "target": "UserName", "resources": ["user"]}, + {"action": "iam:GetUserPolicy", "key": "aws:ResourceTag/${TagKey}", "target": "UserName", "resources": ["user"]}, + {"action": "iam:GetUserPolicy", "key": "iam:ResourceTag/${TagKey}", "target": "UserName", "resources": ["user"]}, + {"action": "iam:ListAccessKeys", "key": "aws:ResourceTag/${TagKey}", "target": "UserName", "resources": ["user"]}, + {"action": "iam:ListAccessKeys", "key": "iam:ResourceTag/${TagKey}", "target": "UserName", "resources": ["user"]}, + {"action": "iam:ListAttachedRolePolicies", "key": "aws:ResourceTag/${TagKey}", "target": "RoleName", "resources": ["role"]}, + {"action": "iam:ListAttachedRolePolicies", "key": "iam:ResourceTag/${TagKey}", "target": "RoleName", "resources": ["role"]}, + {"action": "iam:ListAttachedUserPolicies", "key": "aws:ResourceTag/${TagKey}", "target": "UserName", "resources": ["user"]}, + {"action": "iam:ListAttachedUserPolicies", "key": "iam:ResourceTag/${TagKey}", "target": "UserName", "resources": ["user"]}, + {"action": "iam:ListGroupsForUser", "key": "aws:ResourceTag/${TagKey}", "target": "UserName", "resources": ["user"]}, + {"action": "iam:ListGroupsForUser", "key": "iam:ResourceTag/${TagKey}", "target": "UserName", "resources": ["user"]}, + {"action": "iam:ListInstanceProfilesForRole", "key": "aws:ResourceTag/${TagKey}", "target": "RoleName", "resources": ["role"]}, + {"action": "iam:ListInstanceProfilesForRole", "key": "iam:ResourceTag/${TagKey}", "target": "RoleName", "resources": ["role"]}, + {"action": "iam:ListMFADevices", "key": "aws:ResourceTag/${TagKey}", "target": "UserName", "resources": ["user"]}, + {"action": "iam:ListMFADevices", "key": "iam:ResourceTag/${TagKey}", "target": "UserName", "resources": ["user"]}, + {"action": "iam:ListRolePolicies", "key": "aws:ResourceTag/${TagKey}", "target": "RoleName", "resources": ["role"]}, + {"action": "iam:ListRolePolicies", "key": "iam:ResourceTag/${TagKey}", "target": "RoleName", "resources": ["role"]}, + {"action": "iam:ListRoleTags", "key": "aws:ResourceTag/${TagKey}", "target": "RoleName", "resources": ["role"]}, + {"action": "iam:ListRoleTags", "key": "iam:ResourceTag/${TagKey}", "target": "RoleName", "resources": ["role"]}, + {"action": "iam:ListSSHPublicKeys", "key": "aws:ResourceTag/${TagKey}", "target": "UserName", "resources": ["user"]}, + {"action": "iam:ListSSHPublicKeys", "key": "iam:ResourceTag/${TagKey}", "target": "UserName", "resources": ["user"]}, + {"action": "iam:ListServiceSpecificCredentials", "key": "aws:ResourceTag/${TagKey}", "target": "UserName", "resources": ["user"]}, + {"action": "iam:ListServiceSpecificCredentials", "key": "iam:ResourceTag/${TagKey}", "target": "UserName", "resources": ["user"]}, + {"action": "iam:ListSigningCertificates", "key": "aws:ResourceTag/${TagKey}", "target": "UserName", "resources": ["user"]}, + {"action": "iam:ListSigningCertificates", "key": "iam:ResourceTag/${TagKey}", "target": "UserName", "resources": ["user"]}, + {"action": "iam:ListUserPolicies", "key": "aws:ResourceTag/${TagKey}", "target": "UserName", "resources": ["user"]}, + {"action": "iam:ListUserPolicies", "key": "iam:ResourceTag/${TagKey}", "target": "UserName", "resources": ["user"]}, + {"action": "iam:ListUserTags", "key": "aws:ResourceTag/${TagKey}", "target": "UserName", "resources": ["user"]}, + {"action": "iam:ListUserTags", "key": "iam:ResourceTag/${TagKey}", "target": "UserName", "resources": ["user"]}, + {"action": "iam:PutRolePermissionsBoundary", "key": "aws:ResourceTag/${TagKey}", "target": "RoleName", "resources": ["role"]}, + {"action": "iam:PutRolePermissionsBoundary", "key": "iam:ResourceTag/${TagKey}", "target": "RoleName", "resources": ["role"]}, + {"action": "iam:PutRolePolicy", "key": "aws:ResourceTag/${TagKey}", "target": "RoleName", "resources": ["role"]}, {"action": "iam:PutRolePolicy", "key": "iam:PermissionsBoundary", "target": "RoleName"}, + {"action": "iam:PutRolePolicy", "key": "iam:ResourceTag/${TagKey}", "target": "RoleName", "resources": ["role"]}, + {"action": "iam:PutUserPermissionsBoundary", "key": "aws:ResourceTag/${TagKey}", "target": "UserName", "resources": ["user"]}, + {"action": "iam:PutUserPermissionsBoundary", "key": "iam:ResourceTag/${TagKey}", "target": "UserName", "resources": ["user"]}, + {"action": "iam:PutUserPolicy", "key": "aws:ResourceTag/${TagKey}", "target": "UserName", "resources": ["user"]}, {"action": "iam:PutUserPolicy", "key": "iam:PermissionsBoundary", "target": "UserName"}, + {"action": "iam:PutUserPolicy", "key": "iam:ResourceTag/${TagKey}", "target": "UserName", "resources": ["user"]}, + {"action": "iam:ResetServiceSpecificCredential", "key": "aws:ResourceTag/${TagKey}", "target": "UserName", "resources": ["user"]}, + {"action": "iam:ResetServiceSpecificCredential", "key": "iam:ResourceTag/${TagKey}", "target": "UserName", "resources": ["user"]}, + {"action": "iam:ResyncMFADevice", "key": "aws:ResourceTag/${TagKey}", "target": "UserName", "resources": ["user"]}, + {"action": "iam:ResyncMFADevice", "key": "iam:ResourceTag/${TagKey}", "target": "UserName", "resources": ["user"]}, + {"action": "iam:TagRole", "key": "aws:ResourceTag/${TagKey}", "target": "RoleName", "resources": ["role"]}, + {"action": "iam:TagRole", "key": "iam:ResourceTag/${TagKey}", "target": "RoleName", "resources": ["role"]}, + {"action": "iam:TagUser", "key": "aws:ResourceTag/${TagKey}", "target": "UserName", "resources": ["user"]}, + {"action": "iam:TagUser", "key": "iam:ResourceTag/${TagKey}", "target": "UserName", "resources": ["user"]}, + {"action": "iam:UntagRole", "key": "aws:ResourceTag/${TagKey}", "target": "RoleName", "resources": ["role"]}, + {"action": "iam:UntagRole", "key": "iam:ResourceTag/${TagKey}", "target": "RoleName", "resources": ["role"]}, + {"action": "iam:UntagUser", "key": "aws:ResourceTag/${TagKey}", "target": "UserName", "resources": ["user"]}, + {"action": "iam:UntagUser", "key": "iam:ResourceTag/${TagKey}", "target": "UserName", "resources": ["user"]}, + {"action": "iam:UpdateAccessKey", "key": "aws:ResourceTag/${TagKey}", "target": "UserName", "resources": ["user"]}, + {"action": "iam:UpdateAccessKey", "key": "iam:ResourceTag/${TagKey}", "target": "UserName", "resources": ["user"]}, + {"action": "iam:UpdateAssumeRolePolicy", "key": "aws:ResourceTag/${TagKey}", "target": "RoleName", "resources": ["role"]}, {"action": "iam:UpdateAssumeRolePolicy", "key": "iam:PermissionsBoundary", "target": "RoleName"}, + {"action": "iam:UpdateAssumeRolePolicy", "key": "iam:ResourceTag/${TagKey}", "target": "RoleName", "resources": ["role"]}, + {"action": "iam:UpdateLoginProfile", "key": "aws:ResourceTag/${TagKey}", "target": "UserName", "resources": ["user"]}, + {"action": "iam:UpdateLoginProfile", "key": "iam:ResourceTag/${TagKey}", "target": "UserName", "resources": ["user"]}, + {"action": "iam:UpdateRole", "key": "aws:ResourceTag/${TagKey}", "target": "RoleName", "resources": ["role"]}, {"action": "iam:UpdateRole", "key": "iam:PermissionsBoundary", "target": "RoleName"}, - {"action": "iam:UpdateRoleDescription", "key": "iam:PermissionsBoundary", "target": "RoleName"} + {"action": "iam:UpdateRole", "key": "iam:ResourceTag/${TagKey}", "target": "RoleName", "resources": ["role"]}, + {"action": "iam:UpdateRoleDescription", "key": "aws:ResourceTag/${TagKey}", "target": "RoleName", "resources": ["role"]}, + {"action": "iam:UpdateRoleDescription", "key": "iam:PermissionsBoundary", "target": "RoleName"}, + {"action": "iam:UpdateRoleDescription", "key": "iam:ResourceTag/${TagKey}", "target": "RoleName", "resources": ["role"]}, + {"action": "iam:UpdateSSHPublicKey", "key": "aws:ResourceTag/${TagKey}", "target": "UserName", "resources": ["user"]}, + {"action": "iam:UpdateSSHPublicKey", "key": "iam:ResourceTag/${TagKey}", "target": "UserName", "resources": ["user"]}, + {"action": "iam:UpdateServiceSpecificCredential", "key": "aws:ResourceTag/${TagKey}", "target": "UserName", "resources": ["user"]}, + {"action": "iam:UpdateServiceSpecificCredential", "key": "iam:ResourceTag/${TagKey}", "target": "UserName", "resources": ["user"]}, + {"action": "iam:UpdateSigningCertificate", "key": "aws:ResourceTag/${TagKey}", "target": "UserName", "resources": ["user"]}, + {"action": "iam:UpdateSigningCertificate", "key": "iam:ResourceTag/${TagKey}", "target": "UserName", "resources": ["user"]}, + {"action": "iam:UpdateUser", "key": "aws:ResourceTag/${TagKey}", "target": "UserName", "resources": ["user"]}, + {"action": "iam:UpdateUser", "key": "iam:ResourceTag/${TagKey}", "target": "UserName", "resources": ["user"]}, + {"action": "iam:UploadSSHPublicKey", "key": "aws:ResourceTag/${TagKey}", "target": "UserName", "resources": ["user"]}, + {"action": "iam:UploadSSHPublicKey", "key": "iam:ResourceTag/${TagKey}", "target": "UserName", "resources": ["user"]}, + {"action": "iam:UploadSigningCertificate", "key": "aws:ResourceTag/${TagKey}", "target": "UserName", "resources": ["user"]}, + {"action": "iam:UploadSigningCertificate", "key": "iam:ResourceTag/${TagKey}", "target": "UserName", "resources": ["user"]} ], "notRead": [ {"action": "iam:AcceptDelegationRequest", "key": "iam:DelegationRequestOwner", "reason": "the value is the delegation request's owner"}, + {"action": "iam:AddClientIDToOpenIDConnectProvider", "key": "aws:ResourceTag/${TagKey}", "reason": "no member names a stored role or user whose resource tags can be read", "resources": ["oidc-provider"]}, + {"action": "iam:AddRoleToInstanceProfile", "key": "aws:ResourceTag/${TagKey}", "reason": "no member names a stored role or user whose resource tags can be read", "resources": ["instance-profile"]}, {"action": "iam:AssociateDelegationRequest", "key": "iam:DelegationRequestOwner", "reason": "the value is the delegation request's owner"}, {"action": "iam:AttachRolePolicy", "key": "iam:RoleTemplateARN", "reason": "the value is the role template a service acquires the role from"}, + {"action": "iam:ChangePassword", "key": "aws:ResourceTag/${TagKey}", "reason": "no member names a stored role or user whose resource tags can be read", "resources": ["user"]}, + {"action": "iam:ChangePassword", "key": "iam:ResourceTag/${TagKey}", "reason": "no member names a stored role or user whose resource tags can be read", "resources": ["user"]}, {"action": "iam:CreateDelegationRequest", "key": "iam:DelegationRequestOwner", "reason": "the value is the delegation request's owner"}, + {"action": "iam:CreateInstanceProfile", "key": "aws:ResourceTag/${TagKey}", "reason": "no member names a stored role or user whose resource tags can be read", "resources": ["instance-profile"]}, + {"action": "iam:CreateOpenIDConnectProvider", "key": "aws:ResourceTag/${TagKey}", "reason": "no member names a stored role or user whose resource tags can be read", "resources": ["oidc-provider"]}, + {"action": "iam:CreatePolicy", "key": "aws:ResourceTag/${TagKey}", "reason": "no member names a stored role or user whose resource tags can be read", "resources": ["policy"]}, + {"action": "iam:CreatePolicyVersion", "key": "aws:ResourceTag/${TagKey}", "reason": "no member names a stored role or user whose resource tags can be read", "resources": ["policy"]}, + {"action": "iam:CreateRole", "key": "aws:ResourceTag/${TagKey}", "reason": "the target does not exist before creation; request tags are handled by TagOnCreate", "resources": ["role"]}, + {"action": "iam:CreateRole", "key": "iam:ResourceTag/${TagKey}", "reason": "the target does not exist before creation; request tags are handled by TagOnCreate", "resources": ["role"]}, {"action": "iam:CreateRole", "key": "iam:RoleTemplateARN", "reason": "the value is the role template a service acquires the role from"}, + {"action": "iam:CreateSAMLProvider", "key": "aws:ResourceTag/${TagKey}", "reason": "no member names a stored role or user whose resource tags can be read", "resources": ["saml-provider"]}, + {"action": "iam:CreateServiceLinkedRole", "key": "aws:ResourceTag/${TagKey}", "reason": "no member names a stored role or user whose resource tags can be read", "resources": ["role"]}, + {"action": "iam:CreateServiceLinkedRole", "key": "iam:ResourceTag/${TagKey}", "reason": "no member names a stored role or user whose resource tags can be read", "resources": ["role"]}, + {"action": "iam:CreateUser", "key": "aws:ResourceTag/${TagKey}", "reason": "the target does not exist before creation; request tags are handled by TagOnCreate", "resources": ["user"]}, + {"action": "iam:CreateUser", "key": "iam:ResourceTag/${TagKey}", "reason": "the target does not exist before creation; request tags are handled by TagOnCreate", "resources": ["user"]}, + {"action": "iam:CreateVirtualMFADevice", "key": "aws:ResourceTag/${TagKey}", "reason": "no member names a stored role or user whose resource tags can be read", "resources": ["mfa"]}, + {"action": "iam:DeleteInstanceProfile", "key": "aws:ResourceTag/${TagKey}", "reason": "no member names a stored role or user whose resource tags can be read", "resources": ["instance-profile"]}, + {"action": "iam:DeleteOpenIDConnectProvider", "key": "aws:ResourceTag/${TagKey}", "reason": "no member names a stored role or user whose resource tags can be read", "resources": ["oidc-provider"]}, + {"action": "iam:DeletePolicy", "key": "aws:ResourceTag/${TagKey}", "reason": "no member names a stored role or user whose resource tags can be read", "resources": ["policy"]}, + {"action": "iam:DeletePolicyVersion", "key": "aws:ResourceTag/${TagKey}", "reason": "no member names a stored role or user whose resource tags can be read", "resources": ["policy"]}, + {"action": "iam:DeleteSAMLProvider", "key": "aws:ResourceTag/${TagKey}", "reason": "no member names a stored role or user whose resource tags can be read", "resources": ["saml-provider"]}, + {"action": "iam:DeleteServerCertificate", "key": "aws:ResourceTag/${TagKey}", "reason": "no member names a stored role or user whose resource tags can be read", "resources": ["server-certificate"]}, {"action": "iam:DeleteServiceSpecificCredential", "key": "iam:ServiceSpecificCredentialServiceName", "reason": "the value is the named credential's service"}, + {"action": "iam:DeleteVirtualMFADevice", "key": "aws:ResourceTag/${TagKey}", "reason": "no member names a stored role or user whose resource tags can be read", "resources": ["mfa"]}, {"action": "iam:EnableMFADevice", "key": "iam:FIDO-FIPS-140-2-certification", "reason": "the value comes from the FIDO Alliance Metadata Service"}, {"action": "iam:EnableMFADevice", "key": "iam:FIDO-FIPS-140-3-certification", "reason": "the value comes from the FIDO Alliance Metadata Service"}, {"action": "iam:EnableMFADevice", "key": "iam:FIDO-certification", "reason": "the value comes from the FIDO Alliance Metadata Service"}, {"action": "iam:EnableMFADevice", "key": "iam:RegisterSecurityKey", "reason": "the value is the MFA device's registration state"}, + {"action": "iam:GenerateServiceLastAccessedDetails", "key": "aws:ResourceTag/${TagKey}", "reason": "no member names a stored role or user whose resource tags can be read", "resources": ["policy", "role", "user"]}, + {"action": "iam:GenerateServiceLastAccessedDetails", "key": "iam:ResourceTag/${TagKey}", "reason": "no member names a stored role or user whose resource tags can be read", "resources": ["role", "user"]}, + {"action": "iam:GetAccessKeyLastUsed", "key": "aws:ResourceTag/${TagKey}", "reason": "no member names a stored role or user whose resource tags can be read", "resources": ["user"]}, + {"action": "iam:GetAccessKeyLastUsed", "key": "iam:ResourceTag/${TagKey}", "reason": "no member names a stored role or user whose resource tags can be read", "resources": ["user"]}, {"action": "iam:GetAccountProperties", "key": "iam:AccountPropertyNamespaces", "reason": "the value is the namespaces of the properties read or written"}, + {"action": "iam:GetContextKeysForPrincipalPolicy", "key": "aws:ResourceTag/${TagKey}", "reason": "no member names a stored role or user whose resource tags can be read", "resources": ["role", "user"]}, + {"action": "iam:GetContextKeysForPrincipalPolicy", "key": "iam:ResourceTag/${TagKey}", "reason": "no member names a stored role or user whose resource tags can be read", "resources": ["role", "user"]}, {"action": "iam:GetDelegationRequest", "key": "iam:DelegationRequestOwner", "reason": "the value is the delegation request's owner"}, {"action": "iam:GetHumanReadableSummary", "key": "iam:DelegationRequestOwner", "reason": "the value is the delegation request's owner"}, + {"action": "iam:GetInstanceProfile", "key": "aws:ResourceTag/${TagKey}", "reason": "no member names a stored role or user whose resource tags can be read", "resources": ["instance-profile"]}, + {"action": "iam:GetOpenIDConnectProvider", "key": "aws:ResourceTag/${TagKey}", "reason": "no member names a stored role or user whose resource tags can be read", "resources": ["oidc-provider"]}, + {"action": "iam:GetPolicy", "key": "aws:ResourceTag/${TagKey}", "reason": "no member names a stored role or user whose resource tags can be read", "resources": ["policy"]}, + {"action": "iam:GetPolicyVersion", "key": "aws:ResourceTag/${TagKey}", "reason": "no member names a stored role or user whose resource tags can be read", "resources": ["policy"]}, {"action": "iam:GetRole", "key": "iam:RoleTemplateARN", "reason": "the value is the role template a service acquires the role from"}, + {"action": "iam:GetSAMLProvider", "key": "aws:ResourceTag/${TagKey}", "reason": "no member names a stored role or user whose resource tags can be read", "resources": ["saml-provider"]}, + {"action": "iam:GetServerCertificate", "key": "aws:ResourceTag/${TagKey}", "reason": "no member names a stored role or user whose resource tags can be read", "resources": ["server-certificate"]}, + {"action": "iam:GetServiceLinkedRoleDeletionStatus", "key": "aws:ResourceTag/${TagKey}", "reason": "no member names a stored role or user whose resource tags can be read", "resources": ["role"]}, + {"action": "iam:GetServiceLinkedRoleDeletionStatus", "key": "iam:ResourceTag/${TagKey}", "reason": "no member names a stored role or user whose resource tags can be read", "resources": ["role"]}, {"action": "iam:ListDelegationRequests", "key": "iam:DelegationRequestOwner", "reason": "the value is the delegation request's owner"}, + {"action": "iam:ListEntitiesForPolicy", "key": "aws:ResourceTag/${TagKey}", "reason": "no member names a stored role or user whose resource tags can be read", "resources": ["policy"]}, + {"action": "iam:ListInstanceProfileTags", "key": "aws:ResourceTag/${TagKey}", "reason": "no member names a stored role or user whose resource tags can be read", "resources": ["instance-profile"]}, + {"action": "iam:ListMFADeviceTags", "key": "aws:ResourceTag/${TagKey}", "reason": "no member names a stored role or user whose resource tags can be read", "resources": ["mfa"]}, + {"action": "iam:ListOpenIDConnectProviderTags", "key": "aws:ResourceTag/${TagKey}", "reason": "no member names a stored role or user whose resource tags can be read", "resources": ["oidc-provider"]}, + {"action": "iam:ListPoliciesGrantingServiceAccess", "key": "aws:ResourceTag/${TagKey}", "reason": "no member names a stored role or user whose resource tags can be read", "resources": ["role", "user"]}, + {"action": "iam:ListPoliciesGrantingServiceAccess", "key": "iam:ResourceTag/${TagKey}", "reason": "no member names a stored role or user whose resource tags can be read", "resources": ["role", "user"]}, + {"action": "iam:ListPolicyTags", "key": "aws:ResourceTag/${TagKey}", "reason": "no member names a stored role or user whose resource tags can be read", "resources": ["policy"]}, + {"action": "iam:ListPolicyVersions", "key": "aws:ResourceTag/${TagKey}", "reason": "no member names a stored role or user whose resource tags can be read", "resources": ["policy"]}, + {"action": "iam:ListSAMLProviderTags", "key": "aws:ResourceTag/${TagKey}", "reason": "no member names a stored role or user whose resource tags can be read", "resources": ["saml-provider"]}, + {"action": "iam:ListServerCertificateTags", "key": "aws:ResourceTag/${TagKey}", "reason": "no member names a stored role or user whose resource tags can be read", "resources": ["server-certificate"]}, + {"action": "iam:PassRole", "key": "aws:ResourceTag/${TagKey}", "reason": "AWS warns that ResourceTag conditions with PassRole do not have reliable results", "resources": ["role"]}, {"action": "iam:PassRole", "key": "iam:AssociatedResourceArn", "reason": "no SDK operation of this name"}, {"action": "iam:PassRole", "key": "iam:PassedToService", "reason": "no SDK operation of this name"}, + {"action": "iam:PassRole", "key": "iam:ResourceTag/${TagKey}", "reason": "AWS warns that ResourceTag conditions with PassRole do not have reliable results", "resources": ["role"]}, {"action": "iam:PutAccountProperties", "key": "iam:AccountPropertyNamespaces", "reason": "the value is the namespaces of the properties read or written"}, {"action": "iam:PutRolePermissionsBoundary", "key": "iam:RoleTemplateARN", "reason": "the value is the role template a service acquires the role from"}, {"action": "iam:PutRolePolicy", "key": "iam:RoleTemplateARN", "reason": "the value is the role template a service acquires the role from"}, {"action": "iam:RejectDelegationRequest", "key": "iam:DelegationRequestOwner", "reason": "the value is the delegation request's owner"}, + {"action": "iam:RemoveClientIDFromOpenIDConnectProvider", "key": "aws:ResourceTag/${TagKey}", "reason": "no member names a stored role or user whose resource tags can be read", "resources": ["oidc-provider"]}, + {"action": "iam:RemoveRoleFromInstanceProfile", "key": "aws:ResourceTag/${TagKey}", "reason": "no member names a stored role or user whose resource tags can be read", "resources": ["instance-profile"]}, {"action": "iam:ResetServiceSpecificCredential", "key": "iam:ServiceSpecificCredentialServiceName", "reason": "the value is the named credential's service"}, {"action": "iam:SendDelegationToken", "key": "iam:DelegationRequestOwner", "reason": "the value is the delegation request's owner"}, + {"action": "iam:SetDefaultPolicyVersion", "key": "aws:ResourceTag/${TagKey}", "reason": "no member names a stored role or user whose resource tags can be read", "resources": ["policy"]}, + {"action": "iam:SimulatePrincipalPolicy", "key": "aws:ResourceTag/${TagKey}", "reason": "no member names a stored role or user whose resource tags can be read", "resources": ["role", "user"]}, + {"action": "iam:SimulatePrincipalPolicy", "key": "iam:ResourceTag/${TagKey}", "reason": "no member names a stored role or user whose resource tags can be read", "resources": ["role", "user"]}, + {"action": "iam:TagInstanceProfile", "key": "aws:ResourceTag/${TagKey}", "reason": "no member names a stored role or user whose resource tags can be read", "resources": ["instance-profile"]}, + {"action": "iam:TagMFADevice", "key": "aws:ResourceTag/${TagKey}", "reason": "no member names a stored role or user whose resource tags can be read", "resources": ["mfa"]}, + {"action": "iam:TagOpenIDConnectProvider", "key": "aws:ResourceTag/${TagKey}", "reason": "no member names a stored role or user whose resource tags can be read", "resources": ["oidc-provider"]}, + {"action": "iam:TagPolicy", "key": "aws:ResourceTag/${TagKey}", "reason": "no member names a stored role or user whose resource tags can be read", "resources": ["policy"]}, {"action": "iam:TagRole", "key": "iam:RoleTemplateARN", "reason": "the value is the role template a service acquires the role from"}, - {"action": "iam:UpdateServiceSpecificCredential", "key": "iam:ServiceSpecificCredentialServiceName", "reason": "the value is the named credential's service"} + {"action": "iam:TagSAMLProvider", "key": "aws:ResourceTag/${TagKey}", "reason": "no member names a stored role or user whose resource tags can be read", "resources": ["saml-provider"]}, + {"action": "iam:TagServerCertificate", "key": "aws:ResourceTag/${TagKey}", "reason": "no member names a stored role or user whose resource tags can be read", "resources": ["server-certificate"]}, + {"action": "iam:UntagInstanceProfile", "key": "aws:ResourceTag/${TagKey}", "reason": "no member names a stored role or user whose resource tags can be read", "resources": ["instance-profile"]}, + {"action": "iam:UntagMFADevice", "key": "aws:ResourceTag/${TagKey}", "reason": "no member names a stored role or user whose resource tags can be read", "resources": ["mfa"]}, + {"action": "iam:UntagOpenIDConnectProvider", "key": "aws:ResourceTag/${TagKey}", "reason": "no member names a stored role or user whose resource tags can be read", "resources": ["oidc-provider"]}, + {"action": "iam:UntagPolicy", "key": "aws:ResourceTag/${TagKey}", "reason": "no member names a stored role or user whose resource tags can be read", "resources": ["policy"]}, + {"action": "iam:UntagSAMLProvider", "key": "aws:ResourceTag/${TagKey}", "reason": "no member names a stored role or user whose resource tags can be read", "resources": ["saml-provider"]}, + {"action": "iam:UntagServerCertificate", "key": "aws:ResourceTag/${TagKey}", "reason": "no member names a stored role or user whose resource tags can be read", "resources": ["server-certificate"]}, + {"action": "iam:UpdateOpenIDConnectProviderThumbprint", "key": "aws:ResourceTag/${TagKey}", "reason": "no member names a stored role or user whose resource tags can be read", "resources": ["oidc-provider"]}, + {"action": "iam:UpdateSAMLProvider", "key": "aws:ResourceTag/${TagKey}", "reason": "no member names a stored role or user whose resource tags can be read", "resources": ["saml-provider"]}, + {"action": "iam:UpdateServerCertificate", "key": "aws:ResourceTag/${TagKey}", "reason": "no member names a stored role or user whose resource tags can be read", "resources": ["server-certificate"]}, + {"action": "iam:UpdateServiceSpecificCredential", "key": "iam:ServiceSpecificCredentialServiceName", "reason": "the value is the named credential's service"}, + {"action": "iam:UploadServerCertificate", "key": "aws:ResourceTag/${TagKey}", "reason": "no member names a stored role or user whose resource tags can be read", "resources": ["server-certificate"]} + ], + "requestTags": [ + {"action": "iam:TagInstanceProfile", "key": "aws:RequestTag/${TagKey}", "member": "Tags", "keyMember": "Key", "valueMember": "Value"}, + {"action": "iam:TagInstanceProfile", "key": "aws:TagKeys", "member": "Tags", "keyMember": "Key", "valueMember": "Value"}, + {"action": "iam:TagMFADevice", "key": "aws:RequestTag/${TagKey}", "member": "Tags", "keyMember": "Key", "valueMember": "Value"}, + {"action": "iam:TagMFADevice", "key": "aws:TagKeys", "member": "Tags", "keyMember": "Key", "valueMember": "Value"}, + {"action": "iam:TagOpenIDConnectProvider", "key": "aws:RequestTag/${TagKey}", "member": "Tags", "keyMember": "Key", "valueMember": "Value"}, + {"action": "iam:TagOpenIDConnectProvider", "key": "aws:TagKeys", "member": "Tags", "keyMember": "Key", "valueMember": "Value"}, + {"action": "iam:TagPolicy", "key": "aws:RequestTag/${TagKey}", "member": "Tags", "keyMember": "Key", "valueMember": "Value"}, + {"action": "iam:TagPolicy", "key": "aws:TagKeys", "member": "Tags", "keyMember": "Key", "valueMember": "Value"}, + {"action": "iam:TagRole", "key": "aws:RequestTag/${TagKey}", "member": "Tags", "keyMember": "Key", "valueMember": "Value"}, + {"action": "iam:TagRole", "key": "aws:TagKeys", "member": "Tags", "keyMember": "Key", "valueMember": "Value"}, + {"action": "iam:TagSAMLProvider", "key": "aws:RequestTag/${TagKey}", "member": "Tags", "keyMember": "Key", "valueMember": "Value"}, + {"action": "iam:TagSAMLProvider", "key": "aws:TagKeys", "member": "Tags", "keyMember": "Key", "valueMember": "Value"}, + {"action": "iam:TagServerCertificate", "key": "aws:RequestTag/${TagKey}", "member": "Tags", "keyMember": "Key", "valueMember": "Value"}, + {"action": "iam:TagServerCertificate", "key": "aws:TagKeys", "member": "Tags", "keyMember": "Key", "valueMember": "Value"}, + {"action": "iam:TagUser", "key": "aws:RequestTag/${TagKey}", "member": "Tags", "keyMember": "Key", "valueMember": "Value"}, + {"action": "iam:TagUser", "key": "aws:TagKeys", "member": "Tags", "keyMember": "Key", "valueMember": "Value"}, + {"action": "iam:UntagInstanceProfile", "key": "aws:TagKeys", "member": "TagKeys"}, + {"action": "iam:UntagMFADevice", "key": "aws:TagKeys", "member": "TagKeys"}, + {"action": "iam:UntagOpenIDConnectProvider", "key": "aws:TagKeys", "member": "TagKeys"}, + {"action": "iam:UntagPolicy", "key": "aws:TagKeys", "member": "TagKeys"}, + {"action": "iam:UntagRole", "key": "aws:TagKeys", "member": "TagKeys"}, + {"action": "iam:UntagSAMLProvider", "key": "aws:TagKeys", "member": "TagKeys"}, + {"action": "iam:UntagServerCertificate", "key": "aws:TagKeys", "member": "TagKeys"}, + {"action": "iam:UntagUser", "key": "aws:TagKeys", "member": "TagKeys"} ] } diff --git a/src/test/java/io/github/hectorvent/floci/core/common/IamConditionContextResolverTest.java b/src/test/java/io/github/hectorvent/floci/core/common/IamConditionContextResolverTest.java index 3cf8b5cdc8..38f4683389 100644 --- a/src/test/java/io/github/hectorvent/floci/core/common/IamConditionContextResolverTest.java +++ b/src/test/java/io/github/hectorvent/floci/core/common/IamConditionContextResolverTest.java @@ -244,6 +244,109 @@ class IamConditionContextResolverTest { } } + @Test + void iamRoleTagsComeFromStoredStateRatherThanRequestTags() { + IamRole role = new IamRole(); + role.setTags(Map.of("Owner", "team-a")); + when(iamService.findRole("123456789012", "tagged")).thenReturn(Optional.of(role)); + Map> context = resolver.resolve("iam", "iam:PutRolePolicy", + formRequest("RoleName=tagged&Tags.member.1.Key=Owner&Tags.member.1.Value=other")); + assertEquals(List.of("team-a"), context.get("aws:ResourceTag/Owner")); + assertEquals(List.of("team-a"), context.get("iam:ResourceTag/Owner")); + assertNull(context.get("aws:RequestTag/Owner")); + assertNull(resolver.resolve("iam", "iam:PassRole", formRequest("RoleName=tagged"))); + assertNull(resolver.resolve("iam", "iam:GetUser", formRequest("UserName=missing&RoleName=tagged"))); + assertNull(resolver.resolve("iam", "iam:PutRolePolicy", formRequest("RoleName=missing"))); + } + + @ParameterizedTest + @ValueSource(strings = {"iam:TagRole", "iam:TagUser", "iam:TagInstanceProfile", "iam:TagMFADevice", + "iam:TagOpenIDConnectProvider", "iam:TagSAMLProvider", "iam:TagPolicy", "iam:TagServerCertificate"}) + void iamTaggingCarriesRequestedValuesAndEveryKey(String action) { + Map> context = resolver.resolve("iam", action, + formRequest("Tags.member.2.Key=Owner&Tags.member.2.Value=team-a&Tags.7.Key=Env&Tags.7.Value=")); + assertEquals(List.of("team-a"), context.get("aws:RequestTag/Owner")); + assertEquals(List.of(""), context.get("aws:RequestTag/Env")); + assertEquals(List.of("Owner", "Env"), context.get("aws:TagKeys")); + } + + @ParameterizedTest + @ValueSource(strings = {"iam:UntagRole", "iam:UntagUser", "iam:UntagInstanceProfile", "iam:UntagMFADevice", + "iam:UntagOpenIDConnectProvider", "iam:UntagSAMLProvider", "iam:UntagPolicy", "iam:UntagServerCertificate"}) + void iamUntaggingReadsSparseKeysAndIgnoresTagValues(String action) { + assertEquals(Map.of("aws:TagKeys", List.of("Owner", "Env")), resolver.resolve("iam", action, + formRequest("TagKeys.member.2=Owner&TagKeys.7=Env&Tags.member.1.Key=Wrong&Tags.member.1.Value=x"))); + assertNull(resolver.resolve("iam", action, formRequest(""))); + } + + @Test + void iamRoleTagsAreAccountScopedAndUseTheFirstBodyValue() { + IamRole role = new IamRole(); + role.setTags(Map.of("Owner", "team-a")); + when(iamService.findRole("123456789012", "tagged")).thenReturn(Optional.of(role)); + ContainerRequestContext request = formRequest("RoleName=missing&RoleName=tagged"); + UriInfo uri = mock(UriInfo.class); + MultivaluedMap query = new MultivaluedHashMap<>(); + query.putSingle("RoleName", "tagged"); + when(request.getUriInfo()).thenReturn(uri); + when(uri.getQueryParameters()).thenReturn(query); + assertNull(resolver.resolve("iam", "iam:GetRole", request)); + requestContext.setAccountId("222222222222"); + assertNull(resolver.resolve("iam", "iam:GetRole", formRequest("RoleName=tagged"))); + } + + @ParameterizedTest + @ValueSource(strings = {"iam:GetUser", "iam:PutUserPolicy", "iam:TagUser", "iam:CreateAccessKey"}) + void iamUserTagsFollowTheGeneratedTargetAndRequestAccount(String action) { + IamUser user = new IamUser(); + user.setTags(Map.of("Owner", "user-team")); + IamRole role = new IamRole(); + role.setTags(Map.of("Owner", "role-team")); + when(iamService.findUser("123456789012", "tagged")).thenReturn(Optional.of(user)); + when(iamService.findRole("123456789012", "decoy")).thenReturn(Optional.of(role)); + assertEquals(Map.of("aws:ResourceTag/Owner", List.of("user-team"), + "iam:ResourceTag/Owner", List.of("user-team")), + resolver.resolve("iam", action, formRequest("UserName=tagged&RoleName=decoy"))); + assertNull(resolver.resolve("iam", action, formRequest("UserName=missing&RoleName=decoy"))); + assertNull(resolver.resolve("iam", action, formRequest("UserName=missing&UserName=tagged"))); + requestContext.setAccountId("222222222222"); + assertNull(resolver.resolve("iam", action, formRequest("UserName=tagged&RoleName=decoy"))); + } + + @Test + void secondaryRoleAndCreationTargetsDoNotSupplyStoredResourceTags() { + IamRole role = new IamRole(); + role.setTags(Map.of("Owner", "team-a")); + when(iamService.findRole("123456789012", "tagged")).thenReturn(Optional.of(role)); + for (String action : List.of("iam:AddRoleToInstanceProfile", "iam:RemoveRoleFromInstanceProfile", + "iam:CreateRole", "iam:PassRole")) { + assertNull(resolver.resolve("iam", action, formRequest("RoleName=tagged&InstanceProfileName=profile"))); + } + IamUser user = new IamUser(); + user.setTags(Map.of("Owner", "team-a")); + when(iamService.findUser("123456789012", "tagged")).thenReturn(Optional.of(user)); + assertNull(resolver.resolve("iam", "iam:CreateUser", formRequest("UserName=tagged"))); + } + + @Test + void iamRequestTagValuesMatchTheQueryHandlerForGetAndDuplicateParameters() { + assertEquals(List.of("first"), resolver.resolve("iam", "iam:TagUser", + formRequest("Tags.member.1.Key=Owner&Tags.member.1.Value=first&Tags.member.1.Value=second")) + .get("aws:RequestTag/Owner")); + ContainerRequestContext request = mock(ContainerRequestContext.class); + when(request.getMethod()).thenReturn("GET"); + when(request.getProperty(AwsProtocolClaimFilter.CLAIM_PROPERTY)) + .thenReturn(new ProtocolClaim(WireProtocol.AWS_QUERY, null, "TagUser", null)); + UriInfo uri = mock(UriInfo.class); + MultivaluedMap query = new MultivaluedHashMap<>(); + query.putSingle("Tags.3.Key", "Owner"); + query.putSingle("Tags.3.Value", "team-a"); + when(request.getUriInfo()).thenReturn(uri); + when(uri.getQueryParameters()).thenReturn(query); + assertEquals(Map.of("aws:RequestTag/Owner", List.of("team-a"), "aws:TagKeys", List.of("Owner")), + resolver.resolve("iam", "iam:TagUser", request)); + } + @Test void iamPolicyContextKeepsEmptyValuesAndOmitsMissingValues() { assertNull(resolver.resolve("iam", "iam:AttachRolePolicy", formRequest("RoleName=role"))); diff --git a/src/test/java/io/github/hectorvent/floci/services/iam/IamRoleTagConditionIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/iam/IamRoleTagConditionIntegrationTest.java new file mode 100644 index 0000000000..690aa584b1 --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/iam/IamRoleTagConditionIntegrationTest.java @@ -0,0 +1,206 @@ +package io.github.hectorvent.floci.services.iam; + +import io.github.hectorvent.floci.testing.AwsTestClients; +import io.github.hectorvent.floci.testing.EnforcementFixtures; +import io.github.hectorvent.floci.testing.EnforcementFixtures.UserCredentials; +import io.github.hectorvent.floci.testing.IamEnforcementProfile; +import io.github.hectorvent.floci.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 org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; +import software.amazon.awssdk.regions.Region; +import software.amazon.awssdk.services.iam.IamClient; +import software.amazon.awssdk.services.iam.model.IamException; +import software.amazon.awssdk.services.iam.model.Tag; + +import java.net.URI; +import java.util.List; +import java.util.UUID; + +import static io.github.hectorvent.floci.testing.EnforcementFixtures.auth; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; + +@QuarkusTest +@TestProfile(IamEnforcementProfile.class) +class IamRoleTagConditionIntegrationTest { + private static final String TRUST = """ + {"Version":"2012-10-17","Statement":[{"Effect":"Allow", + "Principal":{"Service":"ec2.amazonaws.com"},"Action":"sts:AssumeRole"}]}"""; + private static final String INLINE = """ + {"Version":"2012-10-17","Statement":[{"Effect":"Allow","Action":"s3:GetObject","Resource":"*"}]}"""; + + @TestHTTPResource("/") + URI baseUri; + @RegisterExtension + final PartitionCleanup cleanup = new PartitionCleanup(); + + @ParameterizedTest + @ValueSource(strings = {"aws:ResourceTag/", "iam:ResourceTag/"}) + void storedRoleTagsGatePolicyUpdatesAndExplicitDenies(String prefix) { + try (IamClient admin = AwsTestClients.create(IamClient.builder(), "test", Region.US_EAST_1)) { + String allowed = role(admin, List.of(tag("Owner", "team-a"))); + String other = role(admin, List.of(tag("Owner", "team-b"))); + String untagged = role(admin, List.of()); + String blocked = role(admin, List.of(tag("Owner", "team-a"), tag("Blocked", "yes"))); + String policy = """ + {"Version":"2012-10-17","Statement":[ + {"Effect":"Allow","Action":"iam:PutRolePolicy","Resource":"*", + "Condition":{"StringEquals":{"%sOwner":"team-a"}}}, + {"Effect":"Deny","Action":"iam:PutRolePolicy","Resource":"*", + "Condition":{"StringEquals":{"%sBlocked":"yes"}}}]}""".formatted(prefix, prefix); + try (IamClient caller = caller(policy)) { + caller.putRolePolicy(r -> r.roleName(allowed).policyName("inline").policyDocument(INLINE)); + for (String name : List.of(other, untagged, blocked)) { + denied(() -> caller.putRolePolicy(r -> r.roleName(name).policyName("inline").policyDocument(INLINE))); + assertEquals(List.of(), admin.listRolePolicies(r -> r.roleName(name)).policyNames()); + } + admin.untagRole(r -> r.roleName(allowed).tagKeys("Owner")); + denied(() -> caller.putRolePolicy(r -> r.roleName(allowed).policyName("second").policyDocument(INLINE))); + assertEquals(List.of("inline"), admin.listRolePolicies(r -> r.roleName(allowed)).policyNames()); + } + } + } + + @Test + void tagRoleDistinguishesOldTagsFromTheRequestedUpdate() { + try (IamClient admin = AwsTestClients.create(IamClient.builder(), "test", Region.US_EAST_1)) { + String owned = role(admin, List.of(tag("Owner", "team-a"))); + String other = role(admin, List.of(tag("Owner", "team-b"))); + String policy = """ + {"Version":"2012-10-17","Statement":[{"Effect":"Allow","Action":"iam:TagRole","Resource":"*", + "Condition":{"StringEquals":{"aws:ResourceTag/Owner":"team-a","aws:RequestTag/Owner":"team-b"}, + "ForAllValues:StringEquals":{"aws:TagKeys":["Owner"]},"Null":{"aws:TagKeys":"false"}}}]}"""; + try (IamClient caller = caller(policy)) { + denied(() -> caller.tagRole(r -> r.roleName(other).tags(tag("Owner", "team-b")))); + denied(() -> caller.tagRole(r -> r.roleName(owned).tags(tag("Owner", "team-a")))); + denied(() -> caller.tagRole(r -> r.roleName(owned).tags(tag("Owner", "team-b"), tag("Extra", "x")))); + assertEquals(List.of(tag("Owner", "team-a")), admin.listRoleTags(r -> r.roleName(owned)).tags()); + caller.tagRole(r -> r.roleName(owned).tags(tag("Owner", "team-b"))); + assertEquals(List.of(tag("Owner", "team-b")), admin.listRoleTags(r -> r.roleName(owned)).tags()); + denied(() -> caller.tagRole(r -> r.roleName(owned).tags(tag("Owner", "team-b")))); + } + } + } + + @Test + void tagUserUsesRequestedValuesAndUntagUserChecksEveryRequestedKey() { + try (IamClient admin = AwsTestClients.create(IamClient.builder(), "test", Region.US_EAST_1)) { + String user = "tag-target-" + suffix(); + admin.createUser(r -> r.userName(user)); + cleanup.register(() -> EnforcementFixtures.removeUser(baseUri.getPort(), auth("test", "iam"), user)); + String policy = """ + {"Version":"2012-10-17","Statement":[ + {"Effect":"Allow","Action":"iam:TagUser","Resource":"*", + "Condition":{"StringEquals":{"aws:RequestTag/Env":"dev"}, + "ForAllValues:StringEquals":{"aws:TagKeys":["Env"]}}}, + {"Effect":"Allow","Action":"iam:UntagUser","Resource":"*", + "Condition":{"ForAllValues:StringEquals":{"aws:TagKeys":["Env"]}, + "Null":{"aws:TagKeys":"false"}}}]}"""; + try (IamClient caller = caller(policy)) { + denied(() -> caller.tagUser(r -> r.userName(user).tags(tag("Env", "prod")))); + denied(() -> caller.tagUser(r -> r.userName(user).tags(tag("Env", "dev"), tag("Owner", "other")))); + caller.tagUser(r -> r.userName(user).tags(tag("Env", "dev"))); + denied(() -> caller.untagUser(r -> r.userName(user).tagKeys("Env", "Owner"))); + assertEquals(List.of(tag("Env", "dev")), admin.listUserTags(r -> r.userName(user)).tags()); + caller.untagUser(r -> r.userName(user).tagKeys("Env")); + assertEquals(List.of(), admin.listUserTags(r -> r.userName(user)).tags()); + } + } + } + + @ParameterizedTest + @ValueSource(strings = {"aws:ResourceTag/", "iam:ResourceTag/"}) + void storedUserTagsGatePolicyUpdatesAndExplicitDenies(String prefix) { + try (IamClient admin = AwsTestClients.create(IamClient.builder(), "test", Region.US_EAST_1)) { + String owned = user(admin, List.of(tag("Owner", "team-a"))); + String other = user(admin, List.of(tag("Owner", "team-b"))); + String untagged = user(admin, List.of()); + String blocked = user(admin, List.of(tag("Owner", "team-a"), tag("Blocked", "yes"))); + String policy = """ + {"Version":"2012-10-17","Statement":[ + {"Effect":"Allow","Action":"iam:PutUserPolicy","Resource":"*", + "Condition":{"StringEquals":{"%sOwner":"team-a"}}}, + {"Effect":"Deny","Action":"iam:PutUserPolicy","Resource":"*", + "Condition":{"StringEquals":{"%sBlocked":"yes"}}}]}""".formatted(prefix, prefix); + try (IamClient caller = caller(policy)) { + caller.putUserPolicy(r -> r.userName(owned).policyName("inline").policyDocument(INLINE)); + for (String name : List.of(other, untagged, blocked)) { + denied(() -> caller.putUserPolicy(r -> r.userName(name).policyName("inline").policyDocument(INLINE))); + assertEquals(List.of(), admin.listUserPolicies(r -> r.userName(name)).policyNames()); + } + admin.untagUser(r -> r.userName(owned).tagKeys("Owner")); + denied(() -> caller.putUserPolicy(r -> r.userName(owned).policyName("second").policyDocument(INLINE))); + assertEquals(List.of("inline"), admin.listUserPolicies(r -> r.userName(owned)).policyNames()); + } + } + } + + @Test + void policyTaggingAndUntaggingEnforceGeneratedRequestTagConditions() { + try (IamClient admin = AwsTestClients.create(IamClient.builder(), "test", Region.US_EAST_1)) { + String arn = admin.createPolicy(r -> r.policyName("tag-policy-" + suffix()) + .policyDocument(INLINE)).policy().arn(); + String policy = """ + {"Version":"2012-10-17","Statement":[ + {"Effect":"Allow","Action":"iam:TagPolicy","Resource":"*", + "Condition":{"StringEquals":{"aws:RequestTag/Env":"dev"}, + "ForAllValues:StringEquals":{"aws:TagKeys":["Env"]}}}, + {"Effect":"Allow","Action":"iam:UntagPolicy","Resource":"*", + "Condition":{"ForAllValues:StringEquals":{"aws:TagKeys":["Env"]}, + "Null":{"aws:TagKeys":"false"}}}]}"""; + try (IamClient caller = caller(policy)) { + denied(() -> caller.tagPolicy(r -> r.policyArn(arn).tags(tag("Env", "prod")))); + denied(() -> caller.tagPolicy(r -> r.policyArn(arn).tags(tag("Env", "dev"), tag("Owner", "other")))); + assertEquals(List.of(), admin.listPolicyTags(r -> r.policyArn(arn)).tags()); + caller.tagPolicy(r -> r.policyArn(arn).tags(tag("Env", "dev"))); + denied(() -> caller.untagPolicy(r -> r.policyArn(arn).tagKeys("Env", "Owner"))); + assertEquals(List.of(tag("Env", "dev")), admin.listPolicyTags(r -> r.policyArn(arn)).tags()); + caller.untagPolicy(r -> r.policyArn(arn).tagKeys("Env")); + assertEquals(List.of(), admin.listPolicyTags(r -> r.policyArn(arn)).tags()); + } finally { + admin.deletePolicy(r -> r.policyArn(arn)); + } + } + } + + private String user(IamClient admin, List tags) { + String name = "tag-user-" + suffix(); + admin.createUser(r -> r.userName(name).tags(tags)); + cleanup.register(() -> EnforcementFixtures.removeUser(baseUri.getPort(), auth("test", "iam"), name)); + return name; + } + + private String role(IamClient admin, List tags) { + String name = "tag-role-" + suffix(); + admin.createRole(r -> r.roleName(name).path("/tag-context/").assumeRolePolicyDocument(TRUST).tags(tags)); + cleanup.register(() -> EnforcementFixtures.removeRole(baseUri.getPort(), auth("test", "iam"), name)); + return name; + } + + private IamClient caller(String policy) { + String name = "tag-caller-" + suffix(); + UserCredentials credentials = EnforcementFixtures.createUser(cleanup, baseUri.getPort(), auth("test", "iam"), name); + EnforcementFixtures.putUserPolicy(baseUri.getPort(), auth("test", "iam"), name, "tags", policy); + return AwsTestClients.create(IamClient.builder(), credentials.accessKeyId(), credentials.secretAccessKey(), + Region.US_EAST_1); + } + + private static void denied(Runnable operation) { + IamException error = assertThrows(IamException.class, operation::run); + assertEquals(403, error.statusCode()); + assertEquals("AccessDenied", error.awsErrorDetails().errorCode()); + } + + private static Tag tag(String key, String value) { + return Tag.builder().key(key).value(value).build(); + } + + private static String suffix() { + return UUID.randomUUID().toString().substring(0, 8); + } +} diff --git a/tools/aws/regen_iam_condition_keys.py b/tools/aws/regen_iam_condition_keys.py index 0caff0f5ec..d80e20d59b 100644 --- a/tools/aws/regen_iam_condition_keys.py +++ b/tools/aws/regen_iam_condition_keys.py @@ -16,6 +16,12 @@ hand-edited entry fails, as does a BY_HAND member botocore no longer has or a BY file does not list. --verify compares every pair and key type with the live reference and fails on any difference, added pairs included: a key missing from the context stops a conditioned Allow matching and a conditioned Deny applying. --source reads a saved reference. + +Resource tag keys use the same fromTarget route as permissions boundaries for existing roles +and users. Unsupported targets and exceptions are recorded in notRead with a reason. requestTags +lists the request tag keys of actions marked IsTaggingOnly in the reference, with their list +and tag field names derived from botocore. --verify checks action/key coverage against the live +reference; --check re-derives the stored targets and list shapes from pinned botocore. """ from __future__ import annotations @@ -44,7 +50,14 @@ BY_HAND_TYPES = {"String": {"string", "integer"}, "ARN": {"string"}, "Numeric": # Keys whose value, on an action without the member, is the stored target's: the IAM User Guide's # iam:PermissionsBoundary "checks that the specified policy is attached as permissions boundary on the # IAM principal resource". The target is the role or user the request names. -FROM_TARGET = {"iam:PermissionsBoundary"} +RESOURCE_TAG_KEYS = {"aws:ResourceTag/${TagKey}", "iam:ResourceTag/${TagKey}"} +REQUEST_TAG_KEYS = {"aws:RequestTag/${TagKey}", "aws:TagKeys"} +FROM_TARGET = {"iam:PermissionsBoundary"} | RESOURCE_TAG_KEYS +# https://docs.aws.amazon.com/IAM/latest/UserGuide/access_tags.html warns that using ResourceTag +# with PassRole "does not have reliable results". Keep the reference's pairs with this reason. +RESOURCE_TAG_EXCEPTIONS = { + "iam:PassRole": "AWS warns that ResourceTag conditions with PassRole do not have reliable results", +} TARGET_MEMBERS = ("RoleName", "UserName") # Keys whose value, on an action without the member, does not come from the request. NOT_IN_REQUEST = { @@ -60,18 +73,28 @@ NOT_IN_REQUEST = { def action_keys(reference): - """Every (action, key) pair for an iam: key the reference lists, with each key's types.""" + """Every IAM-specific or resource-tag (action, key) pair, with each key's types.""" resources = {r["Name"]: r.get("ConditionKeys", []) for r in reference["Resources"]} pairs = set() for action in reference["Actions"]: keys = set(action.get("ActionConditionKeys", [])) keys |= {k for r in action.get("Resources", []) for k in r.get("ConditionKeys", resources.get(r["Name"], []))} - pairs |= {("iam:" + action["Name"], k) for k in keys if k.startswith("iam:") and "${" not in k} + pairs |= {("iam:" + action["Name"], k) for k in keys + if (k.startswith("iam:") and "${" not in k) or k in RESOURCE_TAG_KEYS} keys = {key for _, key in pairs} types = {k["Name"]: sorted(k.get("Types", [])) for k in reference["ConditionKeys"] if k["Name"] in keys} return sorted(pairs), dict(sorted(types.items())) +def resource_tag_types(reference): + """Keep which resource each tag key describes, so a secondary RoleName is not the target.""" + resources = {r["Name"]: r.get("ConditionKeys", []) for r in reference["Resources"]} + result = {} + for action in reference["Actions"]: + for resource in action.get("Resources", []): + for key in set(resource.get("ConditionKeys", resources.get(resource["Name"], []))) & RESOURCE_TAG_KEYS: + result.setdefault(("iam:" + action["Name"], key), set()).add(resource["Name"]) + return {pair: sorted(names) for pair, names in result.items()} def member_type(model, operation, path): """The botocore type of the request member at a dotted path, or None when there is none.""" @@ -83,9 +106,9 @@ def member_type(model, operation, path): shape = model["shapes"][member["shape"]] return shape["type"] - -def classify(pairs, types, model): +def classify(pairs, types, model, resource_types=None): """The read, fromTarget and notRead entries for the reference's pairs.""" + resource_types = resource_types or {} read, from_target, not_read = [], [], [] for action, key in sorted(pairs): operation = model["operations"].get(action.split(":", 1)[1]) @@ -102,14 +125,27 @@ def classify(pairs, types, model): members = model["shapes"][operation["input"]["shape"]].get("members", {}) \ if operation and "input" in operation else {} member = next((m for m in sorted(members) if m.lower() == local.lower()), None) - if operation is None: + if key in RESOURCE_TAG_KEYS and action in RESOURCE_TAG_EXCEPTIONS: + reason = RESOURCE_TAG_EXCEPTIONS[action] + elif operation is None: reason = "no SDK operation of this name" elif member is None and key in FROM_TARGET: - target = next((m for m in TARGET_MEMBERS if m in members), None) - if target is None: + target = next((m for m in TARGET_MEMBERS if m in members and ( + key not in RESOURCE_TAG_KEYS + or m.removesuffix("Name").lower() in resource_types.get((action, key), []))), None) + if target is not None and key in RESOURCE_TAG_KEYS and action == "iam:Create" + target.removesuffix("Name"): + not_read.append({"action": action, "key": key, + "reason": "the target does not exist before creation; " + "request tags are handled by TagOnCreate"}) + continue + if target is not None: + if member_type(model, operation, target) != "string": + raise ValueError(f"{action}: target {target} is not a string member") + from_target.append({"action": action, "key": key, "target": target}) + continue + if key not in RESOURCE_TAG_KEYS: raise ValueError(f"{action}: no member names the role or user {key} is read from") - from_target.append({"action": action, "key": key, "target": target}) - continue + reason = "no member names a stored role or user whose resource tags can be read" elif member is None: reason = NOT_IN_REQUEST.get(key, "no member named after the key") elif not set(types.get(key, [])) <= READ_TYPES: @@ -120,26 +156,66 @@ def classify(pairs, types, model): read.append({"action": action, "key": key, "member": member}) continue not_read.append({"action": action, "key": key, "reason": reason}) + for entry in from_target + not_read: + if entry["key"] in RESOURCE_TAG_KEYS: + entry["resources"] = resource_types.get((entry["action"], entry["key"]), []) return read, from_target, not_read - def require_by_hand_listed(pairs): stale = sorted(set(BY_HAND) - set(pairs)) if stale: raise ValueError(f"BY_HAND names pairs the reference does not list: {stale}") +def request_tag_entry(action, key, model): + """Find the unique tag structure list or string list in the operation's input shape.""" + operation = model["operations"].get(action.removeprefix("iam:")) + members = model["shapes"][operation["input"]["shape"]].get("members", {}) \ + if operation and "input" in operation else {} + candidates = [] + for name, member in sorted(members.items()): + shape = model["shapes"][member["shape"]] + if shape["type"] != "list": + continue + item = model["shapes"][shape["member"]["shape"]] + entry = {"action": action, "key": key, "member": member.get("locationName", name)} + if item["type"] == "string" and key == "aws:TagKeys": + candidates.append(entry) + elif item["type"] == "structure" and key in REQUEST_TAG_KEYS: + fields = item.get("members", {}) + keys = [n for n in fields if n.lower() in {"key", "tagkey"}] + values = [n for n in fields if n.lower() in {"value", "tagvalue"}] + if len(keys) == len(values) == 1 and all( + model["shapes"][fields[n]["shape"]]["type"] == "string" for n in keys + values): + candidates.append({**entry, "keyMember": fields[keys[0]].get("locationName", keys[0]), + "valueMember": fields[values[0]].get("locationName", values[0])}) + if len(candidates) != 1: + raise ValueError(f"{action}: expected one request tag list for {key}, found {len(candidates)}") + return candidates[0] + +def request_tag_context(reference, model): + return [request_tag_entry("iam:" + action["Name"], key, model) + for action in sorted(reference["Actions"], key=lambda a: a["Name"]) + if action.get("Annotations", {}).get("Properties", {}).get("IsTaggingOnly") is True + for key in sorted(set(action.get("ActionConditionKeys", [])) & REQUEST_TAG_KEYS)] + +def validate_request_tags(entries, model): + pairs = [(entry["action"], entry["key"]) for entry in entries] + if len(pairs) != len(set(pairs)) or entries != [request_tag_entry(action, key, model) + for action, key in sorted(pairs)]: + raise ValueError("IAM request tag members differ from pinned botocore") + def pairs_of(document): return sorted((e["action"], e["key"]) for e in document["read"] + document["fromTarget"] + document["notRead"]) - def render(document): """The document with one entry to a line.""" lines = ["{"] for key in ("source", "botocore", "types"): lines.append(f' "{key}": {json.dumps(document[key])},') - for section, tail in (("read", ","), ("fromTarget", ","), ("notRead", "")): + for section, tail in (("read", ","), ("fromTarget", ","), ("notRead", ","), + ("requestTags", "")): entries = document[section] lines.append(f' "{section}": [') lines += [f" {json.dumps(e)}{',' if i < len(entries) - 1 else ''}" for i, e in enumerate(entries)] @@ -147,7 +223,6 @@ def render(document): lines.append("}") return "\n".join(lines) + "\n" - def main(argv=None): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--check", action="store_true") @@ -162,9 +237,12 @@ def main(argv=None): raise ValueError("an IAM condition key pair is listed twice") require_by_hand_listed(pairs) model = load_model(latest_model_dir(resolve_botocore_data(args.botocore_data)[0], "iam")) - if classify(pairs, document["types"], model) != ( + resource_types = {(e["action"], e["key"]): e["resources"] + for e in document["fromTarget"] + document["notRead"] if e["key"] in RESOURCE_TAG_KEYS} + if classify(pairs, document["types"], model, resource_types) != ( document["read"], document["fromTarget"], document["notRead"]): raise ValueError("IAM condition key members differ from pinned botocore") + validate_request_tags(document["requestTags"], model) return 0 try: if args.source: @@ -185,12 +263,21 @@ def main(argv=None): print(f"the table names {key} on {action}, which AWS no longer lists", file=sys.stderr) if set(pairs) != vendored or document["types"] != types: raise ValueError("IAM condition keys differ from AWS Service Reference") + model = load_model(latest_model_dir(resolve_botocore_data(args.botocore_data)[0], "iam")) + if classify(pairs, types, model, resource_tag_types(reference)) != ( + document["read"], document["fromTarget"], document["notRead"]): + raise ValueError("IAM condition key targets differ from AWS Service Reference") + if request_tag_context(reference, model) != document["requestTags"]: + raise ValueError("IAM tag condition keys differ from AWS Service Reference") return 0 require_by_hand_listed(pairs) data, provenance = resolve_botocore_data(args.botocore_data) - read, from_target, not_read = classify(pairs, types, load_model(latest_model_dir(data, "iam"))) + model = load_model(latest_model_dir(data, "iam")) + read, from_target, not_read = classify(pairs, types, model, resource_tag_types(reference)) + request_tags = request_tag_context(reference, model) OUTPUT.write_text(render({"source": URL, "botocore": provenance, "types": types, - "read": read, "fromTarget": from_target, "notRead": not_read})) + "read": read, "fromTarget": from_target, "notRead": not_read, + "requestTags": request_tags})) return 0 diff --git a/tools/aws/test_regen_iam_condition_keys.py b/tools/aws/test_regen_iam_condition_keys.py index 8018deeddb..62207185f6 100644 --- a/tools/aws/test_regen_iam_condition_keys.py +++ b/tools/aws/test_regen_iam_condition_keys.py @@ -30,7 +30,7 @@ MODEL = {"operations": { }} -def test_resource_and_action_keys_are_combined_and_global_keys_dropped(): +def test_resource_and_action_keys_are_combined_and_unrelated_global_keys_dropped(): reference = {"Resources": [{"Name": "role", "ConditionKeys": ["iam:PermissionsBoundary", "aws:ResourceTag/${TagKey}"]}], "ConditionKeys": [{"Name": "iam:PermissionsBoundary", "Types": ["ARN"]}, {"Name": "iam:PolicyARN", "Types": ["ARN"]}, @@ -38,7 +38,8 @@ def test_resource_and_action_keys_are_combined_and_global_keys_dropped(): "Actions": [{"Name": "AttachRolePolicy", "ActionConditionKeys": ["iam:PolicyARN", "aws:TagKeys"], "Resources": [{"Name": "role"}]}]} assert action_keys(reference) == ( - [("iam:AttachRolePolicy", "iam:PermissionsBoundary"), ("iam:AttachRolePolicy", "iam:PolicyARN")], + [("iam:AttachRolePolicy", "aws:ResourceTag/${TagKey}"), + ("iam:AttachRolePolicy", "iam:PermissionsBoundary"), ("iam:AttachRolePolicy", "iam:PolicyARN")], {"iam:PermissionsBoundary": ["ARN"], "iam:PolicyARN": ["ARN"]}) @@ -123,8 +124,8 @@ def test_vendored_table_reads_nine_keys_on_fourteen_actions_and_the_boundary_of_ ("iam:CreateServiceSpecificCredential", "iam:ServiceSpecificCredentialServiceName"), ("iam:GenerateOrganizationsAccessReport", "iam:OrganizationsPolicyId")} assert not [e for e in document["notRead"] if e["key"] == "iam:PermissionsBoundary"] - targets = {e["action"]: e["target"] for e in document["fromTarget"]} - assert len(targets) == 15 and {e["key"] for e in document["fromTarget"]} == {"iam:PermissionsBoundary"} + targets = {e["action"]: e["target"] for e in document["fromTarget"] if e["key"] == "iam:PermissionsBoundary"} + assert len(targets) == 15 assert targets["iam:GetRole"] == "RoleName" and targets["iam:DeleteUserPermissionsBoundary"] == "UserName" @@ -150,24 +151,46 @@ def test_check_fails_on_a_hand_edited_member(tmp_path, monkeypatch): regen_iam_condition_keys.main(["--check"]) -def test_verify_fails_on_a_pair_the_table_does_not_name(tmp_path, monkeypatch): +def reference_from_document(document): + actions = {} + for entry in document["read"] + document["fromTarget"] + document["notRead"]: + name = entry["action"].removeprefix("iam:") + action = actions.setdefault(name, {"Name": name, "ActionConditionKeys": [], "Resources": []}) + if entry.get("resources"): + for resource in entry["resources"]: + action["Resources"].append({"Name": resource, "ConditionKeys": [entry["key"]]}) + else: + action["ActionConditionKeys"].append(entry["key"]) + for entry in document["requestTags"]: + name = entry["action"].removeprefix("iam:") + action = actions.setdefault(name, {"Name": name, "ActionConditionKeys": [], "Resources": []}) + action["Annotations"] = {"Properties": {"IsTaggingOnly": True}} + action["ActionConditionKeys"].append(entry["key"]) + return {"Resources": [], "Actions": list(actions.values()), + "ConditionKeys": [{"Name": key, "Types": types} for key, types in document["types"].items()]} + + +def test_verify_fails_on_a_pair_the_table_does_not_name(tmp_path): document = json.loads(OUTPUT.read_text()) - reference = {"Resources": [], "ConditionKeys": [{"Name": k, "Types": t} for k, t in document["types"].items()], - "Actions": []} - for action, key in pairs_of(document) + [("iam:GetRole", "iam:PolicyARN")]: - entry = next((a for a in reference["Actions"] if a["Name"] == action.split(":", 1)[1]), None) - if entry is None: - entry = {"Name": action.split(":", 1)[1], "ActionConditionKeys": []} - reference["Actions"].append(entry) - entry["ActionConditionKeys"].append(key) + reference = reference_from_document(document) source = tmp_path / "iam.json" source.write_text(json.dumps(reference)) + assert regen_iam_condition_keys.main(["--verify", "--source", str(source)]) == 0 + reference["Actions"].append({"Name": "GetRole", "ActionConditionKeys": ["iam:PolicyARN"]}) + source.write_text(json.dumps(reference)) with pytest.raises(ValueError, match="differ from AWS Service Reference"): regen_iam_condition_keys.main(["--verify", "--source", str(source)]) - reference["Actions"] = [a for a in reference["Actions"] if a["Name"] != "GetRole"] + [ - {"Name": "GetRole", "ActionConditionKeys": ["iam:PermissionsBoundary", "iam:RoleTemplateARN"]}] + + +def test_verify_fails_when_resource_type_changes_but_condition_keys_do_not(tmp_path): + reference = reference_from_document(json.loads(OUTPUT.read_text())) + action = next(a for a in reference["Actions"] if a["Name"] == "GetUser") + for resource in action["Resources"]: + resource["Name"] = "role" + source = tmp_path / "iam.json" source.write_text(json.dumps(reference)) - assert regen_iam_condition_keys.main(["--verify", "--source", str(source)]) == 0 + with pytest.raises(ValueError, match="targets differ from AWS Service Reference"): + regen_iam_condition_keys.main(["--verify", "--source", str(source)]) @pytest.mark.parametrize("changed", [ @@ -212,3 +235,92 @@ def run_aggregate_gate(tmp_path, changed, fail): ["make", "--no-print-directory", "iam-data-verify", "CHANGED=" + changed, "MAKE=" + str(recursive_make)], cwd=OUTPUT.parents[4], capture_output=True, text=True, check=False) + + +def test_resource_tags_use_the_same_target_route_and_keep_reasoned_exceptions(): + model = json.loads(json.dumps(MODEL)) + for name in ("CreateRole", "PassRole", "AddRoleToInstanceProfile"): + model["operations"][name] = {"input": {"shape": "GetInput"}} + for name in ("CreateUser", "CreateAccessKey", "GetUser"): + model["operations"][name] = {"input": {"shape": "UserInput"}} + reference = {"ConditionKeys": [], "Resources": [ + {"Name": name, "ConditionKeys": sorted(regen_iam_condition_keys.RESOURCE_TAG_KEYS)} + for name in ("role", "user", "instance-profile")], "Actions": [ + {"Name": name, "Resources": [{"Name": resource}]} for name, resource in ( + ("GetRole", "role"), ("CreateRole", "role"), ("PassRole", "role"), + ("GetUser", "user"), ("CreateUser", "user"), ("CreateAccessKey", "user"), + ("AddRoleToInstanceProfile", "instance-profile"))]} + pairs, types = action_keys(reference) + read, targets, not_read = classify(pairs, types, model, regen_iam_condition_keys.resource_tag_types(reference)) + assert read == [] + assert {(e["action"], e["target"]) for e in targets} == { + ("iam:GetRole", "RoleName"), ("iam:GetUser", "UserName"), ("iam:CreateAccessKey", "UserName")} + assert {e["action"] for e in not_read} == { + "iam:PassRole", "iam:CreateRole", "iam:CreateUser", "iam:AddRoleToInstanceProfile"} + assert all("reliable results" in e["reason"] for e in not_read if e["action"] == "iam:PassRole") + reference["Actions"][0]["Resources"][0]["ConditionKeys"] = [] + assert not [pair for pair in action_keys(reference)[0] if pair[0] == "iam:GetRole"] + + +def tag_model(): + return {"operations": {"ApplyLabels": {"input": {"shape": "Input"}}, + "RemoveLabels": {"input": {"shape": "RemoveInput"}}}, "shapes": { + "Input": {"members": {"Labels": {"shape": "List", "locationName": "WireTags"}}}, + "RemoveInput": {"members": {"Names": {"shape": "Keys"}}}, + "List": {"type": "list", "member": {"shape": "Tag"}}, + "Keys": {"type": "list", "member": {"shape": "String"}}, + "Tag": {"type": "structure", "members": {"TagKey": {"shape": "String", "locationName": "Name"}, + "TagValue": {"shape": "String", "locationName": "Text"}}}, + "String": {"type": "string"}}} + + +def test_tag_request_actions_and_members_are_inferred_without_operation_or_member_names(): + model = tag_model() + reference = {"Actions": [ + {"Name": "ApplyLabels", "Annotations": {"Properties": {"IsTaggingOnly": True}}, + "ActionConditionKeys": sorted(regen_iam_condition_keys.REQUEST_TAG_KEYS)}, + {"Name": "RemoveLabels", "Annotations": {"Properties": {"IsTaggingOnly": True}}, + "ActionConditionKeys": ["aws:TagKeys"]}, + {"Name": "CreateRole", "ActionConditionKeys": sorted(regen_iam_condition_keys.REQUEST_TAG_KEYS)}]} + entries = regen_iam_condition_keys.request_tag_context(reference, model) + assert entries == [ + {"action": "iam:ApplyLabels", "key": "aws:RequestTag/${TagKey}", "member": "WireTags", + "keyMember": "Name", "valueMember": "Text"}, + {"action": "iam:ApplyLabels", "key": "aws:TagKeys", "member": "WireTags", + "keyMember": "Name", "valueMember": "Text"}, + {"action": "iam:RemoveLabels", "key": "aws:TagKeys", "member": "Names"}] + regen_iam_condition_keys.validate_request_tags(entries, model) + entries[0]["valueMember"] = "Wrong" + with pytest.raises(ValueError, match="differ from pinned botocore"): + regen_iam_condition_keys.validate_request_tags(entries, model) + + +@pytest.mark.parametrize("mutation", ["missing", "ambiguous", "wrong-type"]) +def test_tag_request_shape_drift_fails_instead_of_silently_dropping_context(mutation): + model = tag_model() + if mutation == "missing": + model["shapes"]["Input"]["members"].clear() + elif mutation == "ambiguous": + model["shapes"]["Input"]["members"]["OtherTags"] = {"shape": "List"} + else: + model["shapes"]["String"]["type"] = "integer" + with pytest.raises(ValueError, match="expected one request tag list"): + regen_iam_condition_keys.request_tag_entry("iam:ApplyLabels", "aws:RequestTag/${TagKey}", model) + + +def test_vendored_request_tags_cover_all_sixteen_tagging_actions(): + document = json.loads(OUTPUT.read_text()) + assert {e["action"] for e in document["requestTags"]} == { + "iam:" + verb + resource for verb in ("Tag", "Untag") for resource in ( + "InstanceProfile", "MFADevice", "OpenIDConnectProvider", "Policy", "Role", + "SAMLProvider", "ServerCertificate", "User")} + + +def test_check_rejects_hand_edited_tag_fields(tmp_path, monkeypatch): + document = json.loads(OUTPUT.read_text()) + document["requestTags"][0]["keyMember"] = "Wrong" + edited = tmp_path / "iam-condition-keys.json" + edited.write_text(json.dumps(document)) + monkeypatch.setattr(regen_iam_condition_keys, "OUTPUT", edited) + with pytest.raises(ValueError, match="request tag members differ"): + regen_iam_condition_keys.main(["--check"])