diff --git a/.github/workflows/iam-data-drift.yml b/.github/workflows/iam-data-drift.yml index c3329ba5d9..aef293dd87 100644 --- a/.github/workflows/iam-data-drift.yml +++ b/.github/workflows/iam-data-drift.yml @@ -1,12 +1,12 @@ name: IAM Data Drift -# Checks the eight vendored files that come from AWS's live service reference rather than from a +# Checks the nine vendored files that come from AWS's live service reference rather than from a # pinned dependency: the IAM service namespace list, the map of which resource each IAM action is # authorized against, the map of operations AWS authorizes as an action of another name, the # table of the operations that pass a role and the services they pass it to, the table of the # operations that pass a Lambda network connector, the table of the # tagging actions operations that tag what they create need, and the table of the resources each -# operation's request names, and the DynamoDB condition key table. That +# operation's request names, the DynamoDB condition key table, and the IAM condition key table. That # needs the live service reference index, so unlike every other check here it can # fail without anything in the repository having changed: an AWS outage, or a namespace AWS has # retired. It therefore runs on its own, never as part of a job that ordinary changes trigger. @@ -26,7 +26,8 @@ name: IAM Data Drift # An entry AWS has *added* since the last sync is reported without failing: a new namespace makes # the service-last-accessed report incomplete rather than wrong, and a new action or resource type # leaves that action evaluated against `*`, which is where it was before any of this existed. The -# fix for a real failure is to run the matching sync target and commit the result. +# two condition key tables fail on an added pair as well: a key missing from the context stops a +# conditioned Allow matching and a conditioned Deny applying. The fix for a real failure is to run the matching sync target and commit the result. # # The offline shape check is hermetic and runs per pull request inside the "Vendored AWS data in # sync" job in partition-literals.yml instead. @@ -58,6 +59,9 @@ on: - 'src/main/resources/aws/dynamodb-condition-keys.json' - 'tools/aws/regen_dynamodb_condition_keys.py' - 'tools/aws/test_regen_dynamodb_condition_keys.py' + - 'src/main/resources/aws/iam-condition-keys.json' + - 'tools/aws/regen_iam_condition_keys.py' + - 'tools/aws/test_regen_iam_condition_keys.py' - 'tools/aws/regen_partitions.py' - 'tools/aws/regen_query_services.py' - '.github/workflows/iam-data-drift.yml' diff --git a/.github/workflows/partition-literals.yml b/.github/workflows/partition-literals.yml index 54a6012664..c12cd3d0a8 100644 --- a/.github/workflows/partition-literals.yml +++ b/.github/workflows/partition-literals.yml @@ -103,6 +103,9 @@ jobs: - name: Check DynamoDB condition request members run: make dynamodb-condition-keys-check + - name: Check IAM condition key request members + run: make iam-condition-keys-check + - name: Check partitions.json against a fresh generation run: make aws-data-check diff --git a/Makefile b/Makefile index 4e0bfebf32..b634e15c01 100644 --- a/Makefile +++ b/Makefile @@ -422,6 +422,9 @@ IAM_TAG_ON_CREATE_PATHS := src/main/resources/aws/iam-tag-on-create.json tools/a DYNAMODB_CONDITION_KEYS_PATHS := src/main/resources/aws/dynamodb-condition-keys.json \ tools/aws/regen_dynamodb_condition_keys.py tools/aws/test_regen_dynamodb_condition_keys.py \ tools/aws/regen_partitions.py tools/aws/regen_query_services.py +IAM_CONDITION_KEYS_PATHS := src/main/resources/aws/iam-condition-keys.json \ + tools/aws/regen_iam_condition_keys.py tools/aws/test_regen_iam_condition_keys.py \ + tools/aws/regen_partitions.py tools/aws/regen_query_services.py IAM_REQUEST_RESOURCES_PATHS := src/main/resources/aws/iam-request-resources.json \ tools/aws/regen_iam_request_resources.py $(IAM_PASSED_ROLES_GENERATOR) \ tools/aws/test_regen_iam_request_resources.py @@ -430,7 +433,7 @@ iam-data-verify: ## CI gate (online): every vendored IAM file must still match A @# Every check runs even when an earlier one fails, so one file's drift cannot hide another's @# state. Sequential steps in CI stop at the first failure, which once left the action @# resource gate unexercised while the namespace list was stale. - @namespaces=0; actions=0; authorized=0; passed=0; connectors=0; tagged=0; requested=0; dynamodb=0; \ + @namespaces=0; actions=0; authorized=0; passed=0; connectors=0; tagged=0; requested=0; dynamodb=0; conditionkeys=0; \ covers() { \ [ -z "$(strip $(CHANGED))" ] && return 0; \ for path in $(CHANGED); do case " $$1 " in *" $$path "*) return 0;; esac; done; \ @@ -461,8 +464,12 @@ iam-data-verify: ## CI gate (online): every vendored IAM file must still match A if covers "$(DYNAMODB_CONDITION_KEYS_PATHS)" "the DynamoDB condition key table"; then \ $(MAKE) --no-print-directory dynamodb-condition-keys-verify || dynamodb=$$?; \ fi; \ + if covers "$(IAM_CONDITION_KEYS_PATHS)" "the IAM condition key table"; then \ + $(MAKE) --no-print-directory iam-condition-keys-verify || conditionkeys=$$?; \ + fi; \ if [ $$namespaces -ne 0 ] || [ $$actions -ne 0 ] || [ $$authorized -ne 0 ] || [ $$passed -ne 0 ] \ - || [ $$connectors -ne 0 ] || [ $$tagged -ne 0 ] || [ $$requested -ne 0 ] || [ $$dynamodb -ne 0 ]; then \ + || [ $$connectors -ne 0 ] || [ $$tagged -ne 0 ] || [ $$requested -ne 0 ] || [ $$dynamodb -ne 0 ] \ + || [ $$conditionkeys -ne 0 ]; then \ echo ""; \ echo "error: vendored IAM data does not match upstream:"; \ if [ $$namespaces -ne 0 ]; then \ @@ -487,6 +494,7 @@ iam-data-verify: ## CI gate (online): every vendored IAM file must still match A echo " the table of the resources requests name, see its message above"; \ fi; \ if [ $$dynamodb -ne 0 ]; then echo " the DynamoDB condition key table"; fi; \ + if [ $$conditionkeys -ne 0 ]; then echo " the IAM condition key table"; fi; \ exit 1; \ fi @@ -664,3 +672,11 @@ dynamodb-condition-keys-check: ## Check DynamoDB condition request members again $(PYTHON) tools/aws/regen_dynamodb_condition_keys.py --check dynamodb-condition-keys-verify: ## Check DynamoDB condition action keys against AWS $(PYTHON) tools/aws/regen_dynamodb_condition_keys.py --verify + +.PHONY: iam-condition-keys-sync iam-condition-keys-check iam-condition-keys-verify +iam-condition-keys-sync: ## Regenerate the IAM condition keys requests carry from AWS and botocore + $(PYTHON) tools/aws/regen_iam_condition_keys.py +iam-condition-keys-check: ## Check the IAM condition key request members against pinned botocore + $(PYTHON) tools/aws/regen_iam_condition_keys.py --check +iam-condition-keys-verify: ## Check every IAM condition key and action pair against AWS + $(PYTHON) tools/aws/regen_iam_condition_keys.py --verify diff --git a/docs/services/iam.md b/docs/services/iam.md index 70dd701701..c72d785ba2 100644 --- a/docs/services/iam.md +++ b/docs/services/iam.md @@ -2218,9 +2218,23 @@ trust policy and the value it sits in matches nothing. A `Condition` operator can only match a key floci actually places in the request context. floci populates: -- `iam:PolicyARN`: the managed policy ARN in the form body for `AttachRolePolicy`, - `DetachRolePolicy`, `AttachUserPolicy`, `DetachUserPolicy`, `AttachGroupPolicy` and - `DetachGroupPolicy`. The target role, user or group remains the authorized resource. +- The `iam:` keys an IAM request carries in its own parameters, from + `src/main/resources/aws/iam-condition-keys.json`. `tools/aws/regen_iam_condition_keys.py` + generates it: for each action and `iam:` key the AWS Service Reference lists, the key is read + when the request has a string parameter of the same name, ignoring case. The table reads: + - `iam:PolicyARN` from `PolicyArn` on `AttachRolePolicy`, `DetachRolePolicy`, + `AttachUserPolicy`, `DetachUserPolicy`, `AttachGroupPolicy` and `DetachGroupPolicy`. + - `iam:PermissionsBoundary` from `PermissionsBoundary` on `CreateRole`, `CreateUser`, + `PutRolePermissionsBoundary` and `PutUserPermissionsBoundary`. + - `iam:AWSServiceName` from `AWSServiceName` on `CreateServiceLinkedRole`. + - `iam:NotificationChannel` from `NotificationChannel` on `CreateDelegationRequest`. + - `iam:OrganizationsPolicyId` from `OrganizationsPolicyId` on + `GenerateOrganizationsAccessReport`. + + 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, such as the actions where `iam:PermissionsBoundary` is the target's current + boundary. 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 `ec2:RunInstances` (`TagSpecification.N`), `ec2:CreateTags` (`Tag.N`) and 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 50d3f3ed49..f4b0af29b2 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 @@ -209,14 +209,19 @@ public class IamConditionContextResolver { } private static Map> iamConditionContext(String action, ContainerRequestContext ctx) { - return switch (action) { - case "iam:AttachRolePolicy", "iam:DetachRolePolicy", "iam:AttachUserPolicy", - "iam:DetachUserPolicy", "iam:AttachGroupPolicy", "iam:DetachGroupPolicy" -> { - String policyArn = formParameters(ctx).get("PolicyArn"); - yield policyArn == null ? null : Map.of("iam:PolicyARN", List.of(policyArn)); + Map members = IamConditionKeys.members(action); + if (members.isEmpty()) { + return null; + } + Map form = formParameters(ctx); + Map> conditions = new LinkedHashMap<>(); + members.forEach((key, member) -> { + String value = form.get(member); + if (value != null) { + conditions.put(key, List.of(value)); } - default -> null; - }; + }); + return conditions.isEmpty() ? null : conditions; } public static Map> withGlobalContext(Map> serviceContext, 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 new file mode 100644 index 0000000000..9b2cc8cd8a --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/core/common/IamConditionKeys.java @@ -0,0 +1,40 @@ +package io.github.hectorvent.floci.core.common; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; + +import java.util.LinkedHashMap; +import java.util.Map; + +/** + * The {@code iam:} condition keys an IAM request carries in its own members, generated from the + * AWS Service Reference and pinned botocore by {@code tools/aws/regen_iam_condition_keys.py}. + */ +final class IamConditionKeys { + + private static final Map> MEMBERS = VendoredResources.read( + "aws/iam-condition-keys.json", "IAM condition keys", input -> { + JsonNode read = new ObjectMapper().readTree(input).path("read"); + if (!read.isArray() || read.isEmpty()) { + throw new IllegalStateException("Malformed IAM condition key table"); + } + Map> members = new LinkedHashMap<>(); + for (JsonNode entry : read) { + if (!entry.path("action").isTextual() || !entry.path("key").isTextual() + || !entry.path("member").isTextual()) { + throw new IllegalStateException("Malformed IAM condition key entry: " + entry); + } + members.computeIfAbsent(entry.get("action").asText(), action -> new LinkedHashMap<>()) + .put(entry.get("key").asText(), entry.get("member").asText()); + } + members.replaceAll((action, keys) -> Map.copyOf(keys)); + return Map.copyOf(members); + }); + + private IamConditionKeys() {} + + /** Each condition key a request for {@code action} carries, to the member that holds it; empty when none. */ + static Map members(String action) { + return MEMBERS.getOrDefault(action, Map.of()); + } +} diff --git a/src/main/resources/aws/iam-condition-keys.json b/src/main/resources/aws/iam-condition-keys.json new file mode 100644 index 0000000000..511d66a18a --- /dev/null +++ b/src/main/resources/aws/iam-condition-keys.json @@ -0,0 +1,66 @@ +{ + "source": "https://servicereference.us-east-1.amazonaws.com/v1/iam/iam.json", + "botocore": "botocore 1.43.113 (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"]}, + "read": [ + {"action": "iam:AttachGroupPolicy", "key": "iam:PolicyARN", "member": "PolicyArn"}, + {"action": "iam:AttachRolePolicy", "key": "iam:PolicyARN", "member": "PolicyArn"}, + {"action": "iam:AttachUserPolicy", "key": "iam:PolicyARN", "member": "PolicyArn"}, + {"action": "iam:CreateDelegationRequest", "key": "iam:NotificationChannel", "member": "NotificationChannel"}, + {"action": "iam:CreateRole", "key": "iam:PermissionsBoundary", "member": "PermissionsBoundary"}, + {"action": "iam:CreateServiceLinkedRole", "key": "iam:AWSServiceName", "member": "AWSServiceName"}, + {"action": "iam:CreateUser", "key": "iam:PermissionsBoundary", "member": "PermissionsBoundary"}, + {"action": "iam:DetachGroupPolicy", "key": "iam:PolicyARN", "member": "PolicyArn"}, + {"action": "iam:DetachRolePolicy", "key": "iam:PolicyARN", "member": "PolicyArn"}, + {"action": "iam:DetachUserPolicy", "key": "iam:PolicyARN", "member": "PolicyArn"}, + {"action": "iam:GenerateOrganizationsAccessReport", "key": "iam:OrganizationsPolicyId", "member": "OrganizationsPolicyId"}, + {"action": "iam:PutRolePermissionsBoundary", "key": "iam:PermissionsBoundary", "member": "PermissionsBoundary"}, + {"action": "iam:PutUserPermissionsBoundary", "key": "iam:PermissionsBoundary", "member": "PermissionsBoundary"} + ], + "notRead": [ + {"action": "iam:AcceptDelegationRequest", "key": "iam:DelegationRequestOwner", "reason": "no member named after the key"}, + {"action": "iam:AssociateDelegationRequest", "key": "iam:DelegationRequestOwner", "reason": "no member named after the key"}, + {"action": "iam:AttachRolePolicy", "key": "iam:PermissionsBoundary", "reason": "the value is the target's current permissions boundary"}, + {"action": "iam:AttachRolePolicy", "key": "iam:RoleTemplateARN", "reason": "no member named after the key"}, + {"action": "iam:AttachUserPolicy", "key": "iam:PermissionsBoundary", "reason": "the value is the target's current permissions boundary"}, + {"action": "iam:CreateDelegationRequest", "key": "iam:DelegationDuration", "reason": "no member named after the key"}, + {"action": "iam:CreateDelegationRequest", "key": "iam:DelegationRequestOwner", "reason": "no member named after the key"}, + {"action": "iam:CreateDelegationRequest", "key": "iam:TemplateArn", "reason": "no member named after the key"}, + {"action": "iam:CreateRole", "key": "iam:RoleTemplateARN", "reason": "no member named after the key"}, + {"action": "iam:CreateServiceSpecificCredential", "key": "iam:ServiceSpecificCredentialAgeDays", "reason": "no member named after the key"}, + {"action": "iam:CreateServiceSpecificCredential", "key": "iam:ServiceSpecificCredentialServiceName", "reason": "no member named after the key"}, + {"action": "iam:DeleteRole", "key": "iam:PermissionsBoundary", "reason": "the value is the target's current permissions boundary"}, + {"action": "iam:DeleteRolePermissionsBoundary", "key": "iam:PermissionsBoundary", "reason": "the value is the target's current permissions boundary"}, + {"action": "iam:DeleteRolePolicy", "key": "iam:PermissionsBoundary", "reason": "the value is the target's current permissions boundary"}, + {"action": "iam:DeleteServiceSpecificCredential", "key": "iam:ServiceSpecificCredentialServiceName", "reason": "no member named after the key"}, + {"action": "iam:DeleteUserPermissionsBoundary", "key": "iam:PermissionsBoundary", "reason": "the value is the target's current permissions boundary"}, + {"action": "iam:DeleteUserPolicy", "key": "iam:PermissionsBoundary", "reason": "the value is the target's current permissions boundary"}, + {"action": "iam:DetachRolePolicy", "key": "iam:PermissionsBoundary", "reason": "the value is the target's current permissions boundary"}, + {"action": "iam:DetachUserPolicy", "key": "iam:PermissionsBoundary", "reason": "the value is the target's current permissions boundary"}, + {"action": "iam:EnableMFADevice", "key": "iam:FIDO-FIPS-140-2-certification", "reason": "no member named after the key"}, + {"action": "iam:EnableMFADevice", "key": "iam:FIDO-FIPS-140-3-certification", "reason": "no member named after the key"}, + {"action": "iam:EnableMFADevice", "key": "iam:FIDO-certification", "reason": "no member named after the key"}, + {"action": "iam:EnableMFADevice", "key": "iam:RegisterSecurityKey", "reason": "no member named after the key"}, + {"action": "iam:GetAccountProperties", "key": "iam:AccountPropertyNamespaces", "reason": "no member named after the key"}, + {"action": "iam:GetDelegationRequest", "key": "iam:DelegationRequestOwner", "reason": "no member named after the key"}, + {"action": "iam:GetHumanReadableSummary", "key": "iam:DelegationRequestOwner", "reason": "no member named after the key"}, + {"action": "iam:GetRole", "key": "iam:PermissionsBoundary", "reason": "the value is the target's current permissions boundary"}, + {"action": "iam:GetRole", "key": "iam:RoleTemplateARN", "reason": "no member named after the key"}, + {"action": "iam:ListDelegationRequests", "key": "iam:DelegationRequestOwner", "reason": "no member named after the key"}, + {"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:PutAccountProperties", "key": "iam:AccountPropertyNamespaces", "reason": "no member named after the key"}, + {"action": "iam:PutRolePermissionsBoundary", "key": "iam:RoleTemplateARN", "reason": "no member named after the key"}, + {"action": "iam:PutRolePolicy", "key": "iam:PermissionsBoundary", "reason": "the value is the target's current permissions boundary"}, + {"action": "iam:PutRolePolicy", "key": "iam:RoleTemplateARN", "reason": "no member named after the key"}, + {"action": "iam:PutUserPolicy", "key": "iam:PermissionsBoundary", "reason": "the value is the target's current permissions boundary"}, + {"action": "iam:RejectDelegationRequest", "key": "iam:DelegationRequestOwner", "reason": "no member named after the key"}, + {"action": "iam:ResetServiceSpecificCredential", "key": "iam:ServiceSpecificCredentialServiceName", "reason": "no member named after the key"}, + {"action": "iam:SendDelegationToken", "key": "iam:DelegationRequestOwner", "reason": "no member named after the key"}, + {"action": "iam:TagRole", "key": "iam:RoleTemplateARN", "reason": "no member named after the key"}, + {"action": "iam:UpdateAssumeRolePolicy", "key": "iam:PermissionsBoundary", "reason": "the value is the target's current permissions boundary"}, + {"action": "iam:UpdateRole", "key": "iam:PermissionsBoundary", "reason": "the value is the target's current permissions boundary"}, + {"action": "iam:UpdateRoleDescription", "key": "iam:PermissionsBoundary", "reason": "the value is the target's current permissions boundary"}, + {"action": "iam:UpdateServiceSpecificCredential", "key": "iam:ServiceSpecificCredentialServiceName", "reason": "no member named after the key"} + ] +} 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 00ed3d3327..16a3de0270 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 @@ -201,6 +201,63 @@ class IamConditionContextResolverTest { formRequest("PolicyArn=arn%3Aaws%3Aiam%3A%3A123456789012%3Apolicy%2FTeam%2FA%2BB%252F"))); } + @Test + void iamPermissionsBoundaryComesFromTheBoundaryParameterOfEachActionThatTakesIt() { + for (String action : List.of("iam:CreateRole", "iam:CreateUser", "iam:PutRolePermissionsBoundary", + "iam:PutUserPermissionsBoundary")) { + assertEquals(Map.of("iam:PermissionsBoundary", List.of("arn:aws:iam::123456789012:policy/Boundary")), + resolver.resolve("iam", action, + formRequest("PermissionsBoundary=arn%3Aaws%3Aiam%3A%3A123456789012%3Apolicy%2FBoundary")), + action); + assertNull(resolver.resolve("iam", action, formRequest("RoleName=r&UserName=u")), action); + } + assertNull(resolver.resolve("iam", "iam:GetRole", formRequest("PermissionsBoundary=example"))); + } + + @Test + void iamAwsServiceNameComesFromCreateServiceLinkedRole() { + assertEquals(Map.of("iam:AWSServiceName", List.of("replication.ecr.amazonaws.com")), + resolver.resolve("iam", "iam:CreateServiceLinkedRole", + formRequest("AWSServiceName=replication.ecr.amazonaws.com"))); + assertNull(resolver.resolve("iam", "iam:CreateServiceLinkedRole", formRequest("Description=d"))); + assertNull(resolver.resolve("iam", "iam:DeleteServiceLinkedRole", + formRequest("AWSServiceName=replication.ecr.amazonaws.com"))); + } + + @Test + void iamNotificationChannelComesFromCreateDelegationRequest() { + assertEquals(Map.of("iam:NotificationChannel", List.of("arn:aws:sns:us-east-1:123456789012:t")), + resolver.resolve("iam", "iam:CreateDelegationRequest", + formRequest("NotificationChannel=arn%3Aaws%3Asns%3Aus-east-1%3A123456789012%3At"))); + assertNull(resolver.resolve("iam", "iam:CreateDelegationRequest", formRequest("Description=d"))); + } + + @Test + void iamOrganizationsPolicyIdComesFromGenerateOrganizationsAccessReport() { + assertEquals(Map.of("iam:OrganizationsPolicyId", List.of("p-12345678")), + resolver.resolve("iam", "iam:GenerateOrganizationsAccessReport", + formRequest("EntityPath=o-a%2Fr-b&OrganizationsPolicyId=p-12345678"))); + assertNull(resolver.resolve("iam", "iam:GenerateOrganizationsAccessReport", + formRequest("EntityPath=o-a%2Fr-b"))); + } + + @Test + void aPermissionsBoundaryConditionAllowsOnlyACreateRoleThatSetsThatBoundary() { + String policy = """ + {"Version":"2012-10-17","Statement":[{"Effect":"Allow","Action":"iam:CreateRole", + "Resource":"*","Condition":{"StringEquals": + {"iam:PermissionsBoundary":"arn:aws:iam::123456789012:policy/Boundary"}}}]}"""; + + assertEquals(Decision.ALLOW, evaluator.simulateCustomPolicy(List.of(policy), "iam:CreateRole", "*", + resolver.resolve("iam", "iam:CreateRole", formRequest( + "RoleName=r&PermissionsBoundary=arn%3Aaws%3Aiam%3A%3A123456789012%3Apolicy%2FBoundary")))); + assertEquals(Decision.DENY, evaluator.simulateCustomPolicy(List.of(policy), "iam:CreateRole", "*", + resolver.resolve("iam", "iam:CreateRole", formRequest( + "RoleName=r&PermissionsBoundary=arn%3Aaws%3Aiam%3A%3A123456789012%3Apolicy%2FOther")))); + assertEquals(Decision.DENY, evaluator.simulateCustomPolicy(List.of(policy), "iam:CreateRole", "*", + resolver.resolve("iam", "iam:CreateRole", formRequest("RoleName=r")))); + } + @Test void queryGetConditionsUseTheFirstDecodedUrlValue() { MultivaluedMap query = new MultivaluedHashMap<>(); diff --git a/src/test/java/io/github/hectorvent/floci/services/iam/IamAwsServiceNameConditionEnforcementIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/iam/IamAwsServiceNameConditionEnforcementIntegrationTest.java new file mode 100644 index 0000000000..a84730e75d --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/iam/IamAwsServiceNameConditionEnforcementIntegrationTest.java @@ -0,0 +1,66 @@ +package io.github.hectorvent.floci.services.iam; + +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 io.restassured.specification.RequestSpecification; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.RegisterExtension; + +import java.net.URI; +import java.util.UUID; + +import static io.github.hectorvent.floci.testing.EnforcementFixtures.auth; +import static io.restassured.RestAssured.given; +import static org.hamcrest.Matchers.containsString; + +/** + * {@code AmazonEC2ContainerRegistryFullAccess} allows {@code iam:CreateServiceLinkedRole} only with + * {@code StringEquals} {@code iam:AWSServiceName} {@code replication.ecr.amazonaws.com}, as most AWS + * managed policies that create a service-linked role do. The key comes from the request's + * {@code AWSServiceName} member. + */ +@QuarkusTest +@TestProfile(IamEnforcementProfile.class) +class IamAwsServiceNameConditionEnforcementIntegrationTest { + + private static final String ADMIN = "test"; + private static final String POLICY = "arn:aws:iam::aws:policy/AmazonEC2ContainerRegistryFullAccess"; + private static final String ROLE = "AWSServiceRoleForECRReplication"; + + @TestHTTPResource("/") + static URI baseUri; + + @RegisterExtension + final PartitionCleanup cleanup = new PartitionCleanup(); + + @Test + void aManagedPolicyAllowsOnlyTheServiceLinkedRoleItNames() { + String userName = "ecr-admin-" + UUID.randomUUID().toString().substring(0, 8); + UserCredentials user = EnforcementFixtures.createUser(cleanup, baseUri.getPort(), auth(ADMIN, "iam"), + userName); + iam(ADMIN, "AttachUserPolicy").formParam("UserName", userName).formParam("PolicyArn", POLICY) + .post("/").then().statusCode(200); + cleanup.register(() -> iam(ADMIN, "DeleteServiceLinkedRole").formParam("RoleName", ROLE).post("/")); + + iam(user.accessKeyId(), "CreateServiceLinkedRole") + .formParam("AWSServiceName", "memorydb.amazonaws.com").post("/").then() + .statusCode(403) + .body(containsString("AccessDenied")) + .body(containsString("iam:CreateServiceLinkedRole")); + iam(user.accessKeyId(), "CreateServiceLinkedRole") + .formParam("AWSServiceName", "replication.ecr.amazonaws.com").post("/").then() + .statusCode(200) + .body(containsString("" + ROLE + "")); + } + + private static RequestSpecification iam(String accessKeyId, String action) { + return given().contentType("application/x-www-form-urlencoded") + .header("Authorization", auth(accessKeyId, "iam")) + .formParam("Action", action); + } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/iam/IamPermissionsBoundaryConditionEnforcementIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/iam/IamPermissionsBoundaryConditionEnforcementIntegrationTest.java new file mode 100644 index 0000000000..b0b5bf6548 --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/iam/IamPermissionsBoundaryConditionEnforcementIntegrationTest.java @@ -0,0 +1,142 @@ +package io.github.hectorvent.floci.services.iam; + +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 io.restassured.response.ValidatableResponse; +import io.restassured.specification.RequestSpecification; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.RegisterExtension; + +import java.net.URI; +import java.util.UUID; + +import static io.github.hectorvent.floci.testing.EnforcementFixtures.auth; +import static io.restassured.RestAssured.given; +import static org.hamcrest.Matchers.containsString; + +/** + * A delegated administrator may create roles and users only with a given permissions boundary, as in + * the IAM user guide's "Delegating responsibility to others using permissions boundaries" example: + * an allow conditioned on {@code StringEquals} {@code iam:PermissionsBoundary}. The Service + * Authorization Reference lists the key on {@code CreateRole}, {@code CreateUser}, + * {@code PutRolePermissionsBoundary} and {@code PutUserPermissionsBoundary}, which carry the boundary + * in their {@code PermissionsBoundary} parameter. + */ +@QuarkusTest +@TestProfile(IamEnforcementProfile.class) +class IamPermissionsBoundaryConditionEnforcementIntegrationTest { + + private static final String ADMIN = "test"; + private static final String TRUST_POLICY = """ + {"Version":"2012-10-17","Statement":[{"Effect":"Allow", + "Principal":{"Service":"ecs-tasks.amazonaws.com"},"Action":"sts:AssumeRole"}]}"""; + + @TestHTTPResource("/") + static URI baseUri; + + @RegisterExtension + final PartitionCleanup cleanup = new PartitionCleanup(); + + @Test + void createRoleIsAllowedOnlyWithTheBoundaryTheConditionNames() { + String boundary = boundaryPolicy("boundary"); + String other = boundaryPolicy("other"); + UserCredentials delegated = delegatedAdmin(boundary, "iam:CreateRole"); + String role = "bounded-" + suffix(); + cleanup.register(() -> EnforcementFixtures.removeRole(baseUri.getPort(), auth(ADMIN, "iam"), role)); + + denied(createRole(delegated, role).post("/").then(), "iam:CreateRole"); + denied(createRole(delegated, role).formParam("PermissionsBoundary", other).post("/").then(), + "iam:CreateRole"); + createRole(delegated, role).formParam("PermissionsBoundary", boundary).post("/").then() + .statusCode(200) + .body(containsString("" + boundary + "")); + } + + @Test + void createUserAndPutUserPermissionsBoundaryAreAllowedOnlyWithThatBoundary() { + String boundary = boundaryPolicy("boundary"); + String other = boundaryPolicy("other"); + UserCredentials delegated = delegatedAdmin(boundary, "iam:CreateUser", + "iam:PutUserPermissionsBoundary"); + String user = "bounded-" + suffix(); + cleanup.register(() -> EnforcementFixtures.removeUser(baseUri.getPort(), auth(ADMIN, "iam"), user)); + + denied(iam(delegated.accessKeyId(), "CreateUser").formParam("UserName", user).post("/").then(), + "iam:CreateUser"); + iam(delegated.accessKeyId(), "CreateUser").formParam("UserName", user) + .formParam("PermissionsBoundary", boundary).post("/").then().statusCode(200); + + denied(iam(delegated.accessKeyId(), "PutUserPermissionsBoundary").formParam("UserName", user) + .formParam("PermissionsBoundary", other).post("/").then(), "iam:PutUserPermissionsBoundary"); + iam(delegated.accessKeyId(), "PutUserPermissionsBoundary").formParam("UserName", user) + .formParam("PermissionsBoundary", boundary).post("/").then().statusCode(200); + } + + @Test + void putRolePermissionsBoundaryIsAllowedOnlyWithThatBoundary() { + String boundary = boundaryPolicy("boundary"); + String other = boundaryPolicy("other"); + UserCredentials delegated = delegatedAdmin(boundary, "iam:PutRolePermissionsBoundary"); + String role = "rebounded-" + suffix(); + cleanup.register(() -> EnforcementFixtures.removeRole(baseUri.getPort(), auth(ADMIN, "iam"), role)); + createRole(ADMIN, role).post("/").then().statusCode(200); + + denied(iam(delegated.accessKeyId(), "PutRolePermissionsBoundary").formParam("RoleName", role) + .formParam("PermissionsBoundary", other).post("/").then(), "iam:PutRolePermissionsBoundary"); + iam(delegated.accessKeyId(), "PutRolePermissionsBoundary").formParam("RoleName", role) + .formParam("PermissionsBoundary", boundary).post("/").then().statusCode(200); + } + + private String boundaryPolicy(String name) { + String arn = iam(ADMIN, "CreatePolicy") + .formParam("PolicyName", name + "-" + suffix()) + .formParam("PolicyDocument", """ + {"Version":"2012-10-17","Statement":[{"Effect":"Allow","Action":"s3:*","Resource":"*"}]}""") + .post("/").then().statusCode(200) + .extract().path("CreatePolicyResponse.CreatePolicyResult.Policy.Arn"); + cleanup.register(() -> EnforcementFixtures.removePolicy(baseUri.getPort(), auth(ADMIN, "iam"), arn)); + return arn; + } + + private UserCredentials delegatedAdmin(String boundary, String... actions) { + String userName = "delegated-admin-" + suffix(); + UserCredentials credentials = EnforcementFixtures.createUser(cleanup, baseUri.getPort(), + auth(ADMIN, "iam"), userName); + EnforcementFixtures.putUserPolicy(baseUri.getPort(), auth(ADMIN, "iam"), userName, "OnlyWithBoundary", """ + {"Version":"2012-10-17","Statement":[{"Effect":"Allow","Action":["%s"],"Resource":"*", + "Condition":{"StringEquals":{"iam:PermissionsBoundary":"%s"}}}]}""" + .formatted(String.join("\",\"", actions), boundary)); + return credentials; + } + + private RequestSpecification createRole(UserCredentials caller, String roleName) { + return createRole(caller.accessKeyId(), roleName); + } + + private RequestSpecification createRole(String accessKeyId, String roleName) { + return iam(accessKeyId, "CreateRole").formParam("RoleName", roleName) + .formParam("AssumeRolePolicyDocument", TRUST_POLICY); + } + + private static RequestSpecification iam(String accessKeyId, String action) { + return given().contentType("application/x-www-form-urlencoded") + .header("Authorization", auth(accessKeyId, "iam")) + .formParam("Action", action); + } + + private static void denied(ValidatableResponse response, String action) { + response.statusCode(403) + .body(containsString("AccessDenied")) + .body(containsString(action)); + } + + 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 new file mode 100644 index 0000000000..afd0f9aab5 --- /dev/null +++ b/tools/aws/regen_iam_condition_keys.py @@ -0,0 +1,137 @@ +#!/usr/bin/env python3 +"""Generate the table of the IAM condition keys a request carries in its own members. + +The AWS Service Reference lists every iam: condition key each IAM action can be evaluated with. +For each such action and key, pinned botocore says whether the request carries the value: the +operation of the same name has a top-level string member named after the key, ignoring case +(iam:PolicyARN is PolicyArn), and the key's type is String or ARN. Those pairs are read; every +other pair the reference lists is notRead, with the reason. An operation that has the member but +whose action does not list the key is left out, as AWS does not set the key for it. + +--check re-derives read and notRead offline from the pairs in the file and pinned botocore, so a +hand-edited entry fails. --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. +""" +from __future__ import annotations + +import argparse +import json +import sys +import urllib.error +import urllib.request +from pathlib import Path + +from regen_partitions import resolve_botocore_data +from regen_query_services import latest_model_dir, load_model + +OUTPUT = Path(__file__).resolve().parents[2] / "src/main/resources/aws/iam-condition-keys.json" +URL = "https://servicereference.us-east-1.amazonaws.com/v1/iam/iam.json" +READ_TYPES = {"String", "ARN"} +# Keys whose value, on an action without the member, is state of the target the request names. +STORED = { + "iam:PermissionsBoundary": "the value is the target's current permissions boundary", +} + + +def action_keys(reference): + """Every (action, key) pair for an iam: key the reference lists, 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} + 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 classify(pairs, types, model): + """The read entries and the notRead entries for the reference's pairs.""" + read, not_read = [], [] + for action, key in sorted(pairs): + operation = model["operations"].get(action.split(":", 1)[1]) + local = key.split(":", 1)[1] + 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: + reason = "no SDK operation of this name" + elif member is None: + reason = STORED.get(key, "no member named after the key") + elif not set(types.get(key, [])) <= READ_TYPES: + reason = "the key's type is " + ", ".join(types.get(key) or ["not given"]) + elif model["shapes"][members[member]["shape"]]["type"] != "string": + reason = f"{member} is not a string member" + else: + read.append({"action": action, "key": key, "member": member}) + continue + not_read.append({"action": action, "key": key, "reason": reason}) + return read, not_read + + +def pairs_of(document): + return sorted((e["action"], e["key"]) for e in document["read"] + 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", ","), ("notRead", "")): + entries = document[section] + lines.append(f' "{section}": [') + lines += [f" {json.dumps(e)}{',' if i < len(entries) - 1 else ''}" for i, e in enumerate(entries)] + lines.append(" ]" + tail) + lines.append("}") + return "\n".join(lines) + "\n" + + +def main(argv=None): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--check", action="store_true") + parser.add_argument("--verify", action="store_true") + parser.add_argument("--source", type=Path) + parser.add_argument("--botocore-data", type=Path) + args = parser.parse_args(argv) + if args.check: + document = json.loads(OUTPUT.read_text()) + pairs = pairs_of(document) + if len(set(pairs)) != len(pairs): + raise ValueError("an IAM condition key pair is listed twice") + model = load_model(latest_model_dir(resolve_botocore_data(args.botocore_data)[0], "iam")) + if classify(pairs, document["types"], model) != (document["read"], document["notRead"]): + raise ValueError("IAM condition key members differ from pinned botocore") + return 0 + try: + if args.source: + reference = json.loads(args.source.read_text()) + else: + with urllib.request.urlopen(URL, timeout=30) as response: + reference = json.load(response) + except urllib.error.URLError as error: + print(f"could not read {URL}: {error}", file=sys.stderr) + return 2 + pairs, types = action_keys(reference) + if args.verify: + document = json.loads(OUTPUT.read_text()) + vendored = set(pairs_of(document)) + for action, key in sorted(set(pairs) - vendored): + print(f"AWS lists {key} on {action}, which the table does not name", file=sys.stderr) + for action, key in sorted(vendored - set(pairs)): + 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") + return 0 + data, provenance = resolve_botocore_data(args.botocore_data) + read, not_read = classify(pairs, types, load_model(latest_model_dir(data, "iam"))) + OUTPUT.write_text(render({"source": URL, "botocore": provenance, "types": types, + "read": read, "notRead": not_read})) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tools/aws/test_regen_iam_condition_keys.py b/tools/aws/test_regen_iam_condition_keys.py new file mode 100644 index 0000000000..e3accb62f5 --- /dev/null +++ b/tools/aws/test_regen_iam_condition_keys.py @@ -0,0 +1,143 @@ +"""Matching rule and vendored coverage for the IAM condition keys requests carry.""" +import json +import subprocess + +import pytest + +import regen_iam_condition_keys +from regen_iam_condition_keys import OUTPUT, action_keys, classify, pairs_of + +MODEL = {"operations": { + "AttachRolePolicy": {"input": {"shape": "AttachInput"}}, + "GetPolicy": {"input": {"shape": "AttachInput"}}, + "GetRole": {"input": {"shape": "GetInput"}}, + "CreateServiceSpecificCredential": {"input": {"shape": "CredentialInput"}}, +}, "shapes": { + "AttachInput": {"type": "structure", "members": {"PolicyArn": {"shape": "Arn"}}}, + "GetInput": {"type": "structure", "members": {"RoleName": {"shape": "Name"}}}, + "CredentialInput": {"type": "structure", "members": {"CredentialAgeDays": {"shape": "Days"}}}, + "Arn": {"type": "string"}, "Name": {"type": "string"}, "Days": {"type": "integer"}, +}} + + +def test_resource_and_action_keys_are_combined_and_global_keys_dropped(): + reference = {"Resources": [{"Name": "role", "ConditionKeys": ["iam:PermissionsBoundary", "aws:ResourceTag/${TagKey}"]}], + "ConditionKeys": [{"Name": "iam:PermissionsBoundary", "Types": ["ARN"]}, + {"Name": "iam:PolicyARN", "Types": ["ARN"]}, + {"Name": "iam:Unused", "Types": ["String"]}], + "Actions": [{"Name": "AttachRolePolicy", "ActionConditionKeys": ["iam:PolicyARN", "aws:TagKeys"], + "Resources": [{"Name": "role"}]}]} + assert action_keys(reference) == ( + [("iam:AttachRolePolicy", "iam:PermissionsBoundary"), ("iam:AttachRolePolicy", "iam:PolicyARN")], + {"iam:PermissionsBoundary": ["ARN"], "iam:PolicyARN": ["ARN"]}) + + +def test_member_is_matched_ignoring_case_only_on_actions_listing_the_key(): + read, not_read = classify([("iam:AttachRolePolicy", "iam:PolicyARN")], {"iam:PolicyARN": ["ARN"]}, MODEL) + assert read == [{"action": "iam:AttachRolePolicy", "key": "iam:PolicyARN", "member": "PolicyArn"}] + assert not_read == [] + + +def test_unread_pairs_name_their_reason(): + pairs = [("iam:GetRole", "iam:PermissionsBoundary"), ("iam:GetRole", "iam:RoleTemplateARN"), + ("iam:PassRole", "iam:PassedToService"), + ("iam:CreateServiceSpecificCredential", "iam:CredentialAgeDays")] + types = {"iam:PermissionsBoundary": ["ARN"], "iam:RoleTemplateARN": ["ARN"], + "iam:PassedToService": ["String"], "iam:CredentialAgeDays": ["Numeric"]} + read, not_read = classify(pairs, types, MODEL) + assert read == [] + assert {(e["action"], e["key"]): e["reason"] for e in not_read} == { + ("iam:CreateServiceSpecificCredential", "iam:CredentialAgeDays"): "the key's type is Numeric", + ("iam:GetRole", "iam:PermissionsBoundary"): "the value is the target's current permissions boundary", + ("iam:GetRole", "iam:RoleTemplateARN"): "no member named after the key", + ("iam:PassRole", "iam:PassedToService"): "no SDK operation of this name"} + + +def test_vendored_table_reads_the_five_keys_on_thirteen_actions(): + document = json.loads(OUTPUT.read_text()) + assert {(e["action"], e["key"]) for e in document["read"]} == { + *(("iam:" + verb + kind + "Policy", "iam:PolicyARN") + for verb in ("Attach", "Detach") for kind in ("Group", "Role", "User")), + ("iam:CreateRole", "iam:PermissionsBoundary"), ("iam:CreateUser", "iam:PermissionsBoundary"), + ("iam:PutRolePermissionsBoundary", "iam:PermissionsBoundary"), + ("iam:PutUserPermissionsBoundary", "iam:PermissionsBoundary"), + ("iam:CreateServiceLinkedRole", "iam:AWSServiceName"), + ("iam:CreateDelegationRequest", "iam:NotificationChannel"), + ("iam:GenerateOrganizationsAccessReport", "iam:OrganizationsPolicyId")} + current = [e["action"] for e in document["notRead"] if e["key"] == "iam:PermissionsBoundary"] + assert len(current) == 15 and "iam:GetRole" in current + + +def test_check_fails_on_a_hand_edited_member(tmp_path, monkeypatch): + pytest.importorskip("botocore") + document = json.loads(OUTPUT.read_text()) + document["read"][0]["member"] = "PolicyName" + 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="differ from pinned botocore"): + regen_iam_condition_keys.main(["--check"]) + + +def test_verify_fails_on_a_pair_the_table_does_not_name(tmp_path, monkeypatch): + 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) + source = tmp_path / "iam.json" + 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"]}] + source.write_text(json.dumps(reference)) + assert regen_iam_condition_keys.main(["--verify", "--source", str(source)]) == 0 + + +@pytest.mark.parametrize("changed", [ + "src/main/resources/aws/iam-condition-keys.json", + "tools/aws/regen_iam_condition_keys.py", + "tools/aws/test_regen_iam_condition_keys.py", + "tools/aws/regen_partitions.py", + "tools/aws/regen_query_services.py", + "", +]) +def test_aggregate_gate_checks_condition_data_and_imports(tmp_path, changed): + result = run_aggregate_gate(tmp_path, changed, fail=True) + assert "checked:iam-condition-keys-verify" in result.stdout + assert result.returncode != 0 + assert "the IAM condition key table" in result.stdout + + +@pytest.mark.parametrize("changed", [ + "docs/services/iam.md", + "src/main/resources/aws/dynamodb-condition-keys.json", + "src/main/resources/aws/iam-condition-keys.json.bak", +]) +def test_aggregate_gate_does_not_check_unrelated_condition_data(tmp_path, changed): + result = run_aggregate_gate(tmp_path, changed, fail=True) + assert "checked:iam-condition-keys-verify" not in result.stdout + assert result.returncode == 0 + + +def test_aggregate_gate_accepts_successful_condition_check(tmp_path): + result = run_aggregate_gate(tmp_path, "src/main/resources/aws/iam-condition-keys.json", fail=False) + assert "checked:iam-condition-keys-verify" in result.stdout + assert result.returncode == 0 + + +def run_aggregate_gate(tmp_path, changed, fail): + recursive_make = tmp_path / "check-gate" + recursive_make.write_text( + '#!/bin/sh\nprintf "checked:%s\\n" "$2"\n' + + ('[ "$2" != iam-condition-keys-verify ]\n' if fail else 'exit 0\n')) + recursive_make.chmod(0o700) + return subprocess.run( + ["make", "--no-print-directory", "iam-data-verify", "CHANGED=" + changed, + "MAKE=" + str(recursive_make)], + cwd=OUTPUT.parents[4], capture_output=True, text=True, check=False)