Light, fluffy, and always free - The AWS Local Emulator alternative
fix(iam): read condition keys a request carries in a member under another name (#6858)
lex0052eb4b9a9c15
diff --git a/docs/services/iam.md b/docs/services/iam.mdindex 8ae460bb55..500cf31461 100644--- a/docs/services/iam.md+++ b/docs/services/iam.md@@ -2261,13 +2261,19 @@ floci populates:- 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:+ when the request has a string parameter of the same name, ignoring case. Its `BY_HAND` list+ names the parameter for a key whose value sits under another name. 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:NotificationChannel` from `NotificationChannel`, `iam:DelegationDuration` from+ `SessionDuration` and `iam:TemplateArn` from `Permissions.PolicyTemplateArn` on+ `CreateDelegationRequest`.+ - `iam:ServiceSpecificCredentialServiceName` from `ServiceName` and+ `iam:ServiceSpecificCredentialAgeDays` from `CredentialAgeDays` on+ `CreateServiceSpecificCredential`. A numeric key matches the `Numeric` operators.- `iam:OrganizationsPolicyId` from `OrganizationsPolicyId` on`GenerateOrganizationsAccessReport`.diff --git a/src/main/resources/aws/iam-condition-keys.json b/src/main/resources/aws/iam-condition-keys.jsonindex 511d66a18a..1e2f1f58ea 100644--- a/src/main/resources/aws/iam-condition-keys.json+++ b/src/main/resources/aws/iam-condition-keys.json@@ -6,9 +6,13 @@{"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:DelegationDuration", "member": "SessionDuration"},{"action": "iam:CreateDelegationRequest", "key": "iam:NotificationChannel", "member": "NotificationChannel"},+ {"action": "iam:CreateDelegationRequest", "key": "iam:TemplateArn", "member": "Permissions.PolicyTemplateArn"},{"action": "iam:CreateRole", "key": "iam:PermissionsBoundary", "member": "PermissionsBoundary"},{"action": "iam:CreateServiceLinkedRole", "key": "iam:AWSServiceName", "member": "AWSServiceName"},+ {"action": "iam:CreateServiceSpecificCredential", "key": "iam:ServiceSpecificCredentialAgeDays", "member": "CredentialAgeDays"},+ {"action": "iam:CreateServiceSpecificCredential", "key": "iam:ServiceSpecificCredentialServiceName", "member": "ServiceName"},{"action": "iam:CreateUser", "key": "iam:PermissionsBoundary", "member": "PermissionsBoundary"},{"action": "iam:DetachGroupPolicy", "key": "iam:PolicyARN", "member": "PolicyArn"},{"action": "iam:DetachRolePolicy", "key": "iam:PolicyARN", "member": "PolicyArn"},@@ -18,49 +22,45 @@{"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:AcceptDelegationRequest", "key": "iam:DelegationRequestOwner", "reason": "the value is the delegation request's owner"},+ {"action": "iam:AssociateDelegationRequest", "key": "iam:DelegationRequestOwner", "reason": "the value is the delegation request's owner"},{"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:AttachRolePolicy", "key": "iam:RoleTemplateARN", "reason": "the value is the role template a service acquires the role from"},{"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:CreateDelegationRequest", "key": "iam:DelegationRequestOwner", "reason": "the value is the delegation request's owner"},+ {"action": "iam:CreateRole", "key": "iam:RoleTemplateARN", "reason": "the value is the role template a service acquires the role from"},{"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:DeleteServiceSpecificCredential", "key": "iam:ServiceSpecificCredentialServiceName", "reason": "the value is the named credential's service"},{"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: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:GetAccountProperties", "key": "iam:AccountPropertyNamespaces", "reason": "the value is the namespaces of the properties read or written"},+ {"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: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:GetRole", "key": "iam:RoleTemplateARN", "reason": "the value is the role template a service acquires the role from"},+ {"action": "iam:ListDelegationRequests", "key": "iam:DelegationRequestOwner", "reason": "the value is the delegation request's owner"},{"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: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: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:PutRolePolicy", "key": "iam:RoleTemplateARN", "reason": "the value is the role template a service acquires the role from"},{"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:RejectDelegationRequest", "key": "iam:DelegationRequestOwner", "reason": "the value is the delegation request's owner"},+ {"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:TagRole", "key": "iam:RoleTemplateARN", "reason": "the value is the role template a service acquires the role from"},{"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"}+ {"action": "iam:UpdateServiceSpecificCredential", "key": "iam:ServiceSpecificCredentialServiceName", "reason": "the value is the named credential's service"}]}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.javaindex 16a3de0270..756e99aa80 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@@ -232,6 +232,44 @@ class IamConditionContextResolverTest {assertNull(resolver.resolve("iam", "iam:CreateDelegationRequest", formRequest("Description=d")));}+ @Test+ void iamDelegationDurationAndTemplateArnComeFromCreateDelegationRequest() {+ assertEquals(Map.of("iam:DelegationDuration", List.of("43200"),+ "iam:TemplateArn", List.of("arn:aws:iam::aws:template/partner/t")),+ resolver.resolve("iam", "iam:CreateDelegationRequest", formRequest(+ "SessionDuration=43200&Permissions.PolicyTemplateArn=arn%3Aaws%3Aiam%3A%3Aaws%3Atemplate%2Fpartner%2Ft")));+ }++ @Test+ void iamServiceSpecificCredentialKeysComeFromCreateServiceSpecificCredential() {+ assertEquals(Map.of("iam:ServiceSpecificCredentialServiceName", List.of("bedrock.amazonaws.com"),+ "iam:ServiceSpecificCredentialAgeDays", List.of("90")),+ resolver.resolve("iam", "iam:CreateServiceSpecificCredential",+ formRequest("UserName=u&ServiceName=bedrock.amazonaws.com&CredentialAgeDays=90")));+ assertEquals(Map.of("iam:ServiceSpecificCredentialServiceName", List.of("codecommit.amazonaws.com")),+ resolver.resolve("iam", "iam:CreateServiceSpecificCredential",+ formRequest("UserName=u&ServiceName=codecommit.amazonaws.com")));+ assertNull(resolver.resolve("iam", "iam:UpdateServiceSpecificCredential",+ formRequest("ServiceSpecificCredentialId=ACCA1234567890EXAMPLE&Status=Inactive")));+ }++ @Test+ void aCredentialAgeConditionMatchesTheNumericOperators() {+ String policy = """+ {"Version":"2012-10-17","Statement":[{"Effect":"Allow",+ "Action":"iam:CreateServiceSpecificCredential","Resource":"*","Condition":+ {"NumericLessThanEquals":{"iam:ServiceSpecificCredentialAgeDays":"90"}}}]}""";++ assertEquals(Decision.ALLOW, evaluator.simulateCustomPolicy(List.of(policy),+ "iam:CreateServiceSpecificCredential", "*", resolver.resolve("iam",+ "iam:CreateServiceSpecificCredential",+ formRequest("ServiceName=bedrock.amazonaws.com&CredentialAgeDays=30"))));+ assertEquals(Decision.DENY, evaluator.simulateCustomPolicy(List.of(policy),+ "iam:CreateServiceSpecificCredential", "*", resolver.resolve("iam",+ "iam:CreateServiceSpecificCredential",+ formRequest("ServiceName=bedrock.amazonaws.com&CredentialAgeDays=365"))));+ }+@Testvoid iamOrganizationsPolicyIdComesFromGenerateOrganizationsAccessReport() {assertEquals(Map.of("iam:OrganizationsPolicyId", List.of("p-12345678")),diff --git a/src/test/java/io/github/hectorvent/floci/services/iam/IamServiceSpecificCredentialConditionEnforcementIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/iam/IamServiceSpecificCredentialConditionEnforcementIntegrationTest.javanew file mode 100644index 0000000000..8e14e06ff0--- /dev/null+++ b/src/test/java/io/github/hectorvent/floci/services/iam/IamServiceSpecificCredentialConditionEnforcementIntegrationTest.java@@ -0,0 +1,83 @@+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.Response;+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;++/**+ * The IAM User Guide's example for {@code iam:ServiceSpecificCredentialServiceName} and+ * {@code iam:ServiceSpecificCredentialAgeDays}: a user may create Amazon Bedrock API keys that expire+ * within 90 days, and nothing else. The keys come from the request's {@code ServiceName} and+ * {@code CredentialAgeDays} members.+ */+@QuarkusTest+@TestProfile(IamEnforcementProfile.class)+class IamServiceSpecificCredentialConditionEnforcementIntegrationTest {++ private static final String ADMIN = "test";+ private static final String POLICY = """+ {"Version":"2012-10-17","Statement":[{"Effect":"Allow",+ "Action":"iam:CreateServiceSpecificCredential","Resource":"*","Condition":{+ "StringEquals":{"iam:ServiceSpecificCredentialServiceName":"bedrock.amazonaws.com"},+ "NumericLessThanEquals":{"iam:ServiceSpecificCredentialAgeDays":"90"}}}]}""";++ @TestHTTPResource("/")+ static URI baseUri;++ @RegisterExtension+ final PartitionCleanup cleanup = new PartitionCleanup();++ @Test+ void aUserMayCreateOnlyTheServiceAndAgeThePolicyNames() {+ String userName = "bedrock-keys-" + UUID.randomUUID().toString().substring(0, 8);+ UserCredentials user = EnforcementFixtures.createUser(cleanup, baseUri.getPort(), auth(ADMIN, "iam"),+ userName);+ EnforcementFixtures.putUserPolicy(baseUri.getPort(), auth(ADMIN, "iam"), userName, "BedrockKeys", POLICY);++ create(user, userName, "codecommit.amazonaws.com", null).then()+ .statusCode(403)+ .body(containsString("<Code>AccessDenied</Code>"))+ .body(containsString("iam:CreateServiceSpecificCredential"));+ create(user, userName, "bedrock.amazonaws.com", "365").then().statusCode(403);+ create(user, userName, "bedrock.amazonaws.com", null).then().statusCode(403);++ String credentialId = create(user, userName, "bedrock.amazonaws.com", "90").then()+ .statusCode(200)+ .body(containsString("<ServiceName>bedrock.amazonaws.com</ServiceName>"))+ .extract().xmlPath().getString("CreateServiceSpecificCredentialResponse"+ + ".CreateServiceSpecificCredentialResult.ServiceSpecificCredential"+ + ".ServiceSpecificCredentialId");+ cleanup.register(() -> iam(ADMIN, "DeleteServiceSpecificCredential").formParam("UserName", userName)+ .formParam("ServiceSpecificCredentialId", credentialId).post("/"));+ }++ private static Response create(UserCredentials user, String userName, String serviceName, String ageDays) {+ RequestSpecification request = iam(user.accessKeyId(), "CreateServiceSpecificCredential")+ .formParam("UserName", userName).formParam("ServiceName", serviceName);+ if (ageDays != null) {+ request.formParam("CredentialAgeDays", ageDays);+ }+ return request.post("/");+ }++ 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/tools/aws/regen_iam_condition_keys.py b/tools/aws/regen_iam_condition_keys.pyindex afd0f9aab5..c193bfbb11 100644--- a/tools/aws/regen_iam_condition_keys.py+++ b/tools/aws/regen_iam_condition_keys.py@@ -4,12 +4,14 @@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: theoperation 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+(iam:PolicyARN is PolicyArn), and the key's type is String or ARN. BY_HAND names the member for a+pair whose value sits in a member under another name; its type has to fit the key's. Those pairs+are read; every other pair the reference lists is notRead, with the reason. An operation that has the member butwhose 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+hand-edited entry fails, as does a BY_HAND member botocore no longer has or a BY_HAND pair the+file does not list. --verify compares every pair and key type with the live reference andfails on any difference, added pairs included: a key missing from the context stops aconditioned Allow matching and a conditioned Deny applying. --source reads a saved reference."""@@ -28,9 +30,26 @@ from regen_query_services import latest_model_dir, load_modelOUTPUT = 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 = {+# Pairs whose value is a request member under another name: the member path, dotted for a nested one.+BY_HAND = {+ ("iam:CreateDelegationRequest", "iam:DelegationDuration"): "SessionDuration",+ ("iam:CreateDelegationRequest", "iam:TemplateArn"): "Permissions.PolicyTemplateArn",+ ("iam:CreateServiceSpecificCredential", "iam:ServiceSpecificCredentialAgeDays"): "CredentialAgeDays",+ ("iam:CreateServiceSpecificCredential", "iam:ServiceSpecificCredentialServiceName"): "ServiceName",+}+# The botocore types a BY_HAND member may have for each key type; the context value is the member's text.+BY_HAND_TYPES = {"String": {"string", "integer"}, "ARN": {"string"}, "Numeric": {"integer", "long"}}+# Keys whose value, on an action without the member, does not come from the request.+NOT_IN_REQUEST = {+ "iam:AccountPropertyNamespaces": "the value is the namespaces of the properties read or written",+ "iam:DelegationRequestOwner": "the value is the delegation request's owner",+ "iam:FIDO-FIPS-140-2-certification": "the value comes from the FIDO Alliance Metadata Service",+ "iam:FIDO-FIPS-140-3-certification": "the value comes from the FIDO Alliance Metadata Service",+ "iam:FIDO-certification": "the value comes from the FIDO Alliance Metadata Service","iam:PermissionsBoundary": "the value is the target's current permissions boundary",+ "iam:RegisterSecurityKey": "the value is the MFA device's registration state",+ "iam:RoleTemplateARN": "the value is the role template a service acquires the role from",+ "iam:ServiceSpecificCredentialServiceName": "the value is the named credential's service",}@@ -48,11 +67,31 @@ def action_keys(reference):return sorted(pairs), dict(sorted(types.items()))+def member_type(model, operation, path):+ """The botocore type of the request member at a dotted path, or None when there is none."""+ shape = model["shapes"][operation["input"]["shape"]] if operation and "input" in operation else {}+ for name in path.split("."):+ member = shape.get("members", {}).get(name)+ if member is None:+ return None+ shape = model["shapes"][member["shape"]]+ return shape["type"]++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])+ if (action, key) in BY_HAND:+ path = BY_HAND[(action, key)]+ found = member_type(model, operation, path)+ if found is None:+ raise ValueError(f"{action}: BY_HAND member {path} for {key} is not in botocore")+ if not all(found in BY_HAND_TYPES.get(t, set()) for t in types.get(key) or [None]):+ raise ValueError(f"{action}: BY_HAND member {path} is {found}, which does not fit {key}")+ read.append({"action": action, "key": key, "member": path})+ continuelocal = key.split(":", 1)[1]members = model["shapes"][operation["input"]["shape"]].get("members", {}) \if operation and "input" in operation else {}@@ -60,7 +99,7 @@ def classify(pairs, types, model):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")+ reason = NOT_IN_REQUEST.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":@@ -72,6 +111,12 @@ def classify(pairs, types, model):return read, 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 pairs_of(document):return sorted((e["action"], e["key"]) for e in document["read"] + document["notRead"])@@ -102,6 +147,7 @@ def main(argv=None):pairs = pairs_of(document)if len(set(pairs)) != len(pairs):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) != (document["read"], document["notRead"]):raise ValueError("IAM condition key members differ from pinned botocore")@@ -126,6 +172,7 @@ def main(argv=None):if set(pairs) != vendored or document["types"] != types:raise ValueError("IAM condition keys differ from AWS Service Reference")return 0+ require_by_hand_listed(pairs)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,diff --git a/tools/aws/test_regen_iam_condition_keys.py b/tools/aws/test_regen_iam_condition_keys.pyindex e3accb62f5..c6d52d7943 100644--- a/tools/aws/test_regen_iam_condition_keys.py+++ b/tools/aws/test_regen_iam_condition_keys.py@@ -5,17 +5,22 @@ import subprocessimport pytestimport regen_iam_condition_keys-from regen_iam_condition_keys import OUTPUT, action_keys, classify, pairs_of+from regen_iam_condition_keys import OUTPUT, action_keys, classify, pairs_of, require_by_hand_listedMODEL = {"operations": {"AttachRolePolicy": {"input": {"shape": "AttachInput"}},"GetPolicy": {"input": {"shape": "AttachInput"}},"GetRole": {"input": {"shape": "GetInput"}},"CreateServiceSpecificCredential": {"input": {"shape": "CredentialInput"}},+ "CreateDelegationRequest": {"input": {"shape": "DelegationInput"}},}, "shapes": {"AttachInput": {"type": "structure", "members": {"PolicyArn": {"shape": "Arn"}}},"GetInput": {"type": "structure", "members": {"RoleName": {"shape": "Name"}}},- "CredentialInput": {"type": "structure", "members": {"CredentialAgeDays": {"shape": "Days"}}},+ "CredentialInput": {"type": "structure", "members": {"CredentialAgeDays": {"shape": "Days"},+ "ServiceName": {"shape": "Name"}}},+ "DelegationInput": {"type": "structure", "members": {"Permissions": {"shape": "Permission"},+ "SessionDuration": {"shape": "Days"}}},+ "Permission": {"type": "structure", "members": {"PolicyTemplateArn": {"shape": "Arn"}}},"Arn": {"type": "string"}, "Name": {"type": "string"}, "Days": {"type": "integer"},}}@@ -49,11 +54,42 @@ def test_unread_pairs_name_their_reason():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:GetRole", "iam:RoleTemplateARN"): "the value is the role template a service acquires the role from",("iam:PassRole", "iam:PassedToService"): "no SDK operation of this name"}-def test_vendored_table_reads_the_five_keys_on_thirteen_actions():+BY_HAND_TYPES = {"iam:DelegationDuration": ["String"], "iam:TemplateArn": ["ARN"],+ "iam:ServiceSpecificCredentialAgeDays": ["Numeric"],+ "iam:ServiceSpecificCredentialServiceName": ["String"]}+++def test_by_hand_pairs_read_their_member_including_a_nested_one():+ read, not_read = classify(sorted(regen_iam_condition_keys.BY_HAND), BY_HAND_TYPES, MODEL)+ assert not_read == []+ assert {(e["action"], e["key"]): e["member"] for e in read} == regen_iam_condition_keys.BY_HAND+++def test_by_hand_member_missing_from_botocore_fails():+ model = json.loads(json.dumps(MODEL))+ del model["shapes"]["Permission"]["members"]["PolicyTemplateArn"]+ with pytest.raises(ValueError, match="Permissions.PolicyTemplateArn for iam:TemplateArn is not in botocore"):+ classify(sorted(regen_iam_condition_keys.BY_HAND), BY_HAND_TYPES, model)+++def test_by_hand_member_whose_type_does_not_fit_the_key_fails():+ types = dict(BY_HAND_TYPES, **{"iam:ServiceSpecificCredentialAgeDays": ["String"],+ "iam:ServiceSpecificCredentialServiceName": ["Numeric"]})+ with pytest.raises(ValueError, match="ServiceName is string, which does not fit"):+ classify(sorted(regen_iam_condition_keys.BY_HAND), types, MODEL)+++def test_by_hand_pair_the_reference_no_longer_lists_fails():+ pairs = sorted(regen_iam_condition_keys.BY_HAND)[1:]+ with pytest.raises(ValueError, match="BY_HAND names pairs the reference does not list"):+ require_by_hand_listed(pairs)+++def test_vendored_table_reads_nine_keys_on_fourteen_actions():document = json.loads(OUTPUT.read_text())assert {(e["action"], e["key"]) for e in document["read"]} == {*(("iam:" + verb + kind + "Policy", "iam:PolicyARN")@@ -63,6 +99,10 @@ def test_vendored_table_reads_the_five_keys_on_thirteen_actions():("iam:PutUserPermissionsBoundary", "iam:PermissionsBoundary"),("iam:CreateServiceLinkedRole", "iam:AWSServiceName"),("iam:CreateDelegationRequest", "iam:NotificationChannel"),+ ("iam:CreateDelegationRequest", "iam:DelegationDuration"),+ ("iam:CreateDelegationRequest", "iam:TemplateArn"),+ ("iam:CreateServiceSpecificCredential", "iam:ServiceSpecificCredentialAgeDays"),+ ("iam:CreateServiceSpecificCredential", "iam:ServiceSpecificCredentialServiceName"),("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